blob: 3af9ab42c314498fcdea008dd7a692d4dbb00bf4 [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedman456f0182012-01-20 01:26:23 +000044#include "TreeTransform.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000047
Sebastian Redlb49c46c2011-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 Redl5999aec2011-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 Redlb49c46c2011-09-24 17:48:00 +000066 return true;
67}
David Chisnall9f57c292009-08-17 16:35:33 +000068
Ted Kremenek6eb25622012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-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 Jahanian25d09c22011-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 Jahanian6b854c52011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenek6eb25622012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenek6eb25622012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000096 else
Ted Kremenek6eb25622012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenek6eb25622012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith852265f2012-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 Smith6f1e2c62012-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 Smith852265f2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith852265f2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Douglas Gregor171c45a2009-02-18 21:56:37 +0000133/// \brief Determine whether the use of this declaration is valid, and
134/// emit any corresponding diagnostics.
135///
136/// This routine diagnoses various problems with referencing
137/// declarations that can occur when using a declaration. For example,
138/// it might warn if a deprecated or unavailable declaration is being
139/// used, or produce an error (and return true) if a C++0x deleted
140/// function is being used.
141///
142/// \returns true if there was an error (this declaration cannot be
143/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000144///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000145bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000146 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000147 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000148 // If there were any diagnostics suppressed by template argument deduction,
149 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000150 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000151 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
152 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000154 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
155 Diag(Suppressed[I].first, Suppressed[I].second);
156
157 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000158 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000159 // entry from the table, because we want to avoid ever emitting these
160 // diagnostics again.
161 Suppressed.clear();
162 }
163 }
164
Richard Smith30482bc2011-02-20 03:19:35 +0000165 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000166 if (ParsingInitForAutoVars.count(D)) {
167 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
168 << D->getDeclName();
169 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000170 }
171
Douglas Gregor171c45a2009-02-18 21:56:37 +0000172 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000174 if (FD->isDeleted()) {
175 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000176 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000177 return true;
178 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000179 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000180 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000181
Anders Carlsson73067a02010-10-22 23:37:08 +0000182 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000183 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000184 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Douglas Gregor171c45a2009-02-18 21:56:37 +0000185 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000186}
187
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000188/// \brief Retrieve the message suffix that should be added to a
189/// diagnostic complaining about the given function being deleted or
190/// unavailable.
191std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
192 // FIXME: C++0x implicitly-deleted special member functions could be
193 // detected here so that we could improve diagnostics to say, e.g.,
194 // "base class 'A' had a deleted copy constructor".
195 if (FD->isDeleted())
196 return std::string();
197
198 std::string Message;
199 if (FD->getAvailability(&Message))
200 return ": " + Message;
201
202 return std::string();
203}
204
John McCallb46f2872011-09-09 07:56:05 +0000205/// DiagnoseSentinelCalls - This routine checks whether a call or
206/// message-send is to a declaration with the sentinel attribute, and
207/// if so, it checks that the requirements of the sentinel are
208/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000209void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000210 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000211 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000212 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000213 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000214
John McCallb46f2872011-09-09 07:56:05 +0000215 // The number of formal parameters of the declaration.
216 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000217
John McCallb46f2872011-09-09 07:56:05 +0000218 // The kind of declaration. This is also an index into a %select in
219 // the diagnostic.
220 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
221
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000222 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000223 numFormalParams = MD->param_size();
224 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000225 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000226 numFormalParams = FD->param_size();
227 calleeType = CT_Function;
228 } else if (isa<VarDecl>(D)) {
229 QualType type = cast<ValueDecl>(D)->getType();
230 const FunctionType *fn = 0;
231 if (const PointerType *ptr = type->getAs<PointerType>()) {
232 fn = ptr->getPointeeType()->getAs<FunctionType>();
233 if (!fn) return;
234 calleeType = CT_Function;
235 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
236 fn = ptr->getPointeeType()->castAs<FunctionType>();
237 calleeType = CT_Block;
238 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000239 return;
John McCallb46f2872011-09-09 07:56:05 +0000240 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000241
John McCallb46f2872011-09-09 07:56:05 +0000242 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
243 numFormalParams = proto->getNumArgs();
244 } else {
245 numFormalParams = 0;
246 }
247 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000248 return;
249 }
John McCallb46f2872011-09-09 07:56:05 +0000250
251 // "nullPos" is the number of formal parameters at the end which
252 // effectively count as part of the variadic arguments. This is
253 // useful if you would prefer to not have *any* formal parameters,
254 // but the language forces you to have at least one.
255 unsigned nullPos = attr->getNullPos();
256 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
257 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
258
259 // The number of arguments which should follow the sentinel.
260 unsigned numArgsAfterSentinel = attr->getSentinel();
261
262 // If there aren't enough arguments for all the formal parameters,
263 // the sentinel, and the args after the sentinel, complain.
264 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000265 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000266 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000267 return;
268 }
John McCallb46f2872011-09-09 07:56:05 +0000269
270 // Otherwise, find the sentinel expression.
271 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000272 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000273 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000274 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000275
John McCallb46f2872011-09-09 07:56:05 +0000276 // Pick a reasonable string to insert. Optimistically use 'nil' or
277 // 'NULL' if those are actually defined in the context. Only use
278 // 'nil' for ObjC methods, where it's much more likely that the
279 // variadic arguments form a list of object pointers.
280 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000281 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
282 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000283 if (calleeType == CT_Method &&
284 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000285 NullValue = "nil";
286 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
287 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000288 else
John McCallb46f2872011-09-09 07:56:05 +0000289 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000290
291 if (MissingNilLoc.isInvalid())
292 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
293 else
294 Diag(MissingNilLoc, diag::warn_missing_sentinel)
295 << calleeType
296 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000297 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000298}
299
Richard Trieuba63ce62011-09-09 01:45:06 +0000300SourceRange Sema::getExprRange(Expr *E) const {
301 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000302}
303
Chris Lattner513165e2008-07-25 21:10:04 +0000304//===----------------------------------------------------------------------===//
305// Standard Promotions and Conversions
306//===----------------------------------------------------------------------===//
307
Chris Lattner513165e2008-07-25 21:10:04 +0000308/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000309ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000310 // Handle any placeholder expressions which made it here.
311 if (E->getType()->isPlaceholderType()) {
312 ExprResult result = CheckPlaceholderExpr(E);
313 if (result.isInvalid()) return ExprError();
314 E = result.take();
315 }
316
Chris Lattner513165e2008-07-25 21:10:04 +0000317 QualType Ty = E->getType();
318 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
319
Chris Lattner513165e2008-07-25 21:10:04 +0000320 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000321 E = ImpCastExprToType(E, Context.getPointerType(Ty),
322 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000323 else if (Ty->isArrayType()) {
324 // In C90 mode, arrays only promote to pointers if the array expression is
325 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
326 // type 'array of type' is converted to an expression that has type 'pointer
327 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
328 // that has type 'array of type' ...". The relevant change is "an lvalue"
329 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000330 //
331 // C++ 4.2p1:
332 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
333 // T" can be converted to an rvalue of type "pointer to T".
334 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000335 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000336 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
337 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000338 }
John Wiegley01296292011-04-08 18:41:53 +0000339 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000340}
341
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000342static void CheckForNullPointerDereference(Sema &S, Expr *E) {
343 // Check to see if we are dereferencing a null pointer. If so,
344 // and if not volatile-qualified, this is undefined behavior that the
345 // optimizer will delete, so warn about it. People sometimes try to use this
346 // to get a deterministic trap and are surprised by clang's behavior. This
347 // only handles the pattern "*null", which is a very syntactic check.
348 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
349 if (UO->getOpcode() == UO_Deref &&
350 UO->getSubExpr()->IgnoreParenCasts()->
351 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
352 !UO->getType().isVolatileQualified()) {
353 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
354 S.PDiag(diag::warn_indirection_through_null)
355 << UO->getSubExpr()->getSourceRange());
356 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
357 S.PDiag(diag::note_indirection_through_null));
358 }
359}
360
John Wiegley01296292011-04-08 18:41:53 +0000361ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000362 // Handle any placeholder expressions which made it here.
363 if (E->getType()->isPlaceholderType()) {
364 ExprResult result = CheckPlaceholderExpr(E);
365 if (result.isInvalid()) return ExprError();
366 E = result.take();
367 }
368
John McCallf3735e02010-12-01 04:43:34 +0000369 // C++ [conv.lval]p1:
370 // A glvalue of a non-function, non-array type T can be
371 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000372 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000373
John McCall27584242010-12-06 20:48:59 +0000374 QualType T = E->getType();
375 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000376
John McCall27584242010-12-06 20:48:59 +0000377 // We don't want to throw lvalue-to-rvalue casts on top of
378 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000379 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000380 (E->getType() == Context.OverloadTy ||
381 T->isDependentType() ||
382 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000383 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000384
385 // The C standard is actually really unclear on this point, and
386 // DR106 tells us what the result should be but not why. It's
387 // generally best to say that void types just doesn't undergo
388 // lvalue-to-rvalue at all. Note that expressions of unqualified
389 // 'void' type are never l-values, but qualified void can be.
390 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000391 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000392
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000393 CheckForNullPointerDereference(*this, E);
394
John McCall27584242010-12-06 20:48:59 +0000395 // C++ [conv.lval]p1:
396 // [...] If T is a non-class type, the type of the prvalue is the
397 // cv-unqualified version of T. Otherwise, the type of the
398 // rvalue is T.
399 //
400 // C99 6.3.2.1p2:
401 // If the lvalue has qualified type, the value has the unqualified
402 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000403 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000404 if (T.hasQualifiers())
405 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000406
Eli Friedman3bda6b12012-02-02 23:15:15 +0000407 UpdateMarkingForLValueToRValue(E);
408
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000409 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
410 E, 0, VK_RValue));
411
Douglas Gregorc79862f2012-04-12 17:51:55 +0000412 // C11 6.3.2.1p2:
413 // ... if the lvalue has atomic type, the value has the non-atomic version
414 // of the type of the lvalue ...
415 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
416 T = Atomic->getValueType().getUnqualifiedType();
417 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
418 Res.get(), 0, VK_RValue));
419 }
420
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000421 return Res;
John McCall27584242010-12-06 20:48:59 +0000422}
423
John Wiegley01296292011-04-08 18:41:53 +0000424ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
425 ExprResult Res = DefaultFunctionArrayConversion(E);
426 if (Res.isInvalid())
427 return ExprError();
428 Res = DefaultLvalueConversion(Res.take());
429 if (Res.isInvalid())
430 return ExprError();
431 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000432}
433
434
Chris Lattner513165e2008-07-25 21:10:04 +0000435/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000436/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000437/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000438/// apply if the array is an argument to the sizeof or address (&) operators.
439/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000440ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000441 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000442 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
443 if (Res.isInvalid())
444 return Owned(E);
445 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000446
John McCallf3735e02010-12-01 04:43:34 +0000447 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000448 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000449
450 // Half FP is a bit different: it's a storage-only type, meaning that any
451 // "use" of it should be promoted to float.
452 if (Ty->isHalfType())
453 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
454
John McCallf3735e02010-12-01 04:43:34 +0000455 // Try to perform integral promotions if the object has a theoretically
456 // promotable type.
457 if (Ty->isIntegralOrUnscopedEnumerationType()) {
458 // C99 6.3.1.1p2:
459 //
460 // The following may be used in an expression wherever an int or
461 // unsigned int may be used:
462 // - an object or expression with an integer type whose integer
463 // conversion rank is less than or equal to the rank of int
464 // and unsigned int.
465 // - A bit-field of type _Bool, int, signed int, or unsigned int.
466 //
467 // If an int can represent all values of the original type, the
468 // value is converted to an int; otherwise, it is converted to an
469 // unsigned int. These are called the integer promotions. All
470 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000471
John McCallf3735e02010-12-01 04:43:34 +0000472 QualType PTy = Context.isPromotableBitField(E);
473 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000474 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
475 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000476 }
477 if (Ty->isPromotableIntegerType()) {
478 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000479 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
480 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000481 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000482 }
John Wiegley01296292011-04-08 18:41:53 +0000483 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000484}
485
Chris Lattner2ce500f2008-07-25 22:25:12 +0000486/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000487/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000488/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000489ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
490 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000491 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000492
John Wiegley01296292011-04-08 18:41:53 +0000493 ExprResult Res = UsualUnaryConversions(E);
494 if (Res.isInvalid())
495 return Owned(E);
496 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000497
Chris Lattner2ce500f2008-07-25 22:25:12 +0000498 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000499 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000500 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
501
John McCall4bb057d2011-08-27 22:06:17 +0000502 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000503 // promotion, even on class types, but note:
504 // C++11 [conv.lval]p2:
505 // When an lvalue-to-rvalue conversion occurs in an unevaluated
506 // operand or a subexpression thereof the value contained in the
507 // referenced object is not accessed. Otherwise, if the glvalue
508 // has a class type, the conversion copy-initializes a temporary
509 // of type T from the glvalue and the result of the conversion
510 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000511 // FIXME: add some way to gate this entire thing for correctness in
512 // potentially potentially evaluated contexts.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000513 if (getLangOpts().CPlusPlus && E->isGLValue() &&
Eli Friedman05e28012012-01-17 02:13:45 +0000514 ExprEvalContexts.back().Context != Unevaluated) {
515 ExprResult Temp = PerformCopyInitialization(
516 InitializedEntity::InitializeTemporary(E->getType()),
517 E->getExprLoc(),
518 Owned(E));
519 if (Temp.isInvalid())
520 return ExprError();
521 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000522 }
523
John Wiegley01296292011-04-08 18:41:53 +0000524 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000525}
526
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000527/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
528/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000529/// interfaces passed by value.
530ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000531 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000532 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
533 // Strip the unbridged-cast placeholder expression off, if applicable.
534 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
535 (CT == VariadicMethod ||
536 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
537 E = stripARCUnbridgedCast(E);
538
539 // Otherwise, do normal placeholder checking.
540 } else {
541 ExprResult ExprRes = CheckPlaceholderExpr(E);
542 if (ExprRes.isInvalid())
543 return ExprError();
544 E = ExprRes.take();
545 }
546 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000547
John McCall4124c492011-10-17 18:40:02 +0000548 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000549 if (ExprRes.isInvalid())
550 return ExprError();
551 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000552
Douglas Gregor347e0f22011-05-21 19:26:31 +0000553 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000554 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000555 DiagRuntimeBehavior(E->getLocStart(), 0,
556 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
557 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000558 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000559
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000560 // Complain about passing non-POD types through varargs. However, don't
561 // perform this check for incomplete types, which we can get here when we're
562 // in an unevaluated context.
Benjamin Kramer6a0a2112012-04-28 10:00:42 +0000563 if (!E->getType()->isIncompleteType() &&
564 !E->getType().isCXX98PODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000565 // C++0x [expr.call]p7:
566 // Passing a potentially-evaluated argument of class type (Clause 9)
567 // having a non-trivial copy constructor, a non-trivial move constructor,
568 // or a non-trivial destructor, with no corresponding parameter,
569 // is conditionally-supported with implementation-defined semantics.
570 bool TrivialEnough = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000571 if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType()) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000572 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
573 if (Record->hasTrivialCopyConstructor() &&
574 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000575 Record->hasTrivialDestructor()) {
576 DiagRuntimeBehavior(E->getLocStart(), 0,
577 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
578 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000579 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000580 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000581 }
582 }
John McCall31168b02011-06-15 23:02:42 +0000583
584 if (!TrivialEnough &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000585 getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000586 E->getType()->isObjCLifetimeType())
587 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000588
589 if (TrivialEnough) {
590 // Nothing to diagnose. This is okay.
591 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000592 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000593 << getLangOpts().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000594 << CT)) {
595 // Turn this into a trap.
596 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000597 SourceLocation TemplateKWLoc;
Douglas Gregor347e0f22011-05-21 19:26:31 +0000598 UnqualifiedId Name;
599 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
600 E->getLocStart());
Abramo Bagnara7945c982012-01-27 09:46:47 +0000601 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
602 true, false);
Douglas Gregor347e0f22011-05-21 19:26:31 +0000603 if (TrapFn.isInvalid())
604 return ExprError();
605
606 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
607 MultiExprArg(), E->getLocEnd());
608 if (Call.isInvalid())
609 return ExprError();
610
611 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
612 Call.get(), E);
613 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000614 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000615 E = Comma.get();
616 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000617 }
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000618 // c++ rules are enforced elsewhere.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000619 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000620 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000621 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000622 return ExprError();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000623
John Wiegley01296292011-04-08 18:41:53 +0000624 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000625}
626
Richard Trieu7aa58f12011-09-02 20:58:51 +0000627/// \brief Converts an integer to complex float type. Helper function of
628/// UsualArithmeticConversions()
629///
630/// \return false if the integer expression is an integer type and is
631/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000632static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
633 ExprResult &ComplexExpr,
634 QualType IntTy,
635 QualType ComplexTy,
636 bool SkipCast) {
637 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
638 if (SkipCast) return false;
639 if (IntTy->isIntegerType()) {
640 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
641 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
642 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000643 CK_FloatingRealToComplex);
644 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000645 assert(IntTy->isComplexIntegerType());
646 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000647 CK_IntegralComplexToFloatingComplex);
648 }
649 return false;
650}
651
652/// \brief Takes two complex float types and converts them to the same type.
653/// Helper function of UsualArithmeticConversions()
654static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000655handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
656 ExprResult &RHS, QualType LHSType,
657 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000658 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000659 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000660
661 if (order < 0) {
662 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000663 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000664 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
665 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000666 }
667 if (order > 0)
668 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000669 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
670 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000671}
672
673/// \brief Converts otherExpr to complex float and promotes complexExpr if
674/// necessary. Helper function of UsualArithmeticConversions()
675static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000676 ExprResult &ComplexExpr,
677 ExprResult &OtherExpr,
678 QualType ComplexTy,
679 QualType OtherTy,
680 bool ConvertComplexExpr,
681 bool ConvertOtherExpr) {
682 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000683
684 // If just the complexExpr is complex, the otherExpr needs to be converted,
685 // and the complexExpr might need to be promoted.
686 if (order > 0) { // complexExpr is wider
687 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000688 if (ConvertOtherExpr) {
689 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
690 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
691 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692 CK_FloatingRealToComplex);
693 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000694 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000695 }
696
697 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000698 QualType result = (order == 0 ? ComplexTy :
699 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000700
701 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000702 if (ConvertOtherExpr)
703 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000704 CK_FloatingRealToComplex);
705
706 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000707 if (ConvertComplexExpr && order < 0)
708 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000709 CK_FloatingComplexCast);
710
711 return result;
712}
713
714/// \brief Handle arithmetic conversion with complex types. Helper function of
715/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000716static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
717 ExprResult &RHS, QualType LHSType,
718 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000719 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000720 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000721 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000722 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000723 return LHSType;
724 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000725 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000726 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000727
728 // This handles complex/complex, complex/float, or float/complex.
729 // When both operands are complex, the shorter operand is converted to the
730 // type of the longer, and that is the type of the result. This corresponds
731 // to what is done when combining two real floating-point operands.
732 // The fun begins when size promotion occur across type domains.
733 // From H&S 6.3.4: When one operand is complex and the other is a real
734 // floating-point type, the less precise type is converted, within it's
735 // real or complex domain, to the precision of the other type. For example,
736 // when combining a "long double" with a "double _Complex", the
737 // "double _Complex" is promoted to "long double _Complex".
738
Richard Trieu5065cdd2011-09-06 18:25:09 +0000739 bool LHSComplexFloat = LHSType->isComplexType();
740 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000741
742 // If both are complex, just cast to the more precise type.
743 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000744 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
745 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000746 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000747
748 // If only one operand is complex, promote it if necessary and convert the
749 // other operand to complex.
750 if (LHSComplexFloat)
751 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000752 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000753 /*convertOtherExpr*/ true);
754
755 assert(RHSComplexFloat);
756 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000757 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000758 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759}
760
761/// \brief Hande arithmetic conversion from integer to float. Helper function
762/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000763static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
764 ExprResult &IntExpr,
765 QualType FloatTy, QualType IntTy,
766 bool ConvertFloat, bool ConvertInt) {
767 if (IntTy->isIntegerType()) {
768 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000769 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000770 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000772 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000773 }
774
775 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000776 assert(IntTy->isComplexIntegerType());
777 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000778
779 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000780 if (ConvertInt)
781 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000782 CK_IntegralComplexToFloatingComplex);
783
784 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000785 if (ConvertFloat)
786 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000787 CK_FloatingRealToComplex);
788
789 return result;
790}
791
792/// \brief Handle arithmethic conversion with floating point types. Helper
793/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000794static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
795 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000796 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000797 bool LHSFloat = LHSType->isRealFloatingType();
798 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000799
800 // If we have two real floating types, convert the smaller operand
801 // to the bigger result.
802 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000803 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000804 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000805 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
806 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 }
808
809 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000811 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
812 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000813 }
814
815 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000816 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000817 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000818 /*convertInt=*/ true);
819 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000820 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000822 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000823}
824
825/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000826/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000827// FIXME: if the operands are (int, _Complex long), we currently
828// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000829static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
830 ExprResult &RHS, QualType LHSType,
831 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000832 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000833 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
834 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000835
Richard Trieucfe3f212011-09-06 18:38:41 +0000836 if (LHSComplexInt && RHSComplexInt) {
837 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
838 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000839 assert(order && "inequal types with equal element ordering");
840 if (order > 0) {
841 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000842 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
843 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000844 }
845
Richard Trieuba63ce62011-09-09 01:45:06 +0000846 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000847 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
848 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000849 }
850
Richard Trieucfe3f212011-09-06 18:38:41 +0000851 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000852 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000853 // FIXME: This needs to take integer ranks into account
854 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
855 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000856 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
857 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000858 }
859
Richard Trieucfe3f212011-09-06 18:38:41 +0000860 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000861 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000862 // FIXME: This needs to take integer ranks into account
863 if (!IsCompAssign) {
864 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
865 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000866 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000867 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000868 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000869}
870
871/// \brief Handle integer arithmetic conversions. Helper function of
872/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000873static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
874 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000875 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000876 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000877 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
878 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
879 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
880 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000881 // Same signedness; use the higher-ranked type
882 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000883 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
884 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000885 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000886 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
887 return RHSType;
888 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000889 // The unsigned type has greater than or equal rank to the
890 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000891 if (RHSSigned) {
892 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
893 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000894 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000895 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
896 return RHSType;
897 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000898 // The two types are different widths; if we are here, that
899 // means the signed type is larger than the unsigned type, so
900 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000901 if (LHSSigned) {
902 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
903 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000904 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000905 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
906 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000907 } else {
908 // The signed type is higher-ranked than the unsigned type,
909 // but isn't actually any bigger (like unsigned int and long
910 // on most 32-bit systems). Use the unsigned type corresponding
911 // to the signed type.
912 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000913 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
914 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000915 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000916 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000917 return result;
918 }
919}
920
Chris Lattner513165e2008-07-25 21:10:04 +0000921/// UsualArithmeticConversions - Performs various conversions that are common to
922/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000923/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000924/// responsible for emitting appropriate error diagnostics.
925/// FIXME: verify the conversion rules for "complex int" are consistent with
926/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000927QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000928 bool IsCompAssign) {
929 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000930 LHS = UsualUnaryConversions(LHS.take());
931 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000932 return QualType();
933 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000934
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000935 RHS = UsualUnaryConversions(RHS.take());
936 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000937 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000938
Mike Stump11289f42009-09-09 15:08:12 +0000939 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000940 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000941 QualType LHSType =
942 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
943 QualType RHSType =
944 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000945
946 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000947 if (LHSType == RHSType)
948 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000949
950 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
951 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000952 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
953 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000954
John McCalld005ac92010-11-13 08:17:45 +0000955 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000956 QualType LHSUnpromotedType = LHSType;
957 if (LHSType->isPromotableIntegerType())
958 LHSType = Context.getPromotedIntegerType(LHSType);
959 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000960 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000961 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000962 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000963 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000964
John McCalld005ac92010-11-13 08:17:45 +0000965 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000966 if (LHSType == RHSType)
967 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000968
969 // At this point, we have two different arithmetic types.
970
971 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000972 if (LHSType->isComplexType() || RHSType->isComplexType())
973 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000974 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000975
976 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000977 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
978 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000979 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000980
981 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000982 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000983 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000984 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000985
986 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000987 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000988 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000989}
990
Chris Lattner513165e2008-07-25 21:10:04 +0000991//===----------------------------------------------------------------------===//
992// Semantic Analysis for various Expression Types
993//===----------------------------------------------------------------------===//
994
995
Peter Collingbourne91147592011-04-15 00:35:48 +0000996ExprResult
997Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
998 SourceLocation DefaultLoc,
999 SourceLocation RParenLoc,
1000 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001001 MultiTypeArg ArgTypes,
1002 MultiExprArg ArgExprs) {
1003 unsigned NumAssocs = ArgTypes.size();
1004 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001005
Richard Trieuba63ce62011-09-09 01:45:06 +00001006 ParsedType *ParsedTypes = ArgTypes.release();
1007 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +00001008
1009 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1010 for (unsigned i = 0; i < NumAssocs; ++i) {
1011 if (ParsedTypes[i])
1012 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1013 else
1014 Types[i] = 0;
1015 }
1016
1017 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1018 ControllingExpr, Types, Exprs,
1019 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001020 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001021 return ER;
1022}
1023
1024ExprResult
1025Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1026 SourceLocation DefaultLoc,
1027 SourceLocation RParenLoc,
1028 Expr *ControllingExpr,
1029 TypeSourceInfo **Types,
1030 Expr **Exprs,
1031 unsigned NumAssocs) {
1032 bool TypeErrorFound = false,
1033 IsResultDependent = ControllingExpr->isTypeDependent(),
1034 ContainsUnexpandedParameterPack
1035 = ControllingExpr->containsUnexpandedParameterPack();
1036
1037 for (unsigned i = 0; i < NumAssocs; ++i) {
1038 if (Exprs[i]->containsUnexpandedParameterPack())
1039 ContainsUnexpandedParameterPack = true;
1040
1041 if (Types[i]) {
1042 if (Types[i]->getType()->containsUnexpandedParameterPack())
1043 ContainsUnexpandedParameterPack = true;
1044
1045 if (Types[i]->getType()->isDependentType()) {
1046 IsResultDependent = true;
1047 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001048 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001049 // complete object type other than a variably modified type."
1050 unsigned D = 0;
1051 if (Types[i]->getType()->isIncompleteType())
1052 D = diag::err_assoc_type_incomplete;
1053 else if (!Types[i]->getType()->isObjectType())
1054 D = diag::err_assoc_type_nonobject;
1055 else if (Types[i]->getType()->isVariablyModifiedType())
1056 D = diag::err_assoc_type_variably_modified;
1057
1058 if (D != 0) {
1059 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1060 << Types[i]->getTypeLoc().getSourceRange()
1061 << Types[i]->getType();
1062 TypeErrorFound = true;
1063 }
1064
Benjamin Kramere56f3932011-12-23 17:00:35 +00001065 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001066 // selection shall specify compatible types."
1067 for (unsigned j = i+1; j < NumAssocs; ++j)
1068 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1069 Context.typesAreCompatible(Types[i]->getType(),
1070 Types[j]->getType())) {
1071 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1072 diag::err_assoc_compatible_types)
1073 << Types[j]->getTypeLoc().getSourceRange()
1074 << Types[j]->getType()
1075 << Types[i]->getType();
1076 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1077 diag::note_compat_assoc)
1078 << Types[i]->getTypeLoc().getSourceRange()
1079 << Types[i]->getType();
1080 TypeErrorFound = true;
1081 }
1082 }
1083 }
1084 }
1085 if (TypeErrorFound)
1086 return ExprError();
1087
1088 // If we determined that the generic selection is result-dependent, don't
1089 // try to compute the result expression.
1090 if (IsResultDependent)
1091 return Owned(new (Context) GenericSelectionExpr(
1092 Context, KeyLoc, ControllingExpr,
1093 Types, Exprs, NumAssocs, DefaultLoc,
1094 RParenLoc, ContainsUnexpandedParameterPack));
1095
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001096 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001097 unsigned DefaultIndex = -1U;
1098 for (unsigned i = 0; i < NumAssocs; ++i) {
1099 if (!Types[i])
1100 DefaultIndex = i;
1101 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1102 Types[i]->getType()))
1103 CompatIndices.push_back(i);
1104 }
1105
Benjamin Kramere56f3932011-12-23 17:00:35 +00001106 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001107 // type compatible with at most one of the types named in its generic
1108 // association list."
1109 if (CompatIndices.size() > 1) {
1110 // We strip parens here because the controlling expression is typically
1111 // parenthesized in macro definitions.
1112 ControllingExpr = ControllingExpr->IgnoreParens();
1113 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1114 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1115 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001116 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001117 E = CompatIndices.end(); I != E; ++I) {
1118 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1119 diag::note_compat_assoc)
1120 << Types[*I]->getTypeLoc().getSourceRange()
1121 << Types[*I]->getType();
1122 }
1123 return ExprError();
1124 }
1125
Benjamin Kramere56f3932011-12-23 17:00:35 +00001126 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001127 // its controlling expression shall have type compatible with exactly one of
1128 // the types named in its generic association list."
1129 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1130 // We strip parens here because the controlling expression is typically
1131 // parenthesized in macro definitions.
1132 ControllingExpr = ControllingExpr->IgnoreParens();
1133 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1134 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1135 return ExprError();
1136 }
1137
Benjamin Kramere56f3932011-12-23 17:00:35 +00001138 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001139 // type name that is compatible with the type of the controlling expression,
1140 // then the result expression of the generic selection is the expression
1141 // in that generic association. Otherwise, the result expression of the
1142 // generic selection is the expression in the default generic association."
1143 unsigned ResultIndex =
1144 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1145
1146 return Owned(new (Context) GenericSelectionExpr(
1147 Context, KeyLoc, ControllingExpr,
1148 Types, Exprs, NumAssocs, DefaultLoc,
1149 RParenLoc, ContainsUnexpandedParameterPack,
1150 ResultIndex));
1151}
1152
Richard Smith75b67d62012-03-08 01:34:56 +00001153/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1154/// location of the token and the offset of the ud-suffix within it.
1155static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1156 unsigned Offset) {
1157 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001158 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001159}
1160
Richard Smithbcc22fc2012-03-09 08:00:36 +00001161/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1162/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1163static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1164 IdentifierInfo *UDSuffix,
1165 SourceLocation UDSuffixLoc,
1166 ArrayRef<Expr*> Args,
1167 SourceLocation LitEndLoc) {
1168 assert(Args.size() <= 2 && "too many arguments for literal operator");
1169
1170 QualType ArgTy[2];
1171 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1172 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1173 if (ArgTy[ArgIdx]->isArrayType())
1174 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1175 }
1176
1177 DeclarationName OpName =
1178 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1179 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1180 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1181
1182 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1183 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1184 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1185 return ExprError();
1186
1187 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1188}
1189
Steve Naroff83895f72007-09-16 03:34:24 +00001190/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001191/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1192/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1193/// multiple tokens. However, the common case is that StringToks points to one
1194/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001195///
John McCalldadc5752010-08-24 06:29:42 +00001196ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001197Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1198 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001199 assert(NumStringToks && "Must have at least one string!");
1200
Chris Lattner8a24e582009-01-16 18:51:42 +00001201 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001202 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001203 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001204
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001205 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001206 for (unsigned i = 0; i != NumStringToks; ++i)
1207 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001208
Chris Lattner36fc8792008-02-11 00:02:17 +00001209 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001210 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001211 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001212 else if (Literal.isUTF16())
1213 StrTy = Context.Char16Ty;
1214 else if (Literal.isUTF32())
1215 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001216 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001217 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001218
Douglas Gregorfb65e592011-07-27 05:40:30 +00001219 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1220 if (Literal.isWide())
1221 Kind = StringLiteral::Wide;
1222 else if (Literal.isUTF8())
1223 Kind = StringLiteral::UTF8;
1224 else if (Literal.isUTF16())
1225 Kind = StringLiteral::UTF16;
1226 else if (Literal.isUTF32())
1227 Kind = StringLiteral::UTF32;
1228
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001229 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001230 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001231 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001232
Chris Lattner36fc8792008-02-11 00:02:17 +00001233 // Get an array type for the string, according to C99 6.4.5. This includes
1234 // the nul terminator character as well as the string length for pascal
1235 // strings.
1236 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001237 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001238 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001239
Chris Lattner5b183d82006-11-10 05:03:26 +00001240 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001241 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1242 Kind, Literal.Pascal, StrTy,
1243 &StringTokLocs[0],
1244 StringTokLocs.size());
1245 if (Literal.getUDSuffix().empty())
1246 return Owned(Lit);
1247
1248 // We're building a user-defined literal.
1249 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001250 SourceLocation UDSuffixLoc =
1251 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1252 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001253
Richard Smithbcc22fc2012-03-09 08:00:36 +00001254 // Make sure we're allowed user-defined literals here.
1255 if (!UDLScope)
1256 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1257
Richard Smithc67fdd42012-03-07 08:35:16 +00001258 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1259 // operator "" X (str, len)
1260 QualType SizeType = Context.getSizeType();
1261 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1262 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1263 StringTokLocs[0]);
1264 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001265 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1266 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001267}
1268
John McCalldadc5752010-08-24 06:29:42 +00001269ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001270Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001271 SourceLocation Loc,
1272 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001273 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001274 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001275}
1276
John McCallf4cd4f92011-02-09 01:13:10 +00001277/// BuildDeclRefExpr - Build an expression that references a
1278/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001279ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001280Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001281 const DeclarationNameInfo &NameInfo,
1282 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001283 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001284 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1285 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1286 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1287 CalleeTarget = IdentifyCUDATarget(Callee);
1288 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1289 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1290 << CalleeTarget << D->getIdentifier() << CallerTarget;
1291 Diag(D->getLocation(), diag::note_previous_decl)
1292 << D->getIdentifier();
1293 return ExprError();
1294 }
1295 }
1296
John McCall113bee02012-03-10 09:33:50 +00001297 bool refersToEnclosingScope =
1298 (CurContext != D->getDeclContext() &&
1299 D->getDeclContext()->isFunctionOrMethod());
1300
Eli Friedmanfa0df832012-02-02 03:46:19 +00001301 DeclRefExpr *E = DeclRefExpr::Create(Context,
1302 SS ? SS->getWithLocInContext(Context)
1303 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001304 SourceLocation(),
1305 D, refersToEnclosingScope,
1306 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001307
Eli Friedmanfa0df832012-02-02 03:46:19 +00001308 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001309
1310 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001311 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1312 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001313 E->setObjectKind(OK_BitField);
1314
1315 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001316}
1317
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001318/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001319/// possibly a list of template arguments.
1320///
1321/// If this produces template arguments, it is permitted to call
1322/// DecomposeTemplateName.
1323///
1324/// This actually loses a lot of source location information for
1325/// non-standard name kinds; we should consider preserving that in
1326/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001327void
1328Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1329 TemplateArgumentListInfo &Buffer,
1330 DeclarationNameInfo &NameInfo,
1331 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001332 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1333 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1334 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1335
Douglas Gregor5476205b2011-06-23 00:49:38 +00001336 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001337 Id.TemplateId->getTemplateArgs(),
1338 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001339 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001340 TemplateArgsPtr.release();
1341
John McCall3e56fd42010-08-23 07:28:44 +00001342 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001343 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001344 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001345 TemplateArgs = &Buffer;
1346 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001347 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001348 TemplateArgs = 0;
1349 }
1350}
1351
John McCalld681c392009-12-16 08:11:27 +00001352/// Diagnose an empty lookup.
1353///
1354/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001355bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001356 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001357 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001358 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001359 DeclarationName Name = R.getLookupName();
1360
John McCalld681c392009-12-16 08:11:27 +00001361 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001362 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001363 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1364 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001365 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001366 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001367 diagnostic_suggest = diag::err_undeclared_use_suggest;
1368 }
John McCalld681c392009-12-16 08:11:27 +00001369
Douglas Gregor598b08f2009-12-31 05:20:13 +00001370 // If the original lookup was an unqualified lookup, fake an
1371 // unqualified lookup. This is useful when (for example) the
1372 // original lookup would not have found something because it was a
1373 // dependent name.
Francois Pichetde232cb2011-11-25 01:10:54 +00001374 DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1375 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001376 if (isa<CXXRecordDecl>(DC)) {
1377 LookupQualifiedName(R, DC);
1378
1379 if (!R.empty()) {
1380 // Don't give errors about ambiguities in this lookup.
1381 R.suppressDiagnostics();
1382
Francois Pichet857f9d62011-11-17 03:44:24 +00001383 // During a default argument instantiation the CurContext points
1384 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1385 // function parameter list, hence add an explicit check.
1386 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1387 ActiveTemplateInstantiations.back().Kind ==
1388 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001389 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1390 bool isInstance = CurMethod &&
1391 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001392 DC == CurMethod->getParent() && !isDefaultArgument;
1393
John McCalld681c392009-12-16 08:11:27 +00001394
1395 // Give a code modification hint to insert 'this->'.
1396 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1397 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001398 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001399 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1400 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001401 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001402 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001403 if (DepMethod) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001404 if (getLangOpts().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001405 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001406 Diag(R.getNameLoc(), diagnostic) << Name
1407 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1408 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001409 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001410 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1411 R.getNameLoc(), DepThisType, false);
1412 TemplateArgumentListInfo TList;
1413 if (ULE->hasExplicitTemplateArgs())
1414 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001415
Douglas Gregore16af532011-02-28 18:50:33 +00001416 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001417 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001418 CXXDependentScopeMemberExpr *DepExpr =
1419 CXXDependentScopeMemberExpr::Create(
1420 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001421 SS.getWithLocInContext(Context),
1422 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001423 R.getLookupNameInfo(),
1424 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001425 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001426 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001427 // FIXME: we should be able to handle this case too. It is correct
1428 // to add this-> here. This is a workaround for PR7947.
1429 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001430 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001431 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001432 if (getLangOpts().MicrosoftMode)
Francois Pichet78286b22011-11-15 23:33:34 +00001433 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001434 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001435 }
John McCalld681c392009-12-16 08:11:27 +00001436
1437 // Do we really want to note all of these?
1438 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1439 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1440
Francois Pichet857f9d62011-11-17 03:44:24 +00001441 // Return true if we are inside a default argument instantiation
1442 // and the found name refers to an instance member function, otherwise
1443 // the function calling DiagnoseEmptyLookup will try to create an
1444 // implicit member call and this is wrong for default argument.
1445 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1446 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1447 return true;
1448 }
1449
John McCalld681c392009-12-16 08:11:27 +00001450 // Tell the callee to try to recover.
1451 return false;
1452 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001453
1454 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001455 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001456
1457 // In Microsoft mode, if we are performing lookup from within a friend
1458 // function definition declared at class scope then we must set
1459 // DC to the lexical parent to be able to search into the parent
1460 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001461 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001462 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1463 DC->getLexicalParent()->isRecord())
1464 DC = DC->getLexicalParent();
1465 else
1466 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001467 }
1468
Douglas Gregor598b08f2009-12-31 05:20:13 +00001469 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001470 TypoCorrection Corrected;
1471 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001472 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001473 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1474 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001475 R.setLookupName(Corrected.getCorrection());
1476
Hans Wennborg38198de2011-07-12 08:45:31 +00001477 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001478 if (Corrected.isOverloaded()) {
1479 OverloadCandidateSet OCS(R.getNameLoc());
1480 OverloadCandidateSet::iterator Best;
1481 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1482 CDEnd = Corrected.end();
1483 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001484 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001485 dyn_cast<FunctionTemplateDecl>(*CD))
1486 AddTemplateOverloadCandidate(
1487 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001488 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001489 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1490 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1491 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001492 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001493 }
1494 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1495 case OR_Success:
1496 ND = Best->Function;
1497 break;
1498 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001499 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001500 }
1501 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001502 R.addDecl(ND);
1503 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001504 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001505 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1506 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001507 else
1508 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001509 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001510 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001511 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1512 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001513 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001514 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001515
1516 // Tell the callee to try to recover.
1517 return false;
1518 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001519
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001520 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001521 // FIXME: If we ended up with a typo for a type name or
1522 // Objective-C class name, we're in trouble because the parser
1523 // is in the wrong place to recover. Suggest the typo
1524 // correction, but don't make it a fix-it since we're not going
1525 // to recover well anyway.
1526 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001527 Diag(R.getNameLoc(), diagnostic_suggest)
1528 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001529 else
1530 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001531 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001532 << SS.getRange();
1533
1534 // Don't try to recover; it won't work.
1535 return true;
1536 }
1537 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001538 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001539 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001540 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001541 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001542 else
Douglas Gregor25363982010-01-01 00:15:04 +00001543 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001544 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001545 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001546 return true;
1547 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001548 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001549 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001550
1551 // Emit a special diagnostic for failed member lookups.
1552 // FIXME: computing the declaration context might fail here (?)
1553 if (!SS.isEmpty()) {
1554 Diag(R.getNameLoc(), diag::err_no_member)
1555 << Name << computeDeclContext(SS, false)
1556 << SS.getRange();
1557 return true;
1558 }
1559
John McCalld681c392009-12-16 08:11:27 +00001560 // Give up, we can't recover.
1561 Diag(R.getNameLoc(), diagnostic) << Name;
1562 return true;
1563}
1564
John McCalldadc5752010-08-24 06:29:42 +00001565ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001566 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001567 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001568 UnqualifiedId &Id,
1569 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001570 bool IsAddressOfOperand,
1571 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001572 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001573 "cannot be direct & operand and have a trailing lparen");
1574
1575 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001576 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001577
John McCall10eae182009-11-30 22:42:35 +00001578 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001579
1580 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001581 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001582 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001583 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001584
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001585 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001586 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001587 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001588
John McCalle66edc12009-11-24 19:00:30 +00001589 // C++ [temp.dep.expr]p3:
1590 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001591 // -- an identifier that was declared with a dependent type,
1592 // (note: handled after lookup)
1593 // -- a template-id that is dependent,
1594 // (note: handled in BuildTemplateIdExpr)
1595 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001596 // -- a nested-name-specifier that contains a class-name that
1597 // names a dependent type.
1598 // Determine whether this is a member of an unknown specialization;
1599 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001600 bool DependentID = false;
1601 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1602 Name.getCXXNameType()->isDependentType()) {
1603 DependentID = true;
1604 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001605 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001606 if (RequireCompleteDeclContext(SS, DC))
1607 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001608 } else {
1609 DependentID = true;
1610 }
1611 }
1612
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001613 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001614 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1615 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001616
John McCalle66edc12009-11-24 19:00:30 +00001617 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001618 LookupResult R(*this, NameInfo,
1619 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1620 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001621 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001622 // Lookup the template name again to correctly establish the context in
1623 // which it was found. This is really unfortunate as we already did the
1624 // lookup to determine that it was a template name in the first place. If
1625 // this becomes a performance hit, we can work harder to preserve those
1626 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001627 bool MemberOfUnknownSpecialization;
1628 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1629 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001630
1631 if (MemberOfUnknownSpecialization ||
1632 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001633 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1634 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001635 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001636 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001637 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001638
Douglas Gregora5226932011-02-04 13:35:07 +00001639 // If the result might be in a dependent base class, this is a dependent
1640 // id-expression.
1641 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001642 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1643 IsAddressOfOperand, TemplateArgs);
1644
John McCalle66edc12009-11-24 19:00:30 +00001645 // If this reference is in an Objective-C method, then we need to do
1646 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001647 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001648 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001649 if (E.isInvalid())
1650 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001651
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001652 if (Expr *Ex = E.takeAs<Expr>())
1653 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001654 }
Chris Lattner59a25942008-03-31 00:36:02 +00001655 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001656
John McCalle66edc12009-11-24 19:00:30 +00001657 if (R.isAmbiguous())
1658 return ExprError();
1659
Douglas Gregor171c45a2009-02-18 21:56:37 +00001660 // Determine whether this name might be a candidate for
1661 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001662 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001663
John McCalle66edc12009-11-24 19:00:30 +00001664 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001665 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001666 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001667 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001668 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1669 if (D) R.addDecl(D);
1670 }
1671
1672 // If this name wasn't predeclared and if this is not a function
1673 // call, diagnose the problem.
1674 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001675
1676 // In Microsoft mode, if we are inside a template class member function
1677 // and we can't resolve an identifier then assume the identifier is type
1678 // dependent. The goal is to postpone name lookup to instantiation time
1679 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001680 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001681 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001682 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1683 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001684
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001685 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001686 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001687 return ExprError();
1688
1689 assert(!R.empty() &&
1690 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001691
1692 // If we found an Objective-C instance variable, let
1693 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001694 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001695 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1696 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001697 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001698 // In a hopelessly buggy code, Objective-C instance variable
1699 // lookup fails and no expression will be built to reference it.
1700 if (!E.isInvalid() && !E.get())
1701 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001702 return move(E);
1703 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001704 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCalle66edc12009-11-24 19:00:30 +00001707 // This is guaranteed from this point on.
1708 assert(!R.empty() || ADL);
1709
John McCall2d74de92009-12-01 22:10:20 +00001710 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001711 // C++ [class.mfct.non-static]p3:
1712 // When an id-expression that is not part of a class member access
1713 // syntax and not used to form a pointer to member is used in the
1714 // body of a non-static member function of class X, if name lookup
1715 // resolves the name in the id-expression to a non-static non-type
1716 // member of some class C, the id-expression is transformed into a
1717 // class member access expression using (*this) as the
1718 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001719 //
1720 // But we don't actually need to do this for '&' operands if R
1721 // resolved to a function or overloaded function set, because the
1722 // expression is ill-formed if it actually works out to be a
1723 // non-static member function:
1724 //
1725 // C++ [expr.ref]p4:
1726 // Otherwise, if E1.E2 refers to a non-static member function. . .
1727 // [t]he expression can be used only as the left-hand operand of a
1728 // member function call.
1729 //
1730 // There are other safeguards against such uses, but it's important
1731 // to get this right here so that we don't end up making a
1732 // spuriously dependent expression if we're inside a dependent
1733 // instance method.
John McCall57500772009-12-16 12:17:52 +00001734 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001735 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001736 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001737 MightBeImplicitMember = true;
1738 else if (!SS.isEmpty())
1739 MightBeImplicitMember = false;
1740 else if (R.isOverloadedResult())
1741 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001742 else if (R.isUnresolvableResult())
1743 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001744 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001745 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1746 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001747
1748 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001749 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1750 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001751 }
1752
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001753 if (TemplateArgs || TemplateKWLoc.isValid())
1754 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001755
John McCalle66edc12009-11-24 19:00:30 +00001756 return BuildDeclarationNameExpr(SS, R, ADL);
1757}
1758
John McCall10eae182009-11-30 22:42:35 +00001759/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1760/// declaration name, generally during template instantiation.
1761/// There's a large number of things which don't need to be done along
1762/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001763ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001764Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001765 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001766 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001767 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001768 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1769 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001770
John McCall0b66eb32010-05-01 00:40:08 +00001771 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001772 return ExprError();
1773
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001774 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001775 LookupQualifiedName(R, DC);
1776
1777 if (R.isAmbiguous())
1778 return ExprError();
1779
1780 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001781 Diag(NameInfo.getLoc(), diag::err_no_member)
1782 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001783 return ExprError();
1784 }
1785
1786 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1787}
1788
1789/// LookupInObjCMethod - The parser has read a name in, and Sema has
1790/// detected that we're currently inside an ObjC method. Perform some
1791/// additional lookup.
1792///
1793/// Ideally, most of this would be done by lookup, but there's
1794/// actually quite a lot of extra work involved.
1795///
1796/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001797ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001798Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001799 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001800 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001801 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001802
John McCalle66edc12009-11-24 19:00:30 +00001803 // There are two cases to handle here. 1) scoped lookup could have failed,
1804 // in which case we should look for an ivar. 2) scoped lookup could have
1805 // found a decl, but that decl is outside the current instance method (i.e.
1806 // a global variable). In these two cases, we do a lookup for an ivar with
1807 // this name, if the lookup sucedes, we replace it our current decl.
1808
1809 // If we're in a class method, we don't normally want to look for
1810 // ivars. But if we don't find anything else, and there's an
1811 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001812 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001813
1814 bool LookForIvars;
1815 if (Lookup.empty())
1816 LookForIvars = true;
1817 else if (IsClassMethod)
1818 LookForIvars = false;
1819 else
1820 LookForIvars = (Lookup.isSingleResult() &&
1821 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001822 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001823 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001824 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001825 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001826 ObjCIvarDecl *IV = 0;
1827 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001828 // Diagnose using an ivar in a class method.
1829 if (IsClassMethod)
1830 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1831 << IV->getDeclName());
1832
1833 // If we're referencing an invalid decl, just return this as a silent
1834 // error node. The error diagnostic was already emitted on the decl.
1835 if (IV->isInvalidDecl())
1836 return ExprError();
1837
1838 // Check if referencing a field with __attribute__((deprecated)).
1839 if (DiagnoseUseOfDecl(IV, Loc))
1840 return ExprError();
1841
1842 // Diagnose the use of an ivar outside of the declaring class.
1843 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001844 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001845 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001846 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1847
1848 // FIXME: This should use a new expr for a direct reference, don't
1849 // turn this into Self->ivar, just return a BareIVarExpr or something.
1850 IdentifierInfo &II = Context.Idents.get("self");
1851 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001852 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001853 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001854 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001855 SourceLocation TemplateKWLoc;
1856 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001857 SelfName, false, false);
1858 if (SelfExpr.isInvalid())
1859 return ExprError();
1860
John Wiegley01296292011-04-08 18:41:53 +00001861 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1862 if (SelfExpr.isInvalid())
1863 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001864
Eli Friedmanfa0df832012-02-02 03:46:19 +00001865 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001866 return Owned(new (Context)
1867 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001868 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001869 }
Chris Lattner87313662010-04-12 05:10:17 +00001870 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001871 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001872 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1873 ObjCInterfaceDecl *ClassDeclared;
1874 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1875 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001876 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001877 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1878 }
John McCalle66edc12009-11-24 19:00:30 +00001879 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001880 } else if (Lookup.isSingleResult() &&
1881 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1882 // If accessing a stand-alone ivar in a class method, this is an error.
1883 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1884 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1885 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001886 }
1887
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001888 if (Lookup.empty() && II && AllowBuiltinCreation) {
1889 // FIXME. Consolidate this with similar code in LookupName.
1890 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001891 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001892 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1893 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1894 S, Lookup.isForRedeclaration(),
1895 Lookup.getNameLoc());
1896 if (D) Lookup.addDecl(D);
1897 }
1898 }
1899 }
John McCalle66edc12009-11-24 19:00:30 +00001900 // Sentinel value saying that we didn't do anything special.
1901 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001902}
John McCalld14a8642009-11-21 08:51:07 +00001903
John McCall16df1e52010-03-30 21:47:33 +00001904/// \brief Cast a base object to a member's actual type.
1905///
1906/// Logically this happens in three phases:
1907///
1908/// * First we cast from the base type to the naming class.
1909/// The naming class is the class into which we were looking
1910/// when we found the member; it's the qualifier type if a
1911/// qualifier was provided, and otherwise it's the base type.
1912///
1913/// * Next we cast from the naming class to the declaring class.
1914/// If the member we found was brought into a class's scope by
1915/// a using declaration, this is that class; otherwise it's
1916/// the class declaring the member.
1917///
1918/// * Finally we cast from the declaring class to the "true"
1919/// declaring class of the member. This conversion does not
1920/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001921ExprResult
1922Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001923 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001924 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001925 NamedDecl *Member) {
1926 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1927 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001928 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001929
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001930 QualType DestRecordType;
1931 QualType DestType;
1932 QualType FromRecordType;
1933 QualType FromType = From->getType();
1934 bool PointerConversions = false;
1935 if (isa<FieldDecl>(Member)) {
1936 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001937
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001938 if (FromType->getAs<PointerType>()) {
1939 DestType = Context.getPointerType(DestRecordType);
1940 FromRecordType = FromType->getPointeeType();
1941 PointerConversions = true;
1942 } else {
1943 DestType = DestRecordType;
1944 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001945 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001946 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1947 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001948 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001949
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001950 DestType = Method->getThisType(Context);
1951 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001952
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001953 if (FromType->getAs<PointerType>()) {
1954 FromRecordType = FromType->getPointeeType();
1955 PointerConversions = true;
1956 } else {
1957 FromRecordType = FromType;
1958 DestType = DestRecordType;
1959 }
1960 } else {
1961 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001962 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001963 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001964
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001965 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001966 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001967
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 // If the unqualified types are the same, no conversion is necessary.
1969 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001970 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001971
John McCall16df1e52010-03-30 21:47:33 +00001972 SourceRange FromRange = From->getSourceRange();
1973 SourceLocation FromLoc = FromRange.getBegin();
1974
Eli Friedmanbe4b3632011-09-27 21:58:52 +00001975 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001976
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001977 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001978 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001979 // class name.
1980 //
1981 // If the member was a qualified name and the qualified referred to a
1982 // specific base subobject type, we'll cast to that intermediate type
1983 // first and then to the object in which the member is declared. That allows
1984 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1985 //
1986 // class Base { public: int x; };
1987 // class Derived1 : public Base { };
1988 // class Derived2 : public Base { };
1989 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1990 //
1991 // void VeryDerived::f() {
1992 // x = 17; // error: ambiguous base subobjects
1993 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1994 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001995 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001996 QualType QType = QualType(Qualifier->getAsType(), 0);
1997 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1998 assert(QType->isRecordType() && "lookup done with non-record type");
1999
2000 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2001
2002 // In C++98, the qualifier type doesn't actually have to be a base
2003 // type of the object type, in which case we just ignore it.
2004 // Otherwise build the appropriate casts.
2005 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002006 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002007 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002008 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002009 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002010
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002011 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002012 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002013 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2014 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002015
2016 FromType = QType;
2017 FromRecordType = QRecordType;
2018
2019 // If the qualifier type was the same as the destination type,
2020 // we're done.
2021 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002022 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002023 }
2024 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002025
John McCall16df1e52010-03-30 21:47:33 +00002026 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002027
John McCall16df1e52010-03-30 21:47:33 +00002028 // If we actually found the member through a using declaration, cast
2029 // down to the using declaration's type.
2030 //
2031 // Pointer equality is fine here because only one declaration of a
2032 // class ever has member declarations.
2033 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2034 assert(isa<UsingShadowDecl>(FoundDecl));
2035 QualType URecordType = Context.getTypeDeclType(
2036 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2037
2038 // We only need to do this if the naming-class to declaring-class
2039 // conversion is non-trivial.
2040 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2041 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002042 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002043 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002044 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002045 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002046
John McCall16df1e52010-03-30 21:47:33 +00002047 QualType UType = URecordType;
2048 if (PointerConversions)
2049 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002050 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2051 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002052 FromType = UType;
2053 FromRecordType = URecordType;
2054 }
2055
2056 // We don't do access control for the conversion from the
2057 // declaring class to the true declaring class.
2058 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002059 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002060
John McCallcf142162010-08-07 06:22:56 +00002061 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002062 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2063 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002064 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002065 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002066
John Wiegley01296292011-04-08 18:41:53 +00002067 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2068 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002069}
Douglas Gregor3256d042009-06-30 15:47:41 +00002070
John McCalle66edc12009-11-24 19:00:30 +00002071bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002072 const LookupResult &R,
2073 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002074 // Only when used directly as the postfix-expression of a call.
2075 if (!HasTrailingLParen)
2076 return false;
2077
2078 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002079 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002080 return false;
2081
2082 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002083 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002084 return false;
2085
2086 // Turn off ADL when we find certain kinds of declarations during
2087 // normal lookup:
2088 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2089 NamedDecl *D = *I;
2090
2091 // C++0x [basic.lookup.argdep]p3:
2092 // -- a declaration of a class member
2093 // Since using decls preserve this property, we check this on the
2094 // original decl.
John McCall57500772009-12-16 12:17:52 +00002095 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002096 return false;
2097
2098 // C++0x [basic.lookup.argdep]p3:
2099 // -- a block-scope function declaration that is not a
2100 // using-declaration
2101 // NOTE: we also trigger this for function templates (in fact, we
2102 // don't check the decl type at all, since all other decl types
2103 // turn off ADL anyway).
2104 if (isa<UsingShadowDecl>(D))
2105 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2106 else if (D->getDeclContext()->isFunctionOrMethod())
2107 return false;
2108
2109 // C++0x [basic.lookup.argdep]p3:
2110 // -- a declaration that is neither a function or a function
2111 // template
2112 // And also for builtin functions.
2113 if (isa<FunctionDecl>(D)) {
2114 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2115
2116 // But also builtin functions.
2117 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2118 return false;
2119 } else if (!isa<FunctionTemplateDecl>(D))
2120 return false;
2121 }
2122
2123 return true;
2124}
2125
2126
John McCalld14a8642009-11-21 08:51:07 +00002127/// Diagnoses obvious problems with the use of the given declaration
2128/// as an expression. This is only actually called for lookups that
2129/// were not overloaded, and it doesn't promise that the declaration
2130/// will in fact be used.
2131static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002132 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002133 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2134 return true;
2135 }
2136
2137 if (isa<ObjCInterfaceDecl>(D)) {
2138 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2139 return true;
2140 }
2141
2142 if (isa<NamespaceDecl>(D)) {
2143 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2144 return true;
2145 }
2146
2147 return false;
2148}
2149
John McCalldadc5752010-08-24 06:29:42 +00002150ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002151Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002152 LookupResult &R,
2153 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002154 // If this is a single, fully-resolved result and we don't need ADL,
2155 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002156 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002157 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2158 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002159
2160 // We only need to check the declaration if there's exactly one
2161 // result, because in the overloaded case the results can only be
2162 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002163 if (R.isSingleResult() &&
2164 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002165 return ExprError();
2166
John McCall58cc69d2010-01-27 01:50:18 +00002167 // Otherwise, just build an unresolved lookup expression. Suppress
2168 // any lookup-related diagnostics; we'll hash these out later, when
2169 // we've picked a target.
2170 R.suppressDiagnostics();
2171
John McCalld14a8642009-11-21 08:51:07 +00002172 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002173 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002174 SS.getWithLocInContext(Context),
2175 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002176 NeedsADL, R.isOverloadedResult(),
2177 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002178
2179 return Owned(ULE);
2180}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002181
John McCalld14a8642009-11-21 08:51:07 +00002182/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002183ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002184Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002185 const DeclarationNameInfo &NameInfo,
2186 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002187 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002188 assert(!isa<FunctionTemplateDecl>(D) &&
2189 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002190
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002191 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002192 if (CheckDeclInExpr(*this, Loc, D))
2193 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002194
Douglas Gregore7488b92009-12-01 16:58:18 +00002195 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2196 // Specifically diagnose references to class templates that are missing
2197 // a template argument list.
2198 Diag(Loc, diag::err_template_decl_ref)
2199 << Template << SS.getRange();
2200 Diag(Template->getLocation(), diag::note_template_decl_here);
2201 return ExprError();
2202 }
2203
2204 // Make sure that we're referring to a value.
2205 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2206 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002207 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002208 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002209 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002210 return ExprError();
2211 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002212
Douglas Gregor171c45a2009-02-18 21:56:37 +00002213 // Check whether this declaration can be used. Note that we suppress
2214 // this check when we're going to perform argument-dependent lookup
2215 // on this function name, because this might not be the function
2216 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002217 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002218 return ExprError();
2219
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002220 // Only create DeclRefExpr's for valid Decl's.
2221 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002222 return ExprError();
2223
John McCallf3a88602011-02-03 08:15:49 +00002224 // Handle members of anonymous structs and unions. If we got here,
2225 // and the reference is to a class member indirect field, then this
2226 // must be the subject of a pointer-to-member expression.
2227 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2228 if (!indirectField->isCXXClassMember())
2229 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2230 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002231
Eli Friedman9bb33f52012-02-03 02:04:35 +00002232 {
John McCallf4cd4f92011-02-09 01:13:10 +00002233 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002234 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002235
2236 switch (D->getKind()) {
2237 // Ignore all the non-ValueDecl kinds.
2238#define ABSTRACT_DECL(kind)
2239#define VALUE(type, base)
2240#define DECL(type, base) \
2241 case Decl::type:
2242#include "clang/AST/DeclNodes.inc"
2243 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002244
2245 // These shouldn't make it here.
2246 case Decl::ObjCAtDefsField:
2247 case Decl::ObjCIvar:
2248 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002249
2250 // Enum constants are always r-values and never references.
2251 // Unresolved using declarations are dependent.
2252 case Decl::EnumConstant:
2253 case Decl::UnresolvedUsingValue:
2254 valueKind = VK_RValue;
2255 break;
2256
2257 // Fields and indirect fields that got here must be for
2258 // pointer-to-member expressions; we just call them l-values for
2259 // internal consistency, because this subexpression doesn't really
2260 // exist in the high-level semantics.
2261 case Decl::Field:
2262 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002263 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002264 "building reference to field in C?");
2265
2266 // These can't have reference type in well-formed programs, but
2267 // for internal consistency we do this anyway.
2268 type = type.getNonReferenceType();
2269 valueKind = VK_LValue;
2270 break;
2271
2272 // Non-type template parameters are either l-values or r-values
2273 // depending on the type.
2274 case Decl::NonTypeTemplateParm: {
2275 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2276 type = reftype->getPointeeType();
2277 valueKind = VK_LValue; // even if the parameter is an r-value reference
2278 break;
2279 }
2280
2281 // For non-references, we need to strip qualifiers just in case
2282 // the template parameter was declared as 'const int' or whatever.
2283 valueKind = VK_RValue;
2284 type = type.getUnqualifiedType();
2285 break;
2286 }
2287
2288 case Decl::Var:
2289 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002290 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002291 !type.hasQualifiers() &&
2292 type->isVoidType()) {
2293 valueKind = VK_RValue;
2294 break;
2295 }
2296 // fallthrough
2297
2298 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002299 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002300 // These are always l-values.
2301 valueKind = VK_LValue;
2302 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002303
Douglas Gregor812d8f62012-02-18 05:51:20 +00002304 // FIXME: Does the addition of const really only apply in
2305 // potentially-evaluated contexts? Since the variable isn't actually
2306 // captured in an unevaluated context, it seems that the answer is no.
2307 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2308 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2309 if (!CapturedType.isNull())
2310 type = CapturedType;
2311 }
2312
John McCallf4cd4f92011-02-09 01:13:10 +00002313 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002314 }
2315
John McCallf4cd4f92011-02-09 01:13:10 +00002316 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002317 const FunctionType *fty = type->castAs<FunctionType>();
2318
2319 // If we're referring to a function with an __unknown_anytype
2320 // result type, make the entire expression __unknown_anytype.
2321 if (fty->getResultType() == Context.UnknownAnyTy) {
2322 type = Context.UnknownAnyTy;
2323 valueKind = VK_RValue;
2324 break;
2325 }
2326
John McCallf4cd4f92011-02-09 01:13:10 +00002327 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002328 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002329 valueKind = VK_LValue;
2330 break;
2331 }
2332
2333 // C99 DR 316 says that, if a function type comes from a
2334 // function definition (without a prototype), that type is only
2335 // used for checking compatibility. Therefore, when referencing
2336 // the function, we pretend that we don't have the full function
2337 // type.
John McCall2979fe02011-04-12 00:42:48 +00002338 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2339 isa<FunctionProtoType>(fty))
2340 type = Context.getFunctionNoProtoType(fty->getResultType(),
2341 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002342
2343 // Functions are r-values in C.
2344 valueKind = VK_RValue;
2345 break;
2346 }
2347
2348 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002349 // If we're referring to a method with an __unknown_anytype
2350 // result type, make the entire expression __unknown_anytype.
2351 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002352 if (const FunctionProtoType *proto
2353 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002354 if (proto->getResultType() == Context.UnknownAnyTy) {
2355 type = Context.UnknownAnyTy;
2356 valueKind = VK_RValue;
2357 break;
2358 }
2359
John McCallf4cd4f92011-02-09 01:13:10 +00002360 // C++ methods are l-values if static, r-values if non-static.
2361 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2362 valueKind = VK_LValue;
2363 break;
2364 }
2365 // fallthrough
2366
2367 case Decl::CXXConversion:
2368 case Decl::CXXDestructor:
2369 case Decl::CXXConstructor:
2370 valueKind = VK_RValue;
2371 break;
2372 }
2373
2374 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2375 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002376}
Chris Lattnere168f762006-11-10 05:29:30 +00002377
John McCall2979fe02011-04-12 00:42:48 +00002378ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002379 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002380
Chris Lattnere168f762006-11-10 05:29:30 +00002381 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002382 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002383 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2384 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2385 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002386 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002387
Chris Lattnera81a0272008-01-12 08:14:25 +00002388 // Pre-defined identifiers are of type char[x], where x is the length of the
2389 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002390
Anders Carlsson2fb08242009-09-08 18:24:21 +00002391 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002392 if (!currentDecl && getCurBlock())
2393 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002394 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002395 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002396 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002397 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002398
Anders Carlsson0b209a82009-09-11 01:22:35 +00002399 QualType ResTy;
2400 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2401 ResTy = Context.DependentTy;
2402 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002403 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002404
Anders Carlsson0b209a82009-09-11 01:22:35 +00002405 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002406 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002407 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2408 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002409 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002410}
2411
Richard Smithbcc22fc2012-03-09 08:00:36 +00002412ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002413 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002414 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002415 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002416 if (Invalid)
2417 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002418
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002419 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002420 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002421 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002422 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002423
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002424 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002425 if (Literal.isWide())
2426 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002427 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002428 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002429 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002430 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002431 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002432 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002433 else
2434 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002435
Douglas Gregorfb65e592011-07-27 05:40:30 +00002436 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2437 if (Literal.isWide())
2438 Kind = CharacterLiteral::Wide;
2439 else if (Literal.isUTF16())
2440 Kind = CharacterLiteral::UTF16;
2441 else if (Literal.isUTF32())
2442 Kind = CharacterLiteral::UTF32;
2443
Richard Smith75b67d62012-03-08 01:34:56 +00002444 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2445 Tok.getLocation());
2446
2447 if (Literal.getUDSuffix().empty())
2448 return Owned(Lit);
2449
2450 // We're building a user-defined literal.
2451 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2452 SourceLocation UDSuffixLoc =
2453 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2454
Richard Smithbcc22fc2012-03-09 08:00:36 +00002455 // Make sure we're allowed user-defined literals here.
2456 if (!UDLScope)
2457 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2458
Richard Smith75b67d62012-03-08 01:34:56 +00002459 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2460 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002461 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2462 llvm::makeArrayRef(&Lit, 1),
2463 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002464}
2465
Ted Kremeneke65b0862012-03-06 20:05:56 +00002466ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2467 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2468 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2469 Context.IntTy, Loc));
2470}
2471
Richard Smith39570d002012-03-08 08:45:32 +00002472static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2473 QualType Ty, SourceLocation Loc) {
2474 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2475
2476 using llvm::APFloat;
2477 APFloat Val(Format);
2478
2479 APFloat::opStatus result = Literal.GetFloatValue(Val);
2480
2481 // Overflow is always an error, but underflow is only an error if
2482 // we underflowed to zero (APFloat reports denormals as underflow).
2483 if ((result & APFloat::opOverflow) ||
2484 ((result & APFloat::opUnderflow) && Val.isZero())) {
2485 unsigned diagnostic;
2486 SmallString<20> buffer;
2487 if (result & APFloat::opOverflow) {
2488 diagnostic = diag::warn_float_overflow;
2489 APFloat::getLargest(Format).toString(buffer);
2490 } else {
2491 diagnostic = diag::warn_float_underflow;
2492 APFloat::getSmallest(Format).toString(buffer);
2493 }
2494
2495 S.Diag(Loc, diagnostic)
2496 << Ty
2497 << StringRef(buffer.data(), buffer.size());
2498 }
2499
2500 bool isExact = (result == APFloat::opOK);
2501 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2502}
2503
Richard Smithbcc22fc2012-03-09 08:00:36 +00002504ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002505 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002506 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002507 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002508 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002509 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002510 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002511
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002512 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002513 // Add padding so that NumericLiteralParser can overread by one character.
2514 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002515 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002516
Chris Lattner67ca9252007-05-21 01:08:44 +00002517 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002518 bool Invalid = false;
2519 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2520 if (Invalid)
2521 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002522
Mike Stump11289f42009-09-09 15:08:12 +00002523 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002524 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002525 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002526 return ExprError();
2527
Richard Smith39570d002012-03-08 08:45:32 +00002528 if (Literal.hasUDSuffix()) {
2529 // We're building a user-defined literal.
2530 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2531 SourceLocation UDSuffixLoc =
2532 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2533
Richard Smithbcc22fc2012-03-09 08:00:36 +00002534 // Make sure we're allowed user-defined literals here.
2535 if (!UDLScope)
2536 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002537
Richard Smithbcc22fc2012-03-09 08:00:36 +00002538 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002539 if (Literal.isFloatingLiteral()) {
2540 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2541 // long double, the literal is treated as a call of the form
2542 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002543 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002544 } else {
2545 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2546 // unsigned long long, the literal is treated as a call of the form
2547 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002548 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002549 }
2550
Richard Smithbcc22fc2012-03-09 08:00:36 +00002551 DeclarationName OpName =
2552 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2553 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2554 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2555
2556 // Perform literal operator lookup to determine if we're building a raw
2557 // literal or a cooked one.
2558 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2559 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2560 /*AllowRawAndTemplate*/true)) {
2561 case LOLR_Error:
2562 return ExprError();
2563
2564 case LOLR_Cooked: {
2565 Expr *Lit;
2566 if (Literal.isFloatingLiteral()) {
2567 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2568 } else {
2569 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2570 if (Literal.GetIntegerValue(ResultVal))
2571 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2572 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2573 Tok.getLocation());
2574 }
2575 return BuildLiteralOperatorCall(R, OpNameInfo,
2576 llvm::makeArrayRef(&Lit, 1),
2577 Tok.getLocation());
2578 }
2579
2580 case LOLR_Raw: {
2581 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2582 // literal is treated as a call of the form
2583 // operator "" X ("n")
2584 SourceLocation TokLoc = Tok.getLocation();
2585 unsigned Length = Literal.getUDSuffixOffset();
2586 QualType StrTy = Context.getConstantArrayType(
2587 Context.CharTy, llvm::APInt(32, Length + 1),
2588 ArrayType::Normal, 0);
2589 Expr *Lit = StringLiteral::Create(
2590 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2591 /*Pascal*/false, StrTy, &TokLoc, 1);
2592 return BuildLiteralOperatorCall(R, OpNameInfo,
2593 llvm::makeArrayRef(&Lit, 1), TokLoc);
2594 }
2595
2596 case LOLR_Template:
2597 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2598 // template), L is treated as a call fo the form
2599 // operator "" X <'c1', 'c2', ... 'ck'>()
2600 // where n is the source character sequence c1 c2 ... ck.
2601 TemplateArgumentListInfo ExplicitArgs;
2602 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2603 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2604 llvm::APSInt Value(CharBits, CharIsUnsigned);
2605 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2606 Value = ThisTokBegin[I];
2607 TemplateArgument Arg(Value, Context.CharTy);
2608 TemplateArgumentLocInfo ArgInfo;
2609 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2610 }
2611 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2612 Tok.getLocation(), &ExplicitArgs);
2613 }
2614
2615 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002616 }
2617
Chris Lattner1c20a172007-08-26 03:42:43 +00002618 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002619
Chris Lattner1c20a172007-08-26 03:42:43 +00002620 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002621 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002622 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002623 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002624 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002625 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002626 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002627 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002628
Richard Smith39570d002012-03-08 08:45:32 +00002629 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002630
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002631 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002632 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002633 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002634 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002635 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002636 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002637 }
2638 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002639 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002640 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002641 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002642 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002643
Neil Boothac582c52007-08-29 22:00:19 +00002644 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002645 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002646 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002647 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002648 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002649
Chris Lattner67ca9252007-05-21 01:08:44 +00002650 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002651 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2652 // The microsoft literal suffix extensions support 128-bit literals, which
2653 // may be wider than [u]intmax_t.
2654 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2655 MaxWidth = 128;
2656 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002657
Chris Lattner67ca9252007-05-21 01:08:44 +00002658 if (Literal.GetIntegerValue(ResultVal)) {
2659 // If this value didn't fit into uintmax_t, warn and force to ull.
2660 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002661 Ty = Context.UnsignedLongLongTy;
2662 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002663 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002664 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002665 // If this value fits into a ULL, try to figure out what else it fits into
2666 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002667
Chris Lattner67ca9252007-05-21 01:08:44 +00002668 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2669 // be an unsigned int.
2670 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2671
2672 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002673 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002674 if (!Literal.isLong && !Literal.isLongLong) {
2675 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002676 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002677
Chris Lattner67ca9252007-05-21 01:08:44 +00002678 // Does it fit in a unsigned int?
2679 if (ResultVal.isIntN(IntSize)) {
2680 // Does it fit in a signed int?
2681 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002682 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002683 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002684 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002685 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002686 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002687 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002688
Chris Lattner67ca9252007-05-21 01:08:44 +00002689 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002690 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002691 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002692
Chris Lattner67ca9252007-05-21 01:08:44 +00002693 // Does it fit in a unsigned long?
2694 if (ResultVal.isIntN(LongSize)) {
2695 // Does it fit in a signed long?
2696 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002697 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002698 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002699 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002700 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002701 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002702 }
2703
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002704 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002705 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002706 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002707
Chris Lattner67ca9252007-05-21 01:08:44 +00002708 // Does it fit in a unsigned long long?
2709 if (ResultVal.isIntN(LongLongSize)) {
2710 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002711 // To be compatible with MSVC, hex integer literals ending with the
2712 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002713 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002714 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002715 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002716 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002717 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002718 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002719 }
2720 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002721
2722 // If it doesn't fit in unsigned long long, and we're using Microsoft
2723 // extensions, then its a 128-bit integer literal.
2724 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2725 if (Literal.isUnsigned)
2726 Ty = Context.UnsignedInt128Ty;
2727 else
2728 Ty = Context.Int128Ty;
2729 Width = 128;
2730 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002731
Chris Lattner67ca9252007-05-21 01:08:44 +00002732 // If we still couldn't decide a type, we probably have something that
2733 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002734 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002735 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002736 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002737 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002738 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002739
Chris Lattner55258cf2008-05-09 05:59:00 +00002740 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002741 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002742 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002743 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002744 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002745
Chris Lattner1c20a172007-08-26 03:42:43 +00002746 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2747 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002748 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002749 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002750
2751 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002752}
2753
Richard Trieuba63ce62011-09-09 01:45:06 +00002754ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002755 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002756 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002757}
2758
Chandler Carruth62da79c2011-05-26 08:53:12 +00002759static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2760 SourceLocation Loc,
2761 SourceRange ArgRange) {
2762 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2763 // scalar or vector data type argument..."
2764 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2765 // type (C99 6.2.5p18) or void.
2766 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2767 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2768 << T << ArgRange;
2769 return true;
2770 }
2771
2772 assert((T->isVoidType() || !T->isIncompleteType()) &&
2773 "Scalar types should always be complete");
2774 return false;
2775}
2776
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002777static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2778 SourceLocation Loc,
2779 SourceRange ArgRange,
2780 UnaryExprOrTypeTrait TraitKind) {
2781 // C99 6.5.3.4p1:
2782 if (T->isFunctionType()) {
2783 // alignof(function) is allowed as an extension.
2784 if (TraitKind == UETT_SizeOf)
2785 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2786 return false;
2787 }
2788
2789 // Allow sizeof(void)/alignof(void) as an extension.
2790 if (T->isVoidType()) {
2791 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2792 return false;
2793 }
2794
2795 return true;
2796}
2797
2798static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2799 SourceLocation Loc,
2800 SourceRange ArgRange,
2801 UnaryExprOrTypeTrait TraitKind) {
2802 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2803 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2804 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2805 << T << (TraitKind == UETT_SizeOf)
2806 << ArgRange;
2807 return true;
2808 }
2809
2810 return false;
2811}
2812
Chandler Carruth14502c22011-05-26 08:53:10 +00002813/// \brief Check the constrains on expression operands to unary type expression
2814/// and type traits.
2815///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002816/// Completes any types necessary and validates the constraints on the operand
2817/// expression. The logic mostly mirrors the type-based overload, but may modify
2818/// the expression as it completes the type for that expression through template
2819/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002820bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002821 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002822 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002823
2824 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2825 // the result is the size of the referenced type."
2826 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2827 // result shall be the alignment of the referenced type."
2828 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2829 ExprTy = Ref->getPointeeType();
2830
2831 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002832 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2833 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002834
2835 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002836 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2837 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002838 return false;
2839
Richard Trieuba63ce62011-09-09 01:45:06 +00002840 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002841 diag::err_sizeof_alignof_incomplete_type,
2842 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002843 return true;
2844
2845 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002846 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002847 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2848 ExprTy = Ref->getPointeeType();
2849
Richard Trieuba63ce62011-09-09 01:45:06 +00002850 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2851 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002852 return true;
2853
Nico Weber0870deb2011-06-15 02:47:03 +00002854 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002855 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002856 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2857 QualType OType = PVD->getOriginalType();
2858 QualType Type = PVD->getType();
2859 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002860 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002861 << Type << OType;
2862 Diag(PVD->getLocation(), diag::note_declared_at);
2863 }
2864 }
2865 }
2866 }
2867
Chandler Carruth7c430c02011-05-27 01:33:31 +00002868 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002869}
2870
2871/// \brief Check the constraints on operands to unary expression and type
2872/// traits.
2873///
2874/// This will complete any types necessary, and validate the various constraints
2875/// on those operands.
2876///
Steve Naroff71b59a92007-06-04 22:22:31 +00002877/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002878/// C99 6.3.2.1p[2-4] all state:
2879/// Except when it is the operand of the sizeof operator ...
2880///
2881/// C++ [expr.sizeof]p4
2882/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2883/// standard conversions are not applied to the operand of sizeof.
2884///
2885/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002886bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002887 SourceLocation OpLoc,
2888 SourceRange ExprRange,
2889 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002890 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002891 return false;
2892
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002893 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2894 // the result is the size of the referenced type."
2895 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2896 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002897 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2898 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002899
Chandler Carruth62da79c2011-05-26 08:53:12 +00002900 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002901 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002902
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002903 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002904 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002905 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002906 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002907
Richard Trieuba63ce62011-09-09 01:45:06 +00002908 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002909 diag::err_sizeof_alignof_incomplete_type,
2910 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002911 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002912
Richard Trieuba63ce62011-09-09 01:45:06 +00002913 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002914 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002915 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Chris Lattner62975a72009-04-24 00:30:45 +00002917 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002918}
2919
Chandler Carruth14502c22011-05-26 08:53:10 +00002920static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002921 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002922
Mike Stump11289f42009-09-09 15:08:12 +00002923 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002924 if (isa<DeclRefExpr>(E))
2925 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002926
2927 // Cannot know anything else if the expression is dependent.
2928 if (E->isTypeDependent())
2929 return false;
2930
Douglas Gregor71235ec2009-05-02 02:18:30 +00002931 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002932 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2933 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002934 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002935 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002936
2937 // Alignment of a field access is always okay, so long as it isn't a
2938 // bit-field.
2939 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002940 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002941 return false;
2942
Chandler Carruth14502c22011-05-26 08:53:10 +00002943 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002944}
2945
Chandler Carruth14502c22011-05-26 08:53:10 +00002946bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002947 E = E->IgnoreParens();
2948
2949 // Cannot know anything else if the expression is dependent.
2950 if (E->isTypeDependent())
2951 return false;
2952
Chandler Carruth14502c22011-05-26 08:53:10 +00002953 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002954}
2955
Douglas Gregor0950e412009-03-13 21:01:28 +00002956/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002957ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002958Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2959 SourceLocation OpLoc,
2960 UnaryExprOrTypeTrait ExprKind,
2961 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002962 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002963 return ExprError();
2964
John McCallbcd03502009-12-07 02:54:59 +00002965 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002966
Douglas Gregor0950e412009-03-13 21:01:28 +00002967 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002968 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002969 return ExprError();
2970
2971 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002972 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2973 Context.getSizeType(),
2974 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002975}
2976
2977/// \brief Build a sizeof or alignof expression given an expression
2978/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002979ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002980Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2981 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002982 ExprResult PE = CheckPlaceholderExpr(E);
2983 if (PE.isInvalid())
2984 return ExprError();
2985
2986 E = PE.get();
2987
Douglas Gregor0950e412009-03-13 21:01:28 +00002988 // Verify that the operand is valid.
2989 bool isInvalid = false;
2990 if (E->isTypeDependent()) {
2991 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002992 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002993 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002994 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002995 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002996 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002997 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002998 isInvalid = true;
2999 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003000 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003001 }
3002
3003 if (isInvalid)
3004 return ExprError();
3005
Eli Friedmane0afc982012-01-21 01:01:51 +00003006 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3007 PE = TranformToPotentiallyEvaluated(E);
3008 if (PE.isInvalid()) return ExprError();
3009 E = PE.take();
3010 }
3011
Douglas Gregor0950e412009-03-13 21:01:28 +00003012 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003013 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003014 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003015 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003016}
3017
Peter Collingbournee190dee2011-03-11 19:24:49 +00003018/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3019/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003020/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003021ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003022Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003023 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003024 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003025 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003026 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003027
Richard Trieuba63ce62011-09-09 01:45:06 +00003028 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003029 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003030 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003031 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003032 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003033
Douglas Gregor0950e412009-03-13 21:01:28 +00003034 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003035 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003036 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003037}
3038
John Wiegley01296292011-04-08 18:41:53 +00003039static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003040 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003041 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003042 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003043
John McCall34376a62010-12-04 03:47:34 +00003044 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003045 if (V.get()->getObjectKind() != OK_Ordinary) {
3046 V = S.DefaultLvalueConversion(V.take());
3047 if (V.isInvalid())
3048 return QualType();
3049 }
John McCall34376a62010-12-04 03:47:34 +00003050
Chris Lattnere267f5d2007-08-26 05:39:26 +00003051 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003052 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003053 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003054
Chris Lattnere267f5d2007-08-26 05:39:26 +00003055 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003056 if (V.get()->getType()->isArithmeticType())
3057 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003058
John McCall36226622010-10-12 02:09:17 +00003059 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003060 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003061 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003062 if (PR.get() != V.get()) {
3063 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003064 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003065 }
3066
Chris Lattnere267f5d2007-08-26 05:39:26 +00003067 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003068 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003069 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003070 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003071}
3072
3073
Chris Lattnere168f762006-11-10 05:29:30 +00003074
John McCalldadc5752010-08-24 06:29:42 +00003075ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003076Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003077 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003078 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003079 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003080 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003081 case tok::plusplus: Opc = UO_PostInc; break;
3082 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003083 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003084
Sebastian Redla9351792012-02-11 23:51:47 +00003085 // Since this might is a postfix expression, get rid of ParenListExprs.
3086 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3087 if (Result.isInvalid()) return ExprError();
3088 Input = Result.take();
3089
John McCallb268a282010-08-23 23:25:46 +00003090 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003091}
3092
John McCalldadc5752010-08-24 06:29:42 +00003093ExprResult
John McCallb268a282010-08-23 23:25:46 +00003094Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3095 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003096 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003097 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003098 if (Result.isInvalid()) return ExprError();
3099 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003100
John McCallb268a282010-08-23 23:25:46 +00003101 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003102
David Blaikiebbafb8a2012-03-11 07:00:24 +00003103 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003104 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003105 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003106 Context.DependentTy,
3107 VK_LValue, OK_Ordinary,
3108 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003109 }
3110
David Blaikiebbafb8a2012-03-11 07:00:24 +00003111 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003112 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003113 LHSExp->getType()->isEnumeralType() ||
3114 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003115 RHSExp->getType()->isEnumeralType()) &&
3116 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003117 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003118 }
3119
John McCallb268a282010-08-23 23:25:46 +00003120 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003121}
3122
3123
John McCalldadc5752010-08-24 06:29:42 +00003124ExprResult
John McCallb268a282010-08-23 23:25:46 +00003125Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003126 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003127 Expr *LHSExp = Base;
3128 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003129
Chris Lattner36d572b2007-07-16 00:14:47 +00003130 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003131 if (!LHSExp->getType()->getAs<VectorType>()) {
3132 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3133 if (Result.isInvalid())
3134 return ExprError();
3135 LHSExp = Result.take();
3136 }
3137 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3138 if (Result.isInvalid())
3139 return ExprError();
3140 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003141
Chris Lattner36d572b2007-07-16 00:14:47 +00003142 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003143 ExprValueKind VK = VK_LValue;
3144 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003145
Steve Naroffc1aadb12007-03-28 21:49:40 +00003146 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003147 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003148 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003149 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003150 Expr *BaseExpr, *IndexExpr;
3151 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003152 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3153 BaseExpr = LHSExp;
3154 IndexExpr = RHSExp;
3155 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003156 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003157 BaseExpr = LHSExp;
3158 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003159 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003160 } else if (const ObjCObjectPointerType *PTy =
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003161 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003162 BaseExpr = LHSExp;
3163 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003164 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3165 if (!Result.isInvalid())
3166 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003167 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003168 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3169 // Handle the uncommon case of "123[Ptr]".
3170 BaseExpr = RHSExp;
3171 IndexExpr = LHSExp;
3172 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003173 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003174 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003175 // Handle the uncommon case of "123[Ptr]".
3176 BaseExpr = RHSExp;
3177 IndexExpr = LHSExp;
3178 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003179 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003180 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003181 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003182 VK = LHSExp->getValueKind();
3183 if (VK != VK_RValue)
3184 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003185
Chris Lattner36d572b2007-07-16 00:14:47 +00003186 // FIXME: need to deal with const...
3187 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003188 } else if (LHSTy->isArrayType()) {
3189 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003190 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003191 // wasn't promoted because of the C90 rule that doesn't
3192 // allow promoting non-lvalue arrays. Warn, then
3193 // force the promotion here.
3194 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3195 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003196 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3197 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003198 LHSTy = LHSExp->getType();
3199
3200 BaseExpr = LHSExp;
3201 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003202 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003203 } else if (RHSTy->isArrayType()) {
3204 // Same as previous, except for 123[f().a] case
3205 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3206 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003207 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3208 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003209 RHSTy = RHSExp->getType();
3210
3211 BaseExpr = RHSExp;
3212 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003213 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003214 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003215 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3216 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003217 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003218 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003219 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003220 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3221 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003222
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003223 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003224 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3225 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003226 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3227
Douglas Gregorac1fb652009-03-24 19:52:54 +00003228 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003229 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3230 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003231 // incomplete types are not object types.
3232 if (ResultType->isFunctionType()) {
3233 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3234 << ResultType << BaseExpr->getSourceRange();
3235 return ExprError();
3236 }
Mike Stump11289f42009-09-09 15:08:12 +00003237
David Blaikiebbafb8a2012-03-11 07:00:24 +00003238 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003239 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003240 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3241 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003242
3243 // C forbids expressions of unqualified void type from being l-values.
3244 // See IsCForbiddenLValueType.
3245 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003246 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003247 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003248 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003249 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003250
Chris Lattner62975a72009-04-24 00:30:45 +00003251 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003252 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003253 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3254 << ResultType << BaseExpr->getSourceRange();
3255 return ExprError();
3256 }
Mike Stump11289f42009-09-09 15:08:12 +00003257
John McCall4bc41ae2010-11-18 19:01:18 +00003258 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003259 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003260
Mike Stump4e1f26a2009-02-19 03:04:26 +00003261 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003262 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003263}
3264
John McCalldadc5752010-08-24 06:29:42 +00003265ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003266 FunctionDecl *FD,
3267 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003268 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003269 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003270 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003271 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003272 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003273 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003274 return ExprError();
3275 }
3276
3277 if (Param->hasUninstantiatedDefaultArg()) {
3278 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003279
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003280 // Instantiate the expression.
3281 MultiLevelTemplateArgumentList ArgList
3282 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003283
Nico Weber44887f62010-11-29 18:19:25 +00003284 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003285 = ArgList.getInnermost();
3286 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3287 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003288
Nico Weber44887f62010-11-29 18:19:25 +00003289 ExprResult Result;
3290 {
3291 // C++ [dcl.fct.default]p5:
3292 // The names in the [default argument] expression are bound, and
3293 // the semantic constraints are checked, at the point where the
3294 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003295 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003296 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003297 Result = SubstExpr(UninstExpr, ArgList);
3298 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003299 if (Result.isInvalid())
3300 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003301
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003302 // Check the expression as an initializer for the parameter.
3303 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003304 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003305 InitializationKind Kind
3306 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003307 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003308 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003309
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003310 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3311 Result = InitSeq.Perform(*this, Entity, Kind,
3312 MultiExprArg(*this, &ResultE, 1));
3313 if (Result.isInvalid())
3314 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003315
David Blaikief68e8092012-04-30 18:21:31 +00003316 Expr *Arg = Result.takeAs<Expr>();
3317 CheckImplicitConversions(Arg, Arg->getExprLoc());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003318 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003319 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003320 }
3321
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003322 // If the default expression creates temporaries, we need to
3323 // push them to the current stack of expression temporaries so they'll
3324 // be properly destroyed.
3325 // FIXME: We should really be rebuilding the default argument with new
3326 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003327 // We don't need to do that with block decls, though, because
3328 // blocks in default argument expression can never capture anything.
3329 if (isa<ExprWithCleanups>(Param->getInit())) {
3330 // Set the "needs cleanups" bit regardless of whether there are
3331 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003332 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003333
3334 // Append all the objects to the cleanup list. Right now, this
3335 // should always be a no-op, because blocks in default argument
3336 // expressions should never be able to capture anything.
3337 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3338 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003339 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003340
3341 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003342 // Just mark all of the declarations in this potentially-evaluated expression
3343 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003344 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3345 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003346 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003347}
3348
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003349/// ConvertArgumentsForCall - Converts the arguments specified in
3350/// Args/NumArgs to the parameter types of the function FDecl with
3351/// function prototype Proto. Call is the call expression itself, and
3352/// Fn is the function expression. For a C++ member function, this
3353/// routine does not attempt to convert the object argument. Returns
3354/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003355bool
3356Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003357 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003358 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003359 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003360 SourceLocation RParenLoc,
3361 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003362 // Bail out early if calling a builtin with custom typechecking.
3363 // We don't need to do this in the
3364 if (FDecl)
3365 if (unsigned ID = FDecl->getBuiltinID())
3366 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3367 return false;
3368
Mike Stump4e1f26a2009-02-19 03:04:26 +00003369 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003370 // assignment, to the types of the corresponding parameter, ...
3371 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003372 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003373 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003374 unsigned FnKind = Fn->getType()->isBlockPointerType()
3375 ? 1 /* block */
3376 : (IsExecConfig ? 3 /* kernel function (exec config) */
3377 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003378
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003379 // If too few arguments are available (and we don't have default
3380 // arguments for the remaining parameters), don't make the call.
3381 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003382 if (NumArgs < MinArgs) {
3383 Diag(RParenLoc, MinArgs == NumArgsInProto
3384 ? diag::err_typecheck_call_too_few_args
3385 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003386 << FnKind
Peter Collingbourne740afe22011-10-02 23:49:20 +00003387 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003388
3389 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003390 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003391 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3392 << FDecl;
3393
3394 return true;
3395 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003396 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003397 }
3398
3399 // If too many are passed and not variadic, error on the extras and drop
3400 // them.
3401 if (NumArgs > NumArgsInProto) {
3402 if (!Proto->isVariadic()) {
3403 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003404 MinArgs == NumArgsInProto
3405 ? diag::err_typecheck_call_too_many_args
3406 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003407 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003408 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003409 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3410 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003411
3412 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003413 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003414 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3415 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003416
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003417 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003418 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003419 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003420 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003421 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003422 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003423 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003424 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3425 if (Fn->getType()->isBlockPointerType())
3426 CallType = VariadicBlock; // Block
3427 else if (isa<MemberExpr>(Fn))
3428 CallType = VariadicMethod;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003429 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003430 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003431 if (Invalid)
3432 return true;
3433 unsigned TotalNumArgs = AllArgs.size();
3434 for (unsigned i = 0; i < TotalNumArgs; ++i)
3435 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003436
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003437 return false;
3438}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003439
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003440bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3441 FunctionDecl *FDecl,
3442 const FunctionProtoType *Proto,
3443 unsigned FirstProtoArg,
3444 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003445 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003446 VariadicCallType CallType,
3447 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003448 unsigned NumArgsInProto = Proto->getNumArgs();
3449 unsigned NumArgsToCheck = NumArgs;
3450 bool Invalid = false;
3451 if (NumArgs != NumArgsInProto)
3452 // Use default arguments for missing arguments
3453 NumArgsToCheck = NumArgsInProto;
3454 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003455 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003456 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003457 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003458
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003459 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003460 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003461 if (ArgIx < NumArgs) {
3462 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003463
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003464 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003465 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003466 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003467 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003468
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003469 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003470 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003471 if (FDecl && i < FDecl->getNumParams())
3472 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003473
John McCall4124c492011-10-17 18:40:02 +00003474 // Strip the unbridged-cast placeholder expression off, if applicable.
3475 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3476 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3477 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3478 Arg = stripARCUnbridgedCast(Arg);
3479
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003480 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003481 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003482 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3483 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003484 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003485 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003486 Owned(Arg),
3487 /*TopLevelOfInitList=*/false,
3488 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003489 if (ArgE.isInvalid())
3490 return true;
3491
3492 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003493 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003494 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003495
John McCalldadc5752010-08-24 06:29:42 +00003496 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003497 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003498 if (ArgExpr.isInvalid())
3499 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003500
Anders Carlsson355933d2009-08-25 03:49:14 +00003501 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003502 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003503
3504 // Check for array bounds violations for each argument to the call. This
3505 // check only triggers warnings when the argument isn't a more complex Expr
3506 // with its own checking, such as a BinaryOperator.
3507 CheckArrayAccess(Arg);
3508
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003509 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3510 CheckStaticArrayArgument(CallLoc, Param, Arg);
3511
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003512 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003513 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003514
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003515 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003516 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003517
3518 // Assume that extern "C" functions with variadic arguments that
3519 // return __unknown_anytype aren't *really* variadic.
3520 if (Proto->getResultType() == Context.UnknownAnyTy &&
3521 FDecl && FDecl->isExternC()) {
3522 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3523 ExprResult arg;
3524 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3525 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3526 else
3527 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3528 Invalid |= arg.isInvalid();
3529 AllArgs.push_back(arg.take());
3530 }
3531
3532 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3533 } else {
3534 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003535 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3536 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003537 Invalid |= Arg.isInvalid();
3538 AllArgs.push_back(Arg.take());
3539 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003540 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003541
3542 // Check for array bounds violations.
3543 for (unsigned i = ArgIx; i != NumArgs; ++i)
3544 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003545 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003546 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003547}
3548
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003549static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3550 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3551 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3552 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3553 << ATL->getLocalSourceRange();
3554}
3555
3556/// CheckStaticArrayArgument - If the given argument corresponds to a static
3557/// array parameter, check that it is non-null, and that if it is formed by
3558/// array-to-pointer decay, the underlying array is sufficiently large.
3559///
3560/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3561/// array type derivation, then for each call to the function, the value of the
3562/// corresponding actual argument shall provide access to the first element of
3563/// an array with at least as many elements as specified by the size expression.
3564void
3565Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3566 ParmVarDecl *Param,
3567 const Expr *ArgExpr) {
3568 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003569 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003570 return;
3571
3572 QualType OrigTy = Param->getOriginalType();
3573
3574 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3575 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3576 return;
3577
3578 if (ArgExpr->isNullPointerConstant(Context,
3579 Expr::NPC_NeverValueDependent)) {
3580 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3581 DiagnoseCalleeStaticArrayParam(*this, Param);
3582 return;
3583 }
3584
3585 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3586 if (!CAT)
3587 return;
3588
3589 const ConstantArrayType *ArgCAT =
3590 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3591 if (!ArgCAT)
3592 return;
3593
3594 if (ArgCAT->getSize().ult(CAT->getSize())) {
3595 Diag(CallLoc, diag::warn_static_array_too_small)
3596 << ArgExpr->getSourceRange()
3597 << (unsigned) ArgCAT->getSize().getZExtValue()
3598 << (unsigned) CAT->getSize().getZExtValue();
3599 DiagnoseCalleeStaticArrayParam(*this, Param);
3600 }
3601}
3602
John McCall2979fe02011-04-12 00:42:48 +00003603/// Given a function expression of unknown-any type, try to rebuild it
3604/// to have a function type.
3605static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3606
Steve Naroff83895f72007-09-16 03:34:24 +00003607/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003608/// This provides the location of the left/right parens and a list of comma
3609/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003610ExprResult
John McCallb268a282010-08-23 23:25:46 +00003611Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003612 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003613 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003614 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003615
3616 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003617 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003618 if (Result.isInvalid()) return ExprError();
3619 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003620
Richard Trieuba63ce62011-09-09 01:45:06 +00003621 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003622
David Blaikiebbafb8a2012-03-11 07:00:24 +00003623 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003624 // If this is a pseudo-destructor expression, build the call immediately.
3625 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3626 if (NumArgs > 0) {
3627 // Pseudo-destructor calls should not have any arguments.
3628 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003629 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003630 SourceRange(Args[0]->getLocStart(),
3631 Args[NumArgs-1]->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003632 }
Mike Stump11289f42009-09-09 15:08:12 +00003633
Douglas Gregorad8a3362009-09-04 17:36:40 +00003634 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003635 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003636 }
Mike Stump11289f42009-09-09 15:08:12 +00003637
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003638 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003639 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003640 // FIXME: Will need to cache the results of name lookup (including ADL) in
3641 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003642 bool Dependent = false;
3643 if (Fn->isTypeDependent())
3644 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003645 else if (Expr::hasAnyTypeDependentArguments(
3646 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003647 Dependent = true;
3648
Peter Collingbourne41f85462011-02-09 21:07:24 +00003649 if (Dependent) {
3650 if (ExecConfig) {
3651 return Owned(new (Context) CUDAKernelCallExpr(
3652 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3653 Context.DependentTy, VK_RValue, RParenLoc));
3654 } else {
3655 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3656 Context.DependentTy, VK_RValue,
3657 RParenLoc));
3658 }
3659 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003660
3661 // Determine whether this is a call to an object (C++ [over.call.object]).
3662 if (Fn->getType()->isRecordType())
3663 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003664 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003665
John McCall2979fe02011-04-12 00:42:48 +00003666 if (Fn->getType() == Context.UnknownAnyTy) {
3667 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3668 if (result.isInvalid()) return ExprError();
3669 Fn = result.take();
3670 }
3671
John McCall0009fcc2011-04-26 20:42:42 +00003672 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003673 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003674 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003675 }
John McCall0009fcc2011-04-26 20:42:42 +00003676 }
John McCall10eae182009-11-30 22:42:35 +00003677
John McCall0009fcc2011-04-26 20:42:42 +00003678 // Check for overloaded calls. This can happen even in C due to extensions.
3679 if (Fn->getType() == Context.OverloadTy) {
3680 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3681
Douglas Gregorcda22702011-10-13 18:10:35 +00003682 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003683 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003684 OverloadExpr *ovl = find.Expression;
3685 if (isa<UnresolvedLookupExpr>(ovl)) {
3686 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3687 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3688 RParenLoc, ExecConfig);
3689 } else {
John McCall2d74de92009-12-01 22:10:20 +00003690 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003691 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003692 }
3693 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003694 }
3695
Douglas Gregore254f902009-02-04 00:32:51 +00003696 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003697 if (Fn->getType() == Context.UnknownAnyTy) {
3698 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3699 if (result.isInvalid()) return ExprError();
3700 Fn = result.take();
3701 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003702
Eli Friedmane14b1992009-12-26 03:35:45 +00003703 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003704
John McCall57500772009-12-16 12:17:52 +00003705 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003706 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3707 if (UnOp->getOpcode() == UO_AddrOf)
3708 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3709
John McCall57500772009-12-16 12:17:52 +00003710 if (isa<DeclRefExpr>(NakedFn))
3711 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003712 else if (isa<MemberExpr>(NakedFn))
3713 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003714
Peter Collingbourne41f85462011-02-09 21:07:24 +00003715 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003716 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003717}
3718
3719ExprResult
3720Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003721 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003722 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3723 if (!ConfigDecl)
3724 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3725 << "cudaConfigureCall");
3726 QualType ConfigQTy = ConfigDecl->getType();
3727
3728 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003729 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003730 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003731
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003732 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3733 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003734}
3735
Tanya Lattner55808c12011-06-04 00:47:47 +00003736/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3737///
3738/// __builtin_astype( value, dst type )
3739///
Richard Trieuba63ce62011-09-09 01:45:06 +00003740ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003741 SourceLocation BuiltinLoc,
3742 SourceLocation RParenLoc) {
3743 ExprValueKind VK = VK_RValue;
3744 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003745 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3746 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003747 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3748 return ExprError(Diag(BuiltinLoc,
3749 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003750 << DstTy
3751 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003752 << E->getSourceRange());
3753 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003754 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003755}
3756
John McCall57500772009-12-16 12:17:52 +00003757/// BuildResolvedCallExpr - Build a call to a resolved expression,
3758/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003759/// unary-convert to an expression of function-pointer or
3760/// block-pointer type.
3761///
3762/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003763ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003764Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3765 SourceLocation LParenLoc,
3766 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003767 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003768 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003769 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3770
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003771 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003772 ExprResult Result = UsualUnaryConversions(Fn);
3773 if (Result.isInvalid())
3774 return ExprError();
3775 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003776
Chris Lattner08464942007-12-28 05:29:59 +00003777 // Make the call expr early, before semantic checks. This guarantees cleanup
3778 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003779 CallExpr *TheCall;
3780 if (Config) {
3781 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3782 cast<CallExpr>(Config),
3783 Args, NumArgs,
3784 Context.BoolTy,
3785 VK_RValue,
3786 RParenLoc);
3787 } else {
3788 TheCall = new (Context) CallExpr(Context, Fn,
3789 Args, NumArgs,
3790 Context.BoolTy,
3791 VK_RValue,
3792 RParenLoc);
3793 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003794
John McCallbebede42011-02-26 05:39:39 +00003795 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3796
3797 // Bail out early if calling a builtin with custom typechecking.
3798 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3799 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3800
John McCall31996342011-04-07 08:22:57 +00003801 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003802 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003803 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003804 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3805 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003806 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003807 if (FuncT == 0)
3808 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3809 << Fn->getType() << Fn->getSourceRange());
3810 } else if (const BlockPointerType *BPT =
3811 Fn->getType()->getAs<BlockPointerType>()) {
3812 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3813 } else {
John McCall31996342011-04-07 08:22:57 +00003814 // Handle calls to expressions of unknown-any type.
3815 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003816 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003817 if (rewrite.isInvalid()) return ExprError();
3818 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003819 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003820 goto retry;
3821 }
3822
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003823 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3824 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003825 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003826
David Blaikiebbafb8a2012-03-11 07:00:24 +00003827 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003828 if (Config) {
3829 // CUDA: Kernel calls must be to global functions
3830 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3831 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3832 << FDecl->getName() << Fn->getSourceRange());
3833
3834 // CUDA: Kernel function must have 'void' return type
3835 if (!FuncT->getResultType()->isVoidType())
3836 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3837 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003838 } else {
3839 // CUDA: Calls to global functions must be configured
3840 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3841 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3842 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003843 }
3844 }
3845
Eli Friedman3164fb12009-03-22 22:00:50 +00003846 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003847 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003848 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003849 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003850 return ExprError();
3851
Chris Lattner08464942007-12-28 05:29:59 +00003852 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003853 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003854 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003855
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003856 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003857 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003858 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003859 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003860 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003861 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003862
Douglas Gregord8e97de2009-04-02 15:37:10 +00003863 if (FDecl) {
3864 // Check if we have too few/too many template arguments, based
3865 // on our knowledge of the function definition.
3866 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003867 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003868 const FunctionProtoType *Proto
3869 = Def->getType()->getAs<FunctionProtoType>();
3870 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003871 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3872 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003873 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003874
3875 // If the function we're calling isn't a function prototype, but we have
3876 // a function prototype from a prior declaratiom, use that prototype.
3877 if (!FDecl->hasPrototype())
3878 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003879 }
3880
Steve Naroff0b661582007-08-28 23:30:39 +00003881 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003882 for (unsigned i = 0; i != NumArgs; i++) {
3883 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003884
3885 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003886 InitializedEntity Entity
3887 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003888 Proto->getArgType(i),
3889 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003890 ExprResult ArgE = PerformCopyInitialization(Entity,
3891 SourceLocation(),
3892 Owned(Arg));
3893 if (ArgE.isInvalid())
3894 return true;
3895
3896 Arg = ArgE.takeAs<Expr>();
3897
3898 } else {
John Wiegley01296292011-04-08 18:41:53 +00003899 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3900
3901 if (ArgE.isInvalid())
3902 return true;
3903
3904 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003905 }
3906
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003907 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00003908 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003909 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00003910 return ExprError();
3911
Chris Lattner08464942007-12-28 05:29:59 +00003912 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003913 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003914 }
Chris Lattner08464942007-12-28 05:29:59 +00003915
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003916 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3917 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003918 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3919 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003920
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003921 // Check for sentinels
3922 if (NDecl)
3923 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003924
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003925 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003926 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003927 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003928 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003929
John McCallbebede42011-02-26 05:39:39 +00003930 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003931 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003932 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003933 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003934 return ExprError();
3935 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003936
John McCallb268a282010-08-23 23:25:46 +00003937 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003938}
3939
John McCalldadc5752010-08-24 06:29:42 +00003940ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003941Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003942 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003943 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003944 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003945 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003946
3947 TypeSourceInfo *TInfo;
3948 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3949 if (!TInfo)
3950 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3951
John McCallb268a282010-08-23 23:25:46 +00003952 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003953}
3954
John McCalldadc5752010-08-24 06:29:42 +00003955ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003956Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003957 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003958 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003959
Eli Friedman37a186d2008-05-20 05:22:08 +00003960 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003961 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003962 diag::err_illegal_decl_array_incomplete_type,
3963 SourceRange(LParenLoc,
3964 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003965 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003966 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003967 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003968 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003969 } else if (!literalType->isDependentType() &&
3970 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003971 diag::err_typecheck_decl_incomplete_type,
3972 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003973 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003974
Douglas Gregor85dabae2009-12-16 01:38:02 +00003975 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003976 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003977 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003978 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00003979 SourceRange(LParenLoc, RParenLoc),
3980 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00003981 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003982 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003983 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003984 &literalType);
3985 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003986 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003987 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003988
Chris Lattner79413952008-12-04 23:50:19 +00003989 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003990 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003991 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003992 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003993 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003994
John McCall7decc9e2010-11-18 06:31:45 +00003995 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003996 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00003997
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003998 return MaybeBindToTemporary(
3999 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004000 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004001}
4002
John McCalldadc5752010-08-24 06:29:42 +00004003ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004004Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004005 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004006 unsigned NumInit = InitArgList.size();
4007 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004008
John McCall526ab472011-10-25 17:37:35 +00004009 // Immediately handle non-overload placeholders. Overloads can be
4010 // resolved contextually, but everything else here can't.
4011 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00004012 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00004013 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4014
4015 // Ignore failures; dropping the entire initializer list because
4016 // of one failure would be terrible for indexing/etc.
4017 if (result.isInvalid()) continue;
4018
4019 InitList[I] = result.take();
4020 }
4021 }
4022
Steve Naroff30d242c2007-09-15 18:49:24 +00004023 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004024 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004025
Ted Kremenekac034612010-04-13 23:39:13 +00004026 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4027 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004028 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004029 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004030}
4031
John McCallcd78e802011-09-10 01:16:55 +00004032/// Do an explicit extend of the given block pointer if we're in ARC.
4033static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4034 assert(E.get()->getType()->isBlockPointerType());
4035 assert(E.get()->isRValue());
4036
4037 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004038 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004039
4040 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004041 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004042 /*base path*/ 0, VK_RValue);
4043 S.ExprNeedsCleanups = true;
4044}
4045
4046/// Prepare a conversion of the given expression to an ObjC object
4047/// pointer type.
4048CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4049 QualType type = E.get()->getType();
4050 if (type->isObjCObjectPointerType()) {
4051 return CK_BitCast;
4052 } else if (type->isBlockPointerType()) {
4053 maybeExtendBlockObject(*this, E);
4054 return CK_BlockPointerToObjCPointerCast;
4055 } else {
4056 assert(type->isPointerType());
4057 return CK_CPointerToObjCPointerCast;
4058 }
4059}
4060
John McCalld7646252010-11-14 08:17:51 +00004061/// Prepares for a scalar cast, performing all the necessary stages
4062/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004063CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004064 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4065 // Also, callers should have filtered out the invalid cases with
4066 // pointers. Everything else should be possible.
4067
John Wiegley01296292011-04-08 18:41:53 +00004068 QualType SrcTy = Src.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00004069 if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>())
4070 SrcTy = SrcAtomicTy->getValueType();
4071 if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>())
4072 DestTy = DestAtomicTy->getValueType();
4073
John McCall9776e432011-10-06 23:25:11 +00004074 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004075 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004076
John McCall9320b872011-09-09 05:25:32 +00004077 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004078 case Type::STK_MemberPointer:
4079 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004080
John McCall9320b872011-09-09 05:25:32 +00004081 case Type::STK_CPointer:
4082 case Type::STK_BlockPointer:
4083 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004084 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004085 case Type::STK_CPointer:
4086 return CK_BitCast;
4087 case Type::STK_BlockPointer:
4088 return (SrcKind == Type::STK_BlockPointer
4089 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4090 case Type::STK_ObjCObjectPointer:
4091 if (SrcKind == Type::STK_ObjCObjectPointer)
4092 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004093 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004094 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004095 maybeExtendBlockObject(*this, Src);
4096 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004097 case Type::STK_Bool:
4098 return CK_PointerToBoolean;
4099 case Type::STK_Integral:
4100 return CK_PointerToIntegral;
4101 case Type::STK_Floating:
4102 case Type::STK_FloatingComplex:
4103 case Type::STK_IntegralComplex:
4104 case Type::STK_MemberPointer:
4105 llvm_unreachable("illegal cast from pointer");
4106 }
David Blaikie8a40f702012-01-17 06:56:22 +00004107 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004108
John McCall8cb679e2010-11-15 09:13:47 +00004109 case Type::STK_Bool: // casting from bool is like casting from an integer
4110 case Type::STK_Integral:
4111 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004112 case Type::STK_CPointer:
4113 case Type::STK_ObjCObjectPointer:
4114 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004115 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004116 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004117 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004118 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004119 case Type::STK_Bool:
4120 return CK_IntegralToBoolean;
4121 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004122 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004123 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004124 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004125 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004126 Src = ImpCastExprToType(Src.take(),
4127 DestTy->castAs<ComplexType>()->getElementType(),
4128 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004129 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004130 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004131 Src = ImpCastExprToType(Src.take(),
4132 DestTy->castAs<ComplexType>()->getElementType(),
4133 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004134 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004135 case Type::STK_MemberPointer:
4136 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004137 }
David Blaikie8a40f702012-01-17 06:56:22 +00004138 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004139
John McCall8cb679e2010-11-15 09:13:47 +00004140 case Type::STK_Floating:
4141 switch (DestTy->getScalarTypeKind()) {
4142 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004143 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004144 case Type::STK_Bool:
4145 return CK_FloatingToBoolean;
4146 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004147 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004148 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004149 Src = ImpCastExprToType(Src.take(),
4150 DestTy->castAs<ComplexType>()->getElementType(),
4151 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004152 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004153 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004154 Src = ImpCastExprToType(Src.take(),
4155 DestTy->castAs<ComplexType>()->getElementType(),
4156 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004157 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004158 case Type::STK_CPointer:
4159 case Type::STK_ObjCObjectPointer:
4160 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004161 llvm_unreachable("valid float->pointer cast?");
4162 case Type::STK_MemberPointer:
4163 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004164 }
David Blaikie8a40f702012-01-17 06:56:22 +00004165 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004166
John McCall8cb679e2010-11-15 09:13:47 +00004167 case Type::STK_FloatingComplex:
4168 switch (DestTy->getScalarTypeKind()) {
4169 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004170 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004171 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004172 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004173 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004174 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4175 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004176 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004177 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004178 return CK_FloatingCast;
4179 }
John McCall8cb679e2010-11-15 09:13:47 +00004180 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004181 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004182 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004183 Src = ImpCastExprToType(Src.take(),
4184 SrcTy->castAs<ComplexType>()->getElementType(),
4185 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004186 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004187 case Type::STK_CPointer:
4188 case Type::STK_ObjCObjectPointer:
4189 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004190 llvm_unreachable("valid complex float->pointer cast?");
4191 case Type::STK_MemberPointer:
4192 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004193 }
David Blaikie8a40f702012-01-17 06:56:22 +00004194 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004195
John McCall8cb679e2010-11-15 09:13:47 +00004196 case Type::STK_IntegralComplex:
4197 switch (DestTy->getScalarTypeKind()) {
4198 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004199 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004200 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004201 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004202 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004203 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4204 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004205 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004206 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004207 return CK_IntegralCast;
4208 }
John McCall8cb679e2010-11-15 09:13:47 +00004209 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004210 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004211 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004212 Src = ImpCastExprToType(Src.take(),
4213 SrcTy->castAs<ComplexType>()->getElementType(),
4214 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004215 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004216 case Type::STK_CPointer:
4217 case Type::STK_ObjCObjectPointer:
4218 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004219 llvm_unreachable("valid complex int->pointer cast?");
4220 case Type::STK_MemberPointer:
4221 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004222 }
David Blaikie8a40f702012-01-17 06:56:22 +00004223 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004224 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004225
John McCalld7646252010-11-14 08:17:51 +00004226 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004227}
4228
Anders Carlsson525b76b2009-10-16 02:48:28 +00004229bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004230 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004231 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004232
Anders Carlssonde71adf2007-11-27 05:51:55 +00004233 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004234 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004235 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004236 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004237 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004238 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004239 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004240 } else
4241 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004242 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004243 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004244
John McCalle3027922010-08-25 11:45:40 +00004245 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004246 return false;
4247}
4248
John Wiegley01296292011-04-08 18:41:53 +00004249ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4250 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004251 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004252
Anders Carlsson43d70f82009-10-16 05:23:41 +00004253 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004254
Nate Begemanc8961a42009-06-27 22:05:55 +00004255 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4256 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004257 // In OpenCL, casts between vectors of different types are not allowed.
4258 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004259 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004260 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004261 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004262 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004263 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004264 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004265 return ExprError();
4266 }
John McCalle3027922010-08-25 11:45:40 +00004267 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004268 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004269 }
4270
Nate Begemanbd956c42009-06-28 02:36:38 +00004271 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004272 // conversion will take place first from scalar to elt type, and then
4273 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004274 if (SrcTy->isPointerType())
4275 return Diag(R.getBegin(),
4276 diag::err_invalid_conversion_between_vector_and_scalar)
4277 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004278
4279 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004280 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004281 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004282 if (CastExprRes.isInvalid())
4283 return ExprError();
4284 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004285
John McCalle3027922010-08-25 11:45:40 +00004286 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004287 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004288}
4289
John McCalldadc5752010-08-24 06:29:42 +00004290ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004291Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4292 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004293 SourceLocation RParenLoc, Expr *CastExpr) {
4294 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004295 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004296
Richard Trieuba63ce62011-09-09 01:45:06 +00004297 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004298 if (D.isInvalidType())
4299 return ExprError();
4300
David Blaikiebbafb8a2012-03-11 07:00:24 +00004301 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004302 // Check that there are no default arguments (C++ only).
4303 CheckExtraCXXDefaultArguments(D);
4304 }
4305
John McCall42856de2011-10-01 05:17:03 +00004306 checkUnusedDeclAttributes(D);
4307
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004308 QualType castType = castTInfo->getType();
4309 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004310
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004311 bool isVectorLiteral = false;
4312
4313 // Check for an altivec or OpenCL literal,
4314 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004315 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4316 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004317 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004318 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004319 if (PLE && PLE->getNumExprs() == 0) {
4320 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4321 return ExprError();
4322 }
4323 if (PE || PLE->getNumExprs() == 1) {
4324 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4325 if (!E->getType()->isVectorType())
4326 isVectorLiteral = true;
4327 }
4328 else
4329 isVectorLiteral = true;
4330 }
4331
4332 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4333 // then handle it as such.
4334 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004335 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004336
Nate Begeman5ec4b312009-08-10 23:49:36 +00004337 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004338 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4339 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004340 if (isa<ParenListExpr>(CastExpr)) {
4341 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004342 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004343 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004344 }
John McCallebe54742010-01-15 18:56:44 +00004345
Richard Trieuba63ce62011-09-09 01:45:06 +00004346 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004347}
4348
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004349ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4350 SourceLocation RParenLoc, Expr *E,
4351 TypeSourceInfo *TInfo) {
4352 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4353 "Expected paren or paren list expression");
4354
4355 Expr **exprs;
4356 unsigned numExprs;
4357 Expr *subExpr;
4358 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4359 exprs = PE->getExprs();
4360 numExprs = PE->getNumExprs();
4361 } else {
4362 subExpr = cast<ParenExpr>(E)->getSubExpr();
4363 exprs = &subExpr;
4364 numExprs = 1;
4365 }
4366
4367 QualType Ty = TInfo->getType();
4368 assert(Ty->isVectorType() && "Expected vector type");
4369
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004370 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004371 const VectorType *VTy = Ty->getAs<VectorType>();
4372 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4373
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004374 // '(...)' form of vector initialization in AltiVec: the number of
4375 // initializers must be one or must match the size of the vector.
4376 // If a single value is specified in the initializer then it will be
4377 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004378 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004379 // The number of initializers must be one or must match the size of the
4380 // vector. If a single value is specified in the initializer then it will
4381 // be replicated to all the components of the vector
4382 if (numExprs == 1) {
4383 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004384 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4385 if (Literal.isInvalid())
4386 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004387 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004388 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004389 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4390 }
4391 else if (numExprs < numElems) {
4392 Diag(E->getExprLoc(),
4393 diag::err_incorrect_number_of_vector_initializers);
4394 return ExprError();
4395 }
4396 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004397 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004398 }
Tanya Lattner83559382011-07-15 23:07:01 +00004399 else {
4400 // For OpenCL, when the number of initializers is a single value,
4401 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004402 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004403 VTy->getVectorKind() == VectorType::GenericVector &&
4404 numExprs == 1) {
4405 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004406 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4407 if (Literal.isInvalid())
4408 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004409 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004410 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004411 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4412 }
4413
Benjamin Kramer8001f742012-02-14 12:06:21 +00004414 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004415 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004416 // FIXME: This means that pretty-printing the final AST will produce curly
4417 // braces instead of the original commas.
4418 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4419 &initExprs[0],
4420 initExprs.size(), RParenLoc);
4421 initE->setType(Ty);
4422 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4423}
4424
Sebastian Redla9351792012-02-11 23:51:47 +00004425/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4426/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004427ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004428Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4429 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004430 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004431 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004432
John McCalldadc5752010-08-24 06:29:42 +00004433 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004434
Nate Begeman5ec4b312009-08-10 23:49:36 +00004435 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004436 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4437 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004438
John McCallb268a282010-08-23 23:25:46 +00004439 if (Result.isInvalid()) return ExprError();
4440
4441 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004442}
4443
Sebastian Redla9351792012-02-11 23:51:47 +00004444ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4445 SourceLocation R,
4446 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004447 unsigned nexprs = Val.size();
4448 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004449 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004450 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004451 return Owned(expr);
4452}
4453
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004454/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004455/// constant and the other is not a pointer. Returns true if a diagnostic is
4456/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004457bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004458 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004459 Expr *NullExpr = LHSExpr;
4460 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004461 Expr::NullPointerConstantKind NullKind =
4462 NullExpr->isNullPointerConstant(Context,
4463 Expr::NPC_ValueDependentIsNotNull);
4464
4465 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004466 NullExpr = RHSExpr;
4467 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004468 NullKind =
4469 NullExpr->isNullPointerConstant(Context,
4470 Expr::NPC_ValueDependentIsNotNull);
4471 }
4472
4473 if (NullKind == Expr::NPCK_NotNull)
4474 return false;
4475
4476 if (NullKind == Expr::NPCK_ZeroInteger) {
4477 // In this case, check to make sure that we got here from a "NULL"
4478 // string in the source code.
4479 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004480 SourceLocation loc = NullExpr->getExprLoc();
4481 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004482 return false;
4483 }
4484
4485 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4486 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4487 << NonPointerExpr->getType() << DiagType
4488 << NonPointerExpr->getSourceRange();
4489 return true;
4490}
4491
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004492/// \brief Return false if the condition expression is valid, true otherwise.
4493static bool checkCondition(Sema &S, Expr *Cond) {
4494 QualType CondTy = Cond->getType();
4495
4496 // C99 6.5.15p2
4497 if (CondTy->isScalarType()) return false;
4498
4499 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004500 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004501 return false;
4502
4503 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004504 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004505 diag::err_typecheck_cond_expect_scalar :
4506 diag::err_typecheck_cond_expect_scalar_or_vector)
4507 << CondTy;
4508 return true;
4509}
4510
4511/// \brief Return false if the two expressions can be converted to a vector,
4512/// true otherwise
4513static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4514 ExprResult &RHS,
4515 QualType CondTy) {
4516 // Both operands should be of scalar type.
4517 if (!LHS.get()->getType()->isScalarType()) {
4518 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4519 << CondTy;
4520 return true;
4521 }
4522 if (!RHS.get()->getType()->isScalarType()) {
4523 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4524 << CondTy;
4525 return true;
4526 }
4527
4528 // Implicity convert these scalars to the type of the condition.
4529 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4530 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4531 return false;
4532}
4533
4534/// \brief Handle when one or both operands are void type.
4535static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4536 ExprResult &RHS) {
4537 Expr *LHSExpr = LHS.get();
4538 Expr *RHSExpr = RHS.get();
4539
4540 if (!LHSExpr->getType()->isVoidType())
4541 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4542 << RHSExpr->getSourceRange();
4543 if (!RHSExpr->getType()->isVoidType())
4544 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4545 << LHSExpr->getSourceRange();
4546 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4547 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4548 return S.Context.VoidTy;
4549}
4550
4551/// \brief Return false if the NullExpr can be promoted to PointerTy,
4552/// true otherwise.
4553static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4554 QualType PointerTy) {
4555 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4556 !NullExpr.get()->isNullPointerConstant(S.Context,
4557 Expr::NPC_ValueDependentIsNull))
4558 return true;
4559
4560 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4561 return false;
4562}
4563
4564/// \brief Checks compatibility between two pointers and return the resulting
4565/// type.
4566static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4567 ExprResult &RHS,
4568 SourceLocation Loc) {
4569 QualType LHSTy = LHS.get()->getType();
4570 QualType RHSTy = RHS.get()->getType();
4571
4572 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4573 // Two identical pointers types are always compatible.
4574 return LHSTy;
4575 }
4576
4577 QualType lhptee, rhptee;
4578
4579 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004580 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4581 lhptee = LHSBTy->getPointeeType();
4582 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004583 } else {
John McCall9320b872011-09-09 05:25:32 +00004584 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4585 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004586 }
4587
Eli Friedman57a75392012-04-05 22:30:04 +00004588 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4589 // differently qualified versions of compatible types, the result type is
4590 // a pointer to an appropriately qualified version of the composite
4591 // type.
4592
4593 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4594 // clause doesn't make sense for our extensions. E.g. address space 2 should
4595 // be incompatible with address space 3: they may live on different devices or
4596 // anything.
4597 Qualifiers lhQual = lhptee.getQualifiers();
4598 Qualifiers rhQual = rhptee.getQualifiers();
4599
4600 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4601 lhQual.removeCVRQualifiers();
4602 rhQual.removeCVRQualifiers();
4603
4604 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4605 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4606
4607 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4608
4609 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004610 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4611 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4612 << RHS.get()->getSourceRange();
4613 // In this situation, we assume void* type. No especially good
4614 // reason, but this is what gcc does, and we do have to pick
4615 // to get a consistent AST.
4616 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4617 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4618 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4619 return incompatTy;
4620 }
4621
4622 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004623 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4624 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004625
Eli Friedman57a75392012-04-05 22:30:04 +00004626 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4627 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4628 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004629}
4630
4631/// \brief Return the resulting type when the operands are both block pointers.
4632static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4633 ExprResult &LHS,
4634 ExprResult &RHS,
4635 SourceLocation Loc) {
4636 QualType LHSTy = LHS.get()->getType();
4637 QualType RHSTy = RHS.get()->getType();
4638
4639 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4640 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4641 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4642 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4643 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4644 return destType;
4645 }
4646 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4647 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4648 << RHS.get()->getSourceRange();
4649 return QualType();
4650 }
4651
4652 // We have 2 block pointer types.
4653 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4654}
4655
4656/// \brief Return the resulting type when the operands are both pointers.
4657static QualType
4658checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4659 ExprResult &RHS,
4660 SourceLocation Loc) {
4661 // get the pointer types
4662 QualType LHSTy = LHS.get()->getType();
4663 QualType RHSTy = RHS.get()->getType();
4664
4665 // get the "pointed to" types
4666 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4667 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4668
4669 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4670 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4671 // Figure out necessary qualifiers (C99 6.5.15p6)
4672 QualType destPointee
4673 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4674 QualType destType = S.Context.getPointerType(destPointee);
4675 // Add qualifiers if necessary.
4676 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4677 // Promote to void*.
4678 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4679 return destType;
4680 }
4681 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4682 QualType destPointee
4683 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4684 QualType destType = S.Context.getPointerType(destPointee);
4685 // Add qualifiers if necessary.
4686 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4687 // Promote to void*.
4688 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4689 return destType;
4690 }
4691
4692 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4693}
4694
4695/// \brief Return false if the first expression is not an integer and the second
4696/// expression is not a pointer, true otherwise.
4697static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4698 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004699 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004700 if (!PointerExpr->getType()->isPointerType() ||
4701 !Int.get()->getType()->isIntegerType())
4702 return false;
4703
Richard Trieuba63ce62011-09-09 01:45:06 +00004704 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4705 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004706
4707 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4708 << Expr1->getType() << Expr2->getType()
4709 << Expr1->getSourceRange() << Expr2->getSourceRange();
4710 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4711 CK_IntegralToPointer);
4712 return true;
4713}
4714
Richard Trieud33e46e2011-09-06 20:06:39 +00004715/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4716/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004717/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004718QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4719 ExprResult &RHS, ExprValueKind &VK,
4720 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004721 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004722
Richard Trieud33e46e2011-09-06 20:06:39 +00004723 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4724 if (!LHSResult.isUsable()) return QualType();
4725 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004726
Richard Trieud33e46e2011-09-06 20:06:39 +00004727 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4728 if (!RHSResult.isUsable()) return QualType();
4729 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004730
Sebastian Redl1a99f442009-04-16 17:51:27 +00004731 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004732 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004733 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004734
4735 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004736 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004737
John Wiegley01296292011-04-08 18:41:53 +00004738 Cond = UsualUnaryConversions(Cond.take());
4739 if (Cond.isInvalid())
4740 return QualType();
4741 LHS = UsualUnaryConversions(LHS.take());
4742 if (LHS.isInvalid())
4743 return QualType();
4744 RHS = UsualUnaryConversions(RHS.take());
4745 if (RHS.isInvalid())
4746 return QualType();
4747
4748 QualType CondTy = Cond.get()->getType();
4749 QualType LHSTy = LHS.get()->getType();
4750 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004751
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004752 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004753 if (checkCondition(*this, Cond.get()))
4754 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004755
Chris Lattnere2949f42008-01-06 22:42:25 +00004756 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004757 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004758 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004759
Nate Begemanabb5a732010-09-20 22:41:17 +00004760 // OpenCL: If the condition is a vector, and both operands are scalar,
4761 // attempt to implicity convert them to the vector type to act like the
4762 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004763 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004764 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004765 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004766
Chris Lattnere2949f42008-01-06 22:42:25 +00004767 // If both operands have arithmetic type, do the usual arithmetic conversions
4768 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004769 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4770 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004771 if (LHS.isInvalid() || RHS.isInvalid())
4772 return QualType();
4773 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004774 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004775
Chris Lattnere2949f42008-01-06 22:42:25 +00004776 // If both operands are the same structure or union type, the result is that
4777 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004778 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4779 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004780 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004781 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004782 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004783 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004784 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004785 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004786
Chris Lattnere2949f42008-01-06 22:42:25 +00004787 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004788 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004789 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004790 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004791 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004792
Steve Naroff039ad3c2008-01-08 01:11:38 +00004793 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4794 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004795 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4796 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004797
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004798 // All objective-c pointer type analysis is done here.
4799 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4800 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004801 if (LHS.isInvalid() || RHS.isInvalid())
4802 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004803 if (!compositeType.isNull())
4804 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004805
4806
Steve Naroff05efa972009-07-01 14:36:47 +00004807 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004808 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4809 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4810 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004811
Steve Naroff05efa972009-07-01 14:36:47 +00004812 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004813 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4814 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4815 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004816
John McCalle84af4e2010-11-13 01:35:44 +00004817 // GCC compatibility: soften pointer/integer mismatch. Note that
4818 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004819 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4820 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004821 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004822 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4823 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004824 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004825
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004826 // Emit a better diagnostic if one of the expressions is a null pointer
4827 // constant and the other is not a pointer type. In this case, the user most
4828 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004829 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004830 return QualType();
4831
Chris Lattnere2949f42008-01-06 22:42:25 +00004832 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004833 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004834 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4835 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004836 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004837}
4838
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004839/// FindCompositeObjCPointerType - Helper method to find composite type of
4840/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004841QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004842 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004843 QualType LHSTy = LHS.get()->getType();
4844 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004845
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004846 // Handle things like Class and struct objc_class*. Here we case the result
4847 // to the pseudo-builtin, because that will be implicitly cast back to the
4848 // redefinition type if an attempt is made to access its fields.
4849 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004850 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004851 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004852 return LHSTy;
4853 }
4854 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004855 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004856 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004857 return RHSTy;
4858 }
4859 // And the same for struct objc_object* / id
4860 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004861 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004862 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004863 return LHSTy;
4864 }
4865 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004866 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004867 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004868 return RHSTy;
4869 }
4870 // And the same for struct objc_selector* / SEL
4871 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004872 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004873 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004874 return LHSTy;
4875 }
4876 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004877 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004878 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004879 return RHSTy;
4880 }
4881 // Check constraints for Objective-C object pointers types.
4882 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004883
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004884 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4885 // Two identical object pointer types are always compatible.
4886 return LHSTy;
4887 }
John McCall9320b872011-09-09 05:25:32 +00004888 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4889 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004890 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004891
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004892 // If both operands are interfaces and either operand can be
4893 // assigned to the other, use that type as the composite
4894 // type. This allows
4895 // xxx ? (A*) a : (B*) b
4896 // where B is a subclass of A.
4897 //
4898 // Additionally, as for assignment, if either type is 'id'
4899 // allow silent coercion. Finally, if the types are
4900 // incompatible then make sure to use 'id' as the composite
4901 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004902
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004903 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4904 // It could return the composite type.
4905 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4906 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4907 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4908 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4909 } else if ((LHSTy->isObjCQualifiedIdType() ||
4910 RHSTy->isObjCQualifiedIdType()) &&
4911 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4912 // Need to handle "id<xx>" explicitly.
4913 // GCC allows qualified id and any Objective-C type to devolve to
4914 // id. Currently localizing to here until clear this should be
4915 // part of ObjCQualifiedIdTypesAreCompatible.
4916 compositeType = Context.getObjCIdType();
4917 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4918 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004919 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004920 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4921 ;
4922 else {
4923 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4924 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004925 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004926 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004927 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4928 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004929 return incompatTy;
4930 }
4931 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004932 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4933 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004934 return compositeType;
4935 }
4936 // Check Objective-C object pointer types and 'void *'
4937 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004938 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004939 // ARC forbids the implicit conversion of object pointers to 'void *',
4940 // so these types are not compatible.
4941 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4942 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4943 LHS = RHS = true;
4944 return QualType();
4945 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004946 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4947 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4948 QualType destPointee
4949 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4950 QualType destType = Context.getPointerType(destPointee);
4951 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004952 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004953 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004954 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004955 return destType;
4956 }
4957 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004958 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004959 // ARC forbids the implicit conversion of object pointers to 'void *',
4960 // so these types are not compatible.
4961 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4962 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4963 LHS = RHS = true;
4964 return QualType();
4965 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004966 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4967 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4968 QualType destPointee
4969 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4970 QualType destType = Context.getPointerType(destPointee);
4971 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004972 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004973 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004974 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004975 return destType;
4976 }
4977 return QualType();
4978}
4979
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004980/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004981/// ParenRange in parentheses.
4982static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004983 const PartialDiagnostic &Note,
4984 SourceRange ParenRange) {
4985 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4986 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4987 EndLoc.isValid()) {
4988 Self.Diag(Loc, Note)
4989 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4990 << FixItHint::CreateInsertion(EndLoc, ")");
4991 } else {
4992 // We can't display the parentheses, so just show the bare note.
4993 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004994 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004995}
4996
4997static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4998 return Opc >= BO_Mul && Opc <= BO_Shr;
4999}
5000
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005001/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5002/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005003/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5004/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005005static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005006 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005007 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5008 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005009 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005010 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005011
5012 // Built-in binary operator.
5013 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5014 if (IsArithmeticOp(OP->getOpcode())) {
5015 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005016 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005017 return true;
5018 }
5019 }
5020
5021 // Overloaded operator.
5022 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5023 if (Call->getNumArgs() != 2)
5024 return false;
5025
5026 // Make sure this is really a binary operator that is safe to pass into
5027 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5028 OverloadedOperatorKind OO = Call->getOperator();
5029 if (OO < OO_Plus || OO > OO_Arrow)
5030 return false;
5031
5032 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5033 if (IsArithmeticOp(OpKind)) {
5034 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005035 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005036 return true;
5037 }
5038 }
5039
5040 return false;
5041}
5042
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005043static bool IsLogicOp(BinaryOperatorKind Opc) {
5044 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5045}
5046
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005047/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5048/// or is a logical expression such as (x==y) which has int type, but is
5049/// commonly interpreted as boolean.
5050static bool ExprLooksBoolean(Expr *E) {
5051 E = E->IgnoreParenImpCasts();
5052
5053 if (E->getType()->isBooleanType())
5054 return true;
5055 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5056 return IsLogicOp(OP->getOpcode());
5057 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5058 return OP->getOpcode() == UO_LNot;
5059
5060 return false;
5061}
5062
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005063/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5064/// and binary operator are mixed in a way that suggests the programmer assumed
5065/// the conditional operator has higher precedence, for example:
5066/// "int x = a + someBinaryCondition ? 1 : 2".
5067static void DiagnoseConditionalPrecedence(Sema &Self,
5068 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005069 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005070 Expr *LHSExpr,
5071 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005072 BinaryOperatorKind CondOpcode;
5073 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005074
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005075 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005076 return;
5077 if (!ExprLooksBoolean(CondRHS))
5078 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005079
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005080 // The condition is an arithmetic binary expression, with a right-
5081 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005082
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005083 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005084 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005085 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005086
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005087 SuggestParentheses(Self, OpLoc,
5088 Self.PDiag(diag::note_precedence_conditional_silence)
5089 << BinaryOperator::getOpcodeStr(CondOpcode),
5090 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005091
5092 SuggestParentheses(Self, OpLoc,
5093 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005094 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005095}
5096
Steve Naroff83895f72007-09-16 03:34:24 +00005097/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005098/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005099ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005100 SourceLocation ColonLoc,
5101 Expr *CondExpr, Expr *LHSExpr,
5102 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005103 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5104 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005105 OpaqueValueExpr *opaqueValue = 0;
5106 Expr *commonExpr = 0;
5107 if (LHSExpr == 0) {
5108 commonExpr = CondExpr;
5109
5110 // We usually want to apply unary conversions *before* saving, except
5111 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005112 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005113 && !commonExpr->isTypeDependent()
5114 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5115 && commonExpr->isGLValue()
5116 && commonExpr->isOrdinaryOrBitFieldObject()
5117 && RHSExpr->isOrdinaryOrBitFieldObject()
5118 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005119 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5120 if (commonRes.isInvalid())
5121 return ExprError();
5122 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005123 }
5124
5125 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5126 commonExpr->getType(),
5127 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005128 commonExpr->getObjectKind(),
5129 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005130 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005131 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005132
John McCall7decc9e2010-11-18 06:31:45 +00005133 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005134 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005135 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5136 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005137 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005138 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5139 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005140 return ExprError();
5141
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005142 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5143 RHS.get());
5144
John McCallc07a0c72011-02-17 10:25:35 +00005145 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005146 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5147 LHS.take(), ColonLoc,
5148 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005149
5150 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005151 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005152 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5153 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005154}
5155
John McCallaba90822011-01-31 23:13:11 +00005156// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005157// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005158// routine is it effectively iqnores the qualifiers on the top level pointee.
5159// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5160// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005161static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005162checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5163 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5164 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005165
Steve Naroff1f4d7272007-05-11 04:00:31 +00005166 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005167 const Type *lhptee, *rhptee;
5168 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005169 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5170 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005171
John McCallaba90822011-01-31 23:13:11 +00005172 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005173
5174 // C99 6.5.16.1p1: This following citation is common to constraints
5175 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5176 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005177 Qualifiers lq;
5178
John McCall31168b02011-06-15 23:02:42 +00005179 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5180 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5181 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5182 // Ignore lifetime for further calculation.
5183 lhq.removeObjCLifetime();
5184 rhq.removeObjCLifetime();
5185 }
5186
John McCall4fff8f62011-02-01 00:10:29 +00005187 if (!lhq.compatiblyIncludes(rhq)) {
5188 // Treat address-space mismatches as fatal. TODO: address subspaces
5189 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5190 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5191
John McCall31168b02011-06-15 23:02:42 +00005192 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005193 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005194 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005195 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005196 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005197 && (lhptee->isVoidType() || rhptee->isVoidType()))
5198 ; // keep old
5199
John McCall31168b02011-06-15 23:02:42 +00005200 // Treat lifetime mismatches as fatal.
5201 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5202 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5203
John McCall4fff8f62011-02-01 00:10:29 +00005204 // For GCC compatibility, other qualifier mismatches are treated
5205 // as still compatible in C.
5206 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5207 }
Steve Naroff3f597292007-05-11 22:18:03 +00005208
Mike Stump4e1f26a2009-02-19 03:04:26 +00005209 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5210 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005211 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005212 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005213 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005214 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005215
Chris Lattner0a788432008-01-03 22:56:36 +00005216 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005217 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005218 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005219 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005220
Chris Lattner0a788432008-01-03 22:56:36 +00005221 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005222 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005223 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005224
5225 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005226 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005227 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005228 }
John McCall4fff8f62011-02-01 00:10:29 +00005229
Mike Stump4e1f26a2009-02-19 03:04:26 +00005230 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005231 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005232 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5233 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005234 // Check if the pointee types are compatible ignoring the sign.
5235 // We explicitly check for char so that we catch "char" vs
5236 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005237 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005238 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005239 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005240 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005241
Chris Lattnerec3a1562009-10-17 20:33:28 +00005242 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005243 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005244 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005245 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005246
John McCall4fff8f62011-02-01 00:10:29 +00005247 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005248 // Types are compatible ignoring the sign. Qualifier incompatibility
5249 // takes priority over sign incompatibility because the sign
5250 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005251 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005252 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005253
John McCallaba90822011-01-31 23:13:11 +00005254 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005255 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005256
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005257 // If we are a multi-level pointer, it's possible that our issue is simply
5258 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5259 // the eventual target type is the same and the pointers have the same
5260 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005261 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005262 do {
John McCall4fff8f62011-02-01 00:10:29 +00005263 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5264 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005265 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005266
John McCall4fff8f62011-02-01 00:10:29 +00005267 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005268 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005269 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005270
Eli Friedman80160bd2009-03-22 23:59:44 +00005271 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005272 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005273 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005274 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005275 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5276 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005277 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005278}
5279
John McCallaba90822011-01-31 23:13:11 +00005280/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005281/// block pointer types are compatible or whether a block and normal pointer
5282/// are compatible. It is more restrict than comparing two function pointer
5283// types.
John McCallaba90822011-01-31 23:13:11 +00005284static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005285checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5286 QualType RHSType) {
5287 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5288 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005289
Steve Naroff081c7422008-09-04 15:10:53 +00005290 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005291
Steve Naroff081c7422008-09-04 15:10:53 +00005292 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005293 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5294 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005295
John McCallaba90822011-01-31 23:13:11 +00005296 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005297 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005298 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005299
John McCallaba90822011-01-31 23:13:11 +00005300 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005301
Steve Naroff081c7422008-09-04 15:10:53 +00005302 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005303 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5304 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005305
Richard Trieua871b972011-09-06 20:21:22 +00005306 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005307 return Sema::IncompatibleBlockPointer;
5308
Steve Naroff081c7422008-09-04 15:10:53 +00005309 return ConvTy;
5310}
5311
John McCallaba90822011-01-31 23:13:11 +00005312/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005313/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005314static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005315checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5316 QualType RHSType) {
5317 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5318 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005319
Richard Trieua871b972011-09-06 20:21:22 +00005320 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005321 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005322 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5323 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005324 return Sema::IncompatiblePointer;
5325 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005326 }
Richard Trieua871b972011-09-06 20:21:22 +00005327 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005328 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5329 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005330 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005331 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005332 }
Richard Trieua871b972011-09-06 20:21:22 +00005333 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5334 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005335
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005336 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5337 // make an exception for id<P>
5338 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005339 return Sema::CompatiblePointerDiscardsQualifiers;
5340
Richard Trieua871b972011-09-06 20:21:22 +00005341 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005342 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005343 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005344 return Sema::IncompatibleObjCQualifiedId;
5345 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005346}
5347
John McCall29600e12010-11-16 02:32:08 +00005348Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005349Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005350 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005351 // Fake up an opaque expression. We don't actually care about what
5352 // cast operations are required, so if CheckAssignmentConstraints
5353 // adds casts to this they'll be wasted, but fortunately that doesn't
5354 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005355 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5356 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005357 CastKind K = CK_Invalid;
5358
Richard Trieua871b972011-09-06 20:21:22 +00005359 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005360}
5361
Mike Stump4e1f26a2009-02-19 03:04:26 +00005362/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5363/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005364/// pointers. Here are some objectionable examples that GCC considers warnings:
5365///
5366/// int a, *pint;
5367/// short *pshort;
5368/// struct foo *pfoo;
5369///
5370/// pint = pshort; // warning: assignment from incompatible pointer type
5371/// a = pint; // warning: assignment makes integer from pointer without a cast
5372/// pint = a; // warning: assignment makes pointer from integer without a cast
5373/// pint = pfoo; // warning: assignment from incompatible pointer type
5374///
5375/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005376/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005377///
John McCall8cb679e2010-11-15 09:13:47 +00005378/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005379Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005380Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005381 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005382 QualType RHSType = RHS.get()->getType();
5383 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005384
Chris Lattnera52c2f22008-01-04 23:18:45 +00005385 // Get canonical types. We're not formatting these types, just comparing
5386 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005387 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5388 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005389
Eli Friedman0dfb8892011-10-06 23:00:33 +00005390
John McCalle5255932011-01-31 22:28:28 +00005391 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005392 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005393 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005394 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005395 }
5396
David Chisnallfa35df62012-01-16 17:27:18 +00005397 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5398 if (AtomicTy->getValueType() == RHSType) {
5399 Kind = CK_NonAtomicToAtomic;
5400 return Compatible;
5401 }
5402 }
5403
5404 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) {
5405 if (AtomicTy->getValueType() == LHSType) {
5406 Kind = CK_AtomicToNonAtomic;
5407 return Compatible;
5408 }
5409 }
5410
5411
Douglas Gregor6b754842008-10-28 00:22:11 +00005412 // If the left-hand side is a reference type, then we are in a
5413 // (rare!) case where we've allowed the use of references in C,
5414 // e.g., as a parameter type in a built-in function. In this case,
5415 // just make sure that the type referenced is compatible with the
5416 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005417 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005418 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005419 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5420 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005421 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005422 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005423 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005424 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005425 }
John McCalle5255932011-01-31 22:28:28 +00005426
Nate Begemanbd956c42009-06-28 02:36:38 +00005427 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5428 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005429 if (LHSType->isExtVectorType()) {
5430 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005431 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005432 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005433 // CK_VectorSplat does T -> vector T, so first cast to the
5434 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005435 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5436 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005437 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005438 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005439 }
5440 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005441 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005442 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005443 }
Mike Stump11289f42009-09-09 15:08:12 +00005444
John McCalle5255932011-01-31 22:28:28 +00005445 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005446 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5447 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005448 // Allow assignments of an AltiVec vector type to an equivalent GCC
5449 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005450 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005451 Kind = CK_BitCast;
5452 return Compatible;
5453 }
5454
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005455 // If we are allowing lax vector conversions, and LHS and RHS are both
5456 // vectors, the total size only needs to be the same. This is a bitcast;
5457 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005458 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005459 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005460 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005461 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005462 }
Chris Lattner881a2122008-01-04 23:32:24 +00005463 }
5464 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005465 }
Eli Friedman3360d892008-05-30 18:07:22 +00005466
John McCalle5255932011-01-31 22:28:28 +00005467 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005468 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005469 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005470 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005471 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005472 }
Eli Friedman3360d892008-05-30 18:07:22 +00005473
John McCalle5255932011-01-31 22:28:28 +00005474 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005475 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005476 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005477 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005478 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005479 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005480 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005481
John McCalle5255932011-01-31 22:28:28 +00005482 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005483 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005484 Kind = CK_IntegralToPointer; // FIXME: null?
5485 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005486 }
John McCalle5255932011-01-31 22:28:28 +00005487
5488 // C pointers are not compatible with ObjC object pointers,
5489 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005490 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005491 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005492 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005493 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005494 return Compatible;
5495 }
5496
5497 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005498 if (RHSType->isObjCClassType() &&
5499 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005500 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005501 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005502 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005503 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005504
John McCalle5255932011-01-31 22:28:28 +00005505 Kind = CK_BitCast;
5506 return IncompatiblePointer;
5507 }
5508
5509 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005510 if (RHSType->getAs<BlockPointerType>()) {
5511 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005512 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005513 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005514 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005515 }
John McCalle5255932011-01-31 22:28:28 +00005516
Steve Naroff081c7422008-09-04 15:10:53 +00005517 return Incompatible;
5518 }
5519
John McCalle5255932011-01-31 22:28:28 +00005520 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005521 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005522 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005523 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005524 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005525 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005526 }
5527
5528 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005529 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005530 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005531 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005532 }
5533
John McCalle5255932011-01-31 22:28:28 +00005534 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005535 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005536 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005537 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005538 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005539
John McCalle5255932011-01-31 22:28:28 +00005540 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005541 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005542 if (RHSPT->getPointeeType()->isVoidType()) {
5543 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005544 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005545 }
John McCall8cb679e2010-11-15 09:13:47 +00005546
Chris Lattnera52c2f22008-01-04 23:18:45 +00005547 return Incompatible;
5548 }
5549
John McCalle5255932011-01-31 22:28:28 +00005550 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005551 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005552 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005553 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005554 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005555 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005556 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005557 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005558 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005559 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005560 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005561 return result;
John McCalle5255932011-01-31 22:28:28 +00005562 }
5563
5564 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005565 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005566 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005567 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005568 }
5569
John McCalle5255932011-01-31 22:28:28 +00005570 // In general, C pointers are not compatible with ObjC object pointers,
5571 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005572 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005573 Kind = CK_CPointerToObjCPointerCast;
5574
John McCalle5255932011-01-31 22:28:28 +00005575 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005576 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005577 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005578 }
5579
5580 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005581 if (LHSType->isObjCClassType() &&
5582 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005583 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005584 return Compatible;
5585 }
5586
Steve Naroffaccc4882009-07-20 17:56:53 +00005587 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005588 }
John McCalle5255932011-01-31 22:28:28 +00005589
5590 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005591 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005592 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005593 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005594 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005595 }
5596
Steve Naroff7cae42b2009-07-10 23:34:53 +00005597 return Incompatible;
5598 }
John McCalle5255932011-01-31 22:28:28 +00005599
5600 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005601 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005602 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005603 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005604 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005605 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005606 }
Eli Friedman3360d892008-05-30 18:07:22 +00005607
John McCalle5255932011-01-31 22:28:28 +00005608 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005609 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005610 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005611 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005612 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005613
Chris Lattnera52c2f22008-01-04 23:18:45 +00005614 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005615 }
John McCalle5255932011-01-31 22:28:28 +00005616
5617 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005618 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005619 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005620 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005621 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005622 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005623 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005624
John McCalle5255932011-01-31 22:28:28 +00005625 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005626 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005627 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005628 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005629 }
5630
Steve Naroff7cae42b2009-07-10 23:34:53 +00005631 return Incompatible;
5632 }
Eli Friedman3360d892008-05-30 18:07:22 +00005633
John McCalle5255932011-01-31 22:28:28 +00005634 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005635 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5636 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005637 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005638 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005639 }
Bill Wendling216423b2007-05-30 06:30:29 +00005640 }
John McCalle5255932011-01-31 22:28:28 +00005641
Steve Naroff98cf3e92007-06-06 18:38:38 +00005642 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005643}
5644
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005645/// \brief Constructs a transparent union from an expression that is
5646/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005647static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5648 ExprResult &EResult, QualType UnionType,
5649 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005650 // Build an initializer list that designates the appropriate member
5651 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005652 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005653 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005654 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005655 SourceLocation());
5656 Initializer->setType(UnionType);
5657 Initializer->setInitializedFieldInUnion(Field);
5658
5659 // Build a compound literal constructing a value of the transparent
5660 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005661 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005662 EResult = S.Owned(
5663 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5664 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005665}
5666
5667Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005668Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005669 ExprResult &RHS) {
5670 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005671
Mike Stump11289f42009-09-09 15:08:12 +00005672 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005673 // transparent_union GCC extension.
5674 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005675 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005676 return Incompatible;
5677
5678 // The field to initialize within the transparent union.
5679 RecordDecl *UD = UT->getDecl();
5680 FieldDecl *InitField = 0;
5681 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005682 for (RecordDecl::field_iterator it = UD->field_begin(),
5683 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005684 it != itend; ++it) {
5685 if (it->getType()->isPointerType()) {
5686 // If the transparent union contains a pointer type, we allow:
5687 // 1) void pointer
5688 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005689 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005690 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005691 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005692 InitField = &*it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005693 break;
5694 }
Mike Stump11289f42009-09-09 15:08:12 +00005695
Richard Trieueb299142011-09-06 20:40:12 +00005696 if (RHS.get()->isNullPointerConstant(Context,
5697 Expr::NPC_ValueDependentIsNull)) {
5698 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5699 CK_NullToPointer);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005700 InitField = &*it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005701 break;
5702 }
5703 }
5704
John McCall8cb679e2010-11-15 09:13:47 +00005705 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005706 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005707 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005708 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005709 InitField = &*it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005710 break;
5711 }
5712 }
5713
5714 if (!InitField)
5715 return Incompatible;
5716
Richard Trieueb299142011-09-06 20:40:12 +00005717 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005718 return Compatible;
5719}
5720
Chris Lattner9bad62c2008-01-04 18:04:52 +00005721Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005722Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5723 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005724 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005725 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005726 // C++ 5.17p3: If the left operand is not of class type, the
5727 // expression is implicitly converted (C++ 4) to the
5728 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005729 ExprResult Res;
5730 if (Diagnose) {
5731 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5732 AA_Assigning);
5733 } else {
5734 ImplicitConversionSequence ICS =
5735 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5736 /*SuppressUserConversions=*/false,
5737 /*AllowExplicit=*/false,
5738 /*InOverloadResolution=*/false,
5739 /*CStyle=*/false,
5740 /*AllowObjCWritebackConversion=*/false);
5741 if (ICS.isFailure())
5742 return Incompatible;
5743 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5744 ICS, AA_Assigning);
5745 }
John Wiegley01296292011-04-08 18:41:53 +00005746 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005747 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005748 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005749 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005750 !CheckObjCARCUnavailableWeakConversion(LHSType,
5751 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005752 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005753 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005754 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005755 }
5756
5757 // FIXME: Currently, we fall through and treat C++ classes like C
5758 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005759 // FIXME: We also fall through for atomics; not sure what should
5760 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005761 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005762
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005763 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5764 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005765 if ((LHSType->isPointerType() ||
5766 LHSType->isObjCObjectPointerType() ||
5767 LHSType->isBlockPointerType())
5768 && RHS.get()->isNullPointerConstant(Context,
5769 Expr::NPC_ValueDependentIsNull)) {
5770 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005771 return Compatible;
5772 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005773
Chris Lattnere6dcd502007-10-16 02:55:40 +00005774 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005775 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005776 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005777 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005778 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005779 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005780 if (!LHSType->isReferenceType()) {
5781 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5782 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005783 return Incompatible;
5784 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005785
John McCall8cb679e2010-11-15 09:13:47 +00005786 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005787 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005788 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005789
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005790 // C99 6.5.16.1p2: The value of the right operand is converted to the
5791 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005792 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5793 // so that we can use references in built-in functions even in C.
5794 // The getNonReferenceType() call makes sure that the resulting expression
5795 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005796 if (result != Incompatible && RHS.get()->getType() != LHSType)
5797 RHS = ImpCastExprToType(RHS.take(),
5798 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005799 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005800}
5801
Richard Trieueb299142011-09-06 20:40:12 +00005802QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5803 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005804 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005805 << LHS.get()->getType() << RHS.get()->getType()
5806 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005807 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005808}
5809
Richard Trieu859d23f2011-09-06 21:01:04 +00005810QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005811 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005812 if (!IsCompAssign) {
5813 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5814 if (LHS.isInvalid())
5815 return QualType();
5816 }
5817 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5818 if (RHS.isInvalid())
5819 return QualType();
5820
Mike Stump4e1f26a2009-02-19 03:04:26 +00005821 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005822 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005823 QualType LHSType =
5824 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5825 QualType RHSType =
5826 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005827
Nate Begeman191a6b12008-07-14 18:02:46 +00005828 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005829 if (LHSType == RHSType)
5830 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005831
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005832 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005833 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5834 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5835 if (LHSType->isExtVectorType()) {
5836 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5837 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005838 }
5839
Richard Trieuba63ce62011-09-09 01:45:06 +00005840 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005841 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5842 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005843 }
5844
David Blaikiebbafb8a2012-03-11 07:00:24 +00005845 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005846 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005847 // If we are allowing lax vector conversions, and LHS and RHS are both
5848 // vectors, the total size only needs to be the same. This is a
5849 // bitcast; no bits are changed but the result type is different.
5850 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005851 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5852 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005853 }
5854
Nate Begemanbd956c42009-06-28 02:36:38 +00005855 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5856 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5857 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005858 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005859 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005860 std::swap(RHS, LHS);
5861 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005862 }
Mike Stump11289f42009-09-09 15:08:12 +00005863
Nate Begeman886448d2009-06-28 19:12:57 +00005864 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005865 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005866 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005867 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5868 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005869 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005870 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005871 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005872 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5873 if (swapped) std::swap(RHS, LHS);
5874 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005875 }
5876 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005877 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5878 RHSType->isRealFloatingType()) {
5879 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005880 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005881 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005882 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005883 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5884 if (swapped) std::swap(RHS, LHS);
5885 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005886 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005887 }
5888 }
Mike Stump11289f42009-09-09 15:08:12 +00005889
Nate Begeman886448d2009-06-28 19:12:57 +00005890 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005891 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005892 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005893 << LHS.get()->getType() << RHS.get()->getType()
5894 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005895 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005896}
5897
Richard Trieuf8916e12011-09-16 00:53:10 +00005898// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5899// expression. These are mainly cases where the null pointer is used as an
5900// integer instead of a pointer.
5901static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5902 SourceLocation Loc, bool IsCompare) {
5903 // The canonical way to check for a GNU null is with isNullPointerConstant,
5904 // but we use a bit of a hack here for speed; this is a relatively
5905 // hot path, and isNullPointerConstant is slow.
5906 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5907 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5908
5909 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5910
5911 // Avoid analyzing cases where the result will either be invalid (and
5912 // diagnosed as such) or entirely valid and not something to warn about.
5913 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5914 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5915 return;
5916
5917 // Comparison operations would not make sense with a null pointer no matter
5918 // what the other expression is.
5919 if (!IsCompare) {
5920 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5921 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5922 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5923 return;
5924 }
5925
5926 // The rest of the operations only make sense with a null pointer
5927 // if the other expression is a pointer.
5928 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5929 NonNullType->canDecayToPointerType())
5930 return;
5931
5932 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5933 << LHSNull /* LHS is NULL */ << NonNullType
5934 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5935}
5936
Richard Trieu859d23f2011-09-06 21:01:04 +00005937QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005938 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005939 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005940 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5941
Richard Trieu859d23f2011-09-06 21:01:04 +00005942 if (LHS.get()->getType()->isVectorType() ||
5943 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005944 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005945
Richard Trieuba63ce62011-09-09 01:45:06 +00005946 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005947 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005948 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005949
David Chisnallfa35df62012-01-16 17:27:18 +00005950
Richard Trieu859d23f2011-09-06 21:01:04 +00005951 if (!LHS.get()->getType()->isArithmeticType() ||
David Chisnallfa35df62012-01-16 17:27:18 +00005952 !RHS.get()->getType()->isArithmeticType()) {
5953 if (IsCompAssign &&
5954 LHS.get()->getType()->isAtomicType() &&
5955 RHS.get()->getType()->isArithmeticType())
5956 return compType;
Richard Trieu859d23f2011-09-06 21:01:04 +00005957 return InvalidOperands(Loc, LHS, RHS);
David Chisnallfa35df62012-01-16 17:27:18 +00005958 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005959
Chris Lattnerfaa54172010-01-12 21:23:57 +00005960 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005961 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005962 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005963 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005964 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5965 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005966
Chris Lattnerfaa54172010-01-12 21:23:57 +00005967 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005968}
5969
Chris Lattnerfaa54172010-01-12 21:23:57 +00005970QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005971 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005972 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5973
Richard Trieu859d23f2011-09-06 21:01:04 +00005974 if (LHS.get()->getType()->isVectorType() ||
5975 RHS.get()->getType()->isVectorType()) {
5976 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5977 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005978 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005979 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005980 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005981
Richard Trieuba63ce62011-09-09 01:45:06 +00005982 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005983 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005984 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005985
Richard Trieu859d23f2011-09-06 21:01:04 +00005986 if (!LHS.get()->getType()->isIntegerType() ||
5987 !RHS.get()->getType()->isIntegerType())
5988 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005989
Chris Lattnerfaa54172010-01-12 21:23:57 +00005990 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005991 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005992 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005993 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5994 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005995
Chris Lattnerfaa54172010-01-12 21:23:57 +00005996 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005997}
5998
Chandler Carruthc9332212011-06-27 08:02:19 +00005999/// \brief Diagnose invalid arithmetic on two void pointers.
6000static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006001 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006002 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006003 ? diag::err_typecheck_pointer_arith_void_type
6004 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006005 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6006 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006007}
6008
6009/// \brief Diagnose invalid arithmetic on a void pointer.
6010static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6011 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006012 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006013 ? diag::err_typecheck_pointer_arith_void_type
6014 : diag::ext_gnu_void_ptr)
6015 << 0 /* one pointer */ << Pointer->getSourceRange();
6016}
6017
6018/// \brief Diagnose invalid arithmetic on two function pointers.
6019static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6020 Expr *LHS, Expr *RHS) {
6021 assert(LHS->getType()->isAnyPointerType());
6022 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006023 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006024 ? diag::err_typecheck_pointer_arith_function_type
6025 : diag::ext_gnu_ptr_func_arith)
6026 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6027 // We only show the second type if it differs from the first.
6028 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6029 RHS->getType())
6030 << RHS->getType()->getPointeeType()
6031 << LHS->getSourceRange() << RHS->getSourceRange();
6032}
6033
6034/// \brief Diagnose invalid arithmetic on a function pointer.
6035static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6036 Expr *Pointer) {
6037 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006038 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006039 ? diag::err_typecheck_pointer_arith_function_type
6040 : diag::ext_gnu_ptr_func_arith)
6041 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6042 << 0 /* one pointer, so only one type */
6043 << Pointer->getSourceRange();
6044}
6045
Richard Trieu993f3ab2011-09-12 18:08:02 +00006046/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006047///
6048/// \returns True if pointer has incomplete type
6049static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6050 Expr *Operand) {
6051 if ((Operand->getType()->isPointerType() &&
6052 !Operand->getType()->isDependentType()) ||
6053 Operand->getType()->isObjCObjectPointerType()) {
6054 QualType PointeeTy = Operand->getType()->getPointeeType();
6055 if (S.RequireCompleteType(
6056 Loc, PointeeTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006057 diag::err_typecheck_arithmetic_incomplete_type,
6058 PointeeTy, Operand->getSourceRange()))
Richard Trieuaba22802011-09-02 02:15:37 +00006059 return true;
6060 }
6061 return false;
6062}
6063
Chandler Carruthc9332212011-06-27 08:02:19 +00006064/// \brief Check the validity of an arithmetic pointer operand.
6065///
6066/// If the operand has pointer type, this code will check for pointer types
6067/// which are invalid in arithmetic operations. These will be diagnosed
6068/// appropriately, including whether or not the use is supported as an
6069/// extension.
6070///
6071/// \returns True when the operand is valid to use (even if as an extension).
6072static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6073 Expr *Operand) {
6074 if (!Operand->getType()->isAnyPointerType()) return true;
6075
6076 QualType PointeeTy = Operand->getType()->getPointeeType();
6077 if (PointeeTy->isVoidType()) {
6078 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006079 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006080 }
6081 if (PointeeTy->isFunctionType()) {
6082 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006083 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006084 }
6085
Richard Trieuaba22802011-09-02 02:15:37 +00006086 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006087
6088 return true;
6089}
6090
6091/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6092/// operands.
6093///
6094/// This routine will diagnose any invalid arithmetic on pointer operands much
6095/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6096/// for emitting a single diagnostic even for operations where both LHS and RHS
6097/// are (potentially problematic) pointers.
6098///
6099/// \returns True when the operand is valid to use (even if as an extension).
6100static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006101 Expr *LHSExpr, Expr *RHSExpr) {
6102 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6103 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006104 if (!isLHSPointer && !isRHSPointer) return true;
6105
6106 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006107 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6108 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006109
6110 // Check for arithmetic on pointers to incomplete types.
6111 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6112 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6113 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006114 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6115 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6116 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006117
David Blaikiebbafb8a2012-03-11 07:00:24 +00006118 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006119 }
6120
6121 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6122 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6123 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006124 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6125 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6126 RHSExpr);
6127 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006128
David Blaikiebbafb8a2012-03-11 07:00:24 +00006129 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006130 }
6131
Richard Trieu4ae7e972011-09-06 21:13:51 +00006132 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6133 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006134
Chandler Carruthc9332212011-06-27 08:02:19 +00006135 return true;
6136}
6137
Richard Trieub10c6312011-09-01 22:53:23 +00006138/// \brief Check bad cases where we step over interface counts.
6139static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6140 SourceLocation OpLoc,
6141 Expr *Op) {
6142 assert(Op->getType()->isAnyPointerType());
6143 QualType PointeeTy = Op->getType()->getPointeeType();
6144 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6145 return true;
6146
6147 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6148 << PointeeTy << Op->getSourceRange();
6149 return false;
6150}
6151
Nico Weberccec40d2012-03-02 22:01:22 +00006152/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6153/// literal.
6154static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6155 Expr *LHSExpr, Expr *RHSExpr) {
6156 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6157 Expr* IndexExpr = RHSExpr;
6158 if (!StrExpr) {
6159 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6160 IndexExpr = LHSExpr;
6161 }
6162
6163 bool IsStringPlusInt = StrExpr &&
6164 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6165 if (!IsStringPlusInt)
6166 return;
6167
6168 llvm::APSInt index;
6169 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6170 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6171 if (index.isNonNegative() &&
6172 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6173 index.isUnsigned()))
6174 return;
6175 }
6176
6177 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6178 Self.Diag(OpLoc, diag::warn_string_plus_int)
6179 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6180
6181 // Only print a fixit for "str" + int, not for int + "str".
6182 if (IndexExpr == RHSExpr) {
6183 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6184 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6185 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6186 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6187 << FixItHint::CreateInsertion(EndLoc, "]");
6188 } else
6189 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6190}
6191
Richard Trieu993f3ab2011-09-12 18:08:02 +00006192/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006193static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006194 Expr *LHSExpr, Expr *RHSExpr) {
6195 assert(LHSExpr->getType()->isAnyPointerType());
6196 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006197 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006198 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6199 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006200}
6201
Chris Lattnerfaa54172010-01-12 21:23:57 +00006202QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006203 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6204 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006205 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6206
Richard Trieu4ae7e972011-09-06 21:13:51 +00006207 if (LHS.get()->getType()->isVectorType() ||
6208 RHS.get()->getType()->isVectorType()) {
6209 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006210 if (CompLHSTy) *CompLHSTy = compType;
6211 return compType;
6212 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006213
Richard Trieu4ae7e972011-09-06 21:13:51 +00006214 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6215 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006216 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006217
Nico Weberccec40d2012-03-02 22:01:22 +00006218 // Diagnose "string literal" '+' int.
6219 if (Opc == BO_Add)
6220 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6221
Steve Naroffe4718892007-04-27 18:30:00 +00006222 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006223 if (LHS.get()->getType()->isArithmeticType() &&
6224 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006225 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006226 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006227 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006228
David Chisnallfa35df62012-01-16 17:27:18 +00006229 if (LHS.get()->getType()->isAtomicType() &&
6230 RHS.get()->getType()->isArithmeticType()) {
6231 *CompLHSTy = LHS.get()->getType();
6232 return compType;
6233 }
6234
Eli Friedman8e122982008-05-18 18:08:51 +00006235 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006236 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006237 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006238 std::swap(PExp, IExp);
6239
Richard Trieub420bca2011-09-12 18:37:54 +00006240 if (!PExp->getType()->isAnyPointerType())
6241 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006242
Richard Trieub420bca2011-09-12 18:37:54 +00006243 if (!IExp->getType()->isIntegerType())
6244 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006245
Richard Trieub420bca2011-09-12 18:37:54 +00006246 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6247 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006248
Richard Trieub420bca2011-09-12 18:37:54 +00006249 // Diagnose bad cases where we step over interface counts.
6250 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6251 return QualType();
6252
6253 // Check array bounds for pointer arithemtic
6254 CheckArrayAccess(PExp, IExp);
6255
6256 if (CompLHSTy) {
6257 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6258 if (LHSTy.isNull()) {
6259 LHSTy = LHS.get()->getType();
6260 if (LHSTy->isPromotableIntegerType())
6261 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006262 }
Richard Trieub420bca2011-09-12 18:37:54 +00006263 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006264 }
6265
Richard Trieub420bca2011-09-12 18:37:54 +00006266 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006267}
6268
Chris Lattner2a3569b2008-04-07 05:30:13 +00006269// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006270QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006271 SourceLocation Loc,
6272 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006273 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6274
Richard Trieu4ae7e972011-09-06 21:13:51 +00006275 if (LHS.get()->getType()->isVectorType() ||
6276 RHS.get()->getType()->isVectorType()) {
6277 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006278 if (CompLHSTy) *CompLHSTy = compType;
6279 return compType;
6280 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006281
Richard Trieu4ae7e972011-09-06 21:13:51 +00006282 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6283 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006284 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006285
Chris Lattner4d62f422007-12-09 21:53:25 +00006286 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006287
Chris Lattner4d62f422007-12-09 21:53:25 +00006288 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006289 if (LHS.get()->getType()->isArithmeticType() &&
6290 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006291 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006292 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006293 }
Mike Stump11289f42009-09-09 15:08:12 +00006294
David Chisnallfa35df62012-01-16 17:27:18 +00006295 if (LHS.get()->getType()->isAtomicType() &&
6296 RHS.get()->getType()->isArithmeticType()) {
6297 *CompLHSTy = LHS.get()->getType();
6298 return compType;
6299 }
6300
Chris Lattner4d62f422007-12-09 21:53:25 +00006301 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006302 if (LHS.get()->getType()->isAnyPointerType()) {
6303 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006304
Chris Lattner12bdebb2009-04-24 23:50:08 +00006305 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006306 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006307 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006308
Chris Lattner4d62f422007-12-09 21:53:25 +00006309 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006310 if (RHS.get()->getType()->isIntegerType()) {
6311 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006312 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006313
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006314 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006315 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6316 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006317
Richard Trieu4ae7e972011-09-06 21:13:51 +00006318 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6319 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006320 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006321
Chris Lattner4d62f422007-12-09 21:53:25 +00006322 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006323 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006324 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006325 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006326
David Blaikiebbafb8a2012-03-11 07:00:24 +00006327 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006328 // Pointee types must be the same: C++ [expr.add]
6329 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006330 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006331 }
6332 } else {
6333 // Pointee types must be compatible C99 6.5.6p3
6334 if (!Context.typesAreCompatible(
6335 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6336 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006337 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006338 return QualType();
6339 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006340 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006341
Chandler Carruthc9332212011-06-27 08:02:19 +00006342 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006343 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006344 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006345
Richard Trieu4ae7e972011-09-06 21:13:51 +00006346 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006347 return Context.getPointerDiffType();
6348 }
6349 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006350
Richard Trieu4ae7e972011-09-06 21:13:51 +00006351 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006352}
6353
Douglas Gregor0bf31402010-10-08 23:50:27 +00006354static bool isScopedEnumerationType(QualType T) {
6355 if (const EnumType *ET = dyn_cast<EnumType>(T))
6356 return ET->getDecl()->isScoped();
6357 return false;
6358}
6359
Richard Trieue4a19fb2011-09-06 21:21:28 +00006360static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006361 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006362 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006363 llvm::APSInt Right;
6364 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006365 if (RHS.get()->isValueDependent() ||
6366 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006367 return;
6368
6369 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006370 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006371 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006372 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006373 return;
6374 }
6375 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006376 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006377 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006378 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006379 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006380 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006381 return;
6382 }
6383 if (Opc != BO_Shl)
6384 return;
6385
6386 // When left shifting an ICE which is signed, we can check for overflow which
6387 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6388 // integers have defined behavior modulo one more than the maximum value
6389 // representable in the result type, so never warn for those.
6390 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006391 if (LHS.get()->isValueDependent() ||
6392 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6393 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006394 return;
6395 llvm::APInt ResultBits =
6396 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6397 if (LeftBits.uge(ResultBits))
6398 return;
6399 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6400 Result = Result.shl(Right);
6401
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006402 // Print the bit representation of the signed integer as an unsigned
6403 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006404 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006405 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6406
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006407 // If we are only missing a sign bit, this is less likely to result in actual
6408 // bugs -- if the result is cast back to an unsigned type, it will have the
6409 // expected value. Thus we place this behind a different warning that can be
6410 // turned off separately if needed.
6411 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006412 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006413 << HexResult.str() << LHSType
6414 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006415 return;
6416 }
6417
6418 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006419 << HexResult.str() << Result.getMinSignedBits() << LHSType
6420 << Left.getBitWidth() << LHS.get()->getSourceRange()
6421 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006422}
6423
Chris Lattner2a3569b2008-04-07 05:30:13 +00006424// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006425QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006426 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006427 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006428 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6429
Chris Lattner5c11c412007-12-12 05:47:28 +00006430 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006431 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6432 !RHS.get()->getType()->hasIntegerRepresentation())
6433 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006434
Douglas Gregor0bf31402010-10-08 23:50:27 +00006435 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6436 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006437 if (isScopedEnumerationType(LHS.get()->getType()) ||
6438 isScopedEnumerationType(RHS.get()->getType())) {
6439 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006440 }
6441
Nate Begemane46ee9a2009-10-25 02:26:48 +00006442 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006443 if (LHS.get()->getType()->isVectorType() ||
6444 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006445 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006446
Chris Lattner5c11c412007-12-12 05:47:28 +00006447 // Shifts don't perform usual arithmetic conversions, they just do integer
6448 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006449
John McCall57cdd882010-12-16 19:28:59 +00006450 // For the LHS, do usual unary conversions, but then reset them away
6451 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006452 ExprResult OldLHS = LHS;
6453 LHS = UsualUnaryConversions(LHS.take());
6454 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006455 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006456 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006457 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006458
6459 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006460 RHS = UsualUnaryConversions(RHS.take());
6461 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006462 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006463
Ryan Flynnf53fab82009-08-07 16:20:20 +00006464 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006465 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006466
Chris Lattner5c11c412007-12-12 05:47:28 +00006467 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006468 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006469}
6470
Chandler Carruth17773fc2010-07-10 12:30:03 +00006471static bool IsWithinTemplateSpecialization(Decl *D) {
6472 if (DeclContext *DC = D->getDeclContext()) {
6473 if (isa<ClassTemplateSpecializationDecl>(DC))
6474 return true;
6475 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6476 return FD->isFunctionTemplateSpecialization();
6477 }
6478 return false;
6479}
6480
Richard Trieueea56f72011-09-02 03:48:46 +00006481/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006482static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6483 ExprResult &RHS) {
6484 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6485 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006486
6487 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6488 if (!LHSEnumType)
6489 return;
6490 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6491 if (!RHSEnumType)
6492 return;
6493
6494 // Ignore anonymous enums.
6495 if (!LHSEnumType->getDecl()->getIdentifier())
6496 return;
6497 if (!RHSEnumType->getDecl()->getIdentifier())
6498 return;
6499
6500 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6501 return;
6502
6503 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6504 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006505 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006506}
6507
Richard Trieudd82a5c2011-09-02 02:55:45 +00006508/// \brief Diagnose bad pointer comparisons.
6509static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006510 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006511 bool IsError) {
6512 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006513 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006514 << LHS.get()->getType() << RHS.get()->getType()
6515 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006516}
6517
6518/// \brief Returns false if the pointers are converted to a composite type,
6519/// true otherwise.
6520static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006521 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006522 // C++ [expr.rel]p2:
6523 // [...] Pointer conversions (4.10) and qualification
6524 // conversions (4.4) are performed on pointer operands (or on
6525 // a pointer operand and a null pointer constant) to bring
6526 // them to their composite pointer type. [...]
6527 //
6528 // C++ [expr.eq]p1 uses the same notion for (in)equality
6529 // comparisons of pointers.
6530
6531 // C++ [expr.eq]p2:
6532 // In addition, pointers to members can be compared, or a pointer to
6533 // member and a null pointer constant. Pointer to member conversions
6534 // (4.11) and qualification conversions (4.4) are performed to bring
6535 // them to a common type. If one operand is a null pointer constant,
6536 // the common type is the type of the other operand. Otherwise, the
6537 // common type is a pointer to member type similar (4.4) to the type
6538 // of one of the operands, with a cv-qualification signature (4.4)
6539 // that is the union of the cv-qualification signatures of the operand
6540 // types.
6541
Richard Trieu1762d7c2011-09-06 21:27:33 +00006542 QualType LHSType = LHS.get()->getType();
6543 QualType RHSType = RHS.get()->getType();
6544 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6545 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006546
6547 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006548 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006549 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006550 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006551 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006552 return true;
6553 }
6554
6555 if (NonStandardCompositeType)
6556 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006557 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6558 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006559
Richard Trieu1762d7c2011-09-06 21:27:33 +00006560 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6561 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006562 return false;
6563}
6564
6565static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006566 ExprResult &LHS,
6567 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006568 bool IsError) {
6569 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6570 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006571 << LHS.get()->getType() << RHS.get()->getType()
6572 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006573}
6574
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006575// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006576QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006577 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006578 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006579 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6580
John McCalle3027922010-08-25 11:45:40 +00006581 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006582
Chris Lattner9a152e22009-12-05 05:40:13 +00006583 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006584 if (LHS.get()->getType()->isVectorType() ||
6585 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006586 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006587
Richard Trieub80728f2011-09-06 21:43:51 +00006588 QualType LHSType = LHS.get()->getType();
6589 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006590
Richard Trieub80728f2011-09-06 21:43:51 +00006591 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6592 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006593
Richard Trieub80728f2011-09-06 21:43:51 +00006594 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006595
Richard Trieub80728f2011-09-06 21:43:51 +00006596 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006597 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006598 !LHS.get()->getLocStart().isMacroID() &&
6599 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006600 // For non-floating point types, check for self-comparisons of the form
6601 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6602 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006603 //
6604 // NOTE: Don't warn about comparison expressions resulting from macro
6605 // expansion. Also don't warn about comparisons which are only self
6606 // comparisons within a template specialization. The warnings should catch
6607 // obvious cases in the definition of the template anyways. The idea is to
6608 // warn when the typed comparison operator will always evaluate to the same
6609 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006610 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006611 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006612 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006613 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006614 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006615 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006616 << (Opc == BO_EQ
6617 || Opc == BO_LE
6618 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006619 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006620 !DRL->getDecl()->getType()->isReferenceType() &&
6621 !DRR->getDecl()->getType()->isReferenceType()) {
6622 // what is it always going to eval to?
6623 char always_evals_to;
6624 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006625 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006626 always_evals_to = 0; // false
6627 break;
John McCalle3027922010-08-25 11:45:40 +00006628 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006629 always_evals_to = 1; // true
6630 break;
6631 default:
6632 // best we can say is 'a constant'
6633 always_evals_to = 2; // e.g. array1 <= array2
6634 break;
6635 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006636 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006637 << 1 // array
6638 << always_evals_to);
6639 }
6640 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006641 }
Mike Stump11289f42009-09-09 15:08:12 +00006642
Chris Lattner222b8bd2009-03-08 19:39:53 +00006643 if (isa<CastExpr>(LHSStripped))
6644 LHSStripped = LHSStripped->IgnoreParenCasts();
6645 if (isa<CastExpr>(RHSStripped))
6646 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006647
Chris Lattner222b8bd2009-03-08 19:39:53 +00006648 // Warn about comparisons against a string constant (unless the other
6649 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006650 Expr *literalString = 0;
6651 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006652 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006653 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006654 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006655 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006656 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006657 } else if ((isa<StringLiteral>(RHSStripped) ||
6658 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006659 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006660 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006661 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006662 literalStringStripped = RHSStripped;
6663 }
6664
6665 if (literalString) {
6666 std::string resultComparison;
6667 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006668 case BO_LT: resultComparison = ") < 0"; break;
6669 case BO_GT: resultComparison = ") > 0"; break;
6670 case BO_LE: resultComparison = ") <= 0"; break;
6671 case BO_GE: resultComparison = ") >= 0"; break;
6672 case BO_EQ: resultComparison = ") == 0"; break;
6673 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006674 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006675 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006676
Ted Kremenek3427fac2011-02-23 01:52:04 +00006677 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006678 PDiag(diag::warn_stringcompare)
6679 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006680 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006681 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006682 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006683
Douglas Gregorec170db2010-06-08 19:50:34 +00006684 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006685 if (LHS.get()->getType()->isArithmeticType() &&
6686 RHS.get()->getType()->isArithmeticType()) {
6687 UsualArithmeticConversions(LHS, RHS);
6688 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006689 return QualType();
6690 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006691 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006692 LHS = UsualUnaryConversions(LHS.take());
6693 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006694 return QualType();
6695
Richard Trieub80728f2011-09-06 21:43:51 +00006696 RHS = UsualUnaryConversions(RHS.take());
6697 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006698 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006699 }
6700
Richard Trieub80728f2011-09-06 21:43:51 +00006701 LHSType = LHS.get()->getType();
6702 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006703
Douglas Gregorca63811b2008-11-19 03:25:36 +00006704 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006705 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006706
Richard Trieuba63ce62011-09-09 01:45:06 +00006707 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006708 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006709 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006710 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006711 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006712 if (LHSType->hasFloatingRepresentation())
6713 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006714
Richard Trieub80728f2011-09-06 21:43:51 +00006715 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006716 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006717 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006718
Richard Trieub80728f2011-09-06 21:43:51 +00006719 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006720 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006721 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006722 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006723
Douglas Gregorf267edd2010-06-15 21:38:40 +00006724 // All of the following pointer-related warnings are GCC extensions, except
6725 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006726 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006727 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006728 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006729 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006730 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006731
David Blaikiebbafb8a2012-03-11 07:00:24 +00006732 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006733 if (LCanPointeeTy == RCanPointeeTy)
6734 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006735 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006736 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6737 // Valid unless comparison between non-null pointer and function pointer
6738 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006739 // In a SFINAE context, we treat this as a hard error to maintain
6740 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006741 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6742 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006743 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006744 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006745
6746 if (isSFINAEContext())
6747 return QualType();
6748
Richard Trieub80728f2011-09-06 21:43:51 +00006749 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006750 return ResultTy;
6751 }
6752 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006753
Richard Trieub80728f2011-09-06 21:43:51 +00006754 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006755 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006756 else
6757 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006758 }
Eli Friedman16c209612009-08-23 00:27:47 +00006759 // C99 6.5.9p2 and C99 6.5.8p2
6760 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6761 RCanPointeeTy.getUnqualifiedType())) {
6762 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006763 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006764 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006765 << LHSType << RHSType << LHS.get()->getSourceRange()
6766 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006767 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006768 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006769 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6770 // Valid unless comparison between non-null pointer and function pointer
6771 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006772 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006773 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006774 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006775 } else {
6776 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006777 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006778 }
John McCall7684dde2011-03-11 04:25:25 +00006779 if (LCanPointeeTy != RCanPointeeTy) {
6780 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006781 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006782 else
Richard Trieub80728f2011-09-06 21:43:51 +00006783 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006784 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006785 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006786 }
Mike Stump11289f42009-09-09 15:08:12 +00006787
David Blaikiebbafb8a2012-03-11 07:00:24 +00006788 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006789 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006790 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006791 return ResultTy;
6792
Mike Stump11289f42009-09-09 15:08:12 +00006793 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006794 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006795 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006796 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006797 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006798 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6799 RHS = ImpCastExprToType(RHS.take(), LHSType,
6800 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006801 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006802 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006803 return ResultTy;
6804 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006805 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006806 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006807 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006808 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6809 LHS = ImpCastExprToType(LHS.take(), RHSType,
6810 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006811 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006812 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006813 return ResultTy;
6814 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006815
6816 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006817 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006818 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6819 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006820 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006821 else
6822 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006823 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006824
6825 // Handle scoped enumeration types specifically, since they don't promote
6826 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006827 if (LHS.get()->getType()->isEnumeralType() &&
6828 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6829 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006830 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006831 }
Mike Stump11289f42009-09-09 15:08:12 +00006832
Steve Naroff081c7422008-09-04 15:10:53 +00006833 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006834 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006835 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006836 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6837 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006838
Steve Naroff081c7422008-09-04 15:10:53 +00006839 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006840 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006841 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006842 << LHSType << RHSType << LHS.get()->getSourceRange()
6843 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006844 }
Richard Trieub80728f2011-09-06 21:43:51 +00006845 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006846 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006847 }
John Wiegley01296292011-04-08 18:41:53 +00006848
Steve Naroffe18f94c2008-09-28 01:11:11 +00006849 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006850 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006851 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6852 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006853 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006854 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006855 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006856 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006857 ->getPointeeType()->isVoidType())))
6858 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006859 << LHSType << RHSType << LHS.get()->getSourceRange()
6860 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006861 }
John McCall7684dde2011-03-11 04:25:25 +00006862 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006863 LHS = ImpCastExprToType(LHS.take(), RHSType,
6864 RHSType->isPointerType() ? CK_BitCast
6865 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006866 else
John McCall9320b872011-09-09 05:25:32 +00006867 RHS = ImpCastExprToType(RHS.take(), LHSType,
6868 LHSType->isPointerType() ? CK_BitCast
6869 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006870 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006871 }
Steve Naroff081c7422008-09-04 15:10:53 +00006872
Richard Trieub80728f2011-09-06 21:43:51 +00006873 if (LHSType->isObjCObjectPointerType() ||
6874 RHSType->isObjCObjectPointerType()) {
6875 const PointerType *LPT = LHSType->getAs<PointerType>();
6876 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006877 if (LPT || RPT) {
6878 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6879 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006880
Steve Naroff753567f2008-11-17 19:49:16 +00006881 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006882 !Context.typesAreCompatible(LHSType, RHSType)) {
6883 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006884 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006885 }
John McCall7684dde2011-03-11 04:25:25 +00006886 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006887 LHS = ImpCastExprToType(LHS.take(), RHSType,
6888 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006889 else
John McCall9320b872011-09-09 05:25:32 +00006890 RHS = ImpCastExprToType(RHS.take(), LHSType,
6891 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006892 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006893 }
Richard Trieub80728f2011-09-06 21:43:51 +00006894 if (LHSType->isObjCObjectPointerType() &&
6895 RHSType->isObjCObjectPointerType()) {
6896 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6897 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006898 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006899 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006900 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006901 else
Richard Trieub80728f2011-09-06 21:43:51 +00006902 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006903 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006904 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006905 }
Richard Trieub80728f2011-09-06 21:43:51 +00006906 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6907 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006908 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006909 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006910 if ((LHSIsNull && LHSType->isIntegerType()) ||
6911 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006912 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006913 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006914 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006915 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00006916 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00006917 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6918 isError = true;
6919 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006920 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006921
Chris Lattnerd99bd522009-08-23 00:03:44 +00006922 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006923 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006924 << LHSType << RHSType << LHS.get()->getSourceRange()
6925 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006926 if (isError)
6927 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006928 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006929
Richard Trieub80728f2011-09-06 21:43:51 +00006930 if (LHSType->isIntegerType())
6931 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006932 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006933 else
Richard Trieub80728f2011-09-06 21:43:51 +00006934 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006935 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006936 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006937 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006938
Steve Naroff4b191572008-09-04 16:56:14 +00006939 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006940 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006941 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6942 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006943 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006944 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006945 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006946 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6947 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006948 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006949 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006950
Richard Trieub80728f2011-09-06 21:43:51 +00006951 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006952}
6953
Tanya Lattner20248222012-01-16 21:02:28 +00006954
6955// Return a signed type that is of identical size and number of elements.
6956// For floating point vectors, return an integer type of identical size
6957// and number of elements.
6958QualType Sema::GetSignedVectorType(QualType V) {
6959 const VectorType *VTy = V->getAs<VectorType>();
6960 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6961 if (TypeSize == Context.getTypeSize(Context.CharTy))
6962 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6963 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6964 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6965 else if (TypeSize == Context.getTypeSize(Context.IntTy))
6966 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6967 else if (TypeSize == Context.getTypeSize(Context.LongTy))
6968 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6969 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6970 "Unhandled vector element size in vector compare");
6971 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6972}
6973
Nate Begeman191a6b12008-07-14 18:02:46 +00006974/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006975/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006976/// like a scalar comparison, a vector comparison produces a vector of integer
6977/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006978QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006979 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006980 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006981 // Check to make sure we're operating on vectors of the same type and width,
6982 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006983 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006984 if (vType.isNull())
6985 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006986
Richard Trieubcce2f72011-09-07 01:19:57 +00006987 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006988
Anton Yartsev530deb92011-03-27 15:36:07 +00006989 // If AltiVec, the comparison results in a numeric type, i.e.
6990 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006991 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006992 return Context.getLogicalOperationType();
6993
Nate Begeman191a6b12008-07-14 18:02:46 +00006994 // For non-floating point types, check for self-comparisons of the form
6995 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6996 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006997 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00006998 if (DeclRefExpr* DRL
6999 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7000 if (DeclRefExpr* DRR
7001 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007002 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007003 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007004 PDiag(diag::warn_comparison_always)
7005 << 0 // self-
7006 << 2 // "a constant"
7007 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007008 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007009
Nate Begeman191a6b12008-07-14 18:02:46 +00007010 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007011 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007012 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007013 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007014 }
Tanya Lattner20248222012-01-16 21:02:28 +00007015
7016 // Return a signed type for the vector.
7017 return GetSignedVectorType(LHSType);
7018}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007019
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007020QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7021 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007022 // Ensure that either both operands are of the same vector type, or
7023 // one operand is of a vector type and the other is of its element type.
7024 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7025 if (vType.isNull() || vType->isFloatingType())
7026 return InvalidOperands(Loc, LHS, RHS);
7027
7028 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007029}
7030
Steve Naroff218bc2b2007-05-04 21:54:46 +00007031inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007032 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007033 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7034
Richard Trieubcce2f72011-09-07 01:19:57 +00007035 if (LHS.get()->getType()->isVectorType() ||
7036 RHS.get()->getType()->isVectorType()) {
7037 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7038 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007039 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007040
Richard Trieubcce2f72011-09-07 01:19:57 +00007041 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007042 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007043
Richard Trieubcce2f72011-09-07 01:19:57 +00007044 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7045 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007046 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007047 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007048 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007049 LHS = LHSResult.take();
7050 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007051
Richard Trieubcce2f72011-09-07 01:19:57 +00007052 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7053 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007054 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007055 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007056}
7057
Steve Naroff218bc2b2007-05-04 21:54:46 +00007058inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007059 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007060
Tanya Lattner20248222012-01-16 21:02:28 +00007061 // Check vector operands differently.
7062 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7063 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7064
Chris Lattner8406c512010-07-13 19:41:32 +00007065 // Diagnose cases where the user write a logical and/or but probably meant a
7066 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7067 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007068 if (LHS.get()->getType()->isIntegerType() &&
7069 !LHS.get()->getType()->isBooleanType() &&
7070 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007071 // Don't warn in macros or template instantiations.
7072 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007073 // If the RHS can be constant folded, and if it constant folds to something
7074 // that isn't 0 or 1 (which indicate a potential logical operation that
7075 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007076 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007077 llvm::APSInt Result;
7078 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007079 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007080 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007081 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007082 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007083 << (Opc == BO_LAnd ? "&&" : "||");
7084 // Suggest replacing the logical operator with the bitwise version
7085 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7086 << (Opc == BO_LAnd ? "&" : "|")
7087 << FixItHint::CreateReplacement(SourceRange(
7088 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007089 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007090 Opc == BO_LAnd ? "&" : "|");
7091 if (Opc == BO_LAnd)
7092 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7093 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7094 << FixItHint::CreateRemoval(
7095 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007096 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007097 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007098 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007099 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007100 }
Chris Lattner938533d2010-07-24 01:10:11 +00007101 }
Chris Lattner8406c512010-07-13 19:41:32 +00007102
David Blaikiebbafb8a2012-03-11 07:00:24 +00007103 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007104 LHS = UsualUnaryConversions(LHS.take());
7105 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007106 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007107
Richard Trieubcce2f72011-09-07 01:19:57 +00007108 RHS = UsualUnaryConversions(RHS.take());
7109 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007110 return QualType();
7111
Richard Trieubcce2f72011-09-07 01:19:57 +00007112 if (!LHS.get()->getType()->isScalarType() ||
7113 !RHS.get()->getType()->isScalarType())
7114 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007115
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007116 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007117 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007118
John McCall4a2429a2010-06-04 00:29:51 +00007119 // The following is safe because we only use this method for
7120 // non-overloadable operands.
7121
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007122 // C++ [expr.log.and]p1
7123 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007124 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007125 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7126 if (LHSRes.isInvalid())
7127 return InvalidOperands(Loc, LHS, RHS);
7128 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007129
Richard Trieubcce2f72011-09-07 01:19:57 +00007130 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7131 if (RHSRes.isInvalid())
7132 return InvalidOperands(Loc, LHS, RHS);
7133 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007134
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007135 // C++ [expr.log.and]p2
7136 // C++ [expr.log.or]p2
7137 // The result is a bool.
7138 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007139}
7140
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007141/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7142/// is a read-only property; return true if so. A readonly property expression
7143/// depends on various declarations and thus must be treated specially.
7144///
Mike Stump11289f42009-09-09 15:08:12 +00007145static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007146 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7147 if (!PropExpr) return false;
7148 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007149
John McCall526ab472011-10-25 17:37:35 +00007150 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7151 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007152 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007153 PropExpr->getBase()->getType();
7154
John McCall526ab472011-10-25 17:37:35 +00007155 if (const ObjCObjectPointerType *OPT =
7156 BaseType->getAsObjCInterfacePointerType())
7157 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7158 if (S.isPropertyReadonly(PDecl, IFace))
7159 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007160 return false;
7161}
7162
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007163static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007164 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7165 if (!ME) return false;
7166 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7167 ObjCMessageExpr *Base =
7168 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7169 if (!Base) return false;
7170 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007171}
7172
John McCall5fa2ef42012-03-13 00:37:01 +00007173/// Is the given expression (which must be 'const') a reference to a
7174/// variable which was originally non-const, but which has become
7175/// 'const' due to being captured within a block?
7176enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7177static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7178 assert(E->isLValue() && E->getType().isConstQualified());
7179 E = E->IgnoreParens();
7180
7181 // Must be a reference to a declaration from an enclosing scope.
7182 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7183 if (!DRE) return NCCK_None;
7184 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7185
7186 // The declaration must be a variable which is not declared 'const'.
7187 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7188 if (!var) return NCCK_None;
7189 if (var->getType().isConstQualified()) return NCCK_None;
7190 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7191
7192 // Decide whether the first capture was for a block or a lambda.
7193 DeclContext *DC = S.CurContext;
7194 while (DC->getParent() != var->getDeclContext())
7195 DC = DC->getParent();
7196 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7197}
7198
Chris Lattner30bd3272008-11-18 01:22:49 +00007199/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7200/// emit an error and return true. If so, return false.
7201static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007202 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007203 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007204 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007205 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007206 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7207 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007208 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7209 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007210 if (IsLV == Expr::MLV_Valid)
7211 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007212
Chris Lattner30bd3272008-11-18 01:22:49 +00007213 unsigned Diag = 0;
7214 bool NeedType = false;
7215 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007216 case Expr::MLV_ConstQualified:
7217 Diag = diag::err_typecheck_assign_const;
7218
John McCall5fa2ef42012-03-13 00:37:01 +00007219 // Use a specialized diagnostic when we're assigning to an object
7220 // from an enclosing function or block.
7221 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7222 if (NCCK == NCCK_Block)
7223 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7224 else
7225 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7226 break;
7227 }
7228
John McCalld4631322011-06-17 06:42:21 +00007229 // In ARC, use some specialized diagnostics for occasions where we
7230 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007231 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007232 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7233 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7234 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7235
John McCalld4631322011-06-17 06:42:21 +00007236 // Use the normal diagnostic if it's pseudo-__strong but the
7237 // user actually wrote 'const'.
7238 if (var->isARCPseudoStrong() &&
7239 (!var->getTypeSourceInfo() ||
7240 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7241 // There are two pseudo-strong cases:
7242 // - self
John McCall31168b02011-06-15 23:02:42 +00007243 ObjCMethodDecl *method = S.getCurMethodDecl();
7244 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007245 Diag = method->isClassMethod()
7246 ? diag::err_typecheck_arc_assign_self_class_method
7247 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007248
7249 // - fast enumeration variables
7250 else
John McCall31168b02011-06-15 23:02:42 +00007251 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007252
John McCall31168b02011-06-15 23:02:42 +00007253 SourceRange Assign;
7254 if (Loc != OrigLoc)
7255 Assign = SourceRange(OrigLoc, OrigLoc);
7256 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7257 // We need to preserve the AST regardless, so migration tool
7258 // can do its job.
7259 return false;
7260 }
7261 }
7262 }
7263
7264 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007265 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007266 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7267 NeedType = true;
7268 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007269 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007270 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7271 NeedType = true;
7272 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007273 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007274 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7275 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007276 case Expr::MLV_Valid:
7277 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007278 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007279 case Expr::MLV_MemberFunction:
7280 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007281 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7282 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007283 case Expr::MLV_IncompleteType:
7284 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007285 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007286 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007287 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007288 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7289 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007290 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007291 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007292 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007293 case Expr::MLV_InvalidMessageExpression:
7294 Diag = diag::error_readonly_message_assignment;
7295 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007296 case Expr::MLV_SubObjCPropertySetting:
7297 Diag = diag::error_no_subobject_property_setting;
7298 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007299 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007300
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007301 SourceRange Assign;
7302 if (Loc != OrigLoc)
7303 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007304 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007305 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007306 else
Mike Stump11289f42009-09-09 15:08:12 +00007307 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007308 return true;
7309}
7310
7311
7312
7313// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007314QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007315 SourceLocation Loc,
7316 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007317 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7318
Chris Lattner326f7572008-11-18 01:30:42 +00007319 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007320 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007321 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007322
Richard Trieuda4f43a62011-09-07 01:33:52 +00007323 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007324 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7325 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007326 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007327 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007328 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007329 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007330 if (RHS.isInvalid())
7331 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007332 // Special case of NSObject attributes on c-style pointer types.
7333 if (ConvTy == IncompatiblePointer &&
7334 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007335 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007336 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007337 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007338 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007339
John McCall7decc9e2010-11-18 06:31:45 +00007340 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007341 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007342 Diag(Loc, diag::err_objc_object_assignment)
7343 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007344
Chris Lattnerea714382008-08-21 18:04:13 +00007345 // If the RHS is a unary plus or minus, check to see if they = and + are
7346 // right next to each other. If so, the user may have typo'd "x =+ 4"
7347 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007348 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007349 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7350 RHSCheck = ICE->getSubExpr();
7351 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007352 if ((UO->getOpcode() == UO_Plus ||
7353 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007354 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007355 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007356 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007357 // And there is a space or other character before the subexpr of the
7358 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007359 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007360 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007361 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007362 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007363 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007364 }
Chris Lattnerea714382008-08-21 18:04:13 +00007365 }
John McCall31168b02011-06-15 23:02:42 +00007366
7367 if (ConvTy == Compatible) {
7368 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007369 checkRetainCycles(LHSExpr, RHS.get());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007370 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007371 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007372 }
Chris Lattnerea714382008-08-21 18:04:13 +00007373 } else {
7374 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007375 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007376 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007377
Chris Lattner326f7572008-11-18 01:30:42 +00007378 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007379 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007380 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007381
Richard Trieuda4f43a62011-09-07 01:33:52 +00007382 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007383
Steve Naroff98cf3e92007-06-06 18:38:38 +00007384 // C99 6.5.16p3: The type of an assignment expression is the type of the
7385 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007386 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007387 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7388 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007389 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007390 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007391 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007392 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007393}
7394
Chris Lattner326f7572008-11-18 01:30:42 +00007395// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007396static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007397 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007398 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007399
John McCall3aef3d82011-04-10 19:13:55 +00007400 LHS = S.CheckPlaceholderExpr(LHS.take());
7401 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007402 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007403 return QualType();
7404
John McCall73d36182010-10-12 07:14:40 +00007405 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7406 // operands, but not unary promotions.
7407 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007408
John McCall34376a62010-12-04 03:47:34 +00007409 // So we treat the LHS as a ignored value, and in C++ we allow the
7410 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007411 LHS = S.IgnoredValueConversions(LHS.take());
7412 if (LHS.isInvalid())
7413 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007414
David Blaikiebbafb8a2012-03-11 07:00:24 +00007415 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007416 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7417 if (RHS.isInvalid())
7418 return QualType();
7419 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007420 S.RequireCompleteType(Loc, RHS.get()->getType(),
7421 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007422 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007423
John Wiegley01296292011-04-08 18:41:53 +00007424 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007425}
7426
Steve Naroff7a5af782007-07-13 16:58:59 +00007427/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7428/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007429static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7430 ExprValueKind &VK,
7431 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007432 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007433 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007434 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007435
Chris Lattner6b0cf142008-11-21 07:05:48 +00007436 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007437 // Atomic types can be used for increment / decrement where the non-atomic
7438 // versions can, so ignore the _Atomic() specifier for the purpose of
7439 // checking.
7440 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7441 ResType = ResAtomicType->getValueType();
7442
Chris Lattner6b0cf142008-11-21 07:05:48 +00007443 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007444
David Blaikiebbafb8a2012-03-11 07:00:24 +00007445 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007446 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007447 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007448 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007449 return QualType();
7450 }
7451 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007452 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007453 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007454 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007455 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007456 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007457 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007458 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007459
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007460 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007461 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007462 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007463 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007464 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007465 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007466 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007467 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007468 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007469 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007470 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007471 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007472 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007473 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007474 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007475 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007476 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007477 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007478 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007479 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007480 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007481 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007482 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007483 // In C++, a prefix increment is the same type as the operand. Otherwise
7484 // (in C or with postfix), the increment is the unqualified type of the
7485 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007486 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007487 VK = VK_LValue;
7488 return ResType;
7489 } else {
7490 VK = VK_RValue;
7491 return ResType.getUnqualifiedType();
7492 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007493}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007494
7495
Anders Carlsson806700f2008-02-01 07:15:58 +00007496/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007497/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007498/// where the declaration is needed for type checking. We only need to
7499/// handle cases when the expression references a function designator
7500/// or is an lvalue. Here are some examples:
7501/// - &(x) => x
7502/// - &*****f => f for f a function designator.
7503/// - &s.xx => s
7504/// - &s.zz[1].yy -> s, if zz is an array
7505/// - *(x + 1) -> x, if x is an array
7506/// - &"123"[2] -> 0
7507/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007508static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007509 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007510 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007511 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007512 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007513 // If this is an arrow operator, the address is an offset from
7514 // the base's value, so the object the base refers to is
7515 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007516 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007517 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007518 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007519 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007520 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007521 // FIXME: This code shouldn't be necessary! We should catch the implicit
7522 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007523 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7524 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7525 if (ICE->getSubExpr()->getType()->isArrayType())
7526 return getPrimaryDecl(ICE->getSubExpr());
7527 }
7528 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007529 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007530 case Stmt::UnaryOperatorClass: {
7531 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007532
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007533 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007534 case UO_Real:
7535 case UO_Imag:
7536 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007537 return getPrimaryDecl(UO->getSubExpr());
7538 default:
7539 return 0;
7540 }
7541 }
Steve Naroff47500512007-04-19 23:00:49 +00007542 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007543 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007544 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007545 // If the result of an implicit cast is an l-value, we care about
7546 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007547 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007548 default:
7549 return 0;
7550 }
7551}
7552
Richard Trieu5f376f62011-09-07 21:46:33 +00007553namespace {
7554 enum {
7555 AO_Bit_Field = 0,
7556 AO_Vector_Element = 1,
7557 AO_Property_Expansion = 2,
7558 AO_Register_Variable = 3,
7559 AO_No_Error = 4
7560 };
7561}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007562/// \brief Diagnose invalid operand for address of operations.
7563///
7564/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007565static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7566 Expr *E, unsigned Type) {
7567 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7568}
7569
Steve Naroff47500512007-04-19 23:00:49 +00007570/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007571/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007572/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007573/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007574/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007575/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007576/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007577static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007578 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007579 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7580 if (PTy->getKind() == BuiltinType::Overload) {
7581 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7582 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7583 << OrigOp.get()->getSourceRange();
7584 return QualType();
7585 }
7586
7587 return S.Context.OverloadTy;
7588 }
7589
7590 if (PTy->getKind() == BuiltinType::UnknownAny)
7591 return S.Context.UnknownAnyTy;
7592
7593 if (PTy->getKind() == BuiltinType::BoundMember) {
7594 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7595 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007596 return QualType();
7597 }
John McCall526ab472011-10-25 17:37:35 +00007598
7599 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7600 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007601 }
John McCall8d08b9b2010-08-27 09:08:28 +00007602
John McCall526ab472011-10-25 17:37:35 +00007603 if (OrigOp.get()->isTypeDependent())
7604 return S.Context.DependentTy;
7605
7606 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007607
John McCall8d08b9b2010-08-27 09:08:28 +00007608 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007609 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007610
David Blaikiebbafb8a2012-03-11 07:00:24 +00007611 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007612 // Implement C99-only parts of addressof rules.
7613 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007614 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007615 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7616 // (assuming the deref expression is valid).
7617 return uOp->getSubExpr()->getType();
7618 }
7619 // Technically, there should be a check for array subscript
7620 // expressions here, but the result of one is always an lvalue anyway.
7621 }
John McCallf3a88602011-02-03 08:15:49 +00007622 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007623 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007624 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007625
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007626 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007627 bool sfinae = S.isSFINAEContext();
7628 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7629 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007630 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007631 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007632 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007633 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007634 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007635 } else if (lval == Expr::LV_MemberFunction) {
7636 // If it's an instance method, make a member pointer.
7637 // The expression must have exactly the form &A::foo.
7638
7639 // If the underlying expression isn't a decl ref, give up.
7640 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007641 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007642 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007643 return QualType();
7644 }
7645 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7646 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7647
7648 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007649 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007650 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007651 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007652
7653 // The method was named without a qualifier.
7654 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007655 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007656 << op->getSourceRange();
7657 }
7658
John McCall4bc41ae2010-11-18 19:01:18 +00007659 return S.Context.getMemberPointerType(op->getType(),
7660 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007661 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007662 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007663 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007664 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007665 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007666 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007667 AddressOfError = AO_Property_Expansion;
7668 } else {
7669 // FIXME: emit more specific diag...
7670 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7671 << op->getSourceRange();
7672 return QualType();
7673 }
Steve Naroff35d85152007-05-07 00:24:15 +00007674 }
John McCall086a4642010-11-24 05:12:34 +00007675 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007676 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007677 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007678 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007679 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007680 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007681 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007682 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007683 // with the register storage-class specifier.
7684 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007685 // in C++ it is not error to take address of a register
7686 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007687 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007688 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007689 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007690 }
John McCalld14a8642009-11-21 08:51:07 +00007691 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007692 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007693 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007694 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007695 // Could be a pointer to member, though, if there is an explicit
7696 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007697 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007698 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007699 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007700 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007701 S.Diag(OpLoc,
7702 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007703 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007704 return QualType();
7705 }
Mike Stump11289f42009-09-09 15:08:12 +00007706
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007707 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7708 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007709 return S.Context.getMemberPointerType(op->getType(),
7710 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007711 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007712 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007713 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007714 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007715 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007716
Richard Trieu5f376f62011-09-07 21:46:33 +00007717 if (AddressOfError != AO_No_Error) {
7718 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7719 return QualType();
7720 }
7721
Eli Friedmance7f9002009-05-16 23:27:50 +00007722 if (lval == Expr::LV_IncompleteVoidType) {
7723 // Taking the address of a void variable is technically illegal, but we
7724 // allow it in cases which are otherwise valid.
7725 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007726 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007727 }
7728
Steve Naroff47500512007-04-19 23:00:49 +00007729 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007730 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007731 return S.Context.getObjCObjectPointerType(op->getType());
7732 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007733}
7734
Chris Lattner9156f1b2010-07-05 19:17:26 +00007735/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007736static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7737 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007738 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007739 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007740
John Wiegley01296292011-04-08 18:41:53 +00007741 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7742 if (ConvResult.isInvalid())
7743 return QualType();
7744 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007745 QualType OpTy = Op->getType();
7746 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007747
7748 if (isa<CXXReinterpretCastExpr>(Op)) {
7749 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7750 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7751 Op->getSourceRange());
7752 }
7753
Chris Lattner9156f1b2010-07-05 19:17:26 +00007754 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7755 // is an incomplete type or void. It would be possible to warn about
7756 // dereferencing a void pointer, but it's completely well-defined, and such a
7757 // warning is unlikely to catch any mistakes.
7758 if (const PointerType *PT = OpTy->getAs<PointerType>())
7759 Result = PT->getPointeeType();
7760 else if (const ObjCObjectPointerType *OPT =
7761 OpTy->getAs<ObjCObjectPointerType>())
7762 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007763 else {
John McCall3aef3d82011-04-10 19:13:55 +00007764 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007765 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007766 if (PR.take() != Op)
7767 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007768 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007769
Chris Lattner9156f1b2010-07-05 19:17:26 +00007770 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007771 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007772 << OpTy << Op->getSourceRange();
7773 return QualType();
7774 }
John McCall4bc41ae2010-11-18 19:01:18 +00007775
7776 // Dereferences are usually l-values...
7777 VK = VK_LValue;
7778
7779 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007780 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007781 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007782
7783 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007784}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007785
John McCalle3027922010-08-25 11:45:40 +00007786static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007787 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007788 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007789 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007790 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007791 case tok::periodstar: Opc = BO_PtrMemD; break;
7792 case tok::arrowstar: Opc = BO_PtrMemI; break;
7793 case tok::star: Opc = BO_Mul; break;
7794 case tok::slash: Opc = BO_Div; break;
7795 case tok::percent: Opc = BO_Rem; break;
7796 case tok::plus: Opc = BO_Add; break;
7797 case tok::minus: Opc = BO_Sub; break;
7798 case tok::lessless: Opc = BO_Shl; break;
7799 case tok::greatergreater: Opc = BO_Shr; break;
7800 case tok::lessequal: Opc = BO_LE; break;
7801 case tok::less: Opc = BO_LT; break;
7802 case tok::greaterequal: Opc = BO_GE; break;
7803 case tok::greater: Opc = BO_GT; break;
7804 case tok::exclaimequal: Opc = BO_NE; break;
7805 case tok::equalequal: Opc = BO_EQ; break;
7806 case tok::amp: Opc = BO_And; break;
7807 case tok::caret: Opc = BO_Xor; break;
7808 case tok::pipe: Opc = BO_Or; break;
7809 case tok::ampamp: Opc = BO_LAnd; break;
7810 case tok::pipepipe: Opc = BO_LOr; break;
7811 case tok::equal: Opc = BO_Assign; break;
7812 case tok::starequal: Opc = BO_MulAssign; break;
7813 case tok::slashequal: Opc = BO_DivAssign; break;
7814 case tok::percentequal: Opc = BO_RemAssign; break;
7815 case tok::plusequal: Opc = BO_AddAssign; break;
7816 case tok::minusequal: Opc = BO_SubAssign; break;
7817 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7818 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7819 case tok::ampequal: Opc = BO_AndAssign; break;
7820 case tok::caretequal: Opc = BO_XorAssign; break;
7821 case tok::pipeequal: Opc = BO_OrAssign; break;
7822 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007823 }
7824 return Opc;
7825}
7826
John McCalle3027922010-08-25 11:45:40 +00007827static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007828 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007829 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007830 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007831 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007832 case tok::plusplus: Opc = UO_PreInc; break;
7833 case tok::minusminus: Opc = UO_PreDec; break;
7834 case tok::amp: Opc = UO_AddrOf; break;
7835 case tok::star: Opc = UO_Deref; break;
7836 case tok::plus: Opc = UO_Plus; break;
7837 case tok::minus: Opc = UO_Minus; break;
7838 case tok::tilde: Opc = UO_Not; break;
7839 case tok::exclaim: Opc = UO_LNot; break;
7840 case tok::kw___real: Opc = UO_Real; break;
7841 case tok::kw___imag: Opc = UO_Imag; break;
7842 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007843 }
7844 return Opc;
7845}
7846
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007847/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7848/// This warning is only emitted for builtin assignment operations. It is also
7849/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007850static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007851 SourceLocation OpLoc) {
7852 if (!S.ActiveTemplateInstantiations.empty())
7853 return;
7854 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7855 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007856 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7857 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7858 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7859 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7860 if (!LHSDeclRef || !RHSDeclRef ||
7861 LHSDeclRef->getLocation().isMacroID() ||
7862 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007863 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007864 const ValueDecl *LHSDecl =
7865 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7866 const ValueDecl *RHSDecl =
7867 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7868 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007869 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007870 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007871 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007872 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007873 if (RefTy->getPointeeType().isVolatileQualified())
7874 return;
7875
7876 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007877 << LHSDeclRef->getType()
7878 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007879}
7880
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007881/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7882/// operator @p Opc at location @c TokLoc. This routine only supports
7883/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007884ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007885 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007886 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007887 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00007888 // The syntax only allows initializer lists on the RHS of assignment,
7889 // so we don't need to worry about accepting invalid code for
7890 // non-assignment operators.
7891 // C++11 5.17p9:
7892 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
7893 // of x = {} is x = T().
7894 InitializationKind Kind =
7895 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
7896 InitializedEntity Entity =
7897 InitializedEntity::InitializeTemporary(LHSExpr->getType());
7898 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
7899 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
7900 MultiExprArg(&RHSExpr, 1));
7901 if (Init.isInvalid())
7902 return Init;
7903 RHSExpr = Init.take();
7904 }
7905
Richard Trieu4a287fb2011-09-07 01:49:20 +00007906 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007907 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007908 // The following two variables are used for compound assignment operators
7909 QualType CompLHSTy; // Type of LHS after promotions for computation
7910 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007911 ExprValueKind VK = VK_RValue;
7912 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007913
7914 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007915 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007916 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007917 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007918 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7919 VK = LHS.get()->getValueKind();
7920 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007921 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007922 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007923 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007924 break;
John McCalle3027922010-08-25 11:45:40 +00007925 case BO_PtrMemD:
7926 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007927 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007928 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007929 break;
John McCalle3027922010-08-25 11:45:40 +00007930 case BO_Mul:
7931 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007932 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007933 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007934 break;
John McCalle3027922010-08-25 11:45:40 +00007935 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007936 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007937 break;
John McCalle3027922010-08-25 11:45:40 +00007938 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00007939 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007940 break;
John McCalle3027922010-08-25 11:45:40 +00007941 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007942 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007943 break;
John McCalle3027922010-08-25 11:45:40 +00007944 case BO_Shl:
7945 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007946 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007947 break;
John McCalle3027922010-08-25 11:45:40 +00007948 case BO_LE:
7949 case BO_LT:
7950 case BO_GE:
7951 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007952 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007953 break;
John McCalle3027922010-08-25 11:45:40 +00007954 case BO_EQ:
7955 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007956 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007957 break;
John McCalle3027922010-08-25 11:45:40 +00007958 case BO_And:
7959 case BO_Xor:
7960 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007961 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007962 break;
John McCalle3027922010-08-25 11:45:40 +00007963 case BO_LAnd:
7964 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007965 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007966 break;
John McCalle3027922010-08-25 11:45:40 +00007967 case BO_MulAssign:
7968 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007969 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007970 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007971 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007972 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7973 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007974 break;
John McCalle3027922010-08-25 11:45:40 +00007975 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007976 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007977 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007978 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7979 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007980 break;
John McCalle3027922010-08-25 11:45:40 +00007981 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00007982 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00007983 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7984 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007985 break;
John McCalle3027922010-08-25 11:45:40 +00007986 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007987 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7988 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7989 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007990 break;
John McCalle3027922010-08-25 11:45:40 +00007991 case BO_ShlAssign:
7992 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007993 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007994 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007995 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7996 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007997 break;
John McCalle3027922010-08-25 11:45:40 +00007998 case BO_AndAssign:
7999 case BO_XorAssign:
8000 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008001 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008002 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008003 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8004 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008005 break;
John McCalle3027922010-08-25 11:45:40 +00008006 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008007 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008008 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008009 VK = RHS.get()->getValueKind();
8010 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008011 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008012 break;
8013 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008014 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008015 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008016
8017 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008018 CheckArrayAccess(LHS.get());
8019 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008020
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008021 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008022 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008023 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008024 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008025 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008026 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008027 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008028 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008029 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008030 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008031 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008032}
8033
Sebastian Redl44615072009-10-27 12:10:02 +00008034/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8035/// operators are mixed in a way that suggests that the programmer forgot that
8036/// comparison operators have higher precedence. The most typical example of
8037/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008038static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008039 SourceLocation OpLoc, Expr *LHSExpr,
8040 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008041 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008042 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8043 RHSopc = static_cast<BinOp::Opcode>(-1);
8044 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8045 LHSopc = BO->getOpcode();
8046 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8047 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008048
8049 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008050 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008051 return;
8052
8053 // Bitwise operations are sometimes used as eager logical ops.
8054 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008055 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8056 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008057 return;
8058
Richard Trieu4a287fb2011-09-07 01:49:20 +00008059 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8060 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008061 if (!isLeftComp && !isRightComp) return;
8062
Richard Trieu4a287fb2011-09-07 01:49:20 +00008063 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8064 OpLoc)
8065 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8066 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8067 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008068 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008069 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8070 RHSExpr->getLocEnd())
8071 : SourceRange(LHSExpr->getLocStart(),
8072 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008073
8074 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8075 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8076 SuggestParentheses(Self, OpLoc,
8077 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008078 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008079 SuggestParentheses(Self, OpLoc,
8080 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8081 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008082}
8083
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008084/// \brief It accepts a '&' expr that is inside a '|' one.
8085/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8086/// in parentheses.
8087static void
8088EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8089 BinaryOperator *Bop) {
8090 assert(Bop->getOpcode() == BO_And);
8091 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8092 << Bop->getSourceRange() << OpLoc;
8093 SuggestParentheses(Self, Bop->getOperatorLoc(),
8094 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8095 Bop->getSourceRange());
8096}
8097
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008098/// \brief It accepts a '&&' expr that is inside a '||' one.
8099/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8100/// in parentheses.
8101static void
8102EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008103 BinaryOperator *Bop) {
8104 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008105 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8106 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008107 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008108 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008109 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008110}
8111
8112/// \brief Returns true if the given expression can be evaluated as a constant
8113/// 'true'.
8114static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8115 bool Res;
8116 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8117}
8118
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008119/// \brief Returns true if the given expression can be evaluated as a constant
8120/// 'false'.
8121static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8122 bool Res;
8123 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8124}
8125
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008126/// \brief Look for '&&' in the left hand of a '||' expr.
8127static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008128 Expr *LHSExpr, Expr *RHSExpr) {
8129 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008130 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008131 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008132 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008133 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008134 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8135 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8136 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8137 } else if (Bop->getOpcode() == BO_LOr) {
8138 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8139 // If it's "a || b && 1 || c" we didn't warn earlier for
8140 // "a || b && 1", but warn now.
8141 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8142 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8143 }
8144 }
8145 }
8146}
8147
8148/// \brief Look for '&&' in the right hand of a '||' expr.
8149static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008150 Expr *LHSExpr, Expr *RHSExpr) {
8151 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008152 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008153 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008154 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008155 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008156 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8157 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8158 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008159 }
8160 }
8161}
8162
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008163/// \brief Look for '&' in the left or right hand of a '|' expr.
8164static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8165 Expr *OrArg) {
8166 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8167 if (Bop->getOpcode() == BO_And)
8168 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8169 }
8170}
8171
Sebastian Redl43028242009-10-26 15:24:15 +00008172/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008173/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008174static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008175 SourceLocation OpLoc, Expr *LHSExpr,
8176 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008177 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008178 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008179 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008180
8181 // Diagnose "arg1 & arg2 | arg3"
8182 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008183 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8184 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008185 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008186
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008187 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8188 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008189 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008190 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8191 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008192 }
Sebastian Redl43028242009-10-26 15:24:15 +00008193}
8194
Steve Naroff218bc2b2007-05-04 21:54:46 +00008195// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008196ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008197 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008198 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008199 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008200 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8201 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008202
Sebastian Redl43028242009-10-26 15:24:15 +00008203 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008204 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008205
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008206 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008207}
8208
John McCall526ab472011-10-25 17:37:35 +00008209/// Build an overloaded binary operator expression in the given scope.
8210static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8211 BinaryOperatorKind Opc,
8212 Expr *LHS, Expr *RHS) {
8213 // Find all of the overloaded operators visible from this
8214 // point. We perform both an operator-name lookup from the local
8215 // scope and an argument-dependent lookup based on the types of
8216 // the arguments.
8217 UnresolvedSet<16> Functions;
8218 OverloadedOperatorKind OverOp
8219 = BinaryOperator::getOverloadedOperator(Opc);
8220 if (Sc && OverOp != OO_None)
8221 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8222 RHS->getType(), Functions);
8223
8224 // Build the (potentially-overloaded, potentially-dependent)
8225 // binary operation.
8226 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8227}
8228
John McCalldadc5752010-08-24 06:29:42 +00008229ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008230 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008231 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008232 // We want to end up calling one of checkPseudoObjectAssignment
8233 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8234 // both expressions are overloadable or either is type-dependent),
8235 // or CreateBuiltinBinOp (in any other case). We also want to get
8236 // any placeholder types out of the way.
8237
John McCall526ab472011-10-25 17:37:35 +00008238 // Handle pseudo-objects in the LHS.
8239 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8240 // Assignments with a pseudo-object l-value need special analysis.
8241 if (pty->getKind() == BuiltinType::PseudoObject &&
8242 BinaryOperator::isAssignmentOp(Opc))
8243 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8244
8245 // Don't resolve overloads if the other type is overloadable.
8246 if (pty->getKind() == BuiltinType::Overload) {
8247 // We can't actually test that if we still have a placeholder,
8248 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008249 // code below are valid when the LHS is an overload set. Note
8250 // that an overload set can be dependently-typed, but it never
8251 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008252 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8253 if (resolvedRHS.isInvalid()) return ExprError();
8254 RHSExpr = resolvedRHS.take();
8255
John McCall9a43e122011-10-28 01:04:34 +00008256 if (RHSExpr->isTypeDependent() ||
8257 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008258 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8259 }
8260
8261 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8262 if (LHS.isInvalid()) return ExprError();
8263 LHSExpr = LHS.take();
8264 }
8265
8266 // Handle pseudo-objects in the RHS.
8267 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8268 // An overload in the RHS can potentially be resolved by the type
8269 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008270 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8271 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8272 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8273
Eli Friedman419b1ff2012-01-17 21:27:43 +00008274 if (LHSExpr->getType()->isOverloadableType())
8275 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8276
John McCall526ab472011-10-25 17:37:35 +00008277 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008278 }
John McCall526ab472011-10-25 17:37:35 +00008279
8280 // Don't resolve overloads if the other type is overloadable.
8281 if (pty->getKind() == BuiltinType::Overload &&
8282 LHSExpr->getType()->isOverloadableType())
8283 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8284
8285 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8286 if (!resolvedRHS.isUsable()) return ExprError();
8287 RHSExpr = resolvedRHS.take();
8288 }
8289
David Blaikiebbafb8a2012-03-11 07:00:24 +00008290 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008291 // If either expression is type-dependent, always build an
8292 // overloaded op.
8293 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8294 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008295
John McCall9a43e122011-10-28 01:04:34 +00008296 // Otherwise, build an overloaded op if either expression has an
8297 // overloadable type.
8298 if (LHSExpr->getType()->isOverloadableType() ||
8299 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008300 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008301 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008302
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008303 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008304 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008305}
8306
John McCalldadc5752010-08-24 06:29:42 +00008307ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008308 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008309 Expr *InputExpr) {
8310 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008311 ExprValueKind VK = VK_RValue;
8312 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008313 QualType resultType;
8314 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008315 case UO_PreInc:
8316 case UO_PreDec:
8317 case UO_PostInc:
8318 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008319 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008320 Opc == UO_PreInc ||
8321 Opc == UO_PostInc,
8322 Opc == UO_PreInc ||
8323 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008324 break;
John McCalle3027922010-08-25 11:45:40 +00008325 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008326 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008327 break;
John McCall31996342011-04-07 08:22:57 +00008328 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008329 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8330 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008331 break;
John McCall31996342011-04-07 08:22:57 +00008332 }
John McCalle3027922010-08-25 11:45:40 +00008333 case UO_Plus:
8334 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008335 Input = UsualUnaryConversions(Input.take());
8336 if (Input.isInvalid()) return ExprError();
8337 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008338 if (resultType->isDependentType())
8339 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008340 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8341 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008342 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008343 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008344 resultType->isEnumeralType())
8345 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008346 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008347 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008348 resultType->isPointerType())
8349 break;
8350
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008351 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008352 << resultType << Input.get()->getSourceRange());
8353
John McCalle3027922010-08-25 11:45:40 +00008354 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008355 Input = UsualUnaryConversions(Input.take());
8356 if (Input.isInvalid()) return ExprError();
8357 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008358 if (resultType->isDependentType())
8359 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008360 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8361 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8362 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008363 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008364 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008365 else if (resultType->hasIntegerRepresentation())
8366 break;
John McCall526ab472011-10-25 17:37:35 +00008367 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008368 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008369 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008370 }
Steve Naroff35d85152007-05-07 00:24:15 +00008371 break;
John Wiegley01296292011-04-08 18:41:53 +00008372
John McCalle3027922010-08-25 11:45:40 +00008373 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008374 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008375 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8376 if (Input.isInvalid()) return ExprError();
8377 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008378
8379 // Though we still have to promote half FP to float...
8380 if (resultType->isHalfType()) {
8381 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8382 resultType = Context.FloatTy;
8383 }
8384
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008385 if (resultType->isDependentType())
8386 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008387 if (resultType->isScalarType()) {
8388 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008389 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008390 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8391 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008392 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8393 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008394 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008395 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008396 // Vector logical not returns the signed variant of the operand type.
8397 resultType = GetSignedVectorType(resultType);
8398 break;
John McCall36226622010-10-12 02:09:17 +00008399 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008400 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008401 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008402 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008403
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008404 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008405 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008406 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008407 break;
John McCalle3027922010-08-25 11:45:40 +00008408 case UO_Real:
8409 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008410 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008411 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8412 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008413 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008414 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8415 if (Input.get()->getValueKind() != VK_RValue &&
8416 Input.get()->getObjectKind() == OK_Ordinary)
8417 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008418 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008419 // In C, a volatile scalar is read by __imag. In C++, it is not.
8420 Input = DefaultLvalueConversion(Input.take());
8421 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008422 break;
John McCalle3027922010-08-25 11:45:40 +00008423 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008424 resultType = Input.get()->getType();
8425 VK = Input.get()->getValueKind();
8426 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008427 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008428 }
John Wiegley01296292011-04-08 18:41:53 +00008429 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008430 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008431
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008432 // Check for array bounds violations in the operand of the UnaryOperator,
8433 // except for the '*' and '&' operators that have to be handled specially
8434 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8435 // that are explicitly defined as valid by the standard).
8436 if (Opc != UO_AddrOf && Opc != UO_Deref)
8437 CheckArrayAccess(Input.get());
8438
John Wiegley01296292011-04-08 18:41:53 +00008439 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008440 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008441}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008442
Douglas Gregor72341032011-12-14 21:23:13 +00008443/// \brief Determine whether the given expression is a qualified member
8444/// access expression, of a form that could be turned into a pointer to member
8445/// with the address-of operator.
8446static bool isQualifiedMemberAccess(Expr *E) {
8447 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8448 if (!DRE->getQualifier())
8449 return false;
8450
8451 ValueDecl *VD = DRE->getDecl();
8452 if (!VD->isCXXClassMember())
8453 return false;
8454
8455 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8456 return true;
8457 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8458 return Method->isInstance();
8459
8460 return false;
8461 }
8462
8463 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8464 if (!ULE->getQualifier())
8465 return false;
8466
8467 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8468 DEnd = ULE->decls_end();
8469 D != DEnd; ++D) {
8470 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8471 if (Method->isInstance())
8472 return true;
8473 } else {
8474 // Overload set does not contain methods.
8475 break;
8476 }
8477 }
8478
8479 return false;
8480 }
8481
8482 return false;
8483}
8484
John McCalldadc5752010-08-24 06:29:42 +00008485ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008486 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008487 // First things first: handle placeholders so that the
8488 // overloaded-operator check considers the right type.
8489 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8490 // Increment and decrement of pseudo-object references.
8491 if (pty->getKind() == BuiltinType::PseudoObject &&
8492 UnaryOperator::isIncrementDecrementOp(Opc))
8493 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8494
8495 // extension is always a builtin operator.
8496 if (Opc == UO_Extension)
8497 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8498
8499 // & gets special logic for several kinds of placeholder.
8500 // The builtin code knows what to do.
8501 if (Opc == UO_AddrOf &&
8502 (pty->getKind() == BuiltinType::Overload ||
8503 pty->getKind() == BuiltinType::UnknownAny ||
8504 pty->getKind() == BuiltinType::BoundMember))
8505 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8506
8507 // Anything else needs to be handled now.
8508 ExprResult Result = CheckPlaceholderExpr(Input);
8509 if (Result.isInvalid()) return ExprError();
8510 Input = Result.take();
8511 }
8512
David Blaikiebbafb8a2012-03-11 07:00:24 +00008513 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008514 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8515 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008516 // Find all of the overloaded operators visible from this
8517 // point. We perform both an operator-name lookup from the local
8518 // scope and an argument-dependent lookup based on the types of
8519 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008520 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008521 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008522 if (S && OverOp != OO_None)
8523 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8524 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008525
John McCallb268a282010-08-23 23:25:46 +00008526 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008527 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008528
John McCallb268a282010-08-23 23:25:46 +00008529 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008530}
8531
Douglas Gregor5287f092009-11-05 00:51:44 +00008532// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008533ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008534 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008535 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008536}
8537
Steve Naroff66356bd2007-09-16 14:56:35 +00008538/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008539ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008540 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008541 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008542 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008543 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008544 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008545}
8546
John McCall31168b02011-06-15 23:02:42 +00008547/// Given the last statement in a statement-expression, check whether
8548/// the result is a producing expression (like a call to an
8549/// ns_returns_retained function) and, if so, rebuild it to hoist the
8550/// release out of the full-expression. Otherwise, return null.
8551/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008552static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008553 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008554 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008555 if (!cleanups) return 0;
8556
8557 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008558 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008559 return 0;
8560
8561 // Splice out the cast. This shouldn't modify any interesting
8562 // features of the statement.
8563 Expr *producer = cast->getSubExpr();
8564 assert(producer->getType() == cast->getType());
8565 assert(producer->getValueKind() == cast->getValueKind());
8566 cleanups->setSubExpr(producer);
8567 return cleanups;
8568}
8569
John McCall3abee492012-04-04 01:27:53 +00008570void Sema::ActOnStartStmtExpr() {
8571 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8572}
8573
8574void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008575 // Note that function is also called by TreeTransform when leaving a
8576 // StmtExpr scope without rebuilding anything.
8577
John McCall3abee492012-04-04 01:27:53 +00008578 DiscardCleanupsInEvaluationContext();
8579 PopExpressionEvaluationContext();
8580}
8581
John McCalldadc5752010-08-24 06:29:42 +00008582ExprResult
John McCallb268a282010-08-23 23:25:46 +00008583Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008584 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008585 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8586 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8587
John McCall3abee492012-04-04 01:27:53 +00008588 if (hasAnyUnrecoverableErrorsInThisFunction())
8589 DiscardCleanupsInEvaluationContext();
8590 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8591 PopExpressionEvaluationContext();
8592
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008593 bool isFileScope
8594 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008595 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008596 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008597
Chris Lattner366727f2007-07-24 16:58:17 +00008598 // FIXME: there are a variety of strange constraints to enforce here, for
8599 // example, it is not possible to goto into a stmt expression apparently.
8600 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008601
Chris Lattner366727f2007-07-24 16:58:17 +00008602 // If there are sub stmts in the compound stmt, take the type of the last one
8603 // as the type of the stmtexpr.
8604 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008605 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008606 if (!Compound->body_empty()) {
8607 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008608 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008609 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008610 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8611 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008612 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008613 }
John McCall31168b02011-06-15 23:02:42 +00008614
John Wiegley01296292011-04-08 18:41:53 +00008615 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008616 // Do function/array conversion on the last expression, but not
8617 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008618 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8619 if (LastExpr.isInvalid())
8620 return ExprError();
8621 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008622
John Wiegley01296292011-04-08 18:41:53 +00008623 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008624 // In ARC, if the final expression ends in a consume, splice
8625 // the consume out and bind it later. In the alternate case
8626 // (when dealing with a retainable type), the result
8627 // initialization will create a produce. In both cases the
8628 // result will be +1, and we'll need to balance that out with
8629 // a bind.
8630 if (Expr *rebuiltLastStmt
8631 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8632 LastExpr = rebuiltLastStmt;
8633 } else {
8634 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008635 InitializedEntity::InitializeResult(LPLoc,
8636 Ty,
8637 false),
8638 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008639 LastExpr);
8640 }
8641
John Wiegley01296292011-04-08 18:41:53 +00008642 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008643 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008644 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008645 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008646 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008647 else
John Wiegley01296292011-04-08 18:41:53 +00008648 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008649 StmtExprMayBindToTemp = true;
8650 }
8651 }
8652 }
Chris Lattner944d3062008-07-26 19:51:01 +00008653 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008654
Eli Friedmanba961a92009-03-23 00:24:07 +00008655 // FIXME: Check that expression type is complete/non-abstract; statement
8656 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008657 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8658 if (StmtExprMayBindToTemp)
8659 return MaybeBindToTemporary(ResStmtExpr);
8660 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008661}
Steve Naroff78864672007-08-01 22:05:33 +00008662
John McCalldadc5752010-08-24 06:29:42 +00008663ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008664 TypeSourceInfo *TInfo,
8665 OffsetOfComponent *CompPtr,
8666 unsigned NumComponents,
8667 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008668 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008669 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008670 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008671
Chris Lattnerf17bd422007-08-30 17:45:32 +00008672 // We must have at least one component that refers to the type, and the first
8673 // one is known to be a field designator. Verify that the ArgTy represents
8674 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008675 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008676 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8677 << ArgTy << TypeRange);
8678
8679 // Type must be complete per C99 7.17p3 because a declaring a variable
8680 // with an incomplete type would be ill-formed.
8681 if (!Dependent
8682 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008683 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00008684 return ExprError();
8685
Chris Lattner78502cf2007-08-31 21:49:13 +00008686 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8687 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008688 // FIXME: This diagnostic isn't actually visible because the location is in
8689 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008690 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008691 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8692 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008693
8694 bool DidWarnAboutNonPOD = false;
8695 QualType CurrentType = ArgTy;
8696 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008697 SmallVector<OffsetOfNode, 4> Comps;
8698 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008699 for (unsigned i = 0; i != NumComponents; ++i) {
8700 const OffsetOfComponent &OC = CompPtr[i];
8701 if (OC.isBrackets) {
8702 // Offset of an array sub-field. TODO: Should we allow vector elements?
8703 if (!CurrentType->isDependentType()) {
8704 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8705 if(!AT)
8706 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8707 << CurrentType);
8708 CurrentType = AT->getElementType();
8709 } else
8710 CurrentType = Context.DependentTy;
8711
Richard Smith9fcc5c32011-10-17 23:29:39 +00008712 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8713 if (IdxRval.isInvalid())
8714 return ExprError();
8715 Expr *Idx = IdxRval.take();
8716
Douglas Gregor882211c2010-04-28 22:16:22 +00008717 // The expression must be an integral expression.
8718 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008719 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8720 !Idx->getType()->isIntegerType())
8721 return ExprError(Diag(Idx->getLocStart(),
8722 diag::err_typecheck_subscript_not_integer)
8723 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008724
Douglas Gregor882211c2010-04-28 22:16:22 +00008725 // Record this array index.
8726 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008727 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008728 continue;
8729 }
8730
8731 // Offset of a field.
8732 if (CurrentType->isDependentType()) {
8733 // We have the offset of a field, but we can't look into the dependent
8734 // type. Just record the identifier of the field.
8735 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8736 CurrentType = Context.DependentTy;
8737 continue;
8738 }
8739
8740 // We need to have a complete type to look into.
8741 if (RequireCompleteType(OC.LocStart, CurrentType,
8742 diag::err_offsetof_incomplete_type))
8743 return ExprError();
8744
8745 // Look for the designated field.
8746 const RecordType *RC = CurrentType->getAs<RecordType>();
8747 if (!RC)
8748 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8749 << CurrentType);
8750 RecordDecl *RD = RC->getDecl();
8751
8752 // C++ [lib.support.types]p5:
8753 // The macro offsetof accepts a restricted set of type arguments in this
8754 // International Standard. type shall be a POD structure or a POD union
8755 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008756 // C++11 [support.types]p4:
8757 // If type is not a standard-layout class (Clause 9), the results are
8758 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00008759 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008760 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
8761 unsigned DiagID =
8762 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
8763 : diag::warn_offsetof_non_pod_type;
8764
8765 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008766 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008767 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00008768 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8769 << CurrentType))
8770 DidWarnAboutNonPOD = true;
8771 }
8772
8773 // Look for the field.
8774 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8775 LookupQualifiedName(R, RD);
8776 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008777 IndirectFieldDecl *IndirectMemberDecl = 0;
8778 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008779 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008780 MemberDecl = IndirectMemberDecl->getAnonField();
8781 }
8782
Douglas Gregor882211c2010-04-28 22:16:22 +00008783 if (!MemberDecl)
8784 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8785 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8786 OC.LocEnd));
8787
Douglas Gregor10982ea2010-04-28 22:36:06 +00008788 // C99 7.17p3:
8789 // (If the specified member is a bit-field, the behavior is undefined.)
8790 //
8791 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008792 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008793 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8794 << MemberDecl->getDeclName()
8795 << SourceRange(BuiltinLoc, RParenLoc);
8796 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8797 return ExprError();
8798 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008799
8800 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008801 if (IndirectMemberDecl)
8802 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008803
Douglas Gregord1702062010-04-29 00:18:15 +00008804 // If the member was found in a base class, introduce OffsetOfNodes for
8805 // the base class indirections.
8806 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8807 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008808 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008809 CXXBasePath &Path = Paths.front();
8810 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8811 B != BEnd; ++B)
8812 Comps.push_back(OffsetOfNode(B->Base));
8813 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008814
Francois Pichet783dd6e2010-11-21 06:08:52 +00008815 if (IndirectMemberDecl) {
8816 for (IndirectFieldDecl::chain_iterator FI =
8817 IndirectMemberDecl->chain_begin(),
8818 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8819 assert(isa<FieldDecl>(*FI));
8820 Comps.push_back(OffsetOfNode(OC.LocStart,
8821 cast<FieldDecl>(*FI), OC.LocEnd));
8822 }
8823 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008824 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008825
Douglas Gregor882211c2010-04-28 22:16:22 +00008826 CurrentType = MemberDecl->getType().getNonReferenceType();
8827 }
8828
8829 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8830 TInfo, Comps.data(), Comps.size(),
8831 Exprs.data(), Exprs.size(), RParenLoc));
8832}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008833
John McCalldadc5752010-08-24 06:29:42 +00008834ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008835 SourceLocation BuiltinLoc,
8836 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008837 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008838 OffsetOfComponent *CompPtr,
8839 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008840 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008841
Douglas Gregor882211c2010-04-28 22:16:22 +00008842 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008843 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008844 if (ArgTy.isNull())
8845 return ExprError();
8846
Eli Friedman06dcfd92010-08-05 10:15:45 +00008847 if (!ArgTInfo)
8848 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8849
8850 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008851 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008852}
8853
8854
John McCalldadc5752010-08-24 06:29:42 +00008855ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008856 Expr *CondExpr,
8857 Expr *LHSExpr, Expr *RHSExpr,
8858 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008859 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8860
John McCall7decc9e2010-11-18 06:31:45 +00008861 ExprValueKind VK = VK_RValue;
8862 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008863 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008864 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008865 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008866 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008867 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008868 } else {
8869 // The conditional expression is required to be a constant expression.
8870 llvm::APSInt condEval(32);
Richard Smithf4c51d92012-02-04 09:53:13 +00008871 ExprResult CondICE = VerifyIntegerConstantExpression(CondExpr, &condEval,
8872 PDiag(diag::err_typecheck_choose_expr_requires_constant), false);
8873 if (CondICE.isInvalid())
8874 return ExprError();
8875 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00008876
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008877 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008878 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8879
8880 resType = ActiveExpr->getType();
8881 ValueDependent = ActiveExpr->isValueDependent();
8882 VK = ActiveExpr->getValueKind();
8883 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008884 }
8885
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008886 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008887 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008888 resType->isDependentType(),
8889 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008890}
8891
Steve Naroffc540d662008-09-03 18:15:37 +00008892//===----------------------------------------------------------------------===//
8893// Clang Extensions.
8894//===----------------------------------------------------------------------===//
8895
8896/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008897void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008898 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008899 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008900 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008901 if (CurScope)
8902 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008903 else
8904 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00008905
Eli Friedman34b49062012-01-26 03:00:14 +00008906 getCurBlock()->HasImplicitReturnType = true;
8907
John McCallf1a3c2a2011-11-11 03:19:12 +00008908 // Enter a new evaluation context to insulate the block from any
8909 // cleanups from the enclosing full-expression.
8910 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008911}
8912
Mike Stump82f071f2009-02-04 22:31:32 +00008913void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008914 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008915 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008916 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008917
John McCall8cb7bdf2010-06-04 23:28:52 +00008918 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008919 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008920
John McCall3882ace2011-01-05 12:14:39 +00008921 // GetTypeForDeclarator always produces a function type for a block
8922 // literal signature. Furthermore, it is always a FunctionProtoType
8923 // unless the function was written with a typedef.
8924 assert(T->isFunctionType() &&
8925 "GetTypeForDeclarator made a non-function block signature");
8926
8927 // Look for an explicit signature in that function type.
8928 FunctionProtoTypeLoc ExplicitSignature;
8929
8930 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8931 if (isa<FunctionProtoTypeLoc>(tmp)) {
8932 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8933
8934 // Check whether that explicit signature was synthesized by
8935 // GetTypeForDeclarator. If so, don't save that as part of the
8936 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008937 if (ExplicitSignature.getLocalRangeBegin() ==
8938 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008939 // This would be much cheaper if we stored TypeLocs instead of
8940 // TypeSourceInfos.
8941 TypeLoc Result = ExplicitSignature.getResultLoc();
8942 unsigned Size = Result.getFullDataSize();
8943 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8944 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8945
8946 ExplicitSignature = FunctionProtoTypeLoc();
8947 }
John McCalla3ccba02010-06-04 11:21:44 +00008948 }
Mike Stump11289f42009-09-09 15:08:12 +00008949
John McCall3882ace2011-01-05 12:14:39 +00008950 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8951 CurBlock->FunctionType = T;
8952
8953 const FunctionType *Fn = T->getAs<FunctionType>();
8954 QualType RetTy = Fn->getResultType();
8955 bool isVariadic =
8956 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8957
John McCall8e346702010-06-04 19:02:56 +00008958 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008959
John McCalla3ccba02010-06-04 11:21:44 +00008960 // Don't allow returning a objc interface by value.
8961 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008962 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00008963 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8964 return;
8965 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008966
John McCalla3ccba02010-06-04 11:21:44 +00008967 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008968 // return type. TODO: what should we do with declarators like:
8969 // ^ * { ... }
8970 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008971 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00008972 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008973 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00008974 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008975 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008976
John McCalla3ccba02010-06-04 11:21:44 +00008977 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008978 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008979 if (ExplicitSignature) {
8980 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8981 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008982 if (Param->getIdentifier() == 0 &&
8983 !Param->isImplicit() &&
8984 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00008985 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008986 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008987 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008988 }
John McCalla3ccba02010-06-04 11:21:44 +00008989
8990 // Fake up parameter variables if we have a typedef, like
8991 // ^ fntype { ... }
8992 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8993 for (FunctionProtoType::arg_type_iterator
8994 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8995 ParmVarDecl *Param =
8996 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008997 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00008998 *I);
John McCall8e346702010-06-04 19:02:56 +00008999 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009000 }
Steve Naroffc540d662008-09-03 18:15:37 +00009001 }
John McCalla3ccba02010-06-04 11:21:44 +00009002
John McCall8e346702010-06-04 19:02:56 +00009003 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009004 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009005 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009006 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9007 CurBlock->TheDecl->param_end(),
9008 /*CheckParameterNames=*/false);
9009 }
9010
John McCalla3ccba02010-06-04 11:21:44 +00009011 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009012 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009013
John McCalla3ccba02010-06-04 11:21:44 +00009014 // Put the parameter variables in scope. We can bail out immediately
9015 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009016 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009017 return;
9018
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009019 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009020 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9021 (*AI)->setOwningFunction(CurBlock->TheDecl);
9022
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009023 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009024 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009025 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009026
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009027 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009028 }
John McCallf7b2fb52010-01-22 00:28:27 +00009029 }
Steve Naroffc540d662008-09-03 18:15:37 +00009030}
9031
9032/// ActOnBlockError - If there is an error parsing a block, this callback
9033/// is invoked to pop the information about the block from the action impl.
9034void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009035 // Leave the expression-evaluation context.
9036 DiscardCleanupsInEvaluationContext();
9037 PopExpressionEvaluationContext();
9038
Steve Naroffc540d662008-09-03 18:15:37 +00009039 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009040 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009041 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009042}
9043
9044/// ActOnBlockStmtExpr - This is called when the body of a block statement
9045/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009046ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009047 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009048 // If blocks are disabled, emit an error.
9049 if (!LangOpts.Blocks)
9050 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009051
John McCallf1a3c2a2011-11-11 03:19:12 +00009052 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009053 if (hasAnyUnrecoverableErrorsInThisFunction())
9054 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009055 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9056 PopExpressionEvaluationContext();
9057
Douglas Gregor9a28e842010-03-01 23:15:13 +00009058 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009059
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009060 PopDeclContext();
9061
Steve Naroffc540d662008-09-03 18:15:37 +00009062 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009063 if (!BSI->ReturnType.isNull())
9064 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009065
Mike Stump3bf1ab42009-07-28 22:04:01 +00009066 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009067 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009068
John McCallc63de662011-02-02 13:00:07 +00009069 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009070 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9071 SmallVector<BlockDecl::Capture, 4> Captures;
9072 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9073 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9074 if (Cap.isThisCapture())
9075 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009076 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009077 Cap.isNested(), Cap.getCopyExpr());
9078 Captures.push_back(NewCap);
9079 }
9080 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9081 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009082
John McCall8e346702010-06-04 19:02:56 +00009083 // If the user wrote a function type in some form, try to use that.
9084 if (!BSI->FunctionType.isNull()) {
9085 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9086
9087 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9088 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9089
9090 // Turn protoless block types into nullary block types.
9091 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009092 FunctionProtoType::ExtProtoInfo EPI;
9093 EPI.ExtInfo = Ext;
9094 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009095
9096 // Otherwise, if we don't need to change anything about the function type,
9097 // preserve its sugar structure.
9098 } else if (FTy->getResultType() == RetTy &&
9099 (!NoReturn || FTy->getNoReturnAttr())) {
9100 BlockTy = BSI->FunctionType;
9101
9102 // Otherwise, make the minimal modifications to the function type.
9103 } else {
9104 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009105 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9106 EPI.TypeQuals = 0; // FIXME: silently?
9107 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009108 BlockTy = Context.getFunctionType(RetTy,
9109 FPT->arg_type_begin(),
9110 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009111 EPI);
John McCall8e346702010-06-04 19:02:56 +00009112 }
9113
9114 // If we don't have a function type, just build one from nothing.
9115 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009116 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009117 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009118 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009119 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009120
John McCall8e346702010-06-04 19:02:56 +00009121 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9122 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009123 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009124
Chris Lattner45542ea2009-04-19 05:28:12 +00009125 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009126 if (getCurFunction()->NeedsScopeChecking() &&
9127 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009128 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009129
Chris Lattner60f84492011-02-17 23:58:47 +00009130 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009131
Douglas Gregor49695f02011-09-06 20:46:03 +00009132 computeNRVO(Body, getCurBlock());
9133
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009134 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9135 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009136 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009137
John McCall28fc7092011-11-10 05:35:25 +00009138 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009139 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009140 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009141 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009142 ExprCleanupObjects.push_back(Result->getBlockDecl());
9143 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009144
9145 // It also gets a branch-protected scope if any of the captured
9146 // variables needs destruction.
9147 for (BlockDecl::capture_const_iterator
9148 ci = Result->getBlockDecl()->capture_begin(),
9149 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9150 const VarDecl *var = ci->getVariable();
9151 if (var->getType().isDestructedType() != QualType::DK_none) {
9152 getCurFunction()->setHasBranchProtectedScope();
9153 break;
9154 }
9155 }
John McCall28fc7092011-11-10 05:35:25 +00009156 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009157
Douglas Gregor9a28e842010-03-01 23:15:13 +00009158 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009159}
9160
John McCalldadc5752010-08-24 06:29:42 +00009161ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009162 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009163 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009164 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009165 GetTypeFromParser(Ty, &TInfo);
9166 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009167}
9168
John McCalldadc5752010-08-24 06:29:42 +00009169ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009170 Expr *E, TypeSourceInfo *TInfo,
9171 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009172 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009173
Eli Friedman121ba0c2008-08-09 23:32:40 +00009174 // Get the va_list type
9175 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009176 if (VaListType->isArrayType()) {
9177 // Deal with implicit array decay; for example, on x86-64,
9178 // va_list is an array, but it's supposed to decay to
9179 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009180 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009181 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009182 ExprResult Result = UsualUnaryConversions(E);
9183 if (Result.isInvalid())
9184 return ExprError();
9185 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009186 } else {
9187 // Otherwise, the va_list argument must be an l-value because
9188 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009189 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009190 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009191 return ExprError();
9192 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009193
Douglas Gregorad3150c2009-05-19 23:10:31 +00009194 if (!E->isTypeDependent() &&
9195 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009196 return ExprError(Diag(E->getLocStart(),
9197 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009198 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009199 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009200
David Majnemerc75d1a12011-06-14 05:17:32 +00009201 if (!TInfo->getType()->isDependentType()) {
9202 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009203 diag::err_second_parameter_to_va_arg_incomplete,
9204 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009205 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009206
David Majnemerc75d1a12011-06-14 05:17:32 +00009207 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9208 TInfo->getType(),
9209 PDiag(diag::err_second_parameter_to_va_arg_abstract)
9210 << TInfo->getTypeLoc().getSourceRange()))
9211 return ExprError();
9212
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009213 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009214 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009215 TInfo->getType()->isObjCLifetimeType()
9216 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9217 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009218 << TInfo->getType()
9219 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009220 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009221
9222 // Check for va_arg where arguments of the given type will be promoted
9223 // (i.e. this va_arg is guaranteed to have undefined behavior).
9224 QualType PromoteType;
9225 if (TInfo->getType()->isPromotableIntegerType()) {
9226 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9227 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9228 PromoteType = QualType();
9229 }
9230 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9231 PromoteType = Context.DoubleTy;
9232 if (!PromoteType.isNull())
9233 Diag(TInfo->getTypeLoc().getBeginLoc(),
9234 diag::warn_second_parameter_to_va_arg_never_compatible)
9235 << TInfo->getType()
9236 << PromoteType
9237 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009238 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009239
Abramo Bagnara27db2392010-08-10 10:06:15 +00009240 QualType T = TInfo->getType().getNonLValueExprType(Context);
9241 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009242}
9243
John McCalldadc5752010-08-24 06:29:42 +00009244ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009245 // The type of __null will be int or long, depending on the size of
9246 // pointers on the target.
9247 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009248 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9249 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009250 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009251 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009252 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009253 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009254 Ty = Context.LongLongTy;
9255 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009256 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009257 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009258
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009259 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009260}
9261
Alexis Huntc46382e2010-04-28 23:02:27 +00009262static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009263 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009264 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009265 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009266
Anders Carlssonace5d072009-11-10 04:46:30 +00009267 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9268 if (!PT)
9269 return;
9270
9271 // Check if the destination is of type 'id'.
9272 if (!PT->isObjCIdType()) {
9273 // Check if the destination is the 'NSString' interface.
9274 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9275 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9276 return;
9277 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009278
John McCallfe96e0b2011-11-06 09:01:30 +00009279 // Ignore any parens, implicit casts (should only be
9280 // array-to-pointer decays), and not-so-opaque values. The last is
9281 // important for making this trigger for property assignments.
9282 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9283 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9284 if (OV->getSourceExpr())
9285 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9286
9287 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009288 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009289 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009290
Douglas Gregora771f462010-03-31 17:46:05 +00009291 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009292}
9293
Chris Lattner9bad62c2008-01-04 18:04:52 +00009294bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9295 SourceLocation Loc,
9296 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009297 Expr *SrcExpr, AssignmentAction Action,
9298 bool *Complained) {
9299 if (Complained)
9300 *Complained = false;
9301
Chris Lattner9bad62c2008-01-04 18:04:52 +00009302 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009303 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009304 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009305 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009306 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009307 ConversionFixItGenerator ConvHints;
9308 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009309 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009310
Chris Lattner9bad62c2008-01-04 18:04:52 +00009311 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009312 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009313 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009314 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009315 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9316 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009317 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009318 case IntToPointer:
9319 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009320 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9321 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009322 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009323 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009324 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009325 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009326 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9327 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009328 if (Hint.isNull() && !CheckInferredResultType) {
9329 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9330 }
9331 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009332 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009333 case IncompatiblePointerSign:
9334 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9335 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009336 case FunctionVoidPointer:
9337 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9338 break;
John McCall4fff8f62011-02-01 00:10:29 +00009339 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009340 // Perform array-to-pointer decay if necessary.
9341 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9342
John McCall4fff8f62011-02-01 00:10:29 +00009343 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9344 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9345 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9346 DiagKind = diag::err_typecheck_incompatible_address_space;
9347 break;
John McCall31168b02011-06-15 23:02:42 +00009348
9349
9350 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009351 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009352 break;
John McCall4fff8f62011-02-01 00:10:29 +00009353 }
9354
9355 llvm_unreachable("unknown error case for discarding qualifiers!");
9356 // fallthrough
9357 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009358 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009359 // If the qualifiers lost were because we were applying the
9360 // (deprecated) C++ conversion from a string literal to a char*
9361 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9362 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009363 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009364 // bit of refactoring (so that the second argument is an
9365 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009366 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009367 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009368 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009369 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9370 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009371 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9372 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009373 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009374 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009375 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009376 case IntToBlockPointer:
9377 DiagKind = diag::err_int_to_block_pointer;
9378 break;
9379 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009380 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009381 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009382 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009383 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009384 // it can give a more specific diagnostic.
9385 DiagKind = diag::warn_incompatible_qualified_id;
9386 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009387 case IncompatibleVectors:
9388 DiagKind = diag::warn_incompatible_vectors;
9389 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009390 case IncompatibleObjCWeakRef:
9391 DiagKind = diag::err_arc_weak_unavailable_assign;
9392 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009393 case Incompatible:
9394 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009395 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9396 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009397 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009398 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009399 break;
9400 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009401
Douglas Gregorc68e1402010-04-09 00:35:39 +00009402 QualType FirstType, SecondType;
9403 switch (Action) {
9404 case AA_Assigning:
9405 case AA_Initializing:
9406 // The destination type comes first.
9407 FirstType = DstType;
9408 SecondType = SrcType;
9409 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009410
Douglas Gregorc68e1402010-04-09 00:35:39 +00009411 case AA_Returning:
9412 case AA_Passing:
9413 case AA_Converting:
9414 case AA_Sending:
9415 case AA_Casting:
9416 // The source type comes first.
9417 FirstType = SrcType;
9418 SecondType = DstType;
9419 break;
9420 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009421
Anna Zaks3b402712011-07-28 19:51:27 +00009422 PartialDiagnostic FDiag = PDiag(DiagKind);
9423 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9424
9425 // If we can fix the conversion, suggest the FixIts.
9426 assert(ConvHints.isNull() || Hint.isNull());
9427 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009428 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9429 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009430 FDiag << *HI;
9431 } else {
9432 FDiag << Hint;
9433 }
9434 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9435
Richard Trieucaff2472011-11-23 22:32:32 +00009436 if (MayHaveFunctionDiff)
9437 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9438
Anna Zaks3b402712011-07-28 19:51:27 +00009439 Diag(Loc, FDiag);
9440
Richard Trieucaff2472011-11-23 22:32:32 +00009441 if (SecondType == Context.OverloadTy)
9442 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9443 FirstType);
9444
Douglas Gregor33823722011-06-11 01:09:30 +00009445 if (CheckInferredResultType)
9446 EmitRelatedResultTypeNote(SrcExpr);
9447
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009448 if (Complained)
9449 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009450 return isInvalid;
9451}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009452
Richard Smithf4c51d92012-02-04 09:53:13 +00009453ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9454 llvm::APSInt *Result) {
9455 return VerifyIntegerConstantExpression(E, Result,
9456 PDiag(diag::err_expr_not_ice) << LangOpts.CPlusPlus);
9457}
9458
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009459ExprResult
9460Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9461 const PartialDiagnostic &NotIceDiag,
9462 bool AllowFold,
9463 const PartialDiagnostic &FoldDiag) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009464 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009465
David Blaikiebbafb8a2012-03-11 07:00:24 +00009466 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009467 // C++11 [expr.const]p5:
9468 // If an expression of literal class type is used in a context where an
9469 // integral constant expression is required, then that class type shall
9470 // have a single non-explicit conversion function to an integral or
9471 // unscoped enumeration type
9472 ExprResult Converted;
9473 if (NotIceDiag.getDiagID()) {
9474 Converted = ConvertToIntegralOrEnumerationType(
9475 DiagLoc, E,
9476 PDiag(diag::err_ice_not_integral),
9477 PDiag(diag::err_ice_incomplete_type),
9478 PDiag(diag::err_ice_explicit_conversion),
9479 PDiag(diag::note_ice_conversion_here),
9480 PDiag(diag::err_ice_ambiguous_conversion),
9481 PDiag(diag::note_ice_conversion_here),
9482 PDiag(0),
9483 /*AllowScopedEnumerations*/ false);
9484 } else {
9485 // The caller wants to silently enquire whether this is an ICE. Don't
9486 // produce any diagnostics if it isn't.
9487 Converted = ConvertToIntegralOrEnumerationType(
9488 DiagLoc, E, PDiag(), PDiag(), PDiag(), PDiag(),
9489 PDiag(), PDiag(), PDiag(), false);
9490 }
9491 if (Converted.isInvalid())
9492 return Converted;
9493 E = Converted.take();
9494 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9495 return ExprError();
9496 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9497 // An ICE must be of integral or unscoped enumeration type.
9498 if (NotIceDiag.getDiagID())
9499 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
9500 return ExprError();
9501 }
9502
Richard Smith902ca212011-12-14 23:32:26 +00009503 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9504 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009505 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009506 if (Result)
9507 *Result = E->EvaluateKnownConstInt(Context);
9508 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009509 }
9510
Anders Carlssone54e8a12008-11-30 19:50:32 +00009511 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009512 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9513 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009514
Richard Smith902ca212011-12-14 23:32:26 +00009515 // Try to evaluate the expression, and produce diagnostics explaining why it's
9516 // not a constant expression as a side-effect.
9517 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9518 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9519
9520 // In C++11, we can rely on diagnostics being produced for any expression
9521 // which is not a constant expression. If no diagnostics were produced, then
9522 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009523 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +00009524 if (Result)
9525 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009526 return Owned(E);
9527 }
9528
9529 // If our only note is the usual "invalid subexpression" note, just point
9530 // the caret at its location rather than producing an essentially
9531 // redundant note.
9532 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9533 diag::note_invalid_subexpr_in_const_expr) {
9534 DiagLoc = Notes[0].first;
9535 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009536 }
9537
9538 if (!Folded || !AllowFold) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009539 if (NotIceDiag.getDiagID()) {
9540 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
Richard Smith92b1ce02011-12-12 09:28:41 +00009541 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9542 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009543 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009544
Richard Smithf4c51d92012-02-04 09:53:13 +00009545 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009546 }
9547
Richard Smithf4c51d92012-02-04 09:53:13 +00009548 if (FoldDiag.getDiagID())
9549 Diag(DiagLoc, FoldDiag) << E->getSourceRange();
9550 else
9551 Diag(DiagLoc, diag::ext_expr_not_ice)
9552 << E->getSourceRange() << LangOpts.CPlusPlus;
Richard Smith2ec40612012-01-15 03:51:30 +00009553 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9554 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009555
Anders Carlssone54e8a12008-11-30 19:50:32 +00009556 if (Result)
9557 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009558 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009559}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009560
Eli Friedman456f0182012-01-20 01:26:23 +00009561namespace {
9562 // Handle the case where we conclude a expression which we speculatively
9563 // considered to be unevaluated is actually evaluated.
9564 class TransformToPE : public TreeTransform<TransformToPE> {
9565 typedef TreeTransform<TransformToPE> BaseTransform;
9566
9567 public:
9568 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9569
9570 // Make sure we redo semantic analysis
9571 bool AlwaysRebuild() { return true; }
9572
Eli Friedman5f0ca242012-02-06 23:29:57 +00009573 // Make sure we handle LabelStmts correctly.
9574 // FIXME: This does the right thing, but maybe we need a more general
9575 // fix to TreeTransform?
9576 StmtResult TransformLabelStmt(LabelStmt *S) {
9577 S->getDecl()->setStmt(0);
9578 return BaseTransform::TransformLabelStmt(S);
9579 }
9580
Eli Friedman456f0182012-01-20 01:26:23 +00009581 // We need to special-case DeclRefExprs referring to FieldDecls which
9582 // are not part of a member pointer formation; normal TreeTransforming
9583 // doesn't catch this case because of the way we represent them in the AST.
9584 // FIXME: This is a bit ugly; is it really the best way to handle this
9585 // case?
9586 //
9587 // Error on DeclRefExprs referring to FieldDecls.
9588 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9589 if (isa<FieldDecl>(E->getDecl()) &&
9590 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9591 return SemaRef.Diag(E->getLocation(),
9592 diag::err_invalid_non_static_member_use)
9593 << E->getDecl() << E->getSourceRange();
9594
9595 return BaseTransform::TransformDeclRefExpr(E);
9596 }
9597
9598 // Exception: filter out member pointer formation
9599 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9600 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9601 return E;
9602
9603 return BaseTransform::TransformUnaryOperator(E);
9604 }
9605
Douglas Gregor89625492012-02-09 08:14:43 +00009606 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9607 // Lambdas never need to be transformed.
9608 return E;
9609 }
Eli Friedman456f0182012-01-20 01:26:23 +00009610 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009611}
9612
Eli Friedman456f0182012-01-20 01:26:23 +00009613ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009614 assert(ExprEvalContexts.back().Context == Unevaluated &&
9615 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009616 ExprEvalContexts.back().Context =
9617 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9618 if (ExprEvalContexts.back().Context == Unevaluated)
9619 return E;
9620 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009621}
9622
Douglas Gregorff790f12009-11-26 00:44:06 +00009623void
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009624Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +00009625 Decl *LambdaContextDecl,
9626 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009627 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009628 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +00009629 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009630 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +00009631 LambdaContextDecl,
9632 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +00009633 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009634 if (!MaybeODRUseExprs.empty())
9635 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009636}
9637
Richard Trieucfc491d2011-08-02 04:35:43 +00009638void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009639 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009640
Douglas Gregor89625492012-02-09 08:14:43 +00009641 if (!Rec.Lambdas.empty()) {
9642 if (Rec.Context == Unevaluated) {
9643 // C++11 [expr.prim.lambda]p2:
9644 // A lambda-expression shall not appear in an unevaluated operand
9645 // (Clause 5).
9646 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
9647 Diag(Rec.Lambdas[I]->getLocStart(),
9648 diag::err_lambda_unevaluated_operand);
9649 } else {
9650 // Mark the capture expressions odr-used. This was deferred
9651 // during lambda expression creation.
9652 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
9653 LambdaExpr *Lambda = Rec.Lambdas[I];
9654 for (LambdaExpr::capture_init_iterator
9655 C = Lambda->capture_init_begin(),
9656 CEnd = Lambda->capture_init_end();
9657 C != CEnd; ++C) {
9658 MarkDeclarationsReferencedInExpr(*C);
9659 }
9660 }
9661 }
9662 }
9663
Douglas Gregorff790f12009-11-26 00:44:06 +00009664 // When are coming out of an unevaluated context, clear out any
9665 // temporaries that we may have created as part of the evaluation of
9666 // the expression in that context: they aren't relevant because they
9667 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +00009668 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +00009669 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9670 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009671 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009672 CleanupVarDeclMarking();
9673 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +00009674 // Otherwise, merge the contexts together.
9675 } else {
9676 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009677 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
9678 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +00009679 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009680
9681 // Pop the current expression evaluation context off the stack.
9682 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009683}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009684
John McCall31168b02011-06-15 23:02:42 +00009685void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +00009686 ExprCleanupObjects.erase(
9687 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9688 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009689 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009690 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +00009691}
9692
Eli Friedmane0afc982012-01-21 01:01:51 +00009693ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
9694 if (!E->getType()->isVariablyModifiedType())
9695 return E;
9696 return TranformToPotentiallyEvaluated(E);
9697}
9698
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00009699static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009700 // Do not mark anything as "used" within a dependent context; wait for
9701 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009702 if (SemaRef.CurContext->isDependentContext())
9703 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009704
Eli Friedmanfa0df832012-02-02 03:46:19 +00009705 switch (SemaRef.ExprEvalContexts.back().Context) {
9706 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009707 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +00009708 // (Depending on how you read the standard, we actually do need to do
9709 // something here for null pointer constants, but the standard's
9710 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +00009711 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009712
Eli Friedmanfa0df832012-02-02 03:46:19 +00009713 case Sema::ConstantEvaluated:
9714 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +00009715 // We are in a potentially evaluated expression (or a constant-expression
9716 // in C++03); we need to do implicit template instantiation, implicitly
9717 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009718 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009719
Eli Friedmanfa0df832012-02-02 03:46:19 +00009720 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009721 // Referenced declarations will only be used if the construct in the
9722 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009723 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009724 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +00009725 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +00009726}
9727
9728/// \brief Mark a function referenced, and check whether it is odr-used
9729/// (C++ [basic.def.odr]p2, C99 6.9p3)
9730void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
9731 assert(Func && "No function?");
9732
9733 Func->setReferenced();
9734
Richard Smith4a941e22012-02-14 22:25:15 +00009735 // Don't mark this function as used multiple times, unless it's a constexpr
9736 // function which we need to instantiate.
9737 if (Func->isUsed(false) &&
9738 !(Func->isConstexpr() && !Func->getBody() &&
9739 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +00009740 return;
9741
9742 if (!IsPotentiallyEvaluatedContext(*this))
9743 return;
Mike Stump11289f42009-09-09 15:08:12 +00009744
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009745 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009746 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009747 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009748 if (Constructor->isDefaultConstructor()) {
9749 if (Constructor->isTrivial())
9750 return;
9751 if (!Constructor->isUsed(false))
9752 DefineImplicitDefaultConstructor(Loc, Constructor);
9753 } else if (Constructor->isCopyConstructor()) {
9754 if (!Constructor->isUsed(false))
9755 DefineImplicitCopyConstructor(Loc, Constructor);
9756 } else if (Constructor->isMoveConstructor()) {
9757 if (!Constructor->isUsed(false))
9758 DefineImplicitMoveConstructor(Loc, Constructor);
9759 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009760 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009761
Douglas Gregor88d292c2010-05-13 16:44:06 +00009762 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009763 } else if (CXXDestructorDecl *Destructor =
9764 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009765 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
9766 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009767 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009768 if (Destructor->isVirtual())
9769 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009770 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009771 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
9772 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009773 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009774 if (!MethodDecl->isUsed(false)) {
9775 if (MethodDecl->isCopyAssignmentOperator())
9776 DefineImplicitCopyAssignment(Loc, MethodDecl);
9777 else
9778 DefineImplicitMoveAssignment(Loc, MethodDecl);
9779 }
Douglas Gregord3b672c2012-02-16 01:06:16 +00009780 } else if (isa<CXXConversionDecl>(MethodDecl) &&
9781 MethodDecl->getParent()->isLambda()) {
9782 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
9783 if (Conversion->isLambdaToBlockPointerConversion())
9784 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
9785 else
9786 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009787 } else if (MethodDecl->isVirtual())
9788 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009789 }
John McCall83779672011-02-19 02:53:41 +00009790
Eli Friedmanfa0df832012-02-02 03:46:19 +00009791 // Recursive functions should be marked when used from another function.
9792 // FIXME: Is this really right?
9793 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009794
Richard Smithf623c962012-04-17 00:58:00 +00009795 // Instantiate the exception specification for any function which is
9796 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +00009797 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
9798 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +00009799 InstantiateExceptionSpec(Loc, Func);
9800
Eli Friedmanfa0df832012-02-02 03:46:19 +00009801 // Implicit instantiation of function templates and member functions of
9802 // class templates.
9803 if (Func->isImplicitlyInstantiable()) {
9804 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +00009805 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009806 if (FunctionTemplateSpecializationInfo *SpecInfo
9807 = Func->getTemplateSpecializationInfo()) {
9808 if (SpecInfo->getPointOfInstantiation().isInvalid())
9809 SpecInfo->setPointOfInstantiation(Loc);
9810 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009811 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009812 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009813 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
9814 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009815 } else if (MemberSpecializationInfo *MSInfo
9816 = Func->getMemberSpecializationInfo()) {
9817 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +00009818 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009819 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009820 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009821 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009822 PointOfInstantiation = MSInfo->getPointOfInstantiation();
9823 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00009824 }
Mike Stump11289f42009-09-09 15:08:12 +00009825
Richard Smith4a941e22012-02-14 22:25:15 +00009826 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009827 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
9828 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +00009829 PendingLocalImplicitInstantiations.push_back(
9830 std::make_pair(Func, PointOfInstantiation));
9831 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +00009832 // Do not defer instantiations of constexpr functions, to avoid the
9833 // expression evaluator needing to call back into Sema if it sees a
9834 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +00009835 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009836 else {
Richard Smith4a941e22012-02-14 22:25:15 +00009837 PendingInstantiations.push_back(std::make_pair(Func,
9838 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009839 // Notify the consumer that a function was implicitly instantiated.
9840 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
9841 }
John McCall83779672011-02-19 02:53:41 +00009842 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009843 } else {
9844 // Walk redefinitions, as some of them may be instantiable.
9845 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
9846 e(Func->redecls_end()); i != e; ++i) {
9847 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9848 MarkFunctionReferenced(Loc, *i);
9849 }
Sam Weinigbae69142009-09-11 03:29:30 +00009850 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009851
9852 // Keep track of used but undefined functions.
9853 if (!Func->isPure() && !Func->hasBody() &&
9854 Func->getLinkage() != ExternalLinkage) {
9855 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
9856 if (old.isInvalid()) old = Loc;
9857 }
9858
9859 Func->setUsed(true);
9860}
9861
Eli Friedman9bb33f52012-02-03 02:04:35 +00009862static void
9863diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
9864 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +00009865 DeclContext *VarDC = var->getDeclContext();
9866
Eli Friedman9bb33f52012-02-03 02:04:35 +00009867 // If the parameter still belongs to the translation unit, then
9868 // we're actually just using one parameter in the declaration of
9869 // the next.
9870 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +00009871 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +00009872 return;
9873
Eli Friedmandd053f62012-02-07 00:15:00 +00009874 // For C code, don't diagnose about capture if we're not actually in code
9875 // right now; it's impossible to write a non-constant expression outside of
9876 // function context, so we'll get other (more useful) diagnostics later.
9877 //
9878 // For C++, things get a bit more nasty... it would be nice to suppress this
9879 // diagnostic for certain cases like using a local variable in an array bound
9880 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009881 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +00009882 return;
9883
Eli Friedmandd053f62012-02-07 00:15:00 +00009884 if (isa<CXXMethodDecl>(VarDC) &&
9885 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
9886 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
9887 << var->getIdentifier();
9888 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
9889 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
9890 << var->getIdentifier() << fn->getDeclName();
9891 } else if (isa<BlockDecl>(VarDC)) {
9892 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
9893 << var->getIdentifier();
9894 } else {
9895 // FIXME: Is there any other context where a local variable can be
9896 // declared?
9897 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
9898 << var->getIdentifier();
9899 }
Eli Friedman9bb33f52012-02-03 02:04:35 +00009900
Eli Friedman9bb33f52012-02-03 02:04:35 +00009901 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
9902 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +00009903
9904 // FIXME: Add additional diagnostic info about class etc. which prevents
9905 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +00009906}
9907
Douglas Gregor81495f32012-02-12 18:42:33 +00009908/// \brief Capture the given variable in the given lambda expression.
9909static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009910 VarDecl *Var, QualType FieldType,
9911 QualType DeclRefType,
9912 SourceLocation Loc) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009913 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +00009914
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009915 // Build the non-static data member.
9916 FieldDecl *Field
9917 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
9918 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
9919 0, false, false);
9920 Field->setImplicit(true);
9921 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +00009922 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009923
9924 // C++11 [expr.prim.lambda]p21:
9925 // When the lambda-expression is evaluated, the entities that
9926 // are captured by copy are used to direct-initialize each
9927 // corresponding non-static data member of the resulting closure
9928 // object. (For array members, the array elements are
9929 // direct-initialized in increasing subscript order.) These
9930 // initializations are performed in the (unspecified) order in
9931 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009932
Douglas Gregor89625492012-02-09 08:14:43 +00009933 // Introduce a new evaluation context for the initialization, so
9934 // that temporaries introduced as part of the capture are retained
9935 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009936 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9937
Douglas Gregorf02455e2012-02-10 09:26:04 +00009938 // C++ [expr.prim.labda]p12:
9939 // An entity captured by a lambda-expression is odr-used (3.2) in
9940 // the scope containing the lambda-expression.
John McCall113bee02012-03-10 09:33:50 +00009941 Expr *Ref = new (S.Context) DeclRefExpr(Var, false, DeclRefType,
9942 VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +00009943 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +00009944 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +00009945
9946 // When the field has array type, create index variables for each
9947 // dimension of the array. We use these index variables to subscript
9948 // the source array, and other clients (e.g., CodeGen) will perform
9949 // the necessary iteration with these index variables.
9950 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +00009951 QualType BaseType = FieldType;
9952 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +00009953 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +00009954 while (const ConstantArrayType *Array
9955 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +00009956 // Create the iteration variable for this array index.
9957 IdentifierInfo *IterationVarName = 0;
9958 {
9959 SmallString<8> Str;
9960 llvm::raw_svector_ostream OS(Str);
9961 OS << "__i" << IndexVariables.size();
9962 IterationVarName = &S.Context.Idents.get(OS.str());
9963 }
9964 VarDecl *IterationVar
9965 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9966 IterationVarName, SizeType,
9967 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9968 SC_None, SC_None);
9969 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +00009970 LSI->ArrayIndexVars.push_back(IterationVar);
9971
Douglas Gregor199cec72012-02-09 02:45:47 +00009972 // Create a reference to the iteration variable.
9973 ExprResult IterationVarRef
9974 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
9975 assert(!IterationVarRef.isInvalid() &&
9976 "Reference to invented variable cannot fail!");
9977 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
9978 assert(!IterationVarRef.isInvalid() &&
9979 "Conversion of invented variable cannot fail!");
9980
9981 // Subscript the array with this iteration variable.
9982 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
9983 Ref, Loc, IterationVarRef.take(), Loc);
9984 if (Subscript.isInvalid()) {
9985 S.CleanupVarDeclMarking();
9986 S.DiscardCleanupsInEvaluationContext();
9987 S.PopExpressionEvaluationContext();
9988 return ExprError();
9989 }
9990
9991 Ref = Subscript.take();
9992 BaseType = Array->getElementType();
9993 }
9994
9995 // Construct the entity that we will be initializing. For an array, this
9996 // will be first element in the array, which may require several levels
9997 // of array-subscript entities.
9998 SmallVector<InitializedEntity, 4> Entities;
9999 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010000 Entities.push_back(
10001 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010002 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10003 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10004 0,
10005 Entities.back()));
10006
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010007 InitializationKind InitKind
10008 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010009 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010010 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010011 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10012 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010013 MultiExprArg(S, &Ref, 1));
10014
10015 // If this initialization requires any cleanups (e.g., due to a
10016 // default argument to a copy constructor), note that for the
10017 // lambda.
10018 if (S.ExprNeedsCleanups)
10019 LSI->ExprNeedsCleanups = true;
10020
10021 // Exit the expression evaluation context used for the capture.
10022 S.CleanupVarDeclMarking();
10023 S.DiscardCleanupsInEvaluationContext();
10024 S.PopExpressionEvaluationContext();
10025 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010026}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010027
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010028bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10029 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10030 bool BuildAndDiagnose,
10031 QualType &CaptureType,
10032 QualType &DeclRefType) {
10033 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010034
Eli Friedman24af8502012-02-03 22:47:37 +000010035 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010036 if (Var->getDeclContext() == DC) return true;
10037 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010038
Douglas Gregor81495f32012-02-12 18:42:33 +000010039 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010040
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010041 // Walk up the stack to determine whether we can capture the variable,
10042 // performing the "simple" checks that don't depend on type. We stop when
10043 // we've either hit the declared scope of the variable or find an existing
10044 // capture of that variable.
10045 CaptureType = Var->getType();
10046 DeclRefType = CaptureType.getNonReferenceType();
10047 bool Explicit = (Kind != TryCapture_Implicit);
10048 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010049 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010050 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010051 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010052 DeclContext *ParentDC;
10053 if (isa<BlockDecl>(DC))
10054 ParentDC = DC->getParent();
10055 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010056 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010057 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10058 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010059 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010060 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010061 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010062 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010063 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010064
Eli Friedman24af8502012-02-03 22:47:37 +000010065 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010066 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010067
Eli Friedman24af8502012-02-03 22:47:37 +000010068 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010069 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010070 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010071 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010072
10073 // Retrieve the capture type for this variable.
10074 CaptureType = CSI->getCapture(Var).getCaptureType();
10075
10076 // Compute the type of an expression that refers to this variable.
10077 DeclRefType = CaptureType.getNonReferenceType();
10078
10079 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10080 if (Cap.isCopyCapture() &&
10081 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10082 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010083 break;
10084 }
10085
Douglas Gregor81495f32012-02-12 18:42:33 +000010086 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010087 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010088
10089 // Lambdas are not allowed to capture unnamed variables
10090 // (e.g. anonymous unions).
10091 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10092 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010093 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010094 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010095 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10096 Diag(Var->getLocation(), diag::note_declared_at);
10097 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010098 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010099 }
10100
10101 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010102 if (Var->getType()->isVariablyModifiedType()) {
10103 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010104 if (IsBlock)
10105 Diag(Loc, diag::err_ref_vm_type);
10106 else
10107 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10108 Diag(Var->getLocation(), diag::note_previous_decl)
10109 << Var->getDeclName();
10110 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010111 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010112 }
10113
Eli Friedman24af8502012-02-03 22:47:37 +000010114 // Lambdas are not allowed to capture __block variables; they don't
10115 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010116 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010117 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010118 Diag(Loc, diag::err_lambda_capture_block)
10119 << Var->getDeclName();
10120 Diag(Var->getLocation(), diag::note_previous_decl)
10121 << Var->getDeclName();
10122 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010123 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010124 }
10125
Douglas Gregor81495f32012-02-12 18:42:33 +000010126 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10127 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010128 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010129 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10130 Diag(Var->getLocation(), diag::note_previous_decl)
10131 << Var->getDeclName();
10132 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10133 diag::note_lambda_decl);
10134 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010135 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010136 }
10137
10138 FunctionScopesIndex--;
10139 DC = ParentDC;
10140 Explicit = false;
10141 } while (!Var->getDeclContext()->Equals(DC));
10142
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010143 // Walk back down the scope stack, computing the type of the capture at
10144 // each step, checking type-specific requirements, and adding captures if
10145 // requested.
10146 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10147 ++I) {
10148 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010149
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010150 // Compute the type of the capture and of a reference to the capture within
10151 // this scope.
10152 if (isa<BlockScopeInfo>(CSI)) {
10153 Expr *CopyExpr = 0;
10154 bool ByRef = false;
10155
10156 // Blocks are not allowed to capture arrays.
10157 if (CaptureType->isArrayType()) {
10158 if (BuildAndDiagnose) {
10159 Diag(Loc, diag::err_ref_array_type);
10160 Diag(Var->getLocation(), diag::note_previous_decl)
10161 << Var->getDeclName();
10162 }
10163 return true;
10164 }
10165
John McCall67cd5e02012-03-30 05:23:48 +000010166 // Forbid the block-capture of autoreleasing variables.
10167 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10168 if (BuildAndDiagnose) {
10169 Diag(Loc, diag::err_arc_autoreleasing_capture)
10170 << /*block*/ 0;
10171 Diag(Var->getLocation(), diag::note_previous_decl)
10172 << Var->getDeclName();
10173 }
10174 return true;
10175 }
10176
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010177 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10178 // Block capture by reference does not change the capture or
10179 // declaration reference types.
10180 ByRef = true;
10181 } else {
10182 // Block capture by copy introduces 'const'.
10183 CaptureType = CaptureType.getNonReferenceType().withConst();
10184 DeclRefType = CaptureType;
10185
David Blaikiebbafb8a2012-03-11 07:00:24 +000010186 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010187 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10188 // The capture logic needs the destructor, so make sure we mark it.
10189 // Usually this is unnecessary because most local variables have
10190 // their destructors marked at declaration time, but parameters are
10191 // an exception because it's technically only the call site that
10192 // actually requires the destructor.
10193 if (isa<ParmVarDecl>(Var))
10194 FinalizeVarWithDestructor(Var, Record);
10195
10196 // According to the blocks spec, the capture of a variable from
10197 // the stack requires a const copy constructor. This is not true
10198 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010199 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010200 DeclRefType.withConst(),
10201 VK_LValue, Loc);
10202 ExprResult Result
10203 = PerformCopyInitialization(
10204 InitializedEntity::InitializeBlock(Var->getLocation(),
10205 CaptureType, false),
10206 Loc, Owned(DeclRef));
10207
10208 // Build a full-expression copy expression if initialization
10209 // succeeded and used a non-trivial constructor. Recover from
10210 // errors by pretending that the copy isn't necessary.
10211 if (!Result.isInvalid() &&
10212 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10213 ->isTrivial()) {
10214 Result = MaybeCreateExprWithCleanups(Result);
10215 CopyExpr = Result.take();
10216 }
10217 }
10218 }
10219 }
10220
10221 // Actually capture the variable.
10222 if (BuildAndDiagnose)
10223 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10224 SourceLocation(), CaptureType, CopyExpr);
10225 Nested = true;
10226 continue;
10227 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010228
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010229 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10230
10231 // Determine whether we are capturing by reference or by value.
10232 bool ByRef = false;
10233 if (I == N - 1 && Kind != TryCapture_Implicit) {
10234 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010235 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010236 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010237 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010238
10239 // Compute the type of the field that will capture this variable.
10240 if (ByRef) {
10241 // C++11 [expr.prim.lambda]p15:
10242 // An entity is captured by reference if it is implicitly or
10243 // explicitly captured but not captured by copy. It is
10244 // unspecified whether additional unnamed non-static data
10245 // members are declared in the closure type for entities
10246 // captured by reference.
10247 //
10248 // FIXME: It is not clear whether we want to build an lvalue reference
10249 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10250 // to do the former, while EDG does the latter. Core issue 1249 will
10251 // clarify, but for now we follow GCC because it's a more permissive and
10252 // easily defensible position.
10253 CaptureType = Context.getLValueReferenceType(DeclRefType);
10254 } else {
10255 // C++11 [expr.prim.lambda]p14:
10256 // For each entity captured by copy, an unnamed non-static
10257 // data member is declared in the closure type. The
10258 // declaration order of these members is unspecified. The type
10259 // of such a data member is the type of the corresponding
10260 // captured entity if the entity is not a reference to an
10261 // object, or the referenced type otherwise. [Note: If the
10262 // captured entity is a reference to a function, the
10263 // corresponding data member is also a reference to a
10264 // function. - end note ]
10265 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10266 if (!RefType->getPointeeType()->isFunctionType())
10267 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010268 }
John McCall67cd5e02012-03-30 05:23:48 +000010269
10270 // Forbid the lambda copy-capture of autoreleasing variables.
10271 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10272 if (BuildAndDiagnose) {
10273 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10274 Diag(Var->getLocation(), diag::note_previous_decl)
10275 << Var->getDeclName();
10276 }
10277 return true;
10278 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010279 }
10280
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010281 // Capture this variable in the lambda.
10282 Expr *CopyExpr = 0;
10283 if (BuildAndDiagnose) {
10284 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10285 DeclRefType, Loc);
10286 if (!Result.isInvalid())
10287 CopyExpr = Result.take();
10288 }
10289
10290 // Compute the type of a reference to this captured variable.
10291 if (ByRef)
10292 DeclRefType = CaptureType.getNonReferenceType();
10293 else {
10294 // C++ [expr.prim.lambda]p5:
10295 // The closure type for a lambda-expression has a public inline
10296 // function call operator [...]. This function call operator is
10297 // declared const (9.3.1) if and only if the lambda-expression’s
10298 // parameter-declaration-clause is not followed by mutable.
10299 DeclRefType = CaptureType.getNonReferenceType();
10300 if (!LSI->Mutable && !CaptureType->isReferenceType())
10301 DeclRefType.addConst();
10302 }
10303
10304 // Add the capture.
10305 if (BuildAndDiagnose)
10306 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10307 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010308 Nested = true;
10309 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010310
10311 return false;
10312}
10313
10314bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10315 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10316 QualType CaptureType;
10317 QualType DeclRefType;
10318 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10319 /*BuildAndDiagnose=*/true, CaptureType,
10320 DeclRefType);
10321}
10322
10323QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10324 QualType CaptureType;
10325 QualType DeclRefType;
10326
10327 // Determine whether we can capture this variable.
10328 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10329 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10330 return QualType();
10331
10332 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010333}
10334
Eli Friedman3bda6b12012-02-02 23:15:15 +000010335static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10336 SourceLocation Loc) {
10337 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010338 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010339 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010340 Var->getLinkage() != ExternalLinkage &&
10341 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010342 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10343 if (old.isInvalid()) old = Loc;
10344 }
10345
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010346 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010347
Eli Friedman3bda6b12012-02-02 23:15:15 +000010348 Var->setUsed(true);
10349}
10350
10351void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10352 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10353 // an object that satisfies the requirements for appearing in a
10354 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10355 // is immediately applied." This function handles the lvalue-to-rvalue
10356 // conversion part.
10357 MaybeODRUseExprs.erase(E->IgnoreParens());
10358}
10359
Eli Friedmanc6237c62012-02-29 03:16:56 +000010360ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10361 if (!Res.isUsable())
10362 return Res;
10363
10364 // If a constant-expression is a reference to a variable where we delay
10365 // deciding whether it is an odr-use, just assume we will apply the
10366 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10367 // (a non-type template argument), we have special handling anyway.
10368 UpdateMarkingForLValueToRValue(Res.get());
10369 return Res;
10370}
10371
Eli Friedman3bda6b12012-02-02 23:15:15 +000010372void Sema::CleanupVarDeclMarking() {
10373 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10374 e = MaybeODRUseExprs.end();
10375 i != e; ++i) {
10376 VarDecl *Var;
10377 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010378 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010379 Var = cast<VarDecl>(DRE->getDecl());
10380 Loc = DRE->getLocation();
10381 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10382 Var = cast<VarDecl>(ME->getMemberDecl());
10383 Loc = ME->getMemberLoc();
10384 } else {
10385 llvm_unreachable("Unexpcted expression");
10386 }
10387
10388 MarkVarDeclODRUsed(*this, Var, Loc);
10389 }
10390
10391 MaybeODRUseExprs.clear();
10392}
10393
10394// Mark a VarDecl referenced, and perform the necessary handling to compute
10395// odr-uses.
10396static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10397 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010398 Var->setReferenced();
10399
Eli Friedman3bda6b12012-02-02 23:15:15 +000010400 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010401 return;
10402
10403 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010404 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010405 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10406 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010407 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10408 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010409 (!AlreadyInstantiated ||
10410 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010411 if (!AlreadyInstantiated) {
10412 // This is a modification of an existing AST node. Notify listeners.
10413 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10414 L->StaticDataMemberInstantiated(Var);
10415 MSInfo->setPointOfInstantiation(Loc);
10416 }
10417 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010418 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010419 // Do not defer instantiations of variables which could be used in a
10420 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010421 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010422 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010423 SemaRef.PendingInstantiations.push_back(
10424 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010425 }
10426 }
10427
Eli Friedman3bda6b12012-02-02 23:15:15 +000010428 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10429 // an object that satisfies the requirements for appearing in a
10430 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10431 // is immediately applied." We check the first part here, and
10432 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10433 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010434 // C++03 depends on whether we get the C++03 version correct. This does not
10435 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010436 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010437 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010438 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010439 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10440 SemaRef.MaybeODRUseExprs.insert(E);
10441 else
10442 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10443}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010444
Eli Friedman3bda6b12012-02-02 23:15:15 +000010445/// \brief Mark a variable referenced, and check whether it is odr-used
10446/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10447/// used directly for normal expressions referring to VarDecl.
10448void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10449 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010450}
10451
10452static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10453 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010454 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10455 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10456 return;
10457 }
10458
Eli Friedmanfa0df832012-02-02 03:46:19 +000010459 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010460}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010461
Eli Friedmanfa0df832012-02-02 03:46:19 +000010462/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10463void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10464 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10465}
10466
10467/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10468void Sema::MarkMemberReferenced(MemberExpr *E) {
10469 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10470}
10471
Douglas Gregorf02455e2012-02-10 09:26:04 +000010472/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010473/// marks the declaration referenced, and performs odr-use checking for functions
10474/// and variables. This method should not be used when building an normal
10475/// expression which refers to a variable.
10476void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10477 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10478 MarkVariableReferenced(Loc, VD);
10479 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10480 MarkFunctionReferenced(Loc, FD);
10481 else
10482 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010483}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010484
Douglas Gregor5597ab42010-05-07 23:12:07 +000010485namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010486 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010487 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010488 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010489 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10490 Sema &S;
10491 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010492
Douglas Gregor5597ab42010-05-07 23:12:07 +000010493 public:
10494 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010495
Douglas Gregor5597ab42010-05-07 23:12:07 +000010496 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010497
10498 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10499 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010500 };
10501}
10502
Chandler Carruthaf80f662010-06-09 08:17:30 +000010503bool MarkReferencedDecls::TraverseTemplateArgument(
10504 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010505 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000010506 if (Decl *D = Arg.getAsDecl())
10507 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010508 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010509
10510 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010511}
10512
Chandler Carruthaf80f662010-06-09 08:17:30 +000010513bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010514 if (ClassTemplateSpecializationDecl *Spec
10515 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10516 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010517 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010518 }
10519
Chandler Carruthc65667c2010-06-10 10:31:57 +000010520 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010521}
10522
10523void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10524 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010525 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010526}
10527
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010528namespace {
10529 /// \brief Helper class that marks all of the declarations referenced by
10530 /// potentially-evaluated subexpressions as "referenced".
10531 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10532 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010533 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010534
10535 public:
10536 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10537
Douglas Gregor680e9e02012-02-21 19:11:17 +000010538 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10539 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010540
10541 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010542 // If we were asked not to visit local variables, don't.
10543 if (SkipLocalVariables) {
10544 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10545 if (VD->hasLocalStorage())
10546 return;
10547 }
10548
Eli Friedmanfa0df832012-02-02 03:46:19 +000010549 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010550 }
10551
10552 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010553 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010554 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010555 }
10556
John McCall28fc7092011-11-10 05:35:25 +000010557 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010558 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010559 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10560 Visit(E->getSubExpr());
10561 }
10562
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010563 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010564 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010565 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010566 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010567 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010568 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010569 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010570
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010571 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10572 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010573 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010574 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10575 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10576 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010577 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010578 S.LookupDestructor(Record));
10579 }
10580
Douglas Gregor32b3de52010-09-11 23:32:50 +000010581 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010582 }
10583
10584 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010585 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010586 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010587 }
10588
Douglas Gregorf0873f42010-10-19 17:17:35 +000010589 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10590 Visit(E->getExpr());
10591 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010592
10593 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10594 Inherited::VisitImplicitCastExpr(E);
10595
10596 if (E->getCastKind() == CK_LValueToRValue)
10597 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10598 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010599 };
10600}
10601
10602/// \brief Mark any declarations that appear within this expression or any
10603/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010604///
10605/// \param SkipLocalVariables If true, don't mark local variables as
10606/// 'referenced'.
10607void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10608 bool SkipLocalVariables) {
10609 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010610}
10611
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010612/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10613/// of the program being compiled.
10614///
10615/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010616/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010617/// possibility that the code will actually be executable. Code in sizeof()
10618/// expressions, code used only during overload resolution, etc., are not
10619/// potentially evaluated. This routine will suppress such diagnostics or,
10620/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010621/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010622/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010623///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010624/// This routine should be used for all diagnostics that describe the run-time
10625/// behavior of a program, such as passing a non-POD value through an ellipsis.
10626/// Failure to do so will likely result in spurious diagnostics or failures
10627/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000010628bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010629 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010630 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010631 case Unevaluated:
10632 // The argument will never be evaluated, so don't complain.
10633 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010634
Richard Smith764d2fe2011-12-20 02:08:33 +000010635 case ConstantEvaluated:
10636 // Relevant diagnostics should be produced by constant evaluation.
10637 break;
10638
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010639 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010640 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000010641 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000010642 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000010643 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000010644 }
10645 else
10646 Diag(Loc, PD);
10647
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010648 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010649 }
10650
10651 return false;
10652}
10653
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010654bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10655 CallExpr *CE, FunctionDecl *FD) {
10656 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10657 return false;
10658
Richard Smithfd555f62012-02-22 02:04:18 +000010659 // If we're inside a decltype's expression, don't check for a valid return
10660 // type or construct temporaries until we know whether this is the last call.
10661 if (ExprEvalContexts.back().IsDecltype) {
10662 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10663 return false;
10664 }
10665
Douglas Gregora6c5abb2012-05-04 16:48:41 +000010666 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010667 FunctionDecl *FD;
10668 CallExpr *CE;
10669
10670 public:
10671 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
10672 : FD(FD), CE(CE) { }
10673
10674 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
10675 if (!FD) {
10676 S.Diag(Loc, diag::err_call_incomplete_return)
10677 << T << CE->getSourceRange();
10678 return;
10679 }
10680
10681 S.Diag(Loc, diag::err_call_function_incomplete_return)
10682 << CE->getSourceRange() << FD->getDeclName() << T;
10683 S.Diag(FD->getLocation(),
10684 diag::note_function_with_incomplete_return_type_declared_here)
10685 << FD->getDeclName();
10686 }
10687 } Diagnoser(FD, CE);
10688
10689 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010690 return true;
10691
10692 return false;
10693}
10694
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010695// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010696// will prevent this condition from triggering, which is what we want.
10697void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10698 SourceLocation Loc;
10699
John McCall0506e4a2009-11-11 02:41:58 +000010700 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010701 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010702
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010703 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010704 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010705 return;
10706
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010707 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10708
John McCallb0e419e2009-11-12 00:06:05 +000010709 // Greylist some idioms by putting them into a warning subcategory.
10710 if (ObjCMessageExpr *ME
10711 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10712 Selector Sel = ME->getSelector();
10713
John McCallb0e419e2009-11-12 00:06:05 +000010714 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000010715 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010716 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10717
10718 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010719 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010720 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10721 }
John McCall0506e4a2009-11-11 02:41:58 +000010722
John McCalld5707ab2009-10-12 21:59:07 +000010723 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010724 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010725 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010726 return;
10727
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010728 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010729 Loc = Op->getOperatorLoc();
10730 } else {
10731 // Not an assignment.
10732 return;
10733 }
10734
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010735 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010736
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010737 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010738 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10739 Diag(Loc, diag::note_condition_assign_silence)
10740 << FixItHint::CreateInsertion(Open, "(")
10741 << FixItHint::CreateInsertion(Close, ")");
10742
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010743 if (IsOrAssign)
10744 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10745 << FixItHint::CreateReplacement(Loc, "!=");
10746 else
10747 Diag(Loc, diag::note_condition_assign_to_comparison)
10748 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010749}
10750
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010751/// \brief Redundant parentheses over an equality comparison can indicate
10752/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000010753void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010754 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000010755 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010756 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10757 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010758 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000010759 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010760 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010761
Richard Trieuba63ce62011-09-09 01:45:06 +000010762 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010763
10764 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010765 if (opE->getOpcode() == BO_EQ &&
10766 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10767 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010768 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010769
Ted Kremenekae022092011-02-02 02:20:30 +000010770 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010771 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010772 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010773 << FixItHint::CreateRemoval(ParenERange.getBegin())
10774 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010775 Diag(Loc, diag::note_equality_comparison_to_assign)
10776 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010777 }
10778}
10779
John Wiegley01296292011-04-08 18:41:53 +000010780ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010781 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010782 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10783 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010784
John McCall0009fcc2011-04-26 20:42:42 +000010785 ExprResult result = CheckPlaceholderExpr(E);
10786 if (result.isInvalid()) return ExprError();
10787 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010788
John McCall0009fcc2011-04-26 20:42:42 +000010789 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010790 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000010791 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10792
John Wiegley01296292011-04-08 18:41:53 +000010793 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10794 if (ERes.isInvalid())
10795 return ExprError();
10796 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010797
10798 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010799 if (!T->isScalarType()) { // C99 6.8.4.1p1
10800 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10801 << T << E->getSourceRange();
10802 return ExprError();
10803 }
John McCalld5707ab2009-10-12 21:59:07 +000010804 }
10805
John Wiegley01296292011-04-08 18:41:53 +000010806 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010807}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010808
John McCalldadc5752010-08-24 06:29:42 +000010809ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010810 Expr *SubExpr) {
10811 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010812 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010813
Richard Trieuba63ce62011-09-09 01:45:06 +000010814 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010815}
John McCall36e7fe32010-10-12 00:20:44 +000010816
John McCall31996342011-04-07 08:22:57 +000010817namespace {
John McCall2979fe02011-04-12 00:42:48 +000010818 /// A visitor for rebuilding a call to an __unknown_any expression
10819 /// to have an appropriate type.
10820 struct RebuildUnknownAnyFunction
10821 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10822
10823 Sema &S;
10824
10825 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10826
10827 ExprResult VisitStmt(Stmt *S) {
10828 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000010829 }
10830
Richard Trieu10162ab2011-09-09 03:59:41 +000010831 ExprResult VisitExpr(Expr *E) {
10832 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
10833 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010834 return ExprError();
10835 }
10836
10837 /// Rebuild an expression which simply semantically wraps another
10838 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010839 template <class T> ExprResult rebuildSugarExpr(T *E) {
10840 ExprResult SubResult = Visit(E->getSubExpr());
10841 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010842
Richard Trieu10162ab2011-09-09 03:59:41 +000010843 Expr *SubExpr = SubResult.take();
10844 E->setSubExpr(SubExpr);
10845 E->setType(SubExpr->getType());
10846 E->setValueKind(SubExpr->getValueKind());
10847 assert(E->getObjectKind() == OK_Ordinary);
10848 return E;
John McCall2979fe02011-04-12 00:42:48 +000010849 }
10850
Richard Trieu10162ab2011-09-09 03:59:41 +000010851 ExprResult VisitParenExpr(ParenExpr *E) {
10852 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010853 }
10854
Richard Trieu10162ab2011-09-09 03:59:41 +000010855 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10856 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010857 }
10858
Richard Trieu10162ab2011-09-09 03:59:41 +000010859 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10860 ExprResult SubResult = Visit(E->getSubExpr());
10861 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010862
Richard Trieu10162ab2011-09-09 03:59:41 +000010863 Expr *SubExpr = SubResult.take();
10864 E->setSubExpr(SubExpr);
10865 E->setType(S.Context.getPointerType(SubExpr->getType()));
10866 assert(E->getValueKind() == VK_RValue);
10867 assert(E->getObjectKind() == OK_Ordinary);
10868 return E;
John McCall2979fe02011-04-12 00:42:48 +000010869 }
10870
Richard Trieu10162ab2011-09-09 03:59:41 +000010871 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
10872 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010873
Richard Trieu10162ab2011-09-09 03:59:41 +000010874 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000010875
Richard Trieu10162ab2011-09-09 03:59:41 +000010876 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000010877 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000010878 !(isa<CXXMethodDecl>(VD) &&
10879 cast<CXXMethodDecl>(VD)->isInstance()))
10880 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000010881
Richard Trieu10162ab2011-09-09 03:59:41 +000010882 return E;
John McCall2979fe02011-04-12 00:42:48 +000010883 }
10884
Richard Trieu10162ab2011-09-09 03:59:41 +000010885 ExprResult VisitMemberExpr(MemberExpr *E) {
10886 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010887 }
10888
Richard Trieu10162ab2011-09-09 03:59:41 +000010889 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10890 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000010891 }
10892 };
10893}
10894
10895/// Given a function expression of unknown-any type, try to rebuild it
10896/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010897static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
10898 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
10899 if (Result.isInvalid()) return ExprError();
10900 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000010901}
10902
10903namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010904 /// A visitor for rebuilding an expression of type __unknown_anytype
10905 /// into one which resolves the type directly on the referring
10906 /// expression. Strict preservation of the original source
10907 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010908 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010909 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010910
10911 Sema &S;
10912
10913 /// The current destination type.
10914 QualType DestType;
10915
Richard Trieu10162ab2011-09-09 03:59:41 +000010916 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
10917 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000010918
John McCall39439732011-04-09 22:50:59 +000010919 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010920 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000010921 }
10922
Richard Trieu10162ab2011-09-09 03:59:41 +000010923 ExprResult VisitExpr(Expr *E) {
10924 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10925 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010926 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010927 }
10928
Richard Trieu10162ab2011-09-09 03:59:41 +000010929 ExprResult VisitCallExpr(CallExpr *E);
10930 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000010931
John McCall39439732011-04-09 22:50:59 +000010932 /// Rebuild an expression which simply semantically wraps another
10933 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010934 template <class T> ExprResult rebuildSugarExpr(T *E) {
10935 ExprResult SubResult = Visit(E->getSubExpr());
10936 if (SubResult.isInvalid()) return ExprError();
10937 Expr *SubExpr = SubResult.take();
10938 E->setSubExpr(SubExpr);
10939 E->setType(SubExpr->getType());
10940 E->setValueKind(SubExpr->getValueKind());
10941 assert(E->getObjectKind() == OK_Ordinary);
10942 return E;
John McCall39439732011-04-09 22:50:59 +000010943 }
John McCall31996342011-04-07 08:22:57 +000010944
Richard Trieu10162ab2011-09-09 03:59:41 +000010945 ExprResult VisitParenExpr(ParenExpr *E) {
10946 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010947 }
10948
Richard Trieu10162ab2011-09-09 03:59:41 +000010949 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10950 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010951 }
10952
Richard Trieu10162ab2011-09-09 03:59:41 +000010953 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10954 const PointerType *Ptr = DestType->getAs<PointerType>();
10955 if (!Ptr) {
10956 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
10957 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010958 return ExprError();
10959 }
Richard Trieu10162ab2011-09-09 03:59:41 +000010960 assert(E->getValueKind() == VK_RValue);
10961 assert(E->getObjectKind() == OK_Ordinary);
10962 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010963
10964 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010965 DestType = Ptr->getPointeeType();
10966 ExprResult SubResult = Visit(E->getSubExpr());
10967 if (SubResult.isInvalid()) return ExprError();
10968 E->setSubExpr(SubResult.take());
10969 return E;
John McCall2979fe02011-04-12 00:42:48 +000010970 }
10971
Richard Trieu10162ab2011-09-09 03:59:41 +000010972 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000010973
Richard Trieu10162ab2011-09-09 03:59:41 +000010974 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000010975
Richard Trieu10162ab2011-09-09 03:59:41 +000010976 ExprResult VisitMemberExpr(MemberExpr *E) {
10977 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010978 }
John McCall39439732011-04-09 22:50:59 +000010979
Richard Trieu10162ab2011-09-09 03:59:41 +000010980 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10981 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000010982 }
10983 };
10984}
10985
John McCall2d2e8702011-04-11 07:02:50 +000010986/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000010987ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
10988 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010989
10990 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010991 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010992 FK_FunctionPointer,
10993 FK_BlockPointer
10994 };
10995
Richard Trieu10162ab2011-09-09 03:59:41 +000010996 FnKind Kind;
10997 QualType CalleeType = CalleeExpr->getType();
10998 if (CalleeType == S.Context.BoundMemberTy) {
10999 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11000 Kind = FK_MemberFunction;
11001 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11002 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11003 CalleeType = Ptr->getPointeeType();
11004 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011005 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011006 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11007 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011008 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011009 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011010
11011 // Verify that this is a legal result type of a function.
11012 if (DestType->isArrayType() || DestType->isFunctionType()) {
11013 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011014 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011015 diagID = diag::err_block_returning_array_function;
11016
Richard Trieu10162ab2011-09-09 03:59:41 +000011017 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011018 << DestType->isFunctionType() << DestType;
11019 return ExprError();
11020 }
11021
11022 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011023 E->setType(DestType.getNonLValueExprType(S.Context));
11024 E->setValueKind(Expr::getValueKindForType(DestType));
11025 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011026
11027 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011028 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011029 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011030 Proto->arg_type_begin(),
11031 Proto->getNumArgs(),
11032 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011033 else
11034 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011035 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011036
11037 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011038 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011039 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011040 // Nothing to do.
11041 break;
11042
11043 case FK_FunctionPointer:
11044 DestType = S.Context.getPointerType(DestType);
11045 break;
11046
11047 case FK_BlockPointer:
11048 DestType = S.Context.getBlockPointerType(DestType);
11049 break;
11050 }
11051
11052 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011053 ExprResult CalleeResult = Visit(CalleeExpr);
11054 if (!CalleeResult.isUsable()) return ExprError();
11055 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011056
11057 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011058 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011059}
11060
Richard Trieu10162ab2011-09-09 03:59:41 +000011061ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011062 // Verify that this is a legal result type of a call.
11063 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011064 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011065 << DestType->isFunctionType() << DestType;
11066 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011067 }
11068
John McCall3f4138c2011-07-13 17:56:40 +000011069 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011070 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11071 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11072 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011073 }
John McCall2979fe02011-04-12 00:42:48 +000011074
John McCall2d2e8702011-04-11 07:02:50 +000011075 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011076 E->setType(DestType.getNonReferenceType());
11077 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011078
Richard Trieu10162ab2011-09-09 03:59:41 +000011079 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011080}
11081
Richard Trieu10162ab2011-09-09 03:59:41 +000011082ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011083 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011084 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011085 assert(E->getValueKind() == VK_RValue);
11086 assert(E->getObjectKind() == OK_Ordinary);
11087
11088 E->setType(DestType);
11089
11090 // Rebuild the sub-expression as the pointee (function) type.
11091 DestType = DestType->castAs<PointerType>()->getPointeeType();
11092
11093 ExprResult Result = Visit(E->getSubExpr());
11094 if (!Result.isUsable()) return ExprError();
11095
11096 E->setSubExpr(Result.take());
11097 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011098 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011099 assert(E->getValueKind() == VK_RValue);
11100 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011101
Sean Callanan12495112012-03-06 21:34:12 +000011102 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011103
Sean Callanan12495112012-03-06 21:34:12 +000011104 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011105
Sean Callanan12495112012-03-06 21:34:12 +000011106 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11107 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011108
Sean Callanan12495112012-03-06 21:34:12 +000011109 ExprResult Result = Visit(E->getSubExpr());
11110 if (!Result.isUsable()) return ExprError();
11111
11112 E->setSubExpr(Result.take());
11113 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011114 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011115 llvm_unreachable("Unhandled cast type!");
11116 }
John McCall2d2e8702011-04-11 07:02:50 +000011117}
11118
Richard Trieu10162ab2011-09-09 03:59:41 +000011119ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11120 ExprValueKind ValueKind = VK_LValue;
11121 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011122
11123 // We know how to make this work for certain kinds of decls:
11124
11125 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011126 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11127 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11128 DestType = Ptr->getPointeeType();
11129 ExprResult Result = resolveDecl(E, VD);
11130 if (Result.isInvalid()) return ExprError();
11131 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011132 CK_FunctionToPointerDecay, VK_RValue);
11133 }
11134
Richard Trieu10162ab2011-09-09 03:59:41 +000011135 if (!Type->isFunctionType()) {
11136 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11137 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011138 return ExprError();
11139 }
John McCall2d2e8702011-04-11 07:02:50 +000011140
Richard Trieu10162ab2011-09-09 03:59:41 +000011141 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11142 if (MD->isInstance()) {
11143 ValueKind = VK_RValue;
11144 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011145 }
11146
John McCall2d2e8702011-04-11 07:02:50 +000011147 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011148 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011149 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011150
11151 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011152 } else if (isa<VarDecl>(VD)) {
11153 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11154 Type = RefTy->getPointeeType();
11155 } else if (Type->isFunctionType()) {
11156 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11157 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011158 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011159 }
11160
11161 // - nothing else
11162 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011163 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11164 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011165 return ExprError();
11166 }
11167
Richard Trieu10162ab2011-09-09 03:59:41 +000011168 VD->setType(DestType);
11169 E->setType(Type);
11170 E->setValueKind(ValueKind);
11171 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011172}
11173
John McCall31996342011-04-07 08:22:57 +000011174/// Check a cast of an unknown-any type. We intentionally only
11175/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011176ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11177 Expr *CastExpr, CastKind &CastKind,
11178 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011179 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011180 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011181 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011182
Richard Trieuba63ce62011-09-09 01:45:06 +000011183 CastExpr = result.take();
11184 VK = CastExpr->getValueKind();
11185 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011186
Richard Trieuba63ce62011-09-09 01:45:06 +000011187 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011188}
11189
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011190ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11191 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11192}
11193
Richard Trieuba63ce62011-09-09 01:45:06 +000011194static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11195 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011196 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011197 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011198 E = E->IgnoreParenImpCasts();
11199 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11200 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011201 diagID = diag::err_uncasted_call_of_unknown_any;
11202 } else {
John McCall31996342011-04-07 08:22:57 +000011203 break;
John McCall2d2e8702011-04-11 07:02:50 +000011204 }
John McCall31996342011-04-07 08:22:57 +000011205 }
11206
John McCall2d2e8702011-04-11 07:02:50 +000011207 SourceLocation loc;
11208 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011209 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011210 loc = ref->getLocation();
11211 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011212 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011213 loc = mem->getMemberLoc();
11214 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011215 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011216 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011217 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011218 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011219 if (!d) {
11220 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11221 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11222 << orig->getSourceRange();
11223 return ExprError();
11224 }
John McCall2d2e8702011-04-11 07:02:50 +000011225 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011226 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11227 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011228 return ExprError();
11229 }
11230
11231 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011232
11233 // Never recoverable.
11234 return ExprError();
11235}
11236
John McCall36e7fe32010-10-12 00:20:44 +000011237/// Check for operands with placeholder types and complain if found.
11238/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011239ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011240 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11241 if (!placeholderType) return Owned(E);
11242
11243 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011244
John McCall31996342011-04-07 08:22:57 +000011245 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011246 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011247 // Try to resolve a single function template specialization.
11248 // This is obligatory.
11249 ExprResult result = Owned(E);
11250 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11251 return result;
11252
11253 // If that failed, try to recover with a call.
11254 } else {
11255 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11256 /*complain*/ true);
11257 return result;
11258 }
11259 }
John McCall31996342011-04-07 08:22:57 +000011260
John McCall0009fcc2011-04-26 20:42:42 +000011261 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011262 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011263 ExprResult result = Owned(E);
11264 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11265 /*complain*/ true);
11266 return result;
John McCall4124c492011-10-17 18:40:02 +000011267 }
11268
11269 // ARC unbridged casts.
11270 case BuiltinType::ARCUnbridgedCast: {
11271 Expr *realCast = stripARCUnbridgedCast(E);
11272 diagnoseARCUnbridgedCast(realCast);
11273 return Owned(realCast);
11274 }
John McCall0009fcc2011-04-26 20:42:42 +000011275
John McCall31996342011-04-07 08:22:57 +000011276 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011277 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011278 return diagnoseUnknownAnyExpr(*this, E);
11279
John McCall526ab472011-10-25 17:37:35 +000011280 // Pseudo-objects.
11281 case BuiltinType::PseudoObject:
11282 return checkPseudoObjectRValue(E);
11283
John McCalle314e272011-10-18 21:02:43 +000011284 // Everything else should be impossible.
11285#define BUILTIN_TYPE(Id, SingletonId) \
11286 case BuiltinType::Id:
11287#define PLACEHOLDER_TYPE(Id, SingletonId)
11288#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011289 break;
11290 }
11291
11292 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011293}
Richard Trieu2c850c02011-04-21 21:44:26 +000011294
Richard Trieuba63ce62011-09-09 01:45:06 +000011295bool Sema::CheckCaseExpression(Expr *E) {
11296 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011297 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011298 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11299 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011300 return false;
11301}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011302
11303/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11304ExprResult
11305Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11306 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11307 "Unknown Objective-C Boolean value!");
11308 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian29898f42012-04-16 21:03:30 +000011309 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011310}