blob: f82ff4395ded8d9167a6f0e0c412ac1d78fc9fa3 [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
Douglas Gregor171c45a2009-02-18 21:56:37 +0000111/// \brief Determine whether the use of this declaration is valid, and
112/// emit any corresponding diagnostics.
113///
114/// This routine diagnoses various problems with referencing
115/// declarations that can occur when using a declaration. For example,
116/// it might warn if a deprecated or unavailable declaration is being
117/// used, or produce an error (and return true) if a C++0x deleted
118/// function is being used.
119///
120/// \returns true if there was an error (this declaration cannot be
121/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000122///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000123bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000124 const ObjCInterfaceDecl *UnknownObjCClass) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000125 if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
126 // If there were any diagnostics suppressed by template argument deduction,
127 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000128 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000129 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
130 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000131 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000132 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
133 Diag(Suppressed[I].first, Suppressed[I].second);
134
135 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000136 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000137 // entry from the table, because we want to avoid ever emitting these
138 // diagnostics again.
139 Suppressed.clear();
140 }
141 }
142
Richard Smith30482bc2011-02-20 03:19:35 +0000143 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000144 if (ParsingInitForAutoVars.count(D)) {
145 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
146 << D->getDeclName();
147 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000148 }
149
Douglas Gregor171c45a2009-02-18 21:56:37 +0000150 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000151 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000152 if (FD->isDeleted()) {
153 Diag(Loc, diag::err_deleted_function_use);
John McCall31168b02011-06-15 23:02:42 +0000154 Diag(D->getLocation(), diag::note_unavailable_here) << 1 << true;
Douglas Gregor171c45a2009-02-18 21:56:37 +0000155 return true;
156 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000157 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000158 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000159
Anders Carlsson73067a02010-10-22 23:37:08 +0000160 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000161 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000162 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Douglas Gregor171c45a2009-02-18 21:56:37 +0000163 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000164}
165
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000166/// \brief Retrieve the message suffix that should be added to a
167/// diagnostic complaining about the given function being deleted or
168/// unavailable.
169std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
170 // FIXME: C++0x implicitly-deleted special member functions could be
171 // detected here so that we could improve diagnostics to say, e.g.,
172 // "base class 'A' had a deleted copy constructor".
173 if (FD->isDeleted())
174 return std::string();
175
176 std::string Message;
177 if (FD->getAvailability(&Message))
178 return ": " + Message;
179
180 return std::string();
181}
182
John McCallb46f2872011-09-09 07:56:05 +0000183/// DiagnoseSentinelCalls - This routine checks whether a call or
184/// message-send is to a declaration with the sentinel attribute, and
185/// if so, it checks that the requirements of the sentinel are
186/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000187void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000188 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000189 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000190 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000191 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000192
John McCallb46f2872011-09-09 07:56:05 +0000193 // The number of formal parameters of the declaration.
194 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000195
John McCallb46f2872011-09-09 07:56:05 +0000196 // The kind of declaration. This is also an index into a %select in
197 // the diagnostic.
198 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
199
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000200 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000201 numFormalParams = MD->param_size();
202 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000203 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000204 numFormalParams = FD->param_size();
205 calleeType = CT_Function;
206 } else if (isa<VarDecl>(D)) {
207 QualType type = cast<ValueDecl>(D)->getType();
208 const FunctionType *fn = 0;
209 if (const PointerType *ptr = type->getAs<PointerType>()) {
210 fn = ptr->getPointeeType()->getAs<FunctionType>();
211 if (!fn) return;
212 calleeType = CT_Function;
213 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
214 fn = ptr->getPointeeType()->castAs<FunctionType>();
215 calleeType = CT_Block;
216 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000217 return;
John McCallb46f2872011-09-09 07:56:05 +0000218 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000219
John McCallb46f2872011-09-09 07:56:05 +0000220 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
221 numFormalParams = proto->getNumArgs();
222 } else {
223 numFormalParams = 0;
224 }
225 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000226 return;
227 }
John McCallb46f2872011-09-09 07:56:05 +0000228
229 // "nullPos" is the number of formal parameters at the end which
230 // effectively count as part of the variadic arguments. This is
231 // useful if you would prefer to not have *any* formal parameters,
232 // but the language forces you to have at least one.
233 unsigned nullPos = attr->getNullPos();
234 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
235 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
236
237 // The number of arguments which should follow the sentinel.
238 unsigned numArgsAfterSentinel = attr->getSentinel();
239
240 // If there aren't enough arguments for all the formal parameters,
241 // the sentinel, and the args after the sentinel, complain.
242 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000243 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000244 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000245 return;
246 }
John McCallb46f2872011-09-09 07:56:05 +0000247
248 // Otherwise, find the sentinel expression.
249 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000250 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000251 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000252 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000253
John McCallb46f2872011-09-09 07:56:05 +0000254 // Pick a reasonable string to insert. Optimistically use 'nil' or
255 // 'NULL' if those are actually defined in the context. Only use
256 // 'nil' for ObjC methods, where it's much more likely that the
257 // variadic arguments form a list of object pointers.
258 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000259 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
260 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000261 if (calleeType == CT_Method &&
262 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000263 NullValue = "nil";
264 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
265 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000266 else
John McCallb46f2872011-09-09 07:56:05 +0000267 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000268
269 if (MissingNilLoc.isInvalid())
270 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
271 else
272 Diag(MissingNilLoc, diag::warn_missing_sentinel)
273 << calleeType
274 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000275 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000276}
277
Richard Trieuba63ce62011-09-09 01:45:06 +0000278SourceRange Sema::getExprRange(Expr *E) const {
279 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000280}
281
Chris Lattner513165e2008-07-25 21:10:04 +0000282//===----------------------------------------------------------------------===//
283// Standard Promotions and Conversions
284//===----------------------------------------------------------------------===//
285
Chris Lattner513165e2008-07-25 21:10:04 +0000286/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000287ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000288 // Handle any placeholder expressions which made it here.
289 if (E->getType()->isPlaceholderType()) {
290 ExprResult result = CheckPlaceholderExpr(E);
291 if (result.isInvalid()) return ExprError();
292 E = result.take();
293 }
294
Chris Lattner513165e2008-07-25 21:10:04 +0000295 QualType Ty = E->getType();
296 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
297
Chris Lattner513165e2008-07-25 21:10:04 +0000298 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000299 E = ImpCastExprToType(E, Context.getPointerType(Ty),
300 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000301 else if (Ty->isArrayType()) {
302 // In C90 mode, arrays only promote to pointers if the array expression is
303 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
304 // type 'array of type' is converted to an expression that has type 'pointer
305 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
306 // that has type 'array of type' ...". The relevant change is "an lvalue"
307 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000308 //
309 // C++ 4.2p1:
310 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
311 // T" can be converted to an rvalue of type "pointer to T".
312 //
John McCall086a4642010-11-24 05:12:34 +0000313 if (getLangOptions().C99 || getLangOptions().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000314 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
315 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000316 }
John Wiegley01296292011-04-08 18:41:53 +0000317 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000318}
319
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000320static void CheckForNullPointerDereference(Sema &S, Expr *E) {
321 // Check to see if we are dereferencing a null pointer. If so,
322 // and if not volatile-qualified, this is undefined behavior that the
323 // optimizer will delete, so warn about it. People sometimes try to use this
324 // to get a deterministic trap and are surprised by clang's behavior. This
325 // only handles the pattern "*null", which is a very syntactic check.
326 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
327 if (UO->getOpcode() == UO_Deref &&
328 UO->getSubExpr()->IgnoreParenCasts()->
329 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
330 !UO->getType().isVolatileQualified()) {
331 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
332 S.PDiag(diag::warn_indirection_through_null)
333 << UO->getSubExpr()->getSourceRange());
334 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
335 S.PDiag(diag::note_indirection_through_null));
336 }
337}
338
John Wiegley01296292011-04-08 18:41:53 +0000339ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000340 // Handle any placeholder expressions which made it here.
341 if (E->getType()->isPlaceholderType()) {
342 ExprResult result = CheckPlaceholderExpr(E);
343 if (result.isInvalid()) return ExprError();
344 E = result.take();
345 }
346
John McCallf3735e02010-12-01 04:43:34 +0000347 // C++ [conv.lval]p1:
348 // A glvalue of a non-function, non-array type T can be
349 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000350 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000351
John McCall27584242010-12-06 20:48:59 +0000352 QualType T = E->getType();
353 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000354
Eli Friedman0dfb8892011-10-06 23:00:33 +0000355 // We can't do lvalue-to-rvalue on atomics yet.
John McCall526ab472011-10-25 17:37:35 +0000356 if (T->isAtomicType())
Eli Friedman0dfb8892011-10-06 23:00:33 +0000357 return Owned(E);
358
John McCall27584242010-12-06 20:48:59 +0000359 // We don't want to throw lvalue-to-rvalue casts on top of
360 // expressions of certain types in C++.
361 if (getLangOptions().CPlusPlus &&
362 (E->getType() == Context.OverloadTy ||
363 T->isDependentType() ||
364 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000365 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000366
367 // The C standard is actually really unclear on this point, and
368 // DR106 tells us what the result should be but not why. It's
369 // generally best to say that void types just doesn't undergo
370 // lvalue-to-rvalue at all. Note that expressions of unqualified
371 // 'void' type are never l-values, but qualified void can be.
372 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000373 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000374
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000375 CheckForNullPointerDereference(*this, E);
376
John McCall27584242010-12-06 20:48:59 +0000377 // C++ [conv.lval]p1:
378 // [...] If T is a non-class type, the type of the prvalue is the
379 // cv-unqualified version of T. Otherwise, the type of the
380 // rvalue is T.
381 //
382 // C99 6.3.2.1p2:
383 // If the lvalue has qualified type, the value has the unqualified
384 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000385 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000386 if (T.hasQualifiers())
387 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000388
Eli Friedman3bda6b12012-02-02 23:15:15 +0000389 UpdateMarkingForLValueToRValue(E);
390
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000391 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
392 E, 0, VK_RValue));
393
394 return Res;
John McCall27584242010-12-06 20:48:59 +0000395}
396
John Wiegley01296292011-04-08 18:41:53 +0000397ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
398 ExprResult Res = DefaultFunctionArrayConversion(E);
399 if (Res.isInvalid())
400 return ExprError();
401 Res = DefaultLvalueConversion(Res.take());
402 if (Res.isInvalid())
403 return ExprError();
404 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000405}
406
407
Chris Lattner513165e2008-07-25 21:10:04 +0000408/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000409/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000410/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000411/// apply if the array is an argument to the sizeof or address (&) operators.
412/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000413ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000414 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000415 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
416 if (Res.isInvalid())
417 return Owned(E);
418 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000419
John McCallf3735e02010-12-01 04:43:34 +0000420 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000421 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000422
423 // Half FP is a bit different: it's a storage-only type, meaning that any
424 // "use" of it should be promoted to float.
425 if (Ty->isHalfType())
426 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
427
John McCallf3735e02010-12-01 04:43:34 +0000428 // Try to perform integral promotions if the object has a theoretically
429 // promotable type.
430 if (Ty->isIntegralOrUnscopedEnumerationType()) {
431 // C99 6.3.1.1p2:
432 //
433 // The following may be used in an expression wherever an int or
434 // unsigned int may be used:
435 // - an object or expression with an integer type whose integer
436 // conversion rank is less than or equal to the rank of int
437 // and unsigned int.
438 // - A bit-field of type _Bool, int, signed int, or unsigned int.
439 //
440 // If an int can represent all values of the original type, the
441 // value is converted to an int; otherwise, it is converted to an
442 // unsigned int. These are called the integer promotions. All
443 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000444
John McCallf3735e02010-12-01 04:43:34 +0000445 QualType PTy = Context.isPromotableBitField(E);
446 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000447 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
448 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000449 }
450 if (Ty->isPromotableIntegerType()) {
451 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000452 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
453 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000454 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000455 }
John Wiegley01296292011-04-08 18:41:53 +0000456 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000457}
458
Chris Lattner2ce500f2008-07-25 22:25:12 +0000459/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000460/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000461/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000462ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
463 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000464 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000465
John Wiegley01296292011-04-08 18:41:53 +0000466 ExprResult Res = UsualUnaryConversions(E);
467 if (Res.isInvalid())
468 return Owned(E);
469 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000470
Chris Lattner2ce500f2008-07-25 22:25:12 +0000471 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000472 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000473 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
474
John McCall4bb057d2011-08-27 22:06:17 +0000475 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000476 // promotion, even on class types, but note:
477 // C++11 [conv.lval]p2:
478 // When an lvalue-to-rvalue conversion occurs in an unevaluated
479 // operand or a subexpression thereof the value contained in the
480 // referenced object is not accessed. Otherwise, if the glvalue
481 // has a class type, the conversion copy-initializes a temporary
482 // of type T from the glvalue and the result of the conversion
483 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000484 // FIXME: add some way to gate this entire thing for correctness in
485 // potentially potentially evaluated contexts.
486 if (getLangOptions().CPlusPlus && E->isGLValue() &&
487 ExprEvalContexts.back().Context != Unevaluated) {
488 ExprResult Temp = PerformCopyInitialization(
489 InitializedEntity::InitializeTemporary(E->getType()),
490 E->getExprLoc(),
491 Owned(E));
492 if (Temp.isInvalid())
493 return ExprError();
494 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000495 }
496
John Wiegley01296292011-04-08 18:41:53 +0000497 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000498}
499
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000500/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
501/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000502/// interfaces passed by value.
503ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000504 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000505 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
506 // Strip the unbridged-cast placeholder expression off, if applicable.
507 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
508 (CT == VariadicMethod ||
509 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
510 E = stripARCUnbridgedCast(E);
511
512 // Otherwise, do normal placeholder checking.
513 } else {
514 ExprResult ExprRes = CheckPlaceholderExpr(E);
515 if (ExprRes.isInvalid())
516 return ExprError();
517 E = ExprRes.take();
518 }
519 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000520
John McCall4124c492011-10-17 18:40:02 +0000521 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000522 if (ExprRes.isInvalid())
523 return ExprError();
524 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000525
Douglas Gregor347e0f22011-05-21 19:26:31 +0000526 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000527 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000528 DiagRuntimeBehavior(E->getLocStart(), 0,
529 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
530 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000531 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000532
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000533 // Complain about passing non-POD types through varargs. However, don't
534 // perform this check for incomplete types, which we can get here when we're
535 // in an unevaluated context.
536 if (!E->getType()->isIncompleteType() && !E->getType().isPODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000537 // C++0x [expr.call]p7:
538 // Passing a potentially-evaluated argument of class type (Clause 9)
539 // having a non-trivial copy constructor, a non-trivial move constructor,
540 // or a non-trivial destructor, with no corresponding parameter,
541 // is conditionally-supported with implementation-defined semantics.
542 bool TrivialEnough = false;
543 if (getLangOptions().CPlusPlus0x && !E->getType()->isDependentType()) {
544 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
545 if (Record->hasTrivialCopyConstructor() &&
546 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000547 Record->hasTrivialDestructor()) {
548 DiagRuntimeBehavior(E->getLocStart(), 0,
549 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
550 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000551 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000552 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000553 }
554 }
John McCall31168b02011-06-15 23:02:42 +0000555
556 if (!TrivialEnough &&
557 getLangOptions().ObjCAutoRefCount &&
558 E->getType()->isObjCLifetimeType())
559 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000560
561 if (TrivialEnough) {
562 // Nothing to diagnose. This is okay.
563 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000564 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
Douglas Gregor253cadf2011-05-21 16:27:21 +0000565 << getLangOptions().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000566 << CT)) {
567 // Turn this into a trap.
568 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000569 SourceLocation TemplateKWLoc;
Douglas Gregor347e0f22011-05-21 19:26:31 +0000570 UnqualifiedId Name;
571 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
572 E->getLocStart());
Abramo Bagnara7945c982012-01-27 09:46:47 +0000573 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
574 true, false);
Douglas Gregor347e0f22011-05-21 19:26:31 +0000575 if (TrapFn.isInvalid())
576 return ExprError();
577
578 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
579 MultiExprArg(), E->getLocEnd());
580 if (Call.isInvalid())
581 return ExprError();
582
583 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
584 Call.get(), E);
585 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000586 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000587 E = Comma.get();
588 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000589 }
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000590 // c++ rules are enforced elsewhere.
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000591 if (!getLangOptions().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000592 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000593 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000594 return ExprError();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000595
John Wiegley01296292011-04-08 18:41:53 +0000596 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000597}
598
Richard Trieu7aa58f12011-09-02 20:58:51 +0000599/// \brief Converts an integer to complex float type. Helper function of
600/// UsualArithmeticConversions()
601///
602/// \return false if the integer expression is an integer type and is
603/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000604static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
605 ExprResult &ComplexExpr,
606 QualType IntTy,
607 QualType ComplexTy,
608 bool SkipCast) {
609 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
610 if (SkipCast) return false;
611 if (IntTy->isIntegerType()) {
612 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
613 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
614 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000615 CK_FloatingRealToComplex);
616 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000617 assert(IntTy->isComplexIntegerType());
618 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000619 CK_IntegralComplexToFloatingComplex);
620 }
621 return false;
622}
623
624/// \brief Takes two complex float types and converts them to the same type.
625/// Helper function of UsualArithmeticConversions()
626static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000627handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
628 ExprResult &RHS, QualType LHSType,
629 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000630 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000631 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000632
633 if (order < 0) {
634 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000635 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000636 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
637 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000638 }
639 if (order > 0)
640 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000641 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
642 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000643}
644
645/// \brief Converts otherExpr to complex float and promotes complexExpr if
646/// necessary. Helper function of UsualArithmeticConversions()
647static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000648 ExprResult &ComplexExpr,
649 ExprResult &OtherExpr,
650 QualType ComplexTy,
651 QualType OtherTy,
652 bool ConvertComplexExpr,
653 bool ConvertOtherExpr) {
654 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000655
656 // If just the complexExpr is complex, the otherExpr needs to be converted,
657 // and the complexExpr might need to be promoted.
658 if (order > 0) { // complexExpr is wider
659 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000660 if (ConvertOtherExpr) {
661 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
662 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
663 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000664 CK_FloatingRealToComplex);
665 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000666 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000667 }
668
669 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000670 QualType result = (order == 0 ? ComplexTy :
671 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000672
673 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000674 if (ConvertOtherExpr)
675 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000676 CK_FloatingRealToComplex);
677
678 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000679 if (ConvertComplexExpr && order < 0)
680 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000681 CK_FloatingComplexCast);
682
683 return result;
684}
685
686/// \brief Handle arithmetic conversion with complex types. Helper function of
687/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000688static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
689 ExprResult &RHS, QualType LHSType,
690 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000691 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000692 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000693 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000694 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000695 return LHSType;
696 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000697 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000698 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000699
700 // This handles complex/complex, complex/float, or float/complex.
701 // When both operands are complex, the shorter operand is converted to the
702 // type of the longer, and that is the type of the result. This corresponds
703 // to what is done when combining two real floating-point operands.
704 // The fun begins when size promotion occur across type domains.
705 // From H&S 6.3.4: When one operand is complex and the other is a real
706 // floating-point type, the less precise type is converted, within it's
707 // real or complex domain, to the precision of the other type. For example,
708 // when combining a "long double" with a "double _Complex", the
709 // "double _Complex" is promoted to "long double _Complex".
710
Richard Trieu5065cdd2011-09-06 18:25:09 +0000711 bool LHSComplexFloat = LHSType->isComplexType();
712 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000713
714 // If both are complex, just cast to the more precise type.
715 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000716 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
717 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000718 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000719
720 // If only one operand is complex, promote it if necessary and convert the
721 // other operand to complex.
722 if (LHSComplexFloat)
723 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000724 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000725 /*convertOtherExpr*/ true);
726
727 assert(RHSComplexFloat);
728 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000729 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000730 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000731}
732
733/// \brief Hande arithmetic conversion from integer to float. Helper function
734/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000735static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
736 ExprResult &IntExpr,
737 QualType FloatTy, QualType IntTy,
738 bool ConvertFloat, bool ConvertInt) {
739 if (IntTy->isIntegerType()) {
740 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000741 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000742 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000743 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000744 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000745 }
746
747 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000748 assert(IntTy->isComplexIntegerType());
749 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000750
751 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000752 if (ConvertInt)
753 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000754 CK_IntegralComplexToFloatingComplex);
755
756 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000757 if (ConvertFloat)
758 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000759 CK_FloatingRealToComplex);
760
761 return result;
762}
763
764/// \brief Handle arithmethic conversion with floating point types. Helper
765/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000766static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
767 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000768 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000769 bool LHSFloat = LHSType->isRealFloatingType();
770 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000771
772 // If we have two real floating types, convert the smaller operand
773 // to the bigger result.
774 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000775 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000776 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000777 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
778 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000779 }
780
781 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000782 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000783 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
784 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000785 }
786
787 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000788 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000789 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000790 /*convertInt=*/ true);
791 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000792 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000793 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000794 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000795}
796
797/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000798/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000799// FIXME: if the operands are (int, _Complex long), we currently
800// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000801static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
802 ExprResult &RHS, QualType LHSType,
803 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000804 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000805 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
806 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807
Richard Trieucfe3f212011-09-06 18:38:41 +0000808 if (LHSComplexInt && RHSComplexInt) {
809 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
810 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000811 assert(order && "inequal types with equal element ordering");
812 if (order > 0) {
813 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000814 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
815 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000816 }
817
Richard Trieuba63ce62011-09-09 01:45:06 +0000818 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000819 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
820 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000821 }
822
Richard Trieucfe3f212011-09-06 18:38:41 +0000823 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000824 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000825 // FIXME: This needs to take integer ranks into account
826 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
827 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000828 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
829 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000830 }
831
Richard Trieucfe3f212011-09-06 18:38:41 +0000832 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000833 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000834 // FIXME: This needs to take integer ranks into account
835 if (!IsCompAssign) {
836 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
837 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000838 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000839 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000840 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000841}
842
843/// \brief Handle integer arithmetic conversions. Helper function of
844/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000845static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
846 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000847 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000848 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000849 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
850 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
851 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
852 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000853 // Same signedness; use the higher-ranked type
854 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000855 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
856 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000857 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000858 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
859 return RHSType;
860 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000861 // The unsigned type has greater than or equal rank to the
862 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000863 if (RHSSigned) {
864 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
865 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000866 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000867 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
868 return RHSType;
869 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000870 // The two types are different widths; if we are here, that
871 // means the signed type is larger than the unsigned type, so
872 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000873 if (LHSSigned) {
874 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
875 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000876 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000877 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
878 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000879 } else {
880 // The signed type is higher-ranked than the unsigned type,
881 // but isn't actually any bigger (like unsigned int and long
882 // on most 32-bit systems). Use the unsigned type corresponding
883 // to the signed type.
884 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000885 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
886 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000887 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000888 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000889 return result;
890 }
891}
892
Chris Lattner513165e2008-07-25 21:10:04 +0000893/// UsualArithmeticConversions - Performs various conversions that are common to
894/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000895/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000896/// responsible for emitting appropriate error diagnostics.
897/// FIXME: verify the conversion rules for "complex int" are consistent with
898/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000899QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000900 bool IsCompAssign) {
901 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000902 LHS = UsualUnaryConversions(LHS.take());
903 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000904 return QualType();
905 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000906
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000907 RHS = UsualUnaryConversions(RHS.take());
908 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000909 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000910
Mike Stump11289f42009-09-09 15:08:12 +0000911 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000912 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000913 QualType LHSType =
914 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
915 QualType RHSType =
916 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000917
918 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000919 if (LHSType == RHSType)
920 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000921
922 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
923 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000924 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
925 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000926
John McCalld005ac92010-11-13 08:17:45 +0000927 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000928 QualType LHSUnpromotedType = LHSType;
929 if (LHSType->isPromotableIntegerType())
930 LHSType = Context.getPromotedIntegerType(LHSType);
931 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +0000932 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000933 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +0000934 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000935 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +0000936
John McCalld005ac92010-11-13 08:17:45 +0000937 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000938 if (LHSType == RHSType)
939 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +0000940
941 // At this point, we have two different arithmetic types.
942
943 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000944 if (LHSType->isComplexType() || RHSType->isComplexType())
945 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000946 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000947
948 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000949 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
950 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000951 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000952
953 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000954 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000955 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000956 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +0000957
958 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000959 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000960 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +0000961}
962
Chris Lattner513165e2008-07-25 21:10:04 +0000963//===----------------------------------------------------------------------===//
964// Semantic Analysis for various Expression Types
965//===----------------------------------------------------------------------===//
966
967
Peter Collingbourne91147592011-04-15 00:35:48 +0000968ExprResult
969Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
970 SourceLocation DefaultLoc,
971 SourceLocation RParenLoc,
972 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +0000973 MultiTypeArg ArgTypes,
974 MultiExprArg ArgExprs) {
975 unsigned NumAssocs = ArgTypes.size();
976 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +0000977
Richard Trieuba63ce62011-09-09 01:45:06 +0000978 ParsedType *ParsedTypes = ArgTypes.release();
979 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +0000980
981 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
982 for (unsigned i = 0; i < NumAssocs; ++i) {
983 if (ParsedTypes[i])
984 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
985 else
986 Types[i] = 0;
987 }
988
989 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
990 ControllingExpr, Types, Exprs,
991 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +0000992 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +0000993 return ER;
994}
995
996ExprResult
997Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
998 SourceLocation DefaultLoc,
999 SourceLocation RParenLoc,
1000 Expr *ControllingExpr,
1001 TypeSourceInfo **Types,
1002 Expr **Exprs,
1003 unsigned NumAssocs) {
1004 bool TypeErrorFound = false,
1005 IsResultDependent = ControllingExpr->isTypeDependent(),
1006 ContainsUnexpandedParameterPack
1007 = ControllingExpr->containsUnexpandedParameterPack();
1008
1009 for (unsigned i = 0; i < NumAssocs; ++i) {
1010 if (Exprs[i]->containsUnexpandedParameterPack())
1011 ContainsUnexpandedParameterPack = true;
1012
1013 if (Types[i]) {
1014 if (Types[i]->getType()->containsUnexpandedParameterPack())
1015 ContainsUnexpandedParameterPack = true;
1016
1017 if (Types[i]->getType()->isDependentType()) {
1018 IsResultDependent = true;
1019 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001020 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001021 // complete object type other than a variably modified type."
1022 unsigned D = 0;
1023 if (Types[i]->getType()->isIncompleteType())
1024 D = diag::err_assoc_type_incomplete;
1025 else if (!Types[i]->getType()->isObjectType())
1026 D = diag::err_assoc_type_nonobject;
1027 else if (Types[i]->getType()->isVariablyModifiedType())
1028 D = diag::err_assoc_type_variably_modified;
1029
1030 if (D != 0) {
1031 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1032 << Types[i]->getTypeLoc().getSourceRange()
1033 << Types[i]->getType();
1034 TypeErrorFound = true;
1035 }
1036
Benjamin Kramere56f3932011-12-23 17:00:35 +00001037 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001038 // selection shall specify compatible types."
1039 for (unsigned j = i+1; j < NumAssocs; ++j)
1040 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1041 Context.typesAreCompatible(Types[i]->getType(),
1042 Types[j]->getType())) {
1043 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1044 diag::err_assoc_compatible_types)
1045 << Types[j]->getTypeLoc().getSourceRange()
1046 << Types[j]->getType()
1047 << Types[i]->getType();
1048 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1049 diag::note_compat_assoc)
1050 << Types[i]->getTypeLoc().getSourceRange()
1051 << Types[i]->getType();
1052 TypeErrorFound = true;
1053 }
1054 }
1055 }
1056 }
1057 if (TypeErrorFound)
1058 return ExprError();
1059
1060 // If we determined that the generic selection is result-dependent, don't
1061 // try to compute the result expression.
1062 if (IsResultDependent)
1063 return Owned(new (Context) GenericSelectionExpr(
1064 Context, KeyLoc, ControllingExpr,
1065 Types, Exprs, NumAssocs, DefaultLoc,
1066 RParenLoc, ContainsUnexpandedParameterPack));
1067
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001068 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001069 unsigned DefaultIndex = -1U;
1070 for (unsigned i = 0; i < NumAssocs; ++i) {
1071 if (!Types[i])
1072 DefaultIndex = i;
1073 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1074 Types[i]->getType()))
1075 CompatIndices.push_back(i);
1076 }
1077
Benjamin Kramere56f3932011-12-23 17:00:35 +00001078 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001079 // type compatible with at most one of the types named in its generic
1080 // association list."
1081 if (CompatIndices.size() > 1) {
1082 // We strip parens here because the controlling expression is typically
1083 // parenthesized in macro definitions.
1084 ControllingExpr = ControllingExpr->IgnoreParens();
1085 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1086 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1087 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001088 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001089 E = CompatIndices.end(); I != E; ++I) {
1090 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1091 diag::note_compat_assoc)
1092 << Types[*I]->getTypeLoc().getSourceRange()
1093 << Types[*I]->getType();
1094 }
1095 return ExprError();
1096 }
1097
Benjamin Kramere56f3932011-12-23 17:00:35 +00001098 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001099 // its controlling expression shall have type compatible with exactly one of
1100 // the types named in its generic association list."
1101 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1102 // We strip parens here because the controlling expression is typically
1103 // parenthesized in macro definitions.
1104 ControllingExpr = ControllingExpr->IgnoreParens();
1105 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1106 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1107 return ExprError();
1108 }
1109
Benjamin Kramere56f3932011-12-23 17:00:35 +00001110 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001111 // type name that is compatible with the type of the controlling expression,
1112 // then the result expression of the generic selection is the expression
1113 // in that generic association. Otherwise, the result expression of the
1114 // generic selection is the expression in the default generic association."
1115 unsigned ResultIndex =
1116 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1117
1118 return Owned(new (Context) GenericSelectionExpr(
1119 Context, KeyLoc, ControllingExpr,
1120 Types, Exprs, NumAssocs, DefaultLoc,
1121 RParenLoc, ContainsUnexpandedParameterPack,
1122 ResultIndex));
1123}
1124
Richard Smith75b67d62012-03-08 01:34:56 +00001125/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1126/// location of the token and the offset of the ud-suffix within it.
1127static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1128 unsigned Offset) {
1129 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
1130 S.getLangOptions());
1131}
1132
Steve Naroff83895f72007-09-16 03:34:24 +00001133/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001134/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1135/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1136/// multiple tokens. However, the common case is that StringToks points to one
1137/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001138///
John McCalldadc5752010-08-24 06:29:42 +00001139ExprResult
Alexis Hunt3b791862010-08-30 17:47:05 +00001140Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001141 assert(NumStringToks && "Must have at least one string!");
1142
Chris Lattner8a24e582009-01-16 18:51:42 +00001143 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001144 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001145 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001146
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001147 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001148 for (unsigned i = 0; i != NumStringToks; ++i)
1149 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001150
Chris Lattner36fc8792008-02-11 00:02:17 +00001151 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001152 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001153 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001154 else if (Literal.isUTF16())
1155 StrTy = Context.Char16Ty;
1156 else if (Literal.isUTF32())
1157 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001158 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001159 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001160
Douglas Gregorfb65e592011-07-27 05:40:30 +00001161 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1162 if (Literal.isWide())
1163 Kind = StringLiteral::Wide;
1164 else if (Literal.isUTF8())
1165 Kind = StringLiteral::UTF8;
1166 else if (Literal.isUTF16())
1167 Kind = StringLiteral::UTF16;
1168 else if (Literal.isUTF32())
1169 Kind = StringLiteral::UTF32;
1170
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001171 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001172 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001173 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001174
Chris Lattner36fc8792008-02-11 00:02:17 +00001175 // Get an array type for the string, according to C99 6.4.5. This includes
1176 // the nul terminator character as well as the string length for pascal
1177 // strings.
1178 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001179 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001180 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001181
Chris Lattner5b183d82006-11-10 05:03:26 +00001182 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001183 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1184 Kind, Literal.Pascal, StrTy,
1185 &StringTokLocs[0],
1186 StringTokLocs.size());
1187 if (Literal.getUDSuffix().empty())
1188 return Owned(Lit);
1189
1190 // We're building a user-defined literal.
1191 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001192 SourceLocation UDSuffixLoc =
1193 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1194 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001195
1196 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1197 // operator "" X (str, len)
1198 QualType SizeType = Context.getSizeType();
1199 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1200 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1201 StringTokLocs[0]);
1202 Expr *Args[] = { Lit, LenArg };
1203 return BuildLiteralOperatorCall(UDSuffix, UDSuffixLoc, Args,
1204 StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001205}
1206
John McCalldadc5752010-08-24 06:29:42 +00001207ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001208Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001209 SourceLocation Loc,
1210 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001211 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001212 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001213}
1214
John McCallf4cd4f92011-02-09 01:13:10 +00001215/// BuildDeclRefExpr - Build an expression that references a
1216/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001217ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001218Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001219 const DeclarationNameInfo &NameInfo,
1220 const CXXScopeSpec *SS) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001221 if (getLangOptions().CUDA)
1222 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1223 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1224 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1225 CalleeTarget = IdentifyCUDATarget(Callee);
1226 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1227 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1228 << CalleeTarget << D->getIdentifier() << CallerTarget;
1229 Diag(D->getLocation(), diag::note_previous_decl)
1230 << D->getIdentifier();
1231 return ExprError();
1232 }
1233 }
1234
Eli Friedmanfa0df832012-02-02 03:46:19 +00001235 DeclRefExpr *E = DeclRefExpr::Create(Context,
1236 SS ? SS->getWithLocInContext(Context)
1237 : NestedNameSpecifierLoc(),
1238 SourceLocation(),
1239 D, NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001240
Eli Friedmanfa0df832012-02-02 03:46:19 +00001241 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001242
1243 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001244 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1245 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001246 E->setObjectKind(OK_BitField);
1247
1248 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001249}
1250
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001251/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001252/// possibly a list of template arguments.
1253///
1254/// If this produces template arguments, it is permitted to call
1255/// DecomposeTemplateName.
1256///
1257/// This actually loses a lot of source location information for
1258/// non-standard name kinds; we should consider preserving that in
1259/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001260void
1261Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1262 TemplateArgumentListInfo &Buffer,
1263 DeclarationNameInfo &NameInfo,
1264 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001265 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1266 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1267 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1268
Douglas Gregor5476205b2011-06-23 00:49:38 +00001269 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001270 Id.TemplateId->getTemplateArgs(),
1271 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001272 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001273 TemplateArgsPtr.release();
1274
John McCall3e56fd42010-08-23 07:28:44 +00001275 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001276 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001277 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001278 TemplateArgs = &Buffer;
1279 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001280 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001281 TemplateArgs = 0;
1282 }
1283}
1284
John McCalld681c392009-12-16 08:11:27 +00001285/// Diagnose an empty lookup.
1286///
1287/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001288bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001289 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001290 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001291 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001292 DeclarationName Name = R.getLookupName();
1293
John McCalld681c392009-12-16 08:11:27 +00001294 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001295 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001296 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1297 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001298 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001299 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001300 diagnostic_suggest = diag::err_undeclared_use_suggest;
1301 }
John McCalld681c392009-12-16 08:11:27 +00001302
Douglas Gregor598b08f2009-12-31 05:20:13 +00001303 // If the original lookup was an unqualified lookup, fake an
1304 // unqualified lookup. This is useful when (for example) the
1305 // original lookup would not have found something because it was a
1306 // dependent name.
Francois Pichetde232cb2011-11-25 01:10:54 +00001307 DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1308 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001309 if (isa<CXXRecordDecl>(DC)) {
1310 LookupQualifiedName(R, DC);
1311
1312 if (!R.empty()) {
1313 // Don't give errors about ambiguities in this lookup.
1314 R.suppressDiagnostics();
1315
Francois Pichet857f9d62011-11-17 03:44:24 +00001316 // During a default argument instantiation the CurContext points
1317 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1318 // function parameter list, hence add an explicit check.
1319 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1320 ActiveTemplateInstantiations.back().Kind ==
1321 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001322 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1323 bool isInstance = CurMethod &&
1324 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001325 DC == CurMethod->getParent() && !isDefaultArgument;
1326
John McCalld681c392009-12-16 08:11:27 +00001327
1328 // Give a code modification hint to insert 'this->'.
1329 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1330 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001331 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001332 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1333 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001334 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001335 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001336 if (DepMethod) {
Francois Pichet78286b22011-11-15 23:33:34 +00001337 if (getLangOptions().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001338 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001339 Diag(R.getNameLoc(), diagnostic) << Name
1340 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1341 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001342 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001343 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1344 R.getNameLoc(), DepThisType, false);
1345 TemplateArgumentListInfo TList;
1346 if (ULE->hasExplicitTemplateArgs())
1347 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001348
Douglas Gregore16af532011-02-28 18:50:33 +00001349 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001350 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001351 CXXDependentScopeMemberExpr *DepExpr =
1352 CXXDependentScopeMemberExpr::Create(
1353 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001354 SS.getWithLocInContext(Context),
1355 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001356 R.getLookupNameInfo(),
1357 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001358 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001359 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001360 // FIXME: we should be able to handle this case too. It is correct
1361 // to add this-> here. This is a workaround for PR7947.
1362 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001363 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001364 } else {
Francois Pichet78286b22011-11-15 23:33:34 +00001365 if (getLangOptions().MicrosoftMode)
1366 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001367 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001368 }
John McCalld681c392009-12-16 08:11:27 +00001369
1370 // Do we really want to note all of these?
1371 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1372 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1373
Francois Pichet857f9d62011-11-17 03:44:24 +00001374 // Return true if we are inside a default argument instantiation
1375 // and the found name refers to an instance member function, otherwise
1376 // the function calling DiagnoseEmptyLookup will try to create an
1377 // implicit member call and this is wrong for default argument.
1378 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1379 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1380 return true;
1381 }
1382
John McCalld681c392009-12-16 08:11:27 +00001383 // Tell the callee to try to recover.
1384 return false;
1385 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001386
1387 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001388 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001389
1390 // In Microsoft mode, if we are performing lookup from within a friend
1391 // function definition declared at class scope then we must set
1392 // DC to the lexical parent to be able to search into the parent
1393 // class.
Lang Hamesc8c3b402011-11-29 22:37:13 +00001394 if (getLangOptions().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001395 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1396 DC->getLexicalParent()->isRecord())
1397 DC = DC->getLexicalParent();
1398 else
1399 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001400 }
1401
Douglas Gregor598b08f2009-12-31 05:20:13 +00001402 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001403 TypoCorrection Corrected;
1404 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001405 S, &SS, CCC))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001406 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1407 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1408 R.setLookupName(Corrected.getCorrection());
1409
Hans Wennborg38198de2011-07-12 08:45:31 +00001410 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001411 if (Corrected.isOverloaded()) {
1412 OverloadCandidateSet OCS(R.getNameLoc());
1413 OverloadCandidateSet::iterator Best;
1414 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1415 CDEnd = Corrected.end();
1416 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001417 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001418 dyn_cast<FunctionTemplateDecl>(*CD))
1419 AddTemplateOverloadCandidate(
1420 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001421 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001422 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1423 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1424 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001425 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001426 }
1427 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1428 case OR_Success:
1429 ND = Best->Function;
1430 break;
1431 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001432 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001433 }
1434 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001435 R.addDecl(ND);
1436 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001437 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001438 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1439 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001440 else
1441 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001442 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001443 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001444 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1445 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001446 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001447 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001448
1449 // Tell the callee to try to recover.
1450 return false;
1451 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001452
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001453 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001454 // FIXME: If we ended up with a typo for a type name or
1455 // Objective-C class name, we're in trouble because the parser
1456 // is in the wrong place to recover. Suggest the typo
1457 // correction, but don't make it a fix-it since we're not going
1458 // to recover well anyway.
1459 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001460 Diag(R.getNameLoc(), diagnostic_suggest)
1461 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001462 else
1463 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001464 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001465 << SS.getRange();
1466
1467 // Don't try to recover; it won't work.
1468 return true;
1469 }
1470 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001471 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001472 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001473 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001474 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001475 else
Douglas Gregor25363982010-01-01 00:15:04 +00001476 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001477 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001478 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001479 return true;
1480 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001481 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001482 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001483
1484 // Emit a special diagnostic for failed member lookups.
1485 // FIXME: computing the declaration context might fail here (?)
1486 if (!SS.isEmpty()) {
1487 Diag(R.getNameLoc(), diag::err_no_member)
1488 << Name << computeDeclContext(SS, false)
1489 << SS.getRange();
1490 return true;
1491 }
1492
John McCalld681c392009-12-16 08:11:27 +00001493 // Give up, we can't recover.
1494 Diag(R.getNameLoc(), diagnostic) << Name;
1495 return true;
1496}
1497
John McCalldadc5752010-08-24 06:29:42 +00001498ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001499 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001500 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001501 UnqualifiedId &Id,
1502 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001503 bool IsAddressOfOperand,
1504 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001505 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001506 "cannot be direct & operand and have a trailing lparen");
1507
1508 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001509 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001510
John McCall10eae182009-11-30 22:42:35 +00001511 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001512
1513 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001514 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001515 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001516 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001517
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001518 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001519 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001520 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001521
John McCalle66edc12009-11-24 19:00:30 +00001522 // C++ [temp.dep.expr]p3:
1523 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001524 // -- an identifier that was declared with a dependent type,
1525 // (note: handled after lookup)
1526 // -- a template-id that is dependent,
1527 // (note: handled in BuildTemplateIdExpr)
1528 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001529 // -- a nested-name-specifier that contains a class-name that
1530 // names a dependent type.
1531 // Determine whether this is a member of an unknown specialization;
1532 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001533 bool DependentID = false;
1534 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1535 Name.getCXXNameType()->isDependentType()) {
1536 DependentID = true;
1537 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001538 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001539 if (RequireCompleteDeclContext(SS, DC))
1540 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001541 } else {
1542 DependentID = true;
1543 }
1544 }
1545
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001546 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001547 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1548 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001549
John McCalle66edc12009-11-24 19:00:30 +00001550 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001551 LookupResult R(*this, NameInfo,
1552 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1553 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001554 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001555 // Lookup the template name again to correctly establish the context in
1556 // which it was found. This is really unfortunate as we already did the
1557 // lookup to determine that it was a template name in the first place. If
1558 // this becomes a performance hit, we can work harder to preserve those
1559 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001560 bool MemberOfUnknownSpecialization;
1561 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1562 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001563
1564 if (MemberOfUnknownSpecialization ||
1565 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001566 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1567 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001568 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001569 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001570 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001571
Douglas Gregora5226932011-02-04 13:35:07 +00001572 // If the result might be in a dependent base class, this is a dependent
1573 // id-expression.
1574 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001575 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1576 IsAddressOfOperand, TemplateArgs);
1577
John McCalle66edc12009-11-24 19:00:30 +00001578 // If this reference is in an Objective-C method, then we need to do
1579 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001580 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001581 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001582 if (E.isInvalid())
1583 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001584
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001585 if (Expr *Ex = E.takeAs<Expr>())
1586 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001587 }
Chris Lattner59a25942008-03-31 00:36:02 +00001588 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001589
John McCalle66edc12009-11-24 19:00:30 +00001590 if (R.isAmbiguous())
1591 return ExprError();
1592
Douglas Gregor171c45a2009-02-18 21:56:37 +00001593 // Determine whether this name might be a candidate for
1594 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001595 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001596
John McCalle66edc12009-11-24 19:00:30 +00001597 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001598 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001599 // in C90, extension in C99, forbidden in C++).
1600 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1601 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1602 if (D) R.addDecl(D);
1603 }
1604
1605 // If this name wasn't predeclared and if this is not a function
1606 // call, diagnose the problem.
1607 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001608
1609 // In Microsoft mode, if we are inside a template class member function
1610 // and we can't resolve an identifier then assume the identifier is type
1611 // dependent. The goal is to postpone name lookup to instantiation time
1612 // to be able to search into type dependent base classes.
1613 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1614 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001615 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1616 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001617
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001618 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001619 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001620 return ExprError();
1621
1622 assert(!R.empty() &&
1623 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001624
1625 // If we found an Objective-C instance variable, let
1626 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001627 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001628 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1629 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001630 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001631 // In a hopelessly buggy code, Objective-C instance variable
1632 // lookup fails and no expression will be built to reference it.
1633 if (!E.isInvalid() && !E.get())
1634 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001635 return move(E);
1636 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001637 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001638 }
Mike Stump11289f42009-09-09 15:08:12 +00001639
John McCalle66edc12009-11-24 19:00:30 +00001640 // This is guaranteed from this point on.
1641 assert(!R.empty() || ADL);
1642
John McCall2d74de92009-12-01 22:10:20 +00001643 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001644 // C++ [class.mfct.non-static]p3:
1645 // When an id-expression that is not part of a class member access
1646 // syntax and not used to form a pointer to member is used in the
1647 // body of a non-static member function of class X, if name lookup
1648 // resolves the name in the id-expression to a non-static non-type
1649 // member of some class C, the id-expression is transformed into a
1650 // class member access expression using (*this) as the
1651 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001652 //
1653 // But we don't actually need to do this for '&' operands if R
1654 // resolved to a function or overloaded function set, because the
1655 // expression is ill-formed if it actually works out to be a
1656 // non-static member function:
1657 //
1658 // C++ [expr.ref]p4:
1659 // Otherwise, if E1.E2 refers to a non-static member function. . .
1660 // [t]he expression can be used only as the left-hand operand of a
1661 // member function call.
1662 //
1663 // There are other safeguards against such uses, but it's important
1664 // to get this right here so that we don't end up making a
1665 // spuriously dependent expression if we're inside a dependent
1666 // instance method.
John McCall57500772009-12-16 12:17:52 +00001667 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001668 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001669 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001670 MightBeImplicitMember = true;
1671 else if (!SS.isEmpty())
1672 MightBeImplicitMember = false;
1673 else if (R.isOverloadedResult())
1674 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001675 else if (R.isUnresolvableResult())
1676 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001677 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001678 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1679 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001680
1681 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001682 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1683 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001684 }
1685
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001686 if (TemplateArgs || TemplateKWLoc.isValid())
1687 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001688
John McCalle66edc12009-11-24 19:00:30 +00001689 return BuildDeclarationNameExpr(SS, R, ADL);
1690}
1691
John McCall10eae182009-11-30 22:42:35 +00001692/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1693/// declaration name, generally during template instantiation.
1694/// There's a large number of things which don't need to be done along
1695/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001696ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001697Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001698 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001699 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001700 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001701 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1702 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001703
John McCall0b66eb32010-05-01 00:40:08 +00001704 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001705 return ExprError();
1706
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001707 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001708 LookupQualifiedName(R, DC);
1709
1710 if (R.isAmbiguous())
1711 return ExprError();
1712
1713 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001714 Diag(NameInfo.getLoc(), diag::err_no_member)
1715 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001716 return ExprError();
1717 }
1718
1719 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1720}
1721
1722/// LookupInObjCMethod - The parser has read a name in, and Sema has
1723/// detected that we're currently inside an ObjC method. Perform some
1724/// additional lookup.
1725///
1726/// Ideally, most of this would be done by lookup, but there's
1727/// actually quite a lot of extra work involved.
1728///
1729/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001730ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001731Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001732 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001733 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001734 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001735
John McCalle66edc12009-11-24 19:00:30 +00001736 // There are two cases to handle here. 1) scoped lookup could have failed,
1737 // in which case we should look for an ivar. 2) scoped lookup could have
1738 // found a decl, but that decl is outside the current instance method (i.e.
1739 // a global variable). In these two cases, we do a lookup for an ivar with
1740 // this name, if the lookup sucedes, we replace it our current decl.
1741
1742 // If we're in a class method, we don't normally want to look for
1743 // ivars. But if we don't find anything else, and there's an
1744 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001745 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001746
1747 bool LookForIvars;
1748 if (Lookup.empty())
1749 LookForIvars = true;
1750 else if (IsClassMethod)
1751 LookForIvars = false;
1752 else
1753 LookForIvars = (Lookup.isSingleResult() &&
1754 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001755 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001756 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001757 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001758 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001759 ObjCIvarDecl *IV = 0;
1760 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001761 // Diagnose using an ivar in a class method.
1762 if (IsClassMethod)
1763 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1764 << IV->getDeclName());
1765
1766 // If we're referencing an invalid decl, just return this as a silent
1767 // error node. The error diagnostic was already emitted on the decl.
1768 if (IV->isInvalidDecl())
1769 return ExprError();
1770
1771 // Check if referencing a field with __attribute__((deprecated)).
1772 if (DiagnoseUseOfDecl(IV, Loc))
1773 return ExprError();
1774
1775 // Diagnose the use of an ivar outside of the declaring class.
1776 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001777 !declaresSameEntity(ClassDeclared, IFace) &&
1778 !getLangOptions().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001779 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1780
1781 // FIXME: This should use a new expr for a direct reference, don't
1782 // turn this into Self->ivar, just return a BareIVarExpr or something.
1783 IdentifierInfo &II = Context.Idents.get("self");
1784 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001785 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001786 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001787 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001788 SourceLocation TemplateKWLoc;
1789 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001790 SelfName, false, false);
1791 if (SelfExpr.isInvalid())
1792 return ExprError();
1793
John Wiegley01296292011-04-08 18:41:53 +00001794 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1795 if (SelfExpr.isInvalid())
1796 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001797
Eli Friedmanfa0df832012-02-02 03:46:19 +00001798 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001799 return Owned(new (Context)
1800 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001801 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001802 }
Chris Lattner87313662010-04-12 05:10:17 +00001803 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001804 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001805 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1806 ObjCInterfaceDecl *ClassDeclared;
1807 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1808 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001809 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001810 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1811 }
John McCalle66edc12009-11-24 19:00:30 +00001812 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001813 } else if (Lookup.isSingleResult() &&
1814 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1815 // If accessing a stand-alone ivar in a class method, this is an error.
1816 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1817 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1818 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001819 }
1820
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001821 if (Lookup.empty() && II && AllowBuiltinCreation) {
1822 // FIXME. Consolidate this with similar code in LookupName.
1823 if (unsigned BuiltinID = II->getBuiltinID()) {
1824 if (!(getLangOptions().CPlusPlus &&
1825 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1826 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1827 S, Lookup.isForRedeclaration(),
1828 Lookup.getNameLoc());
1829 if (D) Lookup.addDecl(D);
1830 }
1831 }
1832 }
John McCalle66edc12009-11-24 19:00:30 +00001833 // Sentinel value saying that we didn't do anything special.
1834 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001835}
John McCalld14a8642009-11-21 08:51:07 +00001836
John McCall16df1e52010-03-30 21:47:33 +00001837/// \brief Cast a base object to a member's actual type.
1838///
1839/// Logically this happens in three phases:
1840///
1841/// * First we cast from the base type to the naming class.
1842/// The naming class is the class into which we were looking
1843/// when we found the member; it's the qualifier type if a
1844/// qualifier was provided, and otherwise it's the base type.
1845///
1846/// * Next we cast from the naming class to the declaring class.
1847/// If the member we found was brought into a class's scope by
1848/// a using declaration, this is that class; otherwise it's
1849/// the class declaring the member.
1850///
1851/// * Finally we cast from the declaring class to the "true"
1852/// declaring class of the member. This conversion does not
1853/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001854ExprResult
1855Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001856 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001857 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001858 NamedDecl *Member) {
1859 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1860 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001861 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001862
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001863 QualType DestRecordType;
1864 QualType DestType;
1865 QualType FromRecordType;
1866 QualType FromType = From->getType();
1867 bool PointerConversions = false;
1868 if (isa<FieldDecl>(Member)) {
1869 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001870
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001871 if (FromType->getAs<PointerType>()) {
1872 DestType = Context.getPointerType(DestRecordType);
1873 FromRecordType = FromType->getPointeeType();
1874 PointerConversions = true;
1875 } else {
1876 DestType = DestRecordType;
1877 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001878 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001879 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1880 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001881 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001882
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001883 DestType = Method->getThisType(Context);
1884 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001885
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001886 if (FromType->getAs<PointerType>()) {
1887 FromRecordType = FromType->getPointeeType();
1888 PointerConversions = true;
1889 } else {
1890 FromRecordType = FromType;
1891 DestType = DestRecordType;
1892 }
1893 } else {
1894 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001895 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001896 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001897
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001898 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001899 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001900
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001901 // If the unqualified types are the same, no conversion is necessary.
1902 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001903 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001904
John McCall16df1e52010-03-30 21:47:33 +00001905 SourceRange FromRange = From->getSourceRange();
1906 SourceLocation FromLoc = FromRange.getBegin();
1907
Eli Friedmanbe4b3632011-09-27 21:58:52 +00001908 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001909
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001910 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001911 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001912 // class name.
1913 //
1914 // If the member was a qualified name and the qualified referred to a
1915 // specific base subobject type, we'll cast to that intermediate type
1916 // first and then to the object in which the member is declared. That allows
1917 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1918 //
1919 // class Base { public: int x; };
1920 // class Derived1 : public Base { };
1921 // class Derived2 : public Base { };
1922 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1923 //
1924 // void VeryDerived::f() {
1925 // x = 17; // error: ambiguous base subobjects
1926 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1927 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001928 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001929 QualType QType = QualType(Qualifier->getAsType(), 0);
1930 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1931 assert(QType->isRecordType() && "lookup done with non-record type");
1932
1933 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1934
1935 // In C++98, the qualifier type doesn't actually have to be a base
1936 // type of the object type, in which case we just ignore it.
1937 // Otherwise build the appropriate casts.
1938 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001939 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001940 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001941 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00001942 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00001943
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001945 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00001946 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1947 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00001948
1949 FromType = QType;
1950 FromRecordType = QRecordType;
1951
1952 // If the qualifier type was the same as the destination type,
1953 // we're done.
1954 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001955 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001956 }
1957 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001958
John McCall16df1e52010-03-30 21:47:33 +00001959 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001960
John McCall16df1e52010-03-30 21:47:33 +00001961 // If we actually found the member through a using declaration, cast
1962 // down to the using declaration's type.
1963 //
1964 // Pointer equality is fine here because only one declaration of a
1965 // class ever has member declarations.
1966 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
1967 assert(isa<UsingShadowDecl>(FoundDecl));
1968 QualType URecordType = Context.getTypeDeclType(
1969 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
1970
1971 // We only need to do this if the naming-class to declaring-class
1972 // conversion is non-trivial.
1973 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
1974 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00001975 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001976 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001977 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00001978 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00001979
John McCall16df1e52010-03-30 21:47:33 +00001980 QualType UType = URecordType;
1981 if (PointerConversions)
1982 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00001983 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
1984 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00001985 FromType = UType;
1986 FromRecordType = URecordType;
1987 }
1988
1989 // We don't do access control for the conversion from the
1990 // declaring class to the true declaring class.
1991 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001992 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001993
John McCallcf142162010-08-07 06:22:56 +00001994 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00001995 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
1996 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00001997 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00001998 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001999
John Wiegley01296292011-04-08 18:41:53 +00002000 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2001 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002002}
Douglas Gregor3256d042009-06-30 15:47:41 +00002003
John McCalle66edc12009-11-24 19:00:30 +00002004bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002005 const LookupResult &R,
2006 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002007 // Only when used directly as the postfix-expression of a call.
2008 if (!HasTrailingLParen)
2009 return false;
2010
2011 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002012 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002013 return false;
2014
2015 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002016 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002017 return false;
2018
2019 // Turn off ADL when we find certain kinds of declarations during
2020 // normal lookup:
2021 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2022 NamedDecl *D = *I;
2023
2024 // C++0x [basic.lookup.argdep]p3:
2025 // -- a declaration of a class member
2026 // Since using decls preserve this property, we check this on the
2027 // original decl.
John McCall57500772009-12-16 12:17:52 +00002028 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002029 return false;
2030
2031 // C++0x [basic.lookup.argdep]p3:
2032 // -- a block-scope function declaration that is not a
2033 // using-declaration
2034 // NOTE: we also trigger this for function templates (in fact, we
2035 // don't check the decl type at all, since all other decl types
2036 // turn off ADL anyway).
2037 if (isa<UsingShadowDecl>(D))
2038 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2039 else if (D->getDeclContext()->isFunctionOrMethod())
2040 return false;
2041
2042 // C++0x [basic.lookup.argdep]p3:
2043 // -- a declaration that is neither a function or a function
2044 // template
2045 // And also for builtin functions.
2046 if (isa<FunctionDecl>(D)) {
2047 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2048
2049 // But also builtin functions.
2050 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2051 return false;
2052 } else if (!isa<FunctionTemplateDecl>(D))
2053 return false;
2054 }
2055
2056 return true;
2057}
2058
2059
John McCalld14a8642009-11-21 08:51:07 +00002060/// Diagnoses obvious problems with the use of the given declaration
2061/// as an expression. This is only actually called for lookups that
2062/// were not overloaded, and it doesn't promise that the declaration
2063/// will in fact be used.
2064static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002065 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002066 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2067 return true;
2068 }
2069
2070 if (isa<ObjCInterfaceDecl>(D)) {
2071 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2072 return true;
2073 }
2074
2075 if (isa<NamespaceDecl>(D)) {
2076 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2077 return true;
2078 }
2079
2080 return false;
2081}
2082
John McCalldadc5752010-08-24 06:29:42 +00002083ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002084Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002085 LookupResult &R,
2086 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002087 // If this is a single, fully-resolved result and we don't need ADL,
2088 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002089 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002090 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2091 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002092
2093 // We only need to check the declaration if there's exactly one
2094 // result, because in the overloaded case the results can only be
2095 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002096 if (R.isSingleResult() &&
2097 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002098 return ExprError();
2099
John McCall58cc69d2010-01-27 01:50:18 +00002100 // Otherwise, just build an unresolved lookup expression. Suppress
2101 // any lookup-related diagnostics; we'll hash these out later, when
2102 // we've picked a target.
2103 R.suppressDiagnostics();
2104
John McCalld14a8642009-11-21 08:51:07 +00002105 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002106 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002107 SS.getWithLocInContext(Context),
2108 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002109 NeedsADL, R.isOverloadedResult(),
2110 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002111
2112 return Owned(ULE);
2113}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002114
Eli Friedman9bb33f52012-02-03 02:04:35 +00002115static bool shouldBuildBlockDeclRef(ValueDecl *D, Sema &S) {
2116 // Check for a variable with local storage not from the current scope;
2117 // we need to create BlockDeclRefExprs for these.
2118 // FIXME: BlockDeclRefExpr shouldn't exist!
2119 VarDecl *var = dyn_cast<VarDecl>(D);
2120 if (!var)
2121 return false;
2122 if (var->getDeclContext() == S.CurContext)
2123 return false;
2124 if (!var->hasLocalStorage())
2125 return false;
2126 return S.getCurBlock() != 0;
2127}
2128
Eli Friedman9bb33f52012-02-03 02:04:35 +00002129static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
2130 const DeclarationNameInfo &NameInfo) {
2131 VarDecl *var = cast<VarDecl>(VD);
2132 QualType exprType = var->getType().getNonReferenceType();
2133
2134 bool HasBlockAttr = var->hasAttr<BlocksAttr>();
2135 bool ConstAdded = false;
2136 if (!HasBlockAttr) {
2137 ConstAdded = !exprType.isConstQualified();
2138 exprType.addConst();
2139 }
2140
2141 BlockDeclRefExpr *BDRE =
2142 new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
2143 NameInfo.getLoc(), HasBlockAttr,
2144 ConstAdded);
2145
2146 S.MarkBlockDeclRefReferenced(BDRE);
2147
2148 return S.Owned(BDRE);
2149}
2150
John McCalld14a8642009-11-21 08:51:07 +00002151/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002152ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002153Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002154 const DeclarationNameInfo &NameInfo,
2155 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002156 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002157 assert(!isa<FunctionTemplateDecl>(D) &&
2158 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002159
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002160 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002161 if (CheckDeclInExpr(*this, Loc, D))
2162 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002163
Douglas Gregore7488b92009-12-01 16:58:18 +00002164 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2165 // Specifically diagnose references to class templates that are missing
2166 // a template argument list.
2167 Diag(Loc, diag::err_template_decl_ref)
2168 << Template << SS.getRange();
2169 Diag(Template->getLocation(), diag::note_template_decl_here);
2170 return ExprError();
2171 }
2172
2173 // Make sure that we're referring to a value.
2174 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2175 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002176 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002177 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002178 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002179 return ExprError();
2180 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002181
Douglas Gregor171c45a2009-02-18 21:56:37 +00002182 // Check whether this declaration can be used. Note that we suppress
2183 // this check when we're going to perform argument-dependent lookup
2184 // on this function name, because this might not be the function
2185 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002186 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002187 return ExprError();
2188
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002189 // Only create DeclRefExpr's for valid Decl's.
2190 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002191 return ExprError();
2192
John McCallf3a88602011-02-03 08:15:49 +00002193 // Handle members of anonymous structs and unions. If we got here,
2194 // and the reference is to a class member indirect field, then this
2195 // must be the subject of a pointer-to-member expression.
2196 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2197 if (!indirectField->isCXXClassMember())
2198 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2199 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002200
Eli Friedman9bb33f52012-02-03 02:04:35 +00002201 {
John McCallf4cd4f92011-02-09 01:13:10 +00002202 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002203 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002204
2205 switch (D->getKind()) {
2206 // Ignore all the non-ValueDecl kinds.
2207#define ABSTRACT_DECL(kind)
2208#define VALUE(type, base)
2209#define DECL(type, base) \
2210 case Decl::type:
2211#include "clang/AST/DeclNodes.inc"
2212 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002213
2214 // These shouldn't make it here.
2215 case Decl::ObjCAtDefsField:
2216 case Decl::ObjCIvar:
2217 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002218
2219 // Enum constants are always r-values and never references.
2220 // Unresolved using declarations are dependent.
2221 case Decl::EnumConstant:
2222 case Decl::UnresolvedUsingValue:
2223 valueKind = VK_RValue;
2224 break;
2225
2226 // Fields and indirect fields that got here must be for
2227 // pointer-to-member expressions; we just call them l-values for
2228 // internal consistency, because this subexpression doesn't really
2229 // exist in the high-level semantics.
2230 case Decl::Field:
2231 case Decl::IndirectField:
2232 assert(getLangOptions().CPlusPlus &&
2233 "building reference to field in C?");
2234
2235 // These can't have reference type in well-formed programs, but
2236 // for internal consistency we do this anyway.
2237 type = type.getNonReferenceType();
2238 valueKind = VK_LValue;
2239 break;
2240
2241 // Non-type template parameters are either l-values or r-values
2242 // depending on the type.
2243 case Decl::NonTypeTemplateParm: {
2244 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2245 type = reftype->getPointeeType();
2246 valueKind = VK_LValue; // even if the parameter is an r-value reference
2247 break;
2248 }
2249
2250 // For non-references, we need to strip qualifiers just in case
2251 // the template parameter was declared as 'const int' or whatever.
2252 valueKind = VK_RValue;
2253 type = type.getUnqualifiedType();
2254 break;
2255 }
2256
2257 case Decl::Var:
2258 // In C, "extern void blah;" is valid and is an r-value.
2259 if (!getLangOptions().CPlusPlus &&
2260 !type.hasQualifiers() &&
2261 type->isVoidType()) {
2262 valueKind = VK_RValue;
2263 break;
2264 }
2265 // fallthrough
2266
2267 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002268 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002269 // These are always l-values.
2270 valueKind = VK_LValue;
2271 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002272
2273 if (shouldBuildBlockDeclRef(VD, *this))
2274 return BuildBlockDeclRefExpr(*this, VD, NameInfo);
2275
Douglas Gregor812d8f62012-02-18 05:51:20 +00002276 // FIXME: Does the addition of const really only apply in
2277 // potentially-evaluated contexts? Since the variable isn't actually
2278 // captured in an unevaluated context, it seems that the answer is no.
2279 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2280 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2281 if (!CapturedType.isNull())
2282 type = CapturedType;
2283 }
2284
John McCallf4cd4f92011-02-09 01:13:10 +00002285 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002286 }
2287
John McCallf4cd4f92011-02-09 01:13:10 +00002288 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002289 const FunctionType *fty = type->castAs<FunctionType>();
2290
2291 // If we're referring to a function with an __unknown_anytype
2292 // result type, make the entire expression __unknown_anytype.
2293 if (fty->getResultType() == Context.UnknownAnyTy) {
2294 type = Context.UnknownAnyTy;
2295 valueKind = VK_RValue;
2296 break;
2297 }
2298
John McCallf4cd4f92011-02-09 01:13:10 +00002299 // Functions are l-values in C++.
2300 if (getLangOptions().CPlusPlus) {
2301 valueKind = VK_LValue;
2302 break;
2303 }
2304
2305 // C99 DR 316 says that, if a function type comes from a
2306 // function definition (without a prototype), that type is only
2307 // used for checking compatibility. Therefore, when referencing
2308 // the function, we pretend that we don't have the full function
2309 // type.
John McCall2979fe02011-04-12 00:42:48 +00002310 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2311 isa<FunctionProtoType>(fty))
2312 type = Context.getFunctionNoProtoType(fty->getResultType(),
2313 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002314
2315 // Functions are r-values in C.
2316 valueKind = VK_RValue;
2317 break;
2318 }
2319
2320 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002321 // If we're referring to a method with an __unknown_anytype
2322 // result type, make the entire expression __unknown_anytype.
2323 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002324 if (const FunctionProtoType *proto
2325 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002326 if (proto->getResultType() == Context.UnknownAnyTy) {
2327 type = Context.UnknownAnyTy;
2328 valueKind = VK_RValue;
2329 break;
2330 }
2331
John McCallf4cd4f92011-02-09 01:13:10 +00002332 // C++ methods are l-values if static, r-values if non-static.
2333 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2334 valueKind = VK_LValue;
2335 break;
2336 }
2337 // fallthrough
2338
2339 case Decl::CXXConversion:
2340 case Decl::CXXDestructor:
2341 case Decl::CXXConstructor:
2342 valueKind = VK_RValue;
2343 break;
2344 }
2345
2346 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2347 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002348}
Chris Lattnere168f762006-11-10 05:29:30 +00002349
John McCall2979fe02011-04-12 00:42:48 +00002350ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002351 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002352
Chris Lattnere168f762006-11-10 05:29:30 +00002353 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002354 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002355 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2356 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2357 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002358 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002359
Chris Lattnera81a0272008-01-12 08:14:25 +00002360 // Pre-defined identifiers are of type char[x], where x is the length of the
2361 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002362
Anders Carlsson2fb08242009-09-08 18:24:21 +00002363 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002364 if (!currentDecl && getCurBlock())
2365 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002366 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002367 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002368 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002369 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002370
Anders Carlsson0b209a82009-09-11 01:22:35 +00002371 QualType ResTy;
2372 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2373 ResTy = Context.DependentTy;
2374 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002375 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002376
Anders Carlsson0b209a82009-09-11 01:22:35 +00002377 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002378 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002379 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2380 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002381 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002382}
2383
John McCalldadc5752010-08-24 06:29:42 +00002384ExprResult Sema::ActOnCharacterConstant(const Token &Tok) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002385 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002386 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002387 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002388 if (Invalid)
2389 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002390
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002391 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002392 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002393 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002394 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002395
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002396 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002397 if (Literal.isWide())
2398 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002399 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002400 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002401 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002402 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2403 else if (!getLangOptions().CPlusPlus || Literal.isMultiChar())
2404 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002405 else
2406 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002407
Douglas Gregorfb65e592011-07-27 05:40:30 +00002408 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2409 if (Literal.isWide())
2410 Kind = CharacterLiteral::Wide;
2411 else if (Literal.isUTF16())
2412 Kind = CharacterLiteral::UTF16;
2413 else if (Literal.isUTF32())
2414 Kind = CharacterLiteral::UTF32;
2415
Richard Smith75b67d62012-03-08 01:34:56 +00002416 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2417 Tok.getLocation());
2418
2419 if (Literal.getUDSuffix().empty())
2420 return Owned(Lit);
2421
2422 // We're building a user-defined literal.
2423 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2424 SourceLocation UDSuffixLoc =
2425 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2426
2427 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2428 // operator "" X (ch)
2429 return BuildLiteralOperatorCall(UDSuffix, UDSuffixLoc,
2430 llvm::makeArrayRef(&Lit, 1),
2431 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002432}
2433
Ted Kremeneke65b0862012-03-06 20:05:56 +00002434ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2435 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2436 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2437 Context.IntTy, Loc));
2438}
2439
John McCalldadc5752010-08-24 06:29:42 +00002440ExprResult Sema::ActOnNumericConstant(const Token &Tok) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002441 // Fast path for a single digit (which is quite common). A single digit
Steve Narofff2fb89e2007-03-13 20:29:44 +00002442 // cannot have a trigraph, escaped newline, radix prefix, or type suffix.
2443 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002444 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002445 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002446 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002447
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002448 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002449 // Add padding so that NumericLiteralParser can overread by one character.
2450 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002451 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002452
Chris Lattner67ca9252007-05-21 01:08:44 +00002453 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002454 bool Invalid = false;
2455 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2456 if (Invalid)
2457 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002458
Mike Stump11289f42009-09-09 15:08:12 +00002459 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002460 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002461 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002462 return ExprError();
2463
Chris Lattner1c20a172007-08-26 03:42:43 +00002464 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002465
Chris Lattner1c20a172007-08-26 03:42:43 +00002466 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002467 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002468 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002469 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002470 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002471 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002472 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002473 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002474
2475 const llvm::fltSemantics &Format = Context.getFloatTypeSemantics(Ty);
2476
John McCall53b93a02009-12-24 09:08:04 +00002477 using llvm::APFloat;
2478 APFloat Val(Format);
2479
2480 APFloat::opStatus result = Literal.GetFloatValue(Val);
John McCall122c8312009-12-24 11:09:08 +00002481
2482 // Overflow is always an error, but underflow is only an error if
2483 // we underflowed to zero (APFloat reports denormals as underflow).
2484 if ((result & APFloat::opOverflow) ||
2485 ((result & APFloat::opUnderflow) && Val.isZero())) {
John McCall53b93a02009-12-24 09:08:04 +00002486 unsigned diagnostic;
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002487 SmallString<20> buffer;
John McCall53b93a02009-12-24 09:08:04 +00002488 if (result & APFloat::opOverflow) {
John McCall62abc942010-02-26 23:35:57 +00002489 diagnostic = diag::warn_float_overflow;
John McCall53b93a02009-12-24 09:08:04 +00002490 APFloat::getLargest(Format).toString(buffer);
2491 } else {
John McCall62abc942010-02-26 23:35:57 +00002492 diagnostic = diag::warn_float_underflow;
John McCall53b93a02009-12-24 09:08:04 +00002493 APFloat::getSmallest(Format).toString(buffer);
2494 }
2495
2496 Diag(Tok.getLocation(), diagnostic)
2497 << Ty
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002498 << StringRef(buffer.data(), buffer.size());
John McCall53b93a02009-12-24 09:08:04 +00002499 }
2500
2501 bool isExact = (result == APFloat::opOK);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002502 Res = FloatingLiteral::Create(Context, Val, isExact, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002503
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002504 if (Ty == Context.DoubleTy) {
2505 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002506 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002507 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2508 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002509 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002510 }
2511 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002512 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002513 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002514 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002515 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002516
Neil Boothac582c52007-08-29 22:00:19 +00002517 // long long is a C99 feature.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002518 if (!getLangOptions().C99 && Literal.isLongLong)
2519 Diag(Tok.getLocation(),
2520 getLangOptions().CPlusPlus0x ?
2521 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002522
Chris Lattner67ca9252007-05-21 01:08:44 +00002523 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002524 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002525
Chris Lattner67ca9252007-05-21 01:08:44 +00002526 if (Literal.GetIntegerValue(ResultVal)) {
2527 // If this value didn't fit into uintmax_t, warn and force to ull.
2528 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002529 Ty = Context.UnsignedLongLongTy;
2530 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002531 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002532 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002533 // If this value fits into a ULL, try to figure out what else it fits into
2534 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002535
Chris Lattner67ca9252007-05-21 01:08:44 +00002536 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2537 // be an unsigned int.
2538 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2539
2540 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002541 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002542 if (!Literal.isLong && !Literal.isLongLong) {
2543 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002544 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002545
Chris Lattner67ca9252007-05-21 01:08:44 +00002546 // Does it fit in a unsigned int?
2547 if (ResultVal.isIntN(IntSize)) {
2548 // Does it fit in a signed int?
2549 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002550 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002551 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002552 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002553 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002554 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002555 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002556
Chris Lattner67ca9252007-05-21 01:08:44 +00002557 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002558 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002559 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002560
Chris Lattner67ca9252007-05-21 01:08:44 +00002561 // Does it fit in a unsigned long?
2562 if (ResultVal.isIntN(LongSize)) {
2563 // Does it fit in a signed long?
2564 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002565 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002566 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002567 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002568 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002569 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002570 }
2571
Chris Lattner67ca9252007-05-21 01:08:44 +00002572 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002573 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002574 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002575
Chris Lattner67ca9252007-05-21 01:08:44 +00002576 // Does it fit in a unsigned long long?
2577 if (ResultVal.isIntN(LongLongSize)) {
2578 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002579 // To be compatible with MSVC, hex integer literals ending with the
2580 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002581 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002582 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002583 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002584 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002585 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002586 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002587 }
2588 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002589
Chris Lattner67ca9252007-05-21 01:08:44 +00002590 // If we still couldn't decide a type, we probably have something that
2591 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002592 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002593 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002594 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002595 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002596 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002597
Chris Lattner55258cf2008-05-09 05:59:00 +00002598 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002599 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002600 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002601 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002602 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002603
Chris Lattner1c20a172007-08-26 03:42:43 +00002604 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2605 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002606 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002607 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002608
2609 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002610}
2611
Richard Trieuba63ce62011-09-09 01:45:06 +00002612ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002613 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002614 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002615}
2616
Chandler Carruth62da79c2011-05-26 08:53:12 +00002617static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2618 SourceLocation Loc,
2619 SourceRange ArgRange) {
2620 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2621 // scalar or vector data type argument..."
2622 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2623 // type (C99 6.2.5p18) or void.
2624 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2625 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2626 << T << ArgRange;
2627 return true;
2628 }
2629
2630 assert((T->isVoidType() || !T->isIncompleteType()) &&
2631 "Scalar types should always be complete");
2632 return false;
2633}
2634
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002635static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2636 SourceLocation Loc,
2637 SourceRange ArgRange,
2638 UnaryExprOrTypeTrait TraitKind) {
2639 // C99 6.5.3.4p1:
2640 if (T->isFunctionType()) {
2641 // alignof(function) is allowed as an extension.
2642 if (TraitKind == UETT_SizeOf)
2643 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2644 return false;
2645 }
2646
2647 // Allow sizeof(void)/alignof(void) as an extension.
2648 if (T->isVoidType()) {
2649 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2650 return false;
2651 }
2652
2653 return true;
2654}
2655
2656static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2657 SourceLocation Loc,
2658 SourceRange ArgRange,
2659 UnaryExprOrTypeTrait TraitKind) {
2660 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2661 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2662 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2663 << T << (TraitKind == UETT_SizeOf)
2664 << ArgRange;
2665 return true;
2666 }
2667
2668 return false;
2669}
2670
Chandler Carruth14502c22011-05-26 08:53:10 +00002671/// \brief Check the constrains on expression operands to unary type expression
2672/// and type traits.
2673///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002674/// Completes any types necessary and validates the constraints on the operand
2675/// expression. The logic mostly mirrors the type-based overload, but may modify
2676/// the expression as it completes the type for that expression through template
2677/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002678bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002679 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002680 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002681
2682 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2683 // the result is the size of the referenced type."
2684 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2685 // result shall be the alignment of the referenced type."
2686 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2687 ExprTy = Ref->getPointeeType();
2688
2689 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002690 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2691 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002692
2693 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002694 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2695 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002696 return false;
2697
Richard Trieuba63ce62011-09-09 01:45:06 +00002698 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002699 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002700 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002701 std::make_pair(SourceLocation(), PDiag(0))))
2702 return true;
2703
2704 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002705 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002706 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2707 ExprTy = Ref->getPointeeType();
2708
Richard Trieuba63ce62011-09-09 01:45:06 +00002709 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2710 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002711 return true;
2712
Nico Weber0870deb2011-06-15 02:47:03 +00002713 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002714 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002715 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2716 QualType OType = PVD->getOriginalType();
2717 QualType Type = PVD->getType();
2718 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002719 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002720 << Type << OType;
2721 Diag(PVD->getLocation(), diag::note_declared_at);
2722 }
2723 }
2724 }
2725 }
2726
Chandler Carruth7c430c02011-05-27 01:33:31 +00002727 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002728}
2729
2730/// \brief Check the constraints on operands to unary expression and type
2731/// traits.
2732///
2733/// This will complete any types necessary, and validate the various constraints
2734/// on those operands.
2735///
Steve Naroff71b59a92007-06-04 22:22:31 +00002736/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002737/// C99 6.3.2.1p[2-4] all state:
2738/// Except when it is the operand of the sizeof operator ...
2739///
2740/// C++ [expr.sizeof]p4
2741/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2742/// standard conversions are not applied to the operand of sizeof.
2743///
2744/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002745bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002746 SourceLocation OpLoc,
2747 SourceRange ExprRange,
2748 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002749 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002750 return false;
2751
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002752 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2753 // the result is the size of the referenced type."
2754 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2755 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002756 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2757 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002758
Chandler Carruth62da79c2011-05-26 08:53:12 +00002759 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002760 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002761
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002762 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002763 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002764 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002765 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002766
Richard Trieuba63ce62011-09-09 01:45:06 +00002767 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002768 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002769 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002770 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002771
Richard Trieuba63ce62011-09-09 01:45:06 +00002772 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002773 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002774 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002775
Chris Lattner62975a72009-04-24 00:30:45 +00002776 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002777}
2778
Chandler Carruth14502c22011-05-26 08:53:10 +00002779static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002780 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002781
Mike Stump11289f42009-09-09 15:08:12 +00002782 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002783 if (isa<DeclRefExpr>(E))
2784 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002785
2786 // Cannot know anything else if the expression is dependent.
2787 if (E->isTypeDependent())
2788 return false;
2789
Douglas Gregor71235ec2009-05-02 02:18:30 +00002790 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002791 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2792 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002793 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002794 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002795
2796 // Alignment of a field access is always okay, so long as it isn't a
2797 // bit-field.
2798 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002799 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002800 return false;
2801
Chandler Carruth14502c22011-05-26 08:53:10 +00002802 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002803}
2804
Chandler Carruth14502c22011-05-26 08:53:10 +00002805bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002806 E = E->IgnoreParens();
2807
2808 // Cannot know anything else if the expression is dependent.
2809 if (E->isTypeDependent())
2810 return false;
2811
Chandler Carruth14502c22011-05-26 08:53:10 +00002812 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002813}
2814
Douglas Gregor0950e412009-03-13 21:01:28 +00002815/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002816ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002817Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2818 SourceLocation OpLoc,
2819 UnaryExprOrTypeTrait ExprKind,
2820 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002821 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002822 return ExprError();
2823
John McCallbcd03502009-12-07 02:54:59 +00002824 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002825
Douglas Gregor0950e412009-03-13 21:01:28 +00002826 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002827 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002828 return ExprError();
2829
2830 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002831 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2832 Context.getSizeType(),
2833 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002834}
2835
2836/// \brief Build a sizeof or alignof expression given an expression
2837/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002838ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002839Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2840 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002841 ExprResult PE = CheckPlaceholderExpr(E);
2842 if (PE.isInvalid())
2843 return ExprError();
2844
2845 E = PE.get();
2846
Douglas Gregor0950e412009-03-13 21:01:28 +00002847 // Verify that the operand is valid.
2848 bool isInvalid = false;
2849 if (E->isTypeDependent()) {
2850 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002851 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002852 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002853 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002854 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002855 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002856 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002857 isInvalid = true;
2858 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002859 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002860 }
2861
2862 if (isInvalid)
2863 return ExprError();
2864
Eli Friedmane0afc982012-01-21 01:01:51 +00002865 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
2866 PE = TranformToPotentiallyEvaluated(E);
2867 if (PE.isInvalid()) return ExprError();
2868 E = PE.take();
2869 }
2870
Douglas Gregor0950e412009-03-13 21:01:28 +00002871 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00002872 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00002873 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00002874 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002875}
2876
Peter Collingbournee190dee2011-03-11 19:24:49 +00002877/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
2878/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00002879/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00002880ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002881Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002882 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002883 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002884 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002885 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00002886
Richard Trieuba63ce62011-09-09 01:45:06 +00002887 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00002888 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00002889 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002890 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00002891 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002892
Douglas Gregor0950e412009-03-13 21:01:28 +00002893 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00002894 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00002895 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00002896}
2897
John Wiegley01296292011-04-08 18:41:53 +00002898static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002899 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00002900 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00002901 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00002902
John McCall34376a62010-12-04 03:47:34 +00002903 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00002904 if (V.get()->getObjectKind() != OK_Ordinary) {
2905 V = S.DefaultLvalueConversion(V.take());
2906 if (V.isInvalid())
2907 return QualType();
2908 }
John McCall34376a62010-12-04 03:47:34 +00002909
Chris Lattnere267f5d2007-08-26 05:39:26 +00002910 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00002911 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00002912 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00002913
Chris Lattnere267f5d2007-08-26 05:39:26 +00002914 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00002915 if (V.get()->getType()->isArithmeticType())
2916 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002917
John McCall36226622010-10-12 02:09:17 +00002918 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00002919 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00002920 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00002921 if (PR.get() != V.get()) {
2922 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00002923 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00002924 }
2925
Chris Lattnere267f5d2007-08-26 05:39:26 +00002926 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00002927 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00002928 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00002929 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00002930}
2931
2932
Chris Lattnere168f762006-11-10 05:29:30 +00002933
John McCalldadc5752010-08-24 06:29:42 +00002934ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002935Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00002936 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00002937 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00002938 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002939 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00002940 case tok::plusplus: Opc = UO_PostInc; break;
2941 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002942 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002943
Sebastian Redla9351792012-02-11 23:51:47 +00002944 // Since this might is a postfix expression, get rid of ParenListExprs.
2945 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
2946 if (Result.isInvalid()) return ExprError();
2947 Input = Result.take();
2948
John McCallb268a282010-08-23 23:25:46 +00002949 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00002950}
2951
John McCalldadc5752010-08-24 06:29:42 +00002952ExprResult
John McCallb268a282010-08-23 23:25:46 +00002953Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
2954 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00002955 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00002956 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00002957 if (Result.isInvalid()) return ExprError();
2958 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00002959
John McCallb268a282010-08-23 23:25:46 +00002960 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00002961
Douglas Gregor40412ac2008-11-19 17:17:41 +00002962 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002963 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002964 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00002965 Context.DependentTy,
2966 VK_LValue, OK_Ordinary,
2967 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002968 }
2969
Mike Stump11289f42009-09-09 15:08:12 +00002970 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00002971 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00002972 LHSExp->getType()->isEnumeralType() ||
2973 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00002974 RHSExp->getType()->isEnumeralType()) &&
2975 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00002976 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00002977 }
2978
John McCallb268a282010-08-23 23:25:46 +00002979 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00002980}
2981
2982
John McCalldadc5752010-08-24 06:29:42 +00002983ExprResult
John McCallb268a282010-08-23 23:25:46 +00002984Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00002985 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00002986 Expr *LHSExp = Base;
2987 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00002988
Chris Lattner36d572b2007-07-16 00:14:47 +00002989 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00002990 if (!LHSExp->getType()->getAs<VectorType>()) {
2991 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
2992 if (Result.isInvalid())
2993 return ExprError();
2994 LHSExp = Result.take();
2995 }
2996 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
2997 if (Result.isInvalid())
2998 return ExprError();
2999 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003000
Chris Lattner36d572b2007-07-16 00:14:47 +00003001 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003002 ExprValueKind VK = VK_LValue;
3003 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003004
Steve Naroffc1aadb12007-03-28 21:49:40 +00003005 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003006 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003007 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003008 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003009 Expr *BaseExpr, *IndexExpr;
3010 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003011 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3012 BaseExpr = LHSExp;
3013 IndexExpr = RHSExp;
3014 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003015 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003016 BaseExpr = LHSExp;
3017 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003018 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003019 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003020 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003021 BaseExpr = RHSExp;
3022 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003023 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003024 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003025 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003026 BaseExpr = LHSExp;
3027 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003028 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3029 if (!Result.isInvalid())
3030 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003031 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003032 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003033 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003034 // Handle the uncommon case of "123[Ptr]".
3035 BaseExpr = RHSExp;
3036 IndexExpr = LHSExp;
3037 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003038 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003039 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003040 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003041 VK = LHSExp->getValueKind();
3042 if (VK != VK_RValue)
3043 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003044
Chris Lattner36d572b2007-07-16 00:14:47 +00003045 // FIXME: need to deal with const...
3046 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003047 } else if (LHSTy->isArrayType()) {
3048 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003049 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003050 // wasn't promoted because of the C90 rule that doesn't
3051 // allow promoting non-lvalue arrays. Warn, then
3052 // force the promotion here.
3053 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3054 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003055 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3056 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003057 LHSTy = LHSExp->getType();
3058
3059 BaseExpr = LHSExp;
3060 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003061 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003062 } else if (RHSTy->isArrayType()) {
3063 // Same as previous, except for 123[f().a] case
3064 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3065 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003066 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3067 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003068 RHSTy = RHSExp->getType();
3069
3070 BaseExpr = RHSExp;
3071 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003072 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003073 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003074 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3075 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003076 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003077 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003078 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003079 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3080 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003081
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003082 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003083 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3084 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003085 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3086
Douglas Gregorac1fb652009-03-24 19:52:54 +00003087 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003088 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3089 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003090 // incomplete types are not object types.
3091 if (ResultType->isFunctionType()) {
3092 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3093 << ResultType << BaseExpr->getSourceRange();
3094 return ExprError();
3095 }
Mike Stump11289f42009-09-09 15:08:12 +00003096
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003097 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3098 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003099 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3100 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003101
3102 // C forbids expressions of unqualified void type from being l-values.
3103 // See IsCForbiddenLValueType.
3104 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003105 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003106 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003107 PDiag(diag::err_subscript_incomplete_type)
3108 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003109 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003110
Chris Lattner62975a72009-04-24 00:30:45 +00003111 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003112 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003113 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3114 << ResultType << BaseExpr->getSourceRange();
3115 return ExprError();
3116 }
Mike Stump11289f42009-09-09 15:08:12 +00003117
John McCall4bc41ae2010-11-18 19:01:18 +00003118 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003119 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003120
Mike Stump4e1f26a2009-02-19 03:04:26 +00003121 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003122 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003123}
3124
John McCalldadc5752010-08-24 06:29:42 +00003125ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003126 FunctionDecl *FD,
3127 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003128 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003129 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003130 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003131 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003132 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003133 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003134 return ExprError();
3135 }
3136
3137 if (Param->hasUninstantiatedDefaultArg()) {
3138 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003139
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003140 // Instantiate the expression.
3141 MultiLevelTemplateArgumentList ArgList
3142 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003143
Nico Weber44887f62010-11-29 18:19:25 +00003144 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003145 = ArgList.getInnermost();
3146 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3147 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003148
Nico Weber44887f62010-11-29 18:19:25 +00003149 ExprResult Result;
3150 {
3151 // C++ [dcl.fct.default]p5:
3152 // The names in the [default argument] expression are bound, and
3153 // the semantic constraints are checked, at the point where the
3154 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003155 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003156 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003157 Result = SubstExpr(UninstExpr, ArgList);
3158 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003159 if (Result.isInvalid())
3160 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003161
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003162 // Check the expression as an initializer for the parameter.
3163 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003164 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003165 InitializationKind Kind
3166 = InitializationKind::CreateCopy(Param->getLocation(),
3167 /*FIXME:EqualLoc*/UninstExpr->getSourceRange().getBegin());
3168 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003169
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003170 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3171 Result = InitSeq.Perform(*this, Entity, Kind,
3172 MultiExprArg(*this, &ResultE, 1));
3173 if (Result.isInvalid())
3174 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003175
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003176 // Build the default argument expression.
3177 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3178 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003179 }
3180
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003181 // If the default expression creates temporaries, we need to
3182 // push them to the current stack of expression temporaries so they'll
3183 // be properly destroyed.
3184 // FIXME: We should really be rebuilding the default argument with new
3185 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003186 // We don't need to do that with block decls, though, because
3187 // blocks in default argument expression can never capture anything.
3188 if (isa<ExprWithCleanups>(Param->getInit())) {
3189 // Set the "needs cleanups" bit regardless of whether there are
3190 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003191 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003192
3193 // Append all the objects to the cleanup list. Right now, this
3194 // should always be a no-op, because blocks in default argument
3195 // expressions should never be able to capture anything.
3196 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3197 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003198 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003199
3200 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003201 // Just mark all of the declarations in this potentially-evaluated expression
3202 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003203 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3204 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003205 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003206}
3207
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003208/// ConvertArgumentsForCall - Converts the arguments specified in
3209/// Args/NumArgs to the parameter types of the function FDecl with
3210/// function prototype Proto. Call is the call expression itself, and
3211/// Fn is the function expression. For a C++ member function, this
3212/// routine does not attempt to convert the object argument. Returns
3213/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003214bool
3215Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003216 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003217 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003218 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003219 SourceLocation RParenLoc,
3220 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003221 // Bail out early if calling a builtin with custom typechecking.
3222 // We don't need to do this in the
3223 if (FDecl)
3224 if (unsigned ID = FDecl->getBuiltinID())
3225 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3226 return false;
3227
Mike Stump4e1f26a2009-02-19 03:04:26 +00003228 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003229 // assignment, to the types of the corresponding parameter, ...
3230 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003231 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003232 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003233 unsigned FnKind = Fn->getType()->isBlockPointerType()
3234 ? 1 /* block */
3235 : (IsExecConfig ? 3 /* kernel function (exec config) */
3236 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003237
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003238 // If too few arguments are available (and we don't have default
3239 // arguments for the remaining parameters), don't make the call.
3240 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003241 if (NumArgs < MinArgs) {
3242 Diag(RParenLoc, MinArgs == NumArgsInProto
3243 ? diag::err_typecheck_call_too_few_args
3244 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003245 << FnKind
Peter Collingbourne740afe22011-10-02 23:49:20 +00003246 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003247
3248 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003249 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003250 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3251 << FDecl;
3252
3253 return true;
3254 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003255 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003256 }
3257
3258 // If too many are passed and not variadic, error on the extras and drop
3259 // them.
3260 if (NumArgs > NumArgsInProto) {
3261 if (!Proto->isVariadic()) {
3262 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003263 MinArgs == NumArgsInProto
3264 ? diag::err_typecheck_call_too_many_args
3265 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003266 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003267 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003268 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3269 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003270
3271 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003272 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003273 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3274 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003275
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003276 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003277 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003278 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003279 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003280 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003281 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003282 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003283 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3284 if (Fn->getType()->isBlockPointerType())
3285 CallType = VariadicBlock; // Block
3286 else if (isa<MemberExpr>(Fn))
3287 CallType = VariadicMethod;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003288 Invalid = GatherArgumentsForCall(Call->getSourceRange().getBegin(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003289 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003290 if (Invalid)
3291 return true;
3292 unsigned TotalNumArgs = AllArgs.size();
3293 for (unsigned i = 0; i < TotalNumArgs; ++i)
3294 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003295
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003296 return false;
3297}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003298
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003299bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3300 FunctionDecl *FDecl,
3301 const FunctionProtoType *Proto,
3302 unsigned FirstProtoArg,
3303 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003304 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003305 VariadicCallType CallType,
3306 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003307 unsigned NumArgsInProto = Proto->getNumArgs();
3308 unsigned NumArgsToCheck = NumArgs;
3309 bool Invalid = false;
3310 if (NumArgs != NumArgsInProto)
3311 // Use default arguments for missing arguments
3312 NumArgsToCheck = NumArgsInProto;
3313 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003314 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003315 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003316 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003317
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003318 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003319 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003320 if (ArgIx < NumArgs) {
3321 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003322
Eli Friedman3164fb12009-03-22 22:00:50 +00003323 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3324 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003325 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003326 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003327 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003328
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003329 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003330 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003331 if (FDecl && i < FDecl->getNumParams())
3332 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003333
John McCall4124c492011-10-17 18:40:02 +00003334 // Strip the unbridged-cast placeholder expression off, if applicable.
3335 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3336 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3337 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3338 Arg = stripARCUnbridgedCast(Arg);
3339
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003340 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003341 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003342 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3343 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003344 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003345 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003346 Owned(Arg),
3347 /*TopLevelOfInitList=*/false,
3348 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003349 if (ArgE.isInvalid())
3350 return true;
3351
3352 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003353 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003354 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003355
John McCalldadc5752010-08-24 06:29:42 +00003356 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003357 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003358 if (ArgExpr.isInvalid())
3359 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003360
Anders Carlsson355933d2009-08-25 03:49:14 +00003361 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003362 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003363
3364 // Check for array bounds violations for each argument to the call. This
3365 // check only triggers warnings when the argument isn't a more complex Expr
3366 // with its own checking, such as a BinaryOperator.
3367 CheckArrayAccess(Arg);
3368
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003369 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3370 CheckStaticArrayArgument(CallLoc, Param, Arg);
3371
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003372 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003373 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003374
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003375 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003376 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003377
3378 // Assume that extern "C" functions with variadic arguments that
3379 // return __unknown_anytype aren't *really* variadic.
3380 if (Proto->getResultType() == Context.UnknownAnyTy &&
3381 FDecl && FDecl->isExternC()) {
3382 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3383 ExprResult arg;
3384 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3385 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3386 else
3387 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3388 Invalid |= arg.isInvalid();
3389 AllArgs.push_back(arg.take());
3390 }
3391
3392 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3393 } else {
3394 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003395 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3396 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003397 Invalid |= Arg.isInvalid();
3398 AllArgs.push_back(Arg.take());
3399 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003400 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003401
3402 // Check for array bounds violations.
3403 for (unsigned i = ArgIx; i != NumArgs; ++i)
3404 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003405 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003406 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003407}
3408
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003409static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3410 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3411 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3412 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3413 << ATL->getLocalSourceRange();
3414}
3415
3416/// CheckStaticArrayArgument - If the given argument corresponds to a static
3417/// array parameter, check that it is non-null, and that if it is formed by
3418/// array-to-pointer decay, the underlying array is sufficiently large.
3419///
3420/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3421/// array type derivation, then for each call to the function, the value of the
3422/// corresponding actual argument shall provide access to the first element of
3423/// an array with at least as many elements as specified by the size expression.
3424void
3425Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3426 ParmVarDecl *Param,
3427 const Expr *ArgExpr) {
3428 // Static array parameters are not supported in C++.
3429 if (!Param || getLangOptions().CPlusPlus)
3430 return;
3431
3432 QualType OrigTy = Param->getOriginalType();
3433
3434 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3435 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3436 return;
3437
3438 if (ArgExpr->isNullPointerConstant(Context,
3439 Expr::NPC_NeverValueDependent)) {
3440 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3441 DiagnoseCalleeStaticArrayParam(*this, Param);
3442 return;
3443 }
3444
3445 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3446 if (!CAT)
3447 return;
3448
3449 const ConstantArrayType *ArgCAT =
3450 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3451 if (!ArgCAT)
3452 return;
3453
3454 if (ArgCAT->getSize().ult(CAT->getSize())) {
3455 Diag(CallLoc, diag::warn_static_array_too_small)
3456 << ArgExpr->getSourceRange()
3457 << (unsigned) ArgCAT->getSize().getZExtValue()
3458 << (unsigned) CAT->getSize().getZExtValue();
3459 DiagnoseCalleeStaticArrayParam(*this, Param);
3460 }
3461}
3462
John McCall2979fe02011-04-12 00:42:48 +00003463/// Given a function expression of unknown-any type, try to rebuild it
3464/// to have a function type.
3465static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3466
Steve Naroff83895f72007-09-16 03:34:24 +00003467/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003468/// This provides the location of the left/right parens and a list of comma
3469/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003470ExprResult
John McCallb268a282010-08-23 23:25:46 +00003471Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003472 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003473 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003474 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003475
3476 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003477 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003478 if (Result.isInvalid()) return ExprError();
3479 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003480
Richard Trieuba63ce62011-09-09 01:45:06 +00003481 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003482
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003483 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003484 // If this is a pseudo-destructor expression, build the call immediately.
3485 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3486 if (NumArgs > 0) {
3487 // Pseudo-destructor calls should not have any arguments.
3488 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003489 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003490 SourceRange(Args[0]->getLocStart(),
3491 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003492
Douglas Gregorad8a3362009-09-04 17:36:40 +00003493 NumArgs = 0;
3494 }
Mike Stump11289f42009-09-09 15:08:12 +00003495
Douglas Gregorad8a3362009-09-04 17:36:40 +00003496 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003497 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003498 }
Mike Stump11289f42009-09-09 15:08:12 +00003499
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003500 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003501 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003502 // FIXME: Will need to cache the results of name lookup (including ADL) in
3503 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003504 bool Dependent = false;
3505 if (Fn->isTypeDependent())
3506 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003507 else if (Expr::hasAnyTypeDependentArguments(
3508 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003509 Dependent = true;
3510
Peter Collingbourne41f85462011-02-09 21:07:24 +00003511 if (Dependent) {
3512 if (ExecConfig) {
3513 return Owned(new (Context) CUDAKernelCallExpr(
3514 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3515 Context.DependentTy, VK_RValue, RParenLoc));
3516 } else {
3517 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3518 Context.DependentTy, VK_RValue,
3519 RParenLoc));
3520 }
3521 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003522
3523 // Determine whether this is a call to an object (C++ [over.call.object]).
3524 if (Fn->getType()->isRecordType())
3525 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003526 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003527
John McCall2979fe02011-04-12 00:42:48 +00003528 if (Fn->getType() == Context.UnknownAnyTy) {
3529 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3530 if (result.isInvalid()) return ExprError();
3531 Fn = result.take();
3532 }
3533
John McCall0009fcc2011-04-26 20:42:42 +00003534 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003535 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003536 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003537 }
John McCall0009fcc2011-04-26 20:42:42 +00003538 }
John McCall10eae182009-11-30 22:42:35 +00003539
John McCall0009fcc2011-04-26 20:42:42 +00003540 // Check for overloaded calls. This can happen even in C due to extensions.
3541 if (Fn->getType() == Context.OverloadTy) {
3542 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3543
Douglas Gregorcda22702011-10-13 18:10:35 +00003544 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003545 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003546 OverloadExpr *ovl = find.Expression;
3547 if (isa<UnresolvedLookupExpr>(ovl)) {
3548 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3549 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3550 RParenLoc, ExecConfig);
3551 } else {
John McCall2d74de92009-12-01 22:10:20 +00003552 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003553 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003554 }
3555 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003556 }
3557
Douglas Gregore254f902009-02-04 00:32:51 +00003558 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003559 if (Fn->getType() == Context.UnknownAnyTy) {
3560 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3561 if (result.isInvalid()) return ExprError();
3562 Fn = result.take();
3563 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003564
Eli Friedmane14b1992009-12-26 03:35:45 +00003565 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003566
John McCall57500772009-12-16 12:17:52 +00003567 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003568 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3569 if (UnOp->getOpcode() == UO_AddrOf)
3570 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3571
John McCall57500772009-12-16 12:17:52 +00003572 if (isa<DeclRefExpr>(NakedFn))
3573 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003574 else if (isa<MemberExpr>(NakedFn))
3575 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003576
Peter Collingbourne41f85462011-02-09 21:07:24 +00003577 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003578 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003579}
3580
3581ExprResult
3582Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003583 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003584 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3585 if (!ConfigDecl)
3586 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3587 << "cudaConfigureCall");
3588 QualType ConfigQTy = ConfigDecl->getType();
3589
3590 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3591 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003592 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003593
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003594 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3595 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003596}
3597
Tanya Lattner55808c12011-06-04 00:47:47 +00003598/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3599///
3600/// __builtin_astype( value, dst type )
3601///
Richard Trieuba63ce62011-09-09 01:45:06 +00003602ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003603 SourceLocation BuiltinLoc,
3604 SourceLocation RParenLoc) {
3605 ExprValueKind VK = VK_RValue;
3606 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003607 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3608 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003609 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3610 return ExprError(Diag(BuiltinLoc,
3611 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003612 << DstTy
3613 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003614 << E->getSourceRange());
3615 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003616 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003617}
3618
John McCall57500772009-12-16 12:17:52 +00003619/// BuildResolvedCallExpr - Build a call to a resolved expression,
3620/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003621/// unary-convert to an expression of function-pointer or
3622/// block-pointer type.
3623///
3624/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003625ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003626Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3627 SourceLocation LParenLoc,
3628 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003629 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003630 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003631 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3632
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003633 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003634 ExprResult Result = UsualUnaryConversions(Fn);
3635 if (Result.isInvalid())
3636 return ExprError();
3637 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003638
Chris Lattner08464942007-12-28 05:29:59 +00003639 // Make the call expr early, before semantic checks. This guarantees cleanup
3640 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003641 CallExpr *TheCall;
3642 if (Config) {
3643 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3644 cast<CallExpr>(Config),
3645 Args, NumArgs,
3646 Context.BoolTy,
3647 VK_RValue,
3648 RParenLoc);
3649 } else {
3650 TheCall = new (Context) CallExpr(Context, Fn,
3651 Args, NumArgs,
3652 Context.BoolTy,
3653 VK_RValue,
3654 RParenLoc);
3655 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003656
John McCallbebede42011-02-26 05:39:39 +00003657 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3658
3659 // Bail out early if calling a builtin with custom typechecking.
3660 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3661 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3662
John McCall31996342011-04-07 08:22:57 +00003663 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003664 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003665 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003666 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3667 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003668 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003669 if (FuncT == 0)
3670 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3671 << Fn->getType() << Fn->getSourceRange());
3672 } else if (const BlockPointerType *BPT =
3673 Fn->getType()->getAs<BlockPointerType>()) {
3674 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3675 } else {
John McCall31996342011-04-07 08:22:57 +00003676 // Handle calls to expressions of unknown-any type.
3677 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003678 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003679 if (rewrite.isInvalid()) return ExprError();
3680 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003681 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003682 goto retry;
3683 }
3684
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003685 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3686 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003687 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003688
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003689 if (getLangOptions().CUDA) {
3690 if (Config) {
3691 // CUDA: Kernel calls must be to global functions
3692 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3693 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3694 << FDecl->getName() << Fn->getSourceRange());
3695
3696 // CUDA: Kernel function must have 'void' return type
3697 if (!FuncT->getResultType()->isVoidType())
3698 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3699 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003700 } else {
3701 // CUDA: Calls to global functions must be configured
3702 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3703 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3704 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003705 }
3706 }
3707
Eli Friedman3164fb12009-03-22 22:00:50 +00003708 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003709 if (CheckCallReturnType(FuncT->getResultType(),
John McCallb268a282010-08-23 23:25:46 +00003710 Fn->getSourceRange().getBegin(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003711 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003712 return ExprError();
3713
Chris Lattner08464942007-12-28 05:29:59 +00003714 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003715 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003716 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003717
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003718 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003719 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003720 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003721 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003722 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003723 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003724
Douglas Gregord8e97de2009-04-02 15:37:10 +00003725 if (FDecl) {
3726 // Check if we have too few/too many template arguments, based
3727 // on our knowledge of the function definition.
3728 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003729 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003730 const FunctionProtoType *Proto
3731 = Def->getType()->getAs<FunctionProtoType>();
3732 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003733 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3734 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003735 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003736
3737 // If the function we're calling isn't a function prototype, but we have
3738 // a function prototype from a prior declaratiom, use that prototype.
3739 if (!FDecl->hasPrototype())
3740 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003741 }
3742
Steve Naroff0b661582007-08-28 23:30:39 +00003743 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003744 for (unsigned i = 0; i != NumArgs; i++) {
3745 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003746
3747 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003748 InitializedEntity Entity
3749 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003750 Proto->getArgType(i),
3751 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003752 ExprResult ArgE = PerformCopyInitialization(Entity,
3753 SourceLocation(),
3754 Owned(Arg));
3755 if (ArgE.isInvalid())
3756 return true;
3757
3758 Arg = ArgE.takeAs<Expr>();
3759
3760 } else {
John Wiegley01296292011-04-08 18:41:53 +00003761 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3762
3763 if (ArgE.isInvalid())
3764 return true;
3765
3766 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003767 }
3768
Douglas Gregor83025412010-10-26 05:45:40 +00003769 if (RequireCompleteType(Arg->getSourceRange().getBegin(),
3770 Arg->getType(),
3771 PDiag(diag::err_call_incomplete_argument)
3772 << Arg->getSourceRange()))
3773 return ExprError();
3774
Chris Lattner08464942007-12-28 05:29:59 +00003775 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003776 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003777 }
Chris Lattner08464942007-12-28 05:29:59 +00003778
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003779 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3780 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003781 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3782 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003783
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003784 // Check for sentinels
3785 if (NDecl)
3786 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003787
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003788 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003789 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003790 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003791 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003792
John McCallbebede42011-02-26 05:39:39 +00003793 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003794 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003795 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003796 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003797 return ExprError();
3798 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003799
John McCallb268a282010-08-23 23:25:46 +00003800 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003801}
3802
John McCalldadc5752010-08-24 06:29:42 +00003803ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003804Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003805 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003806 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003807 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003808 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003809
3810 TypeSourceInfo *TInfo;
3811 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3812 if (!TInfo)
3813 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3814
John McCallb268a282010-08-23 23:25:46 +00003815 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003816}
3817
John McCalldadc5752010-08-24 06:29:42 +00003818ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003819Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003820 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003821 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003822
Eli Friedman37a186d2008-05-20 05:22:08 +00003823 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003824 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3825 PDiag(diag::err_illegal_decl_array_incomplete_type)
3826 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003827 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003828 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003829 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003830 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003831 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003832 } else if (!literalType->isDependentType() &&
3833 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003834 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003835 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003836 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003837 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003838
Douglas Gregor85dabae2009-12-16 01:38:02 +00003839 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003840 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003841 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003842 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00003843 SourceRange(LParenLoc, RParenLoc),
3844 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00003845 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003846 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003847 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003848 &literalType);
3849 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003850 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003851 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003852
Chris Lattner79413952008-12-04 23:50:19 +00003853 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003854 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003855 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003856 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003857 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003858
John McCall7decc9e2010-11-18 06:31:45 +00003859 // In C, compound literals are l-values for some reason.
3860 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3861
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003862 return MaybeBindToTemporary(
3863 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003864 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003865}
3866
John McCalldadc5752010-08-24 06:29:42 +00003867ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00003868Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00003869 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003870 unsigned NumInit = InitArgList.size();
3871 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00003872
John McCall526ab472011-10-25 17:37:35 +00003873 // Immediately handle non-overload placeholders. Overloads can be
3874 // resolved contextually, but everything else here can't.
3875 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00003876 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00003877 ExprResult result = CheckPlaceholderExpr(InitList[I]);
3878
3879 // Ignore failures; dropping the entire initializer list because
3880 // of one failure would be terrible for indexing/etc.
3881 if (result.isInvalid()) continue;
3882
3883 InitList[I] = result.take();
3884 }
3885 }
3886
Steve Naroff30d242c2007-09-15 18:49:24 +00003887 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00003888 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003889
Ted Kremenekac034612010-04-13 23:39:13 +00003890 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
3891 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00003892 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00003893 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00003894}
3895
John McCallcd78e802011-09-10 01:16:55 +00003896/// Do an explicit extend of the given block pointer if we're in ARC.
3897static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
3898 assert(E.get()->getType()->isBlockPointerType());
3899 assert(E.get()->isRValue());
3900
3901 // Only do this in an r-value context.
3902 if (!S.getLangOptions().ObjCAutoRefCount) return;
3903
3904 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00003905 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00003906 /*base path*/ 0, VK_RValue);
3907 S.ExprNeedsCleanups = true;
3908}
3909
3910/// Prepare a conversion of the given expression to an ObjC object
3911/// pointer type.
3912CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
3913 QualType type = E.get()->getType();
3914 if (type->isObjCObjectPointerType()) {
3915 return CK_BitCast;
3916 } else if (type->isBlockPointerType()) {
3917 maybeExtendBlockObject(*this, E);
3918 return CK_BlockPointerToObjCPointerCast;
3919 } else {
3920 assert(type->isPointerType());
3921 return CK_CPointerToObjCPointerCast;
3922 }
3923}
3924
John McCalld7646252010-11-14 08:17:51 +00003925/// Prepares for a scalar cast, performing all the necessary stages
3926/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00003927CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00003928 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
3929 // Also, callers should have filtered out the invalid cases with
3930 // pointers. Everything else should be possible.
3931
John Wiegley01296292011-04-08 18:41:53 +00003932 QualType SrcTy = Src.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00003933 if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>())
3934 SrcTy = SrcAtomicTy->getValueType();
3935 if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>())
3936 DestTy = DestAtomicTy->getValueType();
3937
John McCall9776e432011-10-06 23:25:11 +00003938 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00003939 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00003940
John McCall9320b872011-09-09 05:25:32 +00003941 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00003942 case Type::STK_MemberPointer:
3943 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00003944
John McCall9320b872011-09-09 05:25:32 +00003945 case Type::STK_CPointer:
3946 case Type::STK_BlockPointer:
3947 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00003948 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003949 case Type::STK_CPointer:
3950 return CK_BitCast;
3951 case Type::STK_BlockPointer:
3952 return (SrcKind == Type::STK_BlockPointer
3953 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
3954 case Type::STK_ObjCObjectPointer:
3955 if (SrcKind == Type::STK_ObjCObjectPointer)
3956 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00003957 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00003958 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00003959 maybeExtendBlockObject(*this, Src);
3960 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00003961 case Type::STK_Bool:
3962 return CK_PointerToBoolean;
3963 case Type::STK_Integral:
3964 return CK_PointerToIntegral;
3965 case Type::STK_Floating:
3966 case Type::STK_FloatingComplex:
3967 case Type::STK_IntegralComplex:
3968 case Type::STK_MemberPointer:
3969 llvm_unreachable("illegal cast from pointer");
3970 }
David Blaikie8a40f702012-01-17 06:56:22 +00003971 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003972
John McCall8cb679e2010-11-15 09:13:47 +00003973 case Type::STK_Bool: // casting from bool is like casting from an integer
3974 case Type::STK_Integral:
3975 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00003976 case Type::STK_CPointer:
3977 case Type::STK_ObjCObjectPointer:
3978 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00003979 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00003980 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00003981 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00003982 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00003983 case Type::STK_Bool:
3984 return CK_IntegralToBoolean;
3985 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00003986 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00003987 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00003988 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00003989 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00003990 Src = ImpCastExprToType(Src.take(),
3991 DestTy->castAs<ComplexType>()->getElementType(),
3992 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00003993 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003994 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00003995 Src = ImpCastExprToType(Src.take(),
3996 DestTy->castAs<ComplexType>()->getElementType(),
3997 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00003998 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00003999 case Type::STK_MemberPointer:
4000 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004001 }
David Blaikie8a40f702012-01-17 06:56:22 +00004002 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004003
John McCall8cb679e2010-11-15 09:13:47 +00004004 case Type::STK_Floating:
4005 switch (DestTy->getScalarTypeKind()) {
4006 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004007 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004008 case Type::STK_Bool:
4009 return CK_FloatingToBoolean;
4010 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004011 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004012 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004013 Src = ImpCastExprToType(Src.take(),
4014 DestTy->castAs<ComplexType>()->getElementType(),
4015 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004016 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004017 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004018 Src = ImpCastExprToType(Src.take(),
4019 DestTy->castAs<ComplexType>()->getElementType(),
4020 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004021 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004022 case Type::STK_CPointer:
4023 case Type::STK_ObjCObjectPointer:
4024 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004025 llvm_unreachable("valid float->pointer cast?");
4026 case Type::STK_MemberPointer:
4027 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004028 }
David Blaikie8a40f702012-01-17 06:56:22 +00004029 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004030
John McCall8cb679e2010-11-15 09:13:47 +00004031 case Type::STK_FloatingComplex:
4032 switch (DestTy->getScalarTypeKind()) {
4033 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004034 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004035 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004036 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004037 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004038 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4039 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004040 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004041 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004042 return CK_FloatingCast;
4043 }
John McCall8cb679e2010-11-15 09:13:47 +00004044 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004045 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004046 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004047 Src = ImpCastExprToType(Src.take(),
4048 SrcTy->castAs<ComplexType>()->getElementType(),
4049 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004050 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004051 case Type::STK_CPointer:
4052 case Type::STK_ObjCObjectPointer:
4053 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004054 llvm_unreachable("valid complex float->pointer cast?");
4055 case Type::STK_MemberPointer:
4056 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004057 }
David Blaikie8a40f702012-01-17 06:56:22 +00004058 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004059
John McCall8cb679e2010-11-15 09:13:47 +00004060 case Type::STK_IntegralComplex:
4061 switch (DestTy->getScalarTypeKind()) {
4062 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004063 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004064 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004065 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004066 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004067 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4068 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004069 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004070 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004071 return CK_IntegralCast;
4072 }
John McCall8cb679e2010-11-15 09:13:47 +00004073 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004074 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004075 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004076 Src = ImpCastExprToType(Src.take(),
4077 SrcTy->castAs<ComplexType>()->getElementType(),
4078 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004079 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004080 case Type::STK_CPointer:
4081 case Type::STK_ObjCObjectPointer:
4082 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004083 llvm_unreachable("valid complex int->pointer cast?");
4084 case Type::STK_MemberPointer:
4085 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004086 }
David Blaikie8a40f702012-01-17 06:56:22 +00004087 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004088 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004089
John McCalld7646252010-11-14 08:17:51 +00004090 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004091}
4092
Anders Carlsson525b76b2009-10-16 02:48:28 +00004093bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004094 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004095 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004096
Anders Carlssonde71adf2007-11-27 05:51:55 +00004097 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004098 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004099 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004100 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004101 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004102 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004103 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004104 } else
4105 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004106 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004107 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004108
John McCalle3027922010-08-25 11:45:40 +00004109 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004110 return false;
4111}
4112
John Wiegley01296292011-04-08 18:41:53 +00004113ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4114 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004115 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004116
Anders Carlsson43d70f82009-10-16 05:23:41 +00004117 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004118
Nate Begemanc8961a42009-06-27 22:05:55 +00004119 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4120 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004121 // In OpenCL, casts between vectors of different types are not allowed.
4122 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004123 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004124 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4125 || (getLangOptions().OpenCL &&
4126 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004127 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004128 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004129 return ExprError();
4130 }
John McCalle3027922010-08-25 11:45:40 +00004131 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004132 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004133 }
4134
Nate Begemanbd956c42009-06-28 02:36:38 +00004135 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004136 // conversion will take place first from scalar to elt type, and then
4137 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004138 if (SrcTy->isPointerType())
4139 return Diag(R.getBegin(),
4140 diag::err_invalid_conversion_between_vector_and_scalar)
4141 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004142
4143 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004144 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004145 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004146 if (CastExprRes.isInvalid())
4147 return ExprError();
4148 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004149
John McCalle3027922010-08-25 11:45:40 +00004150 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004151 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004152}
4153
John McCalldadc5752010-08-24 06:29:42 +00004154ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004155Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4156 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004157 SourceLocation RParenLoc, Expr *CastExpr) {
4158 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004159 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004160
Richard Trieuba63ce62011-09-09 01:45:06 +00004161 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004162 if (D.isInvalidType())
4163 return ExprError();
4164
4165 if (getLangOptions().CPlusPlus) {
4166 // Check that there are no default arguments (C++ only).
4167 CheckExtraCXXDefaultArguments(D);
4168 }
4169
John McCall42856de2011-10-01 05:17:03 +00004170 checkUnusedDeclAttributes(D);
4171
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004172 QualType castType = castTInfo->getType();
4173 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004174
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004175 bool isVectorLiteral = false;
4176
4177 // Check for an altivec or OpenCL literal,
4178 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004179 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4180 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004181 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4182 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004183 if (PLE && PLE->getNumExprs() == 0) {
4184 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4185 return ExprError();
4186 }
4187 if (PE || PLE->getNumExprs() == 1) {
4188 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4189 if (!E->getType()->isVectorType())
4190 isVectorLiteral = true;
4191 }
4192 else
4193 isVectorLiteral = true;
4194 }
4195
4196 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4197 // then handle it as such.
4198 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004199 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004200
Nate Begeman5ec4b312009-08-10 23:49:36 +00004201 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004202 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4203 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004204 if (isa<ParenListExpr>(CastExpr)) {
4205 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004206 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004207 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004208 }
John McCallebe54742010-01-15 18:56:44 +00004209
Richard Trieuba63ce62011-09-09 01:45:06 +00004210 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004211}
4212
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004213ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4214 SourceLocation RParenLoc, Expr *E,
4215 TypeSourceInfo *TInfo) {
4216 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4217 "Expected paren or paren list expression");
4218
4219 Expr **exprs;
4220 unsigned numExprs;
4221 Expr *subExpr;
4222 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4223 exprs = PE->getExprs();
4224 numExprs = PE->getNumExprs();
4225 } else {
4226 subExpr = cast<ParenExpr>(E)->getSubExpr();
4227 exprs = &subExpr;
4228 numExprs = 1;
4229 }
4230
4231 QualType Ty = TInfo->getType();
4232 assert(Ty->isVectorType() && "Expected vector type");
4233
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004234 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004235 const VectorType *VTy = Ty->getAs<VectorType>();
4236 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4237
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004238 // '(...)' form of vector initialization in AltiVec: the number of
4239 // initializers must be one or must match the size of the vector.
4240 // If a single value is specified in the initializer then it will be
4241 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004242 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004243 // The number of initializers must be one or must match the size of the
4244 // vector. If a single value is specified in the initializer then it will
4245 // be replicated to all the components of the vector
4246 if (numExprs == 1) {
4247 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004248 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4249 if (Literal.isInvalid())
4250 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004251 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004252 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004253 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4254 }
4255 else if (numExprs < numElems) {
4256 Diag(E->getExprLoc(),
4257 diag::err_incorrect_number_of_vector_initializers);
4258 return ExprError();
4259 }
4260 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004261 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004262 }
Tanya Lattner83559382011-07-15 23:07:01 +00004263 else {
4264 // For OpenCL, when the number of initializers is a single value,
4265 // it will be replicated to all components of the vector.
4266 if (getLangOptions().OpenCL &&
4267 VTy->getVectorKind() == VectorType::GenericVector &&
4268 numExprs == 1) {
4269 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004270 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4271 if (Literal.isInvalid())
4272 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004273 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004274 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004275 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4276 }
4277
Benjamin Kramer8001f742012-02-14 12:06:21 +00004278 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004279 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004280 // FIXME: This means that pretty-printing the final AST will produce curly
4281 // braces instead of the original commas.
4282 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4283 &initExprs[0],
4284 initExprs.size(), RParenLoc);
4285 initE->setType(Ty);
4286 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4287}
4288
Sebastian Redla9351792012-02-11 23:51:47 +00004289/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4290/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004291ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004292Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4293 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004294 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004295 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004296
John McCalldadc5752010-08-24 06:29:42 +00004297 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004298
Nate Begeman5ec4b312009-08-10 23:49:36 +00004299 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004300 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4301 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004302
John McCallb268a282010-08-23 23:25:46 +00004303 if (Result.isInvalid()) return ExprError();
4304
4305 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004306}
4307
Sebastian Redla9351792012-02-11 23:51:47 +00004308ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4309 SourceLocation R,
4310 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004311 unsigned nexprs = Val.size();
4312 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004313 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004314 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004315 return Owned(expr);
4316}
4317
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004318/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004319/// constant and the other is not a pointer. Returns true if a diagnostic is
4320/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004321bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004322 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004323 Expr *NullExpr = LHSExpr;
4324 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004325 Expr::NullPointerConstantKind NullKind =
4326 NullExpr->isNullPointerConstant(Context,
4327 Expr::NPC_ValueDependentIsNotNull);
4328
4329 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004330 NullExpr = RHSExpr;
4331 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004332 NullKind =
4333 NullExpr->isNullPointerConstant(Context,
4334 Expr::NPC_ValueDependentIsNotNull);
4335 }
4336
4337 if (NullKind == Expr::NPCK_NotNull)
4338 return false;
4339
4340 if (NullKind == Expr::NPCK_ZeroInteger) {
4341 // In this case, check to make sure that we got here from a "NULL"
4342 // string in the source code.
4343 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004344 SourceLocation loc = NullExpr->getExprLoc();
4345 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004346 return false;
4347 }
4348
4349 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4350 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4351 << NonPointerExpr->getType() << DiagType
4352 << NonPointerExpr->getSourceRange();
4353 return true;
4354}
4355
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004356/// \brief Return false if the condition expression is valid, true otherwise.
4357static bool checkCondition(Sema &S, Expr *Cond) {
4358 QualType CondTy = Cond->getType();
4359
4360 // C99 6.5.15p2
4361 if (CondTy->isScalarType()) return false;
4362
4363 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4364 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4365 return false;
4366
4367 // Emit the proper error message.
4368 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4369 diag::err_typecheck_cond_expect_scalar :
4370 diag::err_typecheck_cond_expect_scalar_or_vector)
4371 << CondTy;
4372 return true;
4373}
4374
4375/// \brief Return false if the two expressions can be converted to a vector,
4376/// true otherwise
4377static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4378 ExprResult &RHS,
4379 QualType CondTy) {
4380 // Both operands should be of scalar type.
4381 if (!LHS.get()->getType()->isScalarType()) {
4382 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4383 << CondTy;
4384 return true;
4385 }
4386 if (!RHS.get()->getType()->isScalarType()) {
4387 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4388 << CondTy;
4389 return true;
4390 }
4391
4392 // Implicity convert these scalars to the type of the condition.
4393 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4394 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4395 return false;
4396}
4397
4398/// \brief Handle when one or both operands are void type.
4399static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4400 ExprResult &RHS) {
4401 Expr *LHSExpr = LHS.get();
4402 Expr *RHSExpr = RHS.get();
4403
4404 if (!LHSExpr->getType()->isVoidType())
4405 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4406 << RHSExpr->getSourceRange();
4407 if (!RHSExpr->getType()->isVoidType())
4408 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4409 << LHSExpr->getSourceRange();
4410 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4411 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4412 return S.Context.VoidTy;
4413}
4414
4415/// \brief Return false if the NullExpr can be promoted to PointerTy,
4416/// true otherwise.
4417static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4418 QualType PointerTy) {
4419 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4420 !NullExpr.get()->isNullPointerConstant(S.Context,
4421 Expr::NPC_ValueDependentIsNull))
4422 return true;
4423
4424 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4425 return false;
4426}
4427
4428/// \brief Checks compatibility between two pointers and return the resulting
4429/// type.
4430static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4431 ExprResult &RHS,
4432 SourceLocation Loc) {
4433 QualType LHSTy = LHS.get()->getType();
4434 QualType RHSTy = RHS.get()->getType();
4435
4436 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4437 // Two identical pointers types are always compatible.
4438 return LHSTy;
4439 }
4440
4441 QualType lhptee, rhptee;
4442
4443 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004444 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4445 lhptee = LHSBTy->getPointeeType();
4446 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004447 } else {
John McCall9320b872011-09-09 05:25:32 +00004448 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4449 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004450 }
4451
4452 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4453 rhptee.getUnqualifiedType())) {
4454 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4455 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4456 << RHS.get()->getSourceRange();
4457 // In this situation, we assume void* type. No especially good
4458 // reason, but this is what gcc does, and we do have to pick
4459 // to get a consistent AST.
4460 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4461 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4462 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4463 return incompatTy;
4464 }
4465
4466 // The pointer types are compatible.
4467 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4468 // differently qualified versions of compatible types, the result type is
4469 // a pointer to an appropriately qualified version of the *composite*
4470 // type.
4471 // FIXME: Need to calculate the composite type.
4472 // FIXME: Need to add qualifiers
4473
4474 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4475 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4476 return LHSTy;
4477}
4478
4479/// \brief Return the resulting type when the operands are both block pointers.
4480static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4481 ExprResult &LHS,
4482 ExprResult &RHS,
4483 SourceLocation Loc) {
4484 QualType LHSTy = LHS.get()->getType();
4485 QualType RHSTy = RHS.get()->getType();
4486
4487 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4488 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4489 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4490 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4491 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4492 return destType;
4493 }
4494 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4495 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4496 << RHS.get()->getSourceRange();
4497 return QualType();
4498 }
4499
4500 // We have 2 block pointer types.
4501 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4502}
4503
4504/// \brief Return the resulting type when the operands are both pointers.
4505static QualType
4506checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4507 ExprResult &RHS,
4508 SourceLocation Loc) {
4509 // get the pointer types
4510 QualType LHSTy = LHS.get()->getType();
4511 QualType RHSTy = RHS.get()->getType();
4512
4513 // get the "pointed to" types
4514 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4515 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4516
4517 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4518 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4519 // Figure out necessary qualifiers (C99 6.5.15p6)
4520 QualType destPointee
4521 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4522 QualType destType = S.Context.getPointerType(destPointee);
4523 // Add qualifiers if necessary.
4524 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4525 // Promote to void*.
4526 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4527 return destType;
4528 }
4529 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4530 QualType destPointee
4531 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4532 QualType destType = S.Context.getPointerType(destPointee);
4533 // Add qualifiers if necessary.
4534 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4535 // Promote to void*.
4536 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4537 return destType;
4538 }
4539
4540 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4541}
4542
4543/// \brief Return false if the first expression is not an integer and the second
4544/// expression is not a pointer, true otherwise.
4545static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4546 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004547 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004548 if (!PointerExpr->getType()->isPointerType() ||
4549 !Int.get()->getType()->isIntegerType())
4550 return false;
4551
Richard Trieuba63ce62011-09-09 01:45:06 +00004552 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4553 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004554
4555 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4556 << Expr1->getType() << Expr2->getType()
4557 << Expr1->getSourceRange() << Expr2->getSourceRange();
4558 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4559 CK_IntegralToPointer);
4560 return true;
4561}
4562
Richard Trieud33e46e2011-09-06 20:06:39 +00004563/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4564/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004565/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004566QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4567 ExprResult &RHS, ExprValueKind &VK,
4568 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004569 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004570
Richard Trieud33e46e2011-09-06 20:06:39 +00004571 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4572 if (!LHSResult.isUsable()) return QualType();
4573 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004574
Richard Trieud33e46e2011-09-06 20:06:39 +00004575 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4576 if (!RHSResult.isUsable()) return QualType();
4577 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004578
Sebastian Redl1a99f442009-04-16 17:51:27 +00004579 // C++ is sufficiently different to merit its own checker.
4580 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004581 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004582
4583 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004584 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004585
John Wiegley01296292011-04-08 18:41:53 +00004586 Cond = UsualUnaryConversions(Cond.take());
4587 if (Cond.isInvalid())
4588 return QualType();
4589 LHS = UsualUnaryConversions(LHS.take());
4590 if (LHS.isInvalid())
4591 return QualType();
4592 RHS = UsualUnaryConversions(RHS.take());
4593 if (RHS.isInvalid())
4594 return QualType();
4595
4596 QualType CondTy = Cond.get()->getType();
4597 QualType LHSTy = LHS.get()->getType();
4598 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004599
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004600 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004601 if (checkCondition(*this, Cond.get()))
4602 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004603
Chris Lattnere2949f42008-01-06 22:42:25 +00004604 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004605 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004606 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004607
Nate Begemanabb5a732010-09-20 22:41:17 +00004608 // OpenCL: If the condition is a vector, and both operands are scalar,
4609 // attempt to implicity convert them to the vector type to act like the
4610 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004611 if (getLangOptions().OpenCL && CondTy->isVectorType())
4612 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004613 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004614
Chris Lattnere2949f42008-01-06 22:42:25 +00004615 // If both operands have arithmetic type, do the usual arithmetic conversions
4616 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004617 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4618 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004619 if (LHS.isInvalid() || RHS.isInvalid())
4620 return QualType();
4621 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004622 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004623
Chris Lattnere2949f42008-01-06 22:42:25 +00004624 // If both operands are the same structure or union type, the result is that
4625 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004626 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4627 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004628 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004629 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004630 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004631 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004632 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004633 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004634
Chris Lattnere2949f42008-01-06 22:42:25 +00004635 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004636 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004637 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004638 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004639 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004640
Steve Naroff039ad3c2008-01-08 01:11:38 +00004641 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4642 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004643 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4644 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004645
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004646 // All objective-c pointer type analysis is done here.
4647 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4648 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004649 if (LHS.isInvalid() || RHS.isInvalid())
4650 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004651 if (!compositeType.isNull())
4652 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004653
4654
Steve Naroff05efa972009-07-01 14:36:47 +00004655 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004656 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4657 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4658 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004659
Steve Naroff05efa972009-07-01 14:36:47 +00004660 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004661 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4662 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4663 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004664
John McCalle84af4e2010-11-13 01:35:44 +00004665 // GCC compatibility: soften pointer/integer mismatch. Note that
4666 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004667 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4668 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004669 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004670 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4671 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004672 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004673
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004674 // Emit a better diagnostic if one of the expressions is a null pointer
4675 // constant and the other is not a pointer type. In this case, the user most
4676 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004677 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004678 return QualType();
4679
Chris Lattnere2949f42008-01-06 22:42:25 +00004680 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004681 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004682 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4683 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004684 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004685}
4686
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004687/// FindCompositeObjCPointerType - Helper method to find composite type of
4688/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004689QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004690 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004691 QualType LHSTy = LHS.get()->getType();
4692 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004693
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004694 // Handle things like Class and struct objc_class*. Here we case the result
4695 // to the pseudo-builtin, because that will be implicitly cast back to the
4696 // redefinition type if an attempt is made to access its fields.
4697 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004698 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004699 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004700 return LHSTy;
4701 }
4702 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004703 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004704 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004705 return RHSTy;
4706 }
4707 // And the same for struct objc_object* / id
4708 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004709 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004710 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004711 return LHSTy;
4712 }
4713 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004714 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004715 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004716 return RHSTy;
4717 }
4718 // And the same for struct objc_selector* / SEL
4719 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004720 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004721 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004722 return LHSTy;
4723 }
4724 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004725 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004726 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004727 return RHSTy;
4728 }
4729 // Check constraints for Objective-C object pointers types.
4730 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004731
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004732 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4733 // Two identical object pointer types are always compatible.
4734 return LHSTy;
4735 }
John McCall9320b872011-09-09 05:25:32 +00004736 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4737 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004738 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004739
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004740 // If both operands are interfaces and either operand can be
4741 // assigned to the other, use that type as the composite
4742 // type. This allows
4743 // xxx ? (A*) a : (B*) b
4744 // where B is a subclass of A.
4745 //
4746 // Additionally, as for assignment, if either type is 'id'
4747 // allow silent coercion. Finally, if the types are
4748 // incompatible then make sure to use 'id' as the composite
4749 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004750
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004751 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4752 // It could return the composite type.
4753 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4754 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4755 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4756 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4757 } else if ((LHSTy->isObjCQualifiedIdType() ||
4758 RHSTy->isObjCQualifiedIdType()) &&
4759 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4760 // Need to handle "id<xx>" explicitly.
4761 // GCC allows qualified id and any Objective-C type to devolve to
4762 // id. Currently localizing to here until clear this should be
4763 // part of ObjCQualifiedIdTypesAreCompatible.
4764 compositeType = Context.getObjCIdType();
4765 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4766 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004767 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004768 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4769 ;
4770 else {
4771 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4772 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004773 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004774 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004775 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4776 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004777 return incompatTy;
4778 }
4779 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004780 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4781 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004782 return compositeType;
4783 }
4784 // Check Objective-C object pointer types and 'void *'
4785 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004786 if (getLangOptions().ObjCAutoRefCount) {
4787 // ARC forbids the implicit conversion of object pointers to 'void *',
4788 // so these types are not compatible.
4789 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4790 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4791 LHS = RHS = true;
4792 return QualType();
4793 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004794 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4795 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4796 QualType destPointee
4797 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4798 QualType destType = Context.getPointerType(destPointee);
4799 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004800 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004801 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004802 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004803 return destType;
4804 }
4805 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004806 if (getLangOptions().ObjCAutoRefCount) {
4807 // ARC forbids the implicit conversion of object pointers to 'void *',
4808 // so these types are not compatible.
4809 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4810 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4811 LHS = RHS = true;
4812 return QualType();
4813 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004814 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4815 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4816 QualType destPointee
4817 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4818 QualType destType = Context.getPointerType(destPointee);
4819 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004820 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004821 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004822 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004823 return destType;
4824 }
4825 return QualType();
4826}
4827
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004828/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004829/// ParenRange in parentheses.
4830static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004831 const PartialDiagnostic &Note,
4832 SourceRange ParenRange) {
4833 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4834 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4835 EndLoc.isValid()) {
4836 Self.Diag(Loc, Note)
4837 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4838 << FixItHint::CreateInsertion(EndLoc, ")");
4839 } else {
4840 // We can't display the parentheses, so just show the bare note.
4841 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004842 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004843}
4844
4845static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4846 return Opc >= BO_Mul && Opc <= BO_Shr;
4847}
4848
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004849/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4850/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004851/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4852/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004853static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004854 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004855 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4856 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004857 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004858 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004859
4860 // Built-in binary operator.
4861 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4862 if (IsArithmeticOp(OP->getOpcode())) {
4863 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004864 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004865 return true;
4866 }
4867 }
4868
4869 // Overloaded operator.
4870 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
4871 if (Call->getNumArgs() != 2)
4872 return false;
4873
4874 // Make sure this is really a binary operator that is safe to pass into
4875 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
4876 OverloadedOperatorKind OO = Call->getOperator();
4877 if (OO < OO_Plus || OO > OO_Arrow)
4878 return false;
4879
4880 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
4881 if (IsArithmeticOp(OpKind)) {
4882 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00004883 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004884 return true;
4885 }
4886 }
4887
4888 return false;
4889}
4890
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004891static bool IsLogicOp(BinaryOperatorKind Opc) {
4892 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
4893}
4894
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004895/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
4896/// or is a logical expression such as (x==y) which has int type, but is
4897/// commonly interpreted as boolean.
4898static bool ExprLooksBoolean(Expr *E) {
4899 E = E->IgnoreParenImpCasts();
4900
4901 if (E->getType()->isBooleanType())
4902 return true;
4903 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
4904 return IsLogicOp(OP->getOpcode());
4905 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
4906 return OP->getOpcode() == UO_LNot;
4907
4908 return false;
4909}
4910
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004911/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
4912/// and binary operator are mixed in a way that suggests the programmer assumed
4913/// the conditional operator has higher precedence, for example:
4914/// "int x = a + someBinaryCondition ? 1 : 2".
4915static void DiagnoseConditionalPrecedence(Sema &Self,
4916 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004917 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00004918 Expr *LHSExpr,
4919 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004920 BinaryOperatorKind CondOpcode;
4921 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004922
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004923 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004924 return;
4925 if (!ExprLooksBoolean(CondRHS))
4926 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004927
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004928 // The condition is an arithmetic binary expression, with a right-
4929 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004930
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004931 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00004932 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004933 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004934
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004935 SuggestParentheses(Self, OpLoc,
4936 Self.PDiag(diag::note_precedence_conditional_silence)
4937 << BinaryOperator::getOpcodeStr(CondOpcode),
4938 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00004939
4940 SuggestParentheses(Self, OpLoc,
4941 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00004942 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004943}
4944
Steve Naroff83895f72007-09-16 03:34:24 +00004945/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00004946/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00004947ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00004948 SourceLocation ColonLoc,
4949 Expr *CondExpr, Expr *LHSExpr,
4950 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00004951 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
4952 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00004953 OpaqueValueExpr *opaqueValue = 0;
4954 Expr *commonExpr = 0;
4955 if (LHSExpr == 0) {
4956 commonExpr = CondExpr;
4957
4958 // We usually want to apply unary conversions *before* saving, except
4959 // in the special case of a C++ l-value conditional.
4960 if (!(getLangOptions().CPlusPlus
4961 && !commonExpr->isTypeDependent()
4962 && commonExpr->getValueKind() == RHSExpr->getValueKind()
4963 && commonExpr->isGLValue()
4964 && commonExpr->isOrdinaryOrBitFieldObject()
4965 && RHSExpr->isOrdinaryOrBitFieldObject()
4966 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004967 ExprResult commonRes = UsualUnaryConversions(commonExpr);
4968 if (commonRes.isInvalid())
4969 return ExprError();
4970 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00004971 }
4972
4973 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
4974 commonExpr->getType(),
4975 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00004976 commonExpr->getObjectKind(),
4977 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00004978 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00004979 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00004980
John McCall7decc9e2010-11-18 06:31:45 +00004981 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004982 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00004983 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
4984 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004985 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004986 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
4987 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004988 return ExprError();
4989
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004990 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
4991 RHS.get());
4992
John McCallc07a0c72011-02-17 10:25:35 +00004993 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00004994 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
4995 LHS.take(), ColonLoc,
4996 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00004997
4998 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00004999 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005000 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5001 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005002}
5003
John McCallaba90822011-01-31 23:13:11 +00005004// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005005// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005006// routine is it effectively iqnores the qualifiers on the top level pointee.
5007// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5008// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005009static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005010checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5011 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5012 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005013
Steve Naroff1f4d7272007-05-11 04:00:31 +00005014 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005015 const Type *lhptee, *rhptee;
5016 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005017 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5018 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005019
John McCallaba90822011-01-31 23:13:11 +00005020 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005021
5022 // C99 6.5.16.1p1: This following citation is common to constraints
5023 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5024 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005025 Qualifiers lq;
5026
John McCall31168b02011-06-15 23:02:42 +00005027 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5028 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5029 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5030 // Ignore lifetime for further calculation.
5031 lhq.removeObjCLifetime();
5032 rhq.removeObjCLifetime();
5033 }
5034
John McCall4fff8f62011-02-01 00:10:29 +00005035 if (!lhq.compatiblyIncludes(rhq)) {
5036 // Treat address-space mismatches as fatal. TODO: address subspaces
5037 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5038 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5039
John McCall31168b02011-06-15 23:02:42 +00005040 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005041 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005042 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005043 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005044 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005045 && (lhptee->isVoidType() || rhptee->isVoidType()))
5046 ; // keep old
5047
John McCall31168b02011-06-15 23:02:42 +00005048 // Treat lifetime mismatches as fatal.
5049 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5050 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5051
John McCall4fff8f62011-02-01 00:10:29 +00005052 // For GCC compatibility, other qualifier mismatches are treated
5053 // as still compatible in C.
5054 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5055 }
Steve Naroff3f597292007-05-11 22:18:03 +00005056
Mike Stump4e1f26a2009-02-19 03:04:26 +00005057 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5058 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005059 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005060 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005061 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005062 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005063
Chris Lattner0a788432008-01-03 22:56:36 +00005064 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005065 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005066 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005067 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005068
Chris Lattner0a788432008-01-03 22:56:36 +00005069 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005070 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005071 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005072
5073 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005074 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005075 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005076 }
John McCall4fff8f62011-02-01 00:10:29 +00005077
Mike Stump4e1f26a2009-02-19 03:04:26 +00005078 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005079 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005080 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5081 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005082 // Check if the pointee types are compatible ignoring the sign.
5083 // We explicitly check for char so that we catch "char" vs
5084 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005085 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005086 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005087 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005088 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005089
Chris Lattnerec3a1562009-10-17 20:33:28 +00005090 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005091 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005092 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005093 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005094
John McCall4fff8f62011-02-01 00:10:29 +00005095 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005096 // Types are compatible ignoring the sign. Qualifier incompatibility
5097 // takes priority over sign incompatibility because the sign
5098 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005099 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005100 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005101
John McCallaba90822011-01-31 23:13:11 +00005102 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005103 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005104
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005105 // If we are a multi-level pointer, it's possible that our issue is simply
5106 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5107 // the eventual target type is the same and the pointers have the same
5108 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005109 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005110 do {
John McCall4fff8f62011-02-01 00:10:29 +00005111 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5112 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005113 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005114
John McCall4fff8f62011-02-01 00:10:29 +00005115 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005116 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005117 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005118
Eli Friedman80160bd2009-03-22 23:59:44 +00005119 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005120 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005121 }
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005122 if (!S.getLangOptions().CPlusPlus &&
5123 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5124 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005125 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005126}
5127
John McCallaba90822011-01-31 23:13:11 +00005128/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005129/// block pointer types are compatible or whether a block and normal pointer
5130/// are compatible. It is more restrict than comparing two function pointer
5131// types.
John McCallaba90822011-01-31 23:13:11 +00005132static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005133checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5134 QualType RHSType) {
5135 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5136 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005137
Steve Naroff081c7422008-09-04 15:10:53 +00005138 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005139
Steve Naroff081c7422008-09-04 15:10:53 +00005140 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005141 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5142 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005143
John McCallaba90822011-01-31 23:13:11 +00005144 // In C++, the types have to match exactly.
5145 if (S.getLangOptions().CPlusPlus)
5146 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005147
John McCallaba90822011-01-31 23:13:11 +00005148 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005149
Steve Naroff081c7422008-09-04 15:10:53 +00005150 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005151 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5152 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005153
Richard Trieua871b972011-09-06 20:21:22 +00005154 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005155 return Sema::IncompatibleBlockPointer;
5156
Steve Naroff081c7422008-09-04 15:10:53 +00005157 return ConvTy;
5158}
5159
John McCallaba90822011-01-31 23:13:11 +00005160/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005161/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005162static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005163checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5164 QualType RHSType) {
5165 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5166 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005167
Richard Trieua871b972011-09-06 20:21:22 +00005168 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005169 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005170 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5171 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005172 return Sema::IncompatiblePointer;
5173 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005174 }
Richard Trieua871b972011-09-06 20:21:22 +00005175 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005176 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5177 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005178 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005179 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005180 }
Richard Trieua871b972011-09-06 20:21:22 +00005181 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5182 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005183
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005184 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5185 // make an exception for id<P>
5186 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005187 return Sema::CompatiblePointerDiscardsQualifiers;
5188
Richard Trieua871b972011-09-06 20:21:22 +00005189 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005190 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005191 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005192 return Sema::IncompatibleObjCQualifiedId;
5193 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005194}
5195
John McCall29600e12010-11-16 02:32:08 +00005196Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005197Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005198 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005199 // Fake up an opaque expression. We don't actually care about what
5200 // cast operations are required, so if CheckAssignmentConstraints
5201 // adds casts to this they'll be wasted, but fortunately that doesn't
5202 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005203 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5204 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005205 CastKind K = CK_Invalid;
5206
Richard Trieua871b972011-09-06 20:21:22 +00005207 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005208}
5209
Mike Stump4e1f26a2009-02-19 03:04:26 +00005210/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5211/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005212/// pointers. Here are some objectionable examples that GCC considers warnings:
5213///
5214/// int a, *pint;
5215/// short *pshort;
5216/// struct foo *pfoo;
5217///
5218/// pint = pshort; // warning: assignment from incompatible pointer type
5219/// a = pint; // warning: assignment makes integer from pointer without a cast
5220/// pint = a; // warning: assignment makes pointer from integer without a cast
5221/// pint = pfoo; // warning: assignment from incompatible pointer type
5222///
5223/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005224/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005225///
John McCall8cb679e2010-11-15 09:13:47 +00005226/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005227Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005228Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005229 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005230 QualType RHSType = RHS.get()->getType();
5231 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005232
Chris Lattnera52c2f22008-01-04 23:18:45 +00005233 // Get canonical types. We're not formatting these types, just comparing
5234 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005235 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5236 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005237
Eli Friedman0dfb8892011-10-06 23:00:33 +00005238
John McCalle5255932011-01-31 22:28:28 +00005239 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005240 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005241 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005242 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005243 }
5244
David Chisnallfa35df62012-01-16 17:27:18 +00005245 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5246 if (AtomicTy->getValueType() == RHSType) {
5247 Kind = CK_NonAtomicToAtomic;
5248 return Compatible;
5249 }
5250 }
5251
5252 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) {
5253 if (AtomicTy->getValueType() == LHSType) {
5254 Kind = CK_AtomicToNonAtomic;
5255 return Compatible;
5256 }
5257 }
5258
5259
Douglas Gregor6b754842008-10-28 00:22:11 +00005260 // If the left-hand side is a reference type, then we are in a
5261 // (rare!) case where we've allowed the use of references in C,
5262 // e.g., as a parameter type in a built-in function. In this case,
5263 // just make sure that the type referenced is compatible with the
5264 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005265 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005266 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005267 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5268 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005269 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005270 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005271 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005272 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005273 }
John McCalle5255932011-01-31 22:28:28 +00005274
Nate Begemanbd956c42009-06-28 02:36:38 +00005275 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5276 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005277 if (LHSType->isExtVectorType()) {
5278 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005279 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005280 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005281 // CK_VectorSplat does T -> vector T, so first cast to the
5282 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005283 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5284 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005285 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005286 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005287 }
5288 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005289 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005290 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005291 }
Mike Stump11289f42009-09-09 15:08:12 +00005292
John McCalle5255932011-01-31 22:28:28 +00005293 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005294 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5295 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005296 // Allow assignments of an AltiVec vector type to an equivalent GCC
5297 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005298 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005299 Kind = CK_BitCast;
5300 return Compatible;
5301 }
5302
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005303 // If we are allowing lax vector conversions, and LHS and RHS are both
5304 // vectors, the total size only needs to be the same. This is a bitcast;
5305 // no bits are changed but the result type is different.
5306 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005307 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005308 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005309 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005310 }
Chris Lattner881a2122008-01-04 23:32:24 +00005311 }
5312 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005313 }
Eli Friedman3360d892008-05-30 18:07:22 +00005314
John McCalle5255932011-01-31 22:28:28 +00005315 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005316 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5317 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005318 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005319 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005320 }
Eli Friedman3360d892008-05-30 18:07:22 +00005321
John McCalle5255932011-01-31 22:28:28 +00005322 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005323 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005324 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005325 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005326 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005327 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005328 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005329
John McCalle5255932011-01-31 22:28:28 +00005330 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005331 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005332 Kind = CK_IntegralToPointer; // FIXME: null?
5333 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005334 }
John McCalle5255932011-01-31 22:28:28 +00005335
5336 // C pointers are not compatible with ObjC object pointers,
5337 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005338 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005339 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005340 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005341 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005342 return Compatible;
5343 }
5344
5345 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005346 if (RHSType->isObjCClassType() &&
5347 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005348 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005349 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005350 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005351 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005352
John McCalle5255932011-01-31 22:28:28 +00005353 Kind = CK_BitCast;
5354 return IncompatiblePointer;
5355 }
5356
5357 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005358 if (RHSType->getAs<BlockPointerType>()) {
5359 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005360 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005361 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005362 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005363 }
John McCalle5255932011-01-31 22:28:28 +00005364
Steve Naroff081c7422008-09-04 15:10:53 +00005365 return Incompatible;
5366 }
5367
John McCalle5255932011-01-31 22:28:28 +00005368 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005369 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005370 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005371 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005372 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005373 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005374 }
5375
5376 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005377 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005378 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005379 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005380 }
5381
John McCalle5255932011-01-31 22:28:28 +00005382 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005383 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005384 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005385 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005386 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005387
John McCalle5255932011-01-31 22:28:28 +00005388 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005389 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005390 if (RHSPT->getPointeeType()->isVoidType()) {
5391 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005392 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005393 }
John McCall8cb679e2010-11-15 09:13:47 +00005394
Chris Lattnera52c2f22008-01-04 23:18:45 +00005395 return Incompatible;
5396 }
5397
John McCalle5255932011-01-31 22:28:28 +00005398 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005399 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005400 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005401 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005402 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005403 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005404 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005405 if (getLangOptions().ObjCAutoRefCount &&
5406 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005407 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005408 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005409 return result;
John McCalle5255932011-01-31 22:28:28 +00005410 }
5411
5412 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005413 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005414 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005415 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005416 }
5417
John McCalle5255932011-01-31 22:28:28 +00005418 // In general, C pointers are not compatible with ObjC object pointers,
5419 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005420 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005421 Kind = CK_CPointerToObjCPointerCast;
5422
John McCalle5255932011-01-31 22:28:28 +00005423 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005424 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005425 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005426 }
5427
5428 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005429 if (LHSType->isObjCClassType() &&
5430 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005431 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005432 return Compatible;
5433 }
5434
Steve Naroffaccc4882009-07-20 17:56:53 +00005435 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005436 }
John McCalle5255932011-01-31 22:28:28 +00005437
5438 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005439 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005440 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005441 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005442 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005443 }
5444
Steve Naroff7cae42b2009-07-10 23:34:53 +00005445 return Incompatible;
5446 }
John McCalle5255932011-01-31 22:28:28 +00005447
5448 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005449 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005450 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005451 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005452 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005453 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005454 }
Eli Friedman3360d892008-05-30 18:07:22 +00005455
John McCalle5255932011-01-31 22:28:28 +00005456 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005457 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005458 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005459 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005460 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005461
Chris Lattnera52c2f22008-01-04 23:18:45 +00005462 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005463 }
John McCalle5255932011-01-31 22:28:28 +00005464
5465 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005466 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005467 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005468 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005469 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005470 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005471 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005472
John McCalle5255932011-01-31 22:28:28 +00005473 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005474 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005475 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005476 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005477 }
5478
Steve Naroff7cae42b2009-07-10 23:34:53 +00005479 return Incompatible;
5480 }
Eli Friedman3360d892008-05-30 18:07:22 +00005481
John McCalle5255932011-01-31 22:28:28 +00005482 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005483 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5484 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005485 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005486 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005487 }
Bill Wendling216423b2007-05-30 06:30:29 +00005488 }
John McCalle5255932011-01-31 22:28:28 +00005489
Steve Naroff98cf3e92007-06-06 18:38:38 +00005490 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005491}
5492
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005493/// \brief Constructs a transparent union from an expression that is
5494/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005495static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5496 ExprResult &EResult, QualType UnionType,
5497 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005498 // Build an initializer list that designates the appropriate member
5499 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005500 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005501 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005502 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005503 SourceLocation());
5504 Initializer->setType(UnionType);
5505 Initializer->setInitializedFieldInUnion(Field);
5506
5507 // Build a compound literal constructing a value of the transparent
5508 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005509 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005510 EResult = S.Owned(
5511 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5512 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005513}
5514
5515Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005516Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005517 ExprResult &RHS) {
5518 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005519
Mike Stump11289f42009-09-09 15:08:12 +00005520 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005521 // transparent_union GCC extension.
5522 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005523 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005524 return Incompatible;
5525
5526 // The field to initialize within the transparent union.
5527 RecordDecl *UD = UT->getDecl();
5528 FieldDecl *InitField = 0;
5529 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005530 for (RecordDecl::field_iterator it = UD->field_begin(),
5531 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005532 it != itend; ++it) {
5533 if (it->getType()->isPointerType()) {
5534 // If the transparent union contains a pointer type, we allow:
5535 // 1) void pointer
5536 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005537 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005538 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005539 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005540 InitField = *it;
5541 break;
5542 }
Mike Stump11289f42009-09-09 15:08:12 +00005543
Richard Trieueb299142011-09-06 20:40:12 +00005544 if (RHS.get()->isNullPointerConstant(Context,
5545 Expr::NPC_ValueDependentIsNull)) {
5546 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5547 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005548 InitField = *it;
5549 break;
5550 }
5551 }
5552
John McCall8cb679e2010-11-15 09:13:47 +00005553 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005554 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005555 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005556 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005557 InitField = *it;
5558 break;
5559 }
5560 }
5561
5562 if (!InitField)
5563 return Incompatible;
5564
Richard Trieueb299142011-09-06 20:40:12 +00005565 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005566 return Compatible;
5567}
5568
Chris Lattner9bad62c2008-01-04 18:04:52 +00005569Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005570Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5571 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005572 if (getLangOptions().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005573 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005574 // C++ 5.17p3: If the left operand is not of class type, the
5575 // expression is implicitly converted (C++ 4) to the
5576 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005577 ExprResult Res;
5578 if (Diagnose) {
5579 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5580 AA_Assigning);
5581 } else {
5582 ImplicitConversionSequence ICS =
5583 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5584 /*SuppressUserConversions=*/false,
5585 /*AllowExplicit=*/false,
5586 /*InOverloadResolution=*/false,
5587 /*CStyle=*/false,
5588 /*AllowObjCWritebackConversion=*/false);
5589 if (ICS.isFailure())
5590 return Incompatible;
5591 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5592 ICS, AA_Assigning);
5593 }
John Wiegley01296292011-04-08 18:41:53 +00005594 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005595 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005596 Sema::AssignConvertType result = Compatible;
5597 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005598 !CheckObjCARCUnavailableWeakConversion(LHSType,
5599 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005600 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005601 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005602 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005603 }
5604
5605 // FIXME: Currently, we fall through and treat C++ classes like C
5606 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005607 // FIXME: We also fall through for atomics; not sure what should
5608 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005609 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005610
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005611 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5612 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005613 if ((LHSType->isPointerType() ||
5614 LHSType->isObjCObjectPointerType() ||
5615 LHSType->isBlockPointerType())
5616 && RHS.get()->isNullPointerConstant(Context,
5617 Expr::NPC_ValueDependentIsNull)) {
5618 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005619 return Compatible;
5620 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005621
Chris Lattnere6dcd502007-10-16 02:55:40 +00005622 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005623 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005624 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005625 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005626 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005627 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005628 if (!LHSType->isReferenceType()) {
5629 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5630 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005631 return Incompatible;
5632 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005633
John McCall8cb679e2010-11-15 09:13:47 +00005634 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005635 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005636 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005637
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005638 // C99 6.5.16.1p2: The value of the right operand is converted to the
5639 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005640 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5641 // so that we can use references in built-in functions even in C.
5642 // The getNonReferenceType() call makes sure that the resulting expression
5643 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005644 if (result != Incompatible && RHS.get()->getType() != LHSType)
5645 RHS = ImpCastExprToType(RHS.take(),
5646 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005647 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005648}
5649
Richard Trieueb299142011-09-06 20:40:12 +00005650QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5651 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005652 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005653 << LHS.get()->getType() << RHS.get()->getType()
5654 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005655 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005656}
5657
Richard Trieu859d23f2011-09-06 21:01:04 +00005658QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005659 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005660 if (!IsCompAssign) {
5661 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5662 if (LHS.isInvalid())
5663 return QualType();
5664 }
5665 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5666 if (RHS.isInvalid())
5667 return QualType();
5668
Mike Stump4e1f26a2009-02-19 03:04:26 +00005669 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005670 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005671 QualType LHSType =
5672 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5673 QualType RHSType =
5674 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005675
Nate Begeman191a6b12008-07-14 18:02:46 +00005676 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005677 if (LHSType == RHSType)
5678 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005679
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005680 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005681 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5682 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5683 if (LHSType->isExtVectorType()) {
5684 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5685 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005686 }
5687
Richard Trieuba63ce62011-09-09 01:45:06 +00005688 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005689 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5690 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005691 }
5692
Eli Friedman1408bc92011-06-23 18:10:35 +00005693 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005694 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005695 // If we are allowing lax vector conversions, and LHS and RHS are both
5696 // vectors, the total size only needs to be the same. This is a
5697 // bitcast; no bits are changed but the result type is different.
5698 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005699 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5700 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005701 }
5702
Nate Begemanbd956c42009-06-28 02:36:38 +00005703 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5704 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5705 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005706 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005707 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005708 std::swap(RHS, LHS);
5709 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005710 }
Mike Stump11289f42009-09-09 15:08:12 +00005711
Nate Begeman886448d2009-06-28 19:12:57 +00005712 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005713 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005714 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005715 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5716 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005717 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005718 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005719 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005720 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5721 if (swapped) std::swap(RHS, LHS);
5722 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005723 }
5724 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005725 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5726 RHSType->isRealFloatingType()) {
5727 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005728 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005729 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005730 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005731 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5732 if (swapped) std::swap(RHS, LHS);
5733 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005734 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005735 }
5736 }
Mike Stump11289f42009-09-09 15:08:12 +00005737
Nate Begeman886448d2009-06-28 19:12:57 +00005738 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005739 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005740 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005741 << LHS.get()->getType() << RHS.get()->getType()
5742 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005743 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005744}
5745
Richard Trieuf8916e12011-09-16 00:53:10 +00005746// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5747// expression. These are mainly cases where the null pointer is used as an
5748// integer instead of a pointer.
5749static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5750 SourceLocation Loc, bool IsCompare) {
5751 // The canonical way to check for a GNU null is with isNullPointerConstant,
5752 // but we use a bit of a hack here for speed; this is a relatively
5753 // hot path, and isNullPointerConstant is slow.
5754 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5755 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5756
5757 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5758
5759 // Avoid analyzing cases where the result will either be invalid (and
5760 // diagnosed as such) or entirely valid and not something to warn about.
5761 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5762 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5763 return;
5764
5765 // Comparison operations would not make sense with a null pointer no matter
5766 // what the other expression is.
5767 if (!IsCompare) {
5768 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5769 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5770 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5771 return;
5772 }
5773
5774 // The rest of the operations only make sense with a null pointer
5775 // if the other expression is a pointer.
5776 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5777 NonNullType->canDecayToPointerType())
5778 return;
5779
5780 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5781 << LHSNull /* LHS is NULL */ << NonNullType
5782 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5783}
5784
Richard Trieu859d23f2011-09-06 21:01:04 +00005785QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005786 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005787 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005788 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5789
Richard Trieu859d23f2011-09-06 21:01:04 +00005790 if (LHS.get()->getType()->isVectorType() ||
5791 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005792 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005793
Richard Trieuba63ce62011-09-09 01:45:06 +00005794 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005795 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005796 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005797
David Chisnallfa35df62012-01-16 17:27:18 +00005798
Richard Trieu859d23f2011-09-06 21:01:04 +00005799 if (!LHS.get()->getType()->isArithmeticType() ||
David Chisnallfa35df62012-01-16 17:27:18 +00005800 !RHS.get()->getType()->isArithmeticType()) {
5801 if (IsCompAssign &&
5802 LHS.get()->getType()->isAtomicType() &&
5803 RHS.get()->getType()->isArithmeticType())
5804 return compType;
Richard Trieu859d23f2011-09-06 21:01:04 +00005805 return InvalidOperands(Loc, LHS, RHS);
David Chisnallfa35df62012-01-16 17:27:18 +00005806 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005807
Chris Lattnerfaa54172010-01-12 21:23:57 +00005808 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005809 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005810 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005811 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005812 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5813 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005814
Chris Lattnerfaa54172010-01-12 21:23:57 +00005815 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005816}
5817
Chris Lattnerfaa54172010-01-12 21:23:57 +00005818QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005819 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005820 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5821
Richard Trieu859d23f2011-09-06 21:01:04 +00005822 if (LHS.get()->getType()->isVectorType() ||
5823 RHS.get()->getType()->isVectorType()) {
5824 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5825 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005826 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005827 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005828 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005829
Richard Trieuba63ce62011-09-09 01:45:06 +00005830 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005831 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005832 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005833
Richard Trieu859d23f2011-09-06 21:01:04 +00005834 if (!LHS.get()->getType()->isIntegerType() ||
5835 !RHS.get()->getType()->isIntegerType())
5836 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005837
Chris Lattnerfaa54172010-01-12 21:23:57 +00005838 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005839 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005840 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005841 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5842 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005843
Chris Lattnerfaa54172010-01-12 21:23:57 +00005844 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005845}
5846
Chandler Carruthc9332212011-06-27 08:02:19 +00005847/// \brief Diagnose invalid arithmetic on two void pointers.
5848static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005849 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005850 S.Diag(Loc, S.getLangOptions().CPlusPlus
5851 ? diag::err_typecheck_pointer_arith_void_type
5852 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005853 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5854 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005855}
5856
5857/// \brief Diagnose invalid arithmetic on a void pointer.
5858static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5859 Expr *Pointer) {
5860 S.Diag(Loc, S.getLangOptions().CPlusPlus
5861 ? diag::err_typecheck_pointer_arith_void_type
5862 : diag::ext_gnu_void_ptr)
5863 << 0 /* one pointer */ << Pointer->getSourceRange();
5864}
5865
5866/// \brief Diagnose invalid arithmetic on two function pointers.
5867static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
5868 Expr *LHS, Expr *RHS) {
5869 assert(LHS->getType()->isAnyPointerType());
5870 assert(RHS->getType()->isAnyPointerType());
5871 S.Diag(Loc, S.getLangOptions().CPlusPlus
5872 ? diag::err_typecheck_pointer_arith_function_type
5873 : diag::ext_gnu_ptr_func_arith)
5874 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
5875 // We only show the second type if it differs from the first.
5876 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
5877 RHS->getType())
5878 << RHS->getType()->getPointeeType()
5879 << LHS->getSourceRange() << RHS->getSourceRange();
5880}
5881
5882/// \brief Diagnose invalid arithmetic on a function pointer.
5883static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
5884 Expr *Pointer) {
5885 assert(Pointer->getType()->isAnyPointerType());
5886 S.Diag(Loc, S.getLangOptions().CPlusPlus
5887 ? diag::err_typecheck_pointer_arith_function_type
5888 : diag::ext_gnu_ptr_func_arith)
5889 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
5890 << 0 /* one pointer, so only one type */
5891 << Pointer->getSourceRange();
5892}
5893
Richard Trieu993f3ab2011-09-12 18:08:02 +00005894/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00005895///
5896/// \returns True if pointer has incomplete type
5897static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
5898 Expr *Operand) {
5899 if ((Operand->getType()->isPointerType() &&
5900 !Operand->getType()->isDependentType()) ||
5901 Operand->getType()->isObjCObjectPointerType()) {
5902 QualType PointeeTy = Operand->getType()->getPointeeType();
5903 if (S.RequireCompleteType(
5904 Loc, PointeeTy,
5905 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
5906 << PointeeTy << Operand->getSourceRange()))
5907 return true;
5908 }
5909 return false;
5910}
5911
Chandler Carruthc9332212011-06-27 08:02:19 +00005912/// \brief Check the validity of an arithmetic pointer operand.
5913///
5914/// If the operand has pointer type, this code will check for pointer types
5915/// which are invalid in arithmetic operations. These will be diagnosed
5916/// appropriately, including whether or not the use is supported as an
5917/// extension.
5918///
5919/// \returns True when the operand is valid to use (even if as an extension).
5920static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
5921 Expr *Operand) {
5922 if (!Operand->getType()->isAnyPointerType()) return true;
5923
5924 QualType PointeeTy = Operand->getType()->getPointeeType();
5925 if (PointeeTy->isVoidType()) {
5926 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
5927 return !S.getLangOptions().CPlusPlus;
5928 }
5929 if (PointeeTy->isFunctionType()) {
5930 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
5931 return !S.getLangOptions().CPlusPlus;
5932 }
5933
Richard Trieuaba22802011-09-02 02:15:37 +00005934 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00005935
5936 return true;
5937}
5938
5939/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
5940/// operands.
5941///
5942/// This routine will diagnose any invalid arithmetic on pointer operands much
5943/// like \see checkArithmeticOpPointerOperand. However, it has special logic
5944/// for emitting a single diagnostic even for operations where both LHS and RHS
5945/// are (potentially problematic) pointers.
5946///
5947/// \returns True when the operand is valid to use (even if as an extension).
5948static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005949 Expr *LHSExpr, Expr *RHSExpr) {
5950 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
5951 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005952 if (!isLHSPointer && !isRHSPointer) return true;
5953
5954 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00005955 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
5956 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00005957
5958 // Check for arithmetic on pointers to incomplete types.
5959 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
5960 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
5961 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005962 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
5963 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
5964 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00005965
5966 return !S.getLangOptions().CPlusPlus;
5967 }
5968
5969 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
5970 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
5971 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00005972 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
5973 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
5974 RHSExpr);
5975 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00005976
5977 return !S.getLangOptions().CPlusPlus;
5978 }
5979
Richard Trieu4ae7e972011-09-06 21:13:51 +00005980 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
5981 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00005982
Chandler Carruthc9332212011-06-27 08:02:19 +00005983 return true;
5984}
5985
Richard Trieub10c6312011-09-01 22:53:23 +00005986/// \brief Check bad cases where we step over interface counts.
5987static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
5988 SourceLocation OpLoc,
5989 Expr *Op) {
5990 assert(Op->getType()->isAnyPointerType());
5991 QualType PointeeTy = Op->getType()->getPointeeType();
5992 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
5993 return true;
5994
5995 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
5996 << PointeeTy << Op->getSourceRange();
5997 return false;
5998}
5999
Nico Weberccec40d2012-03-02 22:01:22 +00006000/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6001/// literal.
6002static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6003 Expr *LHSExpr, Expr *RHSExpr) {
6004 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6005 Expr* IndexExpr = RHSExpr;
6006 if (!StrExpr) {
6007 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6008 IndexExpr = LHSExpr;
6009 }
6010
6011 bool IsStringPlusInt = StrExpr &&
6012 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6013 if (!IsStringPlusInt)
6014 return;
6015
6016 llvm::APSInt index;
6017 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6018 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6019 if (index.isNonNegative() &&
6020 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6021 index.isUnsigned()))
6022 return;
6023 }
6024
6025 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6026 Self.Diag(OpLoc, diag::warn_string_plus_int)
6027 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6028
6029 // Only print a fixit for "str" + int, not for int + "str".
6030 if (IndexExpr == RHSExpr) {
6031 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6032 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6033 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6034 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6035 << FixItHint::CreateInsertion(EndLoc, "]");
6036 } else
6037 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6038}
6039
Richard Trieu993f3ab2011-09-12 18:08:02 +00006040/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006041static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006042 Expr *LHSExpr, Expr *RHSExpr) {
6043 assert(LHSExpr->getType()->isAnyPointerType());
6044 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006045 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006046 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6047 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006048}
6049
Chris Lattnerfaa54172010-01-12 21:23:57 +00006050QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006051 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6052 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006053 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6054
Richard Trieu4ae7e972011-09-06 21:13:51 +00006055 if (LHS.get()->getType()->isVectorType() ||
6056 RHS.get()->getType()->isVectorType()) {
6057 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006058 if (CompLHSTy) *CompLHSTy = compType;
6059 return compType;
6060 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006061
Richard Trieu4ae7e972011-09-06 21:13:51 +00006062 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6063 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006064 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006065
Nico Weberccec40d2012-03-02 22:01:22 +00006066 // Diagnose "string literal" '+' int.
6067 if (Opc == BO_Add)
6068 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6069
Steve Naroffe4718892007-04-27 18:30:00 +00006070 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006071 if (LHS.get()->getType()->isArithmeticType() &&
6072 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006073 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006074 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006075 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006076
David Chisnallfa35df62012-01-16 17:27:18 +00006077 if (LHS.get()->getType()->isAtomicType() &&
6078 RHS.get()->getType()->isArithmeticType()) {
6079 *CompLHSTy = LHS.get()->getType();
6080 return compType;
6081 }
6082
Eli Friedman8e122982008-05-18 18:08:51 +00006083 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006084 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006085 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006086 std::swap(PExp, IExp);
6087
Richard Trieub420bca2011-09-12 18:37:54 +00006088 if (!PExp->getType()->isAnyPointerType())
6089 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006090
Richard Trieub420bca2011-09-12 18:37:54 +00006091 if (!IExp->getType()->isIntegerType())
6092 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006093
Richard Trieub420bca2011-09-12 18:37:54 +00006094 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6095 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006096
Richard Trieub420bca2011-09-12 18:37:54 +00006097 // Diagnose bad cases where we step over interface counts.
6098 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6099 return QualType();
6100
6101 // Check array bounds for pointer arithemtic
6102 CheckArrayAccess(PExp, IExp);
6103
6104 if (CompLHSTy) {
6105 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6106 if (LHSTy.isNull()) {
6107 LHSTy = LHS.get()->getType();
6108 if (LHSTy->isPromotableIntegerType())
6109 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006110 }
Richard Trieub420bca2011-09-12 18:37:54 +00006111 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006112 }
6113
Richard Trieub420bca2011-09-12 18:37:54 +00006114 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006115}
6116
Chris Lattner2a3569b2008-04-07 05:30:13 +00006117// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006118QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006119 SourceLocation Loc,
6120 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006121 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6122
Richard Trieu4ae7e972011-09-06 21:13:51 +00006123 if (LHS.get()->getType()->isVectorType() ||
6124 RHS.get()->getType()->isVectorType()) {
6125 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006126 if (CompLHSTy) *CompLHSTy = compType;
6127 return compType;
6128 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006129
Richard Trieu4ae7e972011-09-06 21:13:51 +00006130 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6131 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006132 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006133
Chris Lattner4d62f422007-12-09 21:53:25 +00006134 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006135
Chris Lattner4d62f422007-12-09 21:53:25 +00006136 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006137 if (LHS.get()->getType()->isArithmeticType() &&
6138 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006139 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006140 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006141 }
Mike Stump11289f42009-09-09 15:08:12 +00006142
David Chisnallfa35df62012-01-16 17:27:18 +00006143 if (LHS.get()->getType()->isAtomicType() &&
6144 RHS.get()->getType()->isArithmeticType()) {
6145 *CompLHSTy = LHS.get()->getType();
6146 return compType;
6147 }
6148
Chris Lattner4d62f422007-12-09 21:53:25 +00006149 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006150 if (LHS.get()->getType()->isAnyPointerType()) {
6151 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006152
Chris Lattner12bdebb2009-04-24 23:50:08 +00006153 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006154 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006155 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006156
Chris Lattner4d62f422007-12-09 21:53:25 +00006157 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006158 if (RHS.get()->getType()->isIntegerType()) {
6159 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006160 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006161
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006162 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006163 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6164 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006165
Richard Trieu4ae7e972011-09-06 21:13:51 +00006166 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6167 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006168 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006169
Chris Lattner4d62f422007-12-09 21:53:25 +00006170 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006171 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006172 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006173 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006174
Eli Friedman168fe152009-05-16 13:54:38 +00006175 if (getLangOptions().CPlusPlus) {
6176 // Pointee types must be the same: C++ [expr.add]
6177 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006178 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006179 }
6180 } else {
6181 // Pointee types must be compatible C99 6.5.6p3
6182 if (!Context.typesAreCompatible(
6183 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6184 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006185 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006186 return QualType();
6187 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006188 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006189
Chandler Carruthc9332212011-06-27 08:02:19 +00006190 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006191 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006192 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006193
Richard Trieu4ae7e972011-09-06 21:13:51 +00006194 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006195 return Context.getPointerDiffType();
6196 }
6197 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006198
Richard Trieu4ae7e972011-09-06 21:13:51 +00006199 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006200}
6201
Douglas Gregor0bf31402010-10-08 23:50:27 +00006202static bool isScopedEnumerationType(QualType T) {
6203 if (const EnumType *ET = dyn_cast<EnumType>(T))
6204 return ET->getDecl()->isScoped();
6205 return false;
6206}
6207
Richard Trieue4a19fb2011-09-06 21:21:28 +00006208static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006209 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006210 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006211 llvm::APSInt Right;
6212 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006213 if (RHS.get()->isValueDependent() ||
6214 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006215 return;
6216
6217 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006218 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006219 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006220 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006221 return;
6222 }
6223 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006224 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006225 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006226 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006227 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006228 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006229 return;
6230 }
6231 if (Opc != BO_Shl)
6232 return;
6233
6234 // When left shifting an ICE which is signed, we can check for overflow which
6235 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6236 // integers have defined behavior modulo one more than the maximum value
6237 // representable in the result type, so never warn for those.
6238 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006239 if (LHS.get()->isValueDependent() ||
6240 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6241 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006242 return;
6243 llvm::APInt ResultBits =
6244 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6245 if (LeftBits.uge(ResultBits))
6246 return;
6247 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6248 Result = Result.shl(Right);
6249
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006250 // Print the bit representation of the signed integer as an unsigned
6251 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006252 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006253 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6254
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006255 // If we are only missing a sign bit, this is less likely to result in actual
6256 // bugs -- if the result is cast back to an unsigned type, it will have the
6257 // expected value. Thus we place this behind a different warning that can be
6258 // turned off separately if needed.
6259 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006260 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006261 << HexResult.str() << LHSType
6262 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006263 return;
6264 }
6265
6266 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006267 << HexResult.str() << Result.getMinSignedBits() << LHSType
6268 << Left.getBitWidth() << LHS.get()->getSourceRange()
6269 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006270}
6271
Chris Lattner2a3569b2008-04-07 05:30:13 +00006272// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006273QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006274 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006275 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006276 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6277
Chris Lattner5c11c412007-12-12 05:47:28 +00006278 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006279 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6280 !RHS.get()->getType()->hasIntegerRepresentation())
6281 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006282
Douglas Gregor0bf31402010-10-08 23:50:27 +00006283 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6284 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006285 if (isScopedEnumerationType(LHS.get()->getType()) ||
6286 isScopedEnumerationType(RHS.get()->getType())) {
6287 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006288 }
6289
Nate Begemane46ee9a2009-10-25 02:26:48 +00006290 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006291 if (LHS.get()->getType()->isVectorType() ||
6292 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006293 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006294
Chris Lattner5c11c412007-12-12 05:47:28 +00006295 // Shifts don't perform usual arithmetic conversions, they just do integer
6296 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006297
John McCall57cdd882010-12-16 19:28:59 +00006298 // For the LHS, do usual unary conversions, but then reset them away
6299 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006300 ExprResult OldLHS = LHS;
6301 LHS = UsualUnaryConversions(LHS.take());
6302 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006303 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006304 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006305 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006306
6307 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006308 RHS = UsualUnaryConversions(RHS.take());
6309 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006310 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006311
Ryan Flynnf53fab82009-08-07 16:20:20 +00006312 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006313 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006314
Chris Lattner5c11c412007-12-12 05:47:28 +00006315 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006316 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006317}
6318
Chandler Carruth17773fc2010-07-10 12:30:03 +00006319static bool IsWithinTemplateSpecialization(Decl *D) {
6320 if (DeclContext *DC = D->getDeclContext()) {
6321 if (isa<ClassTemplateSpecializationDecl>(DC))
6322 return true;
6323 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6324 return FD->isFunctionTemplateSpecialization();
6325 }
6326 return false;
6327}
6328
Richard Trieueea56f72011-09-02 03:48:46 +00006329/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006330static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6331 ExprResult &RHS) {
6332 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6333 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006334
6335 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6336 if (!LHSEnumType)
6337 return;
6338 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6339 if (!RHSEnumType)
6340 return;
6341
6342 // Ignore anonymous enums.
6343 if (!LHSEnumType->getDecl()->getIdentifier())
6344 return;
6345 if (!RHSEnumType->getDecl()->getIdentifier())
6346 return;
6347
6348 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6349 return;
6350
6351 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6352 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006353 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006354}
6355
Richard Trieudd82a5c2011-09-02 02:55:45 +00006356/// \brief Diagnose bad pointer comparisons.
6357static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006358 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006359 bool IsError) {
6360 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006361 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006362 << LHS.get()->getType() << RHS.get()->getType()
6363 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006364}
6365
6366/// \brief Returns false if the pointers are converted to a composite type,
6367/// true otherwise.
6368static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006369 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006370 // C++ [expr.rel]p2:
6371 // [...] Pointer conversions (4.10) and qualification
6372 // conversions (4.4) are performed on pointer operands (or on
6373 // a pointer operand and a null pointer constant) to bring
6374 // them to their composite pointer type. [...]
6375 //
6376 // C++ [expr.eq]p1 uses the same notion for (in)equality
6377 // comparisons of pointers.
6378
6379 // C++ [expr.eq]p2:
6380 // In addition, pointers to members can be compared, or a pointer to
6381 // member and a null pointer constant. Pointer to member conversions
6382 // (4.11) and qualification conversions (4.4) are performed to bring
6383 // them to a common type. If one operand is a null pointer constant,
6384 // the common type is the type of the other operand. Otherwise, the
6385 // common type is a pointer to member type similar (4.4) to the type
6386 // of one of the operands, with a cv-qualification signature (4.4)
6387 // that is the union of the cv-qualification signatures of the operand
6388 // types.
6389
Richard Trieu1762d7c2011-09-06 21:27:33 +00006390 QualType LHSType = LHS.get()->getType();
6391 QualType RHSType = RHS.get()->getType();
6392 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6393 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006394
6395 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006396 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006397 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006398 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006399 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006400 return true;
6401 }
6402
6403 if (NonStandardCompositeType)
6404 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006405 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6406 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006407
Richard Trieu1762d7c2011-09-06 21:27:33 +00006408 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6409 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006410 return false;
6411}
6412
6413static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006414 ExprResult &LHS,
6415 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006416 bool IsError) {
6417 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6418 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006419 << LHS.get()->getType() << RHS.get()->getType()
6420 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006421}
6422
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006423// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006424QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006425 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006426 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006427 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6428
John McCalle3027922010-08-25 11:45:40 +00006429 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006430
Chris Lattner9a152e22009-12-05 05:40:13 +00006431 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006432 if (LHS.get()->getType()->isVectorType() ||
6433 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006434 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006435
Richard Trieub80728f2011-09-06 21:43:51 +00006436 QualType LHSType = LHS.get()->getType();
6437 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006438
Richard Trieub80728f2011-09-06 21:43:51 +00006439 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6440 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006441
Richard Trieub80728f2011-09-06 21:43:51 +00006442 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006443
Richard Trieub80728f2011-09-06 21:43:51 +00006444 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006445 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006446 !LHS.get()->getLocStart().isMacroID() &&
6447 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006448 // For non-floating point types, check for self-comparisons of the form
6449 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6450 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006451 //
6452 // NOTE: Don't warn about comparison expressions resulting from macro
6453 // expansion. Also don't warn about comparisons which are only self
6454 // comparisons within a template specialization. The warnings should catch
6455 // obvious cases in the definition of the template anyways. The idea is to
6456 // warn when the typed comparison operator will always evaluate to the same
6457 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006458 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006459 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006460 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006461 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006462 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006463 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006464 << (Opc == BO_EQ
6465 || Opc == BO_LE
6466 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006467 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006468 !DRL->getDecl()->getType()->isReferenceType() &&
6469 !DRR->getDecl()->getType()->isReferenceType()) {
6470 // what is it always going to eval to?
6471 char always_evals_to;
6472 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006473 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006474 always_evals_to = 0; // false
6475 break;
John McCalle3027922010-08-25 11:45:40 +00006476 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006477 always_evals_to = 1; // true
6478 break;
6479 default:
6480 // best we can say is 'a constant'
6481 always_evals_to = 2; // e.g. array1 <= array2
6482 break;
6483 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006484 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006485 << 1 // array
6486 << always_evals_to);
6487 }
6488 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006489 }
Mike Stump11289f42009-09-09 15:08:12 +00006490
Chris Lattner222b8bd2009-03-08 19:39:53 +00006491 if (isa<CastExpr>(LHSStripped))
6492 LHSStripped = LHSStripped->IgnoreParenCasts();
6493 if (isa<CastExpr>(RHSStripped))
6494 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006495
Chris Lattner222b8bd2009-03-08 19:39:53 +00006496 // Warn about comparisons against a string constant (unless the other
6497 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006498 Expr *literalString = 0;
6499 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006500 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006501 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006502 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006503 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006504 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006505 } else if ((isa<StringLiteral>(RHSStripped) ||
6506 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006507 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006508 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006509 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006510 literalStringStripped = RHSStripped;
6511 }
6512
6513 if (literalString) {
6514 std::string resultComparison;
6515 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006516 case BO_LT: resultComparison = ") < 0"; break;
6517 case BO_GT: resultComparison = ") > 0"; break;
6518 case BO_LE: resultComparison = ") <= 0"; break;
6519 case BO_GE: resultComparison = ") >= 0"; break;
6520 case BO_EQ: resultComparison = ") == 0"; break;
6521 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006522 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006523 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006524
Ted Kremenek3427fac2011-02-23 01:52:04 +00006525 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006526 PDiag(diag::warn_stringcompare)
6527 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006528 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006529 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006530 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006531
Douglas Gregorec170db2010-06-08 19:50:34 +00006532 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006533 if (LHS.get()->getType()->isArithmeticType() &&
6534 RHS.get()->getType()->isArithmeticType()) {
6535 UsualArithmeticConversions(LHS, RHS);
6536 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006537 return QualType();
6538 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006539 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006540 LHS = UsualUnaryConversions(LHS.take());
6541 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006542 return QualType();
6543
Richard Trieub80728f2011-09-06 21:43:51 +00006544 RHS = UsualUnaryConversions(RHS.take());
6545 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006546 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006547 }
6548
Richard Trieub80728f2011-09-06 21:43:51 +00006549 LHSType = LHS.get()->getType();
6550 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006551
Douglas Gregorca63811b2008-11-19 03:25:36 +00006552 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006553 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006554
Richard Trieuba63ce62011-09-09 01:45:06 +00006555 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006556 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006557 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006558 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006559 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006560 if (LHSType->hasFloatingRepresentation())
6561 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006562
Richard Trieub80728f2011-09-06 21:43:51 +00006563 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006564 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006565 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006566
Richard Trieub80728f2011-09-06 21:43:51 +00006567 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006568 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006569 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006570 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006571
Douglas Gregorf267edd2010-06-15 21:38:40 +00006572 // All of the following pointer-related warnings are GCC extensions, except
6573 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006574 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006575 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006576 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006577 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006578 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006579
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006580 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006581 if (LCanPointeeTy == RCanPointeeTy)
6582 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006583 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006584 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6585 // Valid unless comparison between non-null pointer and function pointer
6586 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006587 // In a SFINAE context, we treat this as a hard error to maintain
6588 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006589 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6590 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006591 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006592 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006593
6594 if (isSFINAEContext())
6595 return QualType();
6596
Richard Trieub80728f2011-09-06 21:43:51 +00006597 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006598 return ResultTy;
6599 }
6600 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006601
Richard Trieub80728f2011-09-06 21:43:51 +00006602 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006603 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006604 else
6605 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006606 }
Eli Friedman16c209612009-08-23 00:27:47 +00006607 // C99 6.5.9p2 and C99 6.5.8p2
6608 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6609 RCanPointeeTy.getUnqualifiedType())) {
6610 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006611 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006612 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006613 << LHSType << RHSType << LHS.get()->getSourceRange()
6614 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006615 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006616 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006617 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6618 // Valid unless comparison between non-null pointer and function pointer
6619 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006620 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006621 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006622 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006623 } else {
6624 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006625 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006626 }
John McCall7684dde2011-03-11 04:25:25 +00006627 if (LCanPointeeTy != RCanPointeeTy) {
6628 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006629 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006630 else
Richard Trieub80728f2011-09-06 21:43:51 +00006631 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006632 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006633 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006634 }
Mike Stump11289f42009-09-09 15:08:12 +00006635
Sebastian Redl576fd422009-05-10 18:38:11 +00006636 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006637 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006638 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006639 return ResultTy;
6640
Mike Stump11289f42009-09-09 15:08:12 +00006641 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006642 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006643 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006644 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006645 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006646 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6647 RHS = ImpCastExprToType(RHS.take(), LHSType,
6648 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006649 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006650 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006651 return ResultTy;
6652 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006653 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006654 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006655 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006656 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6657 LHS = ImpCastExprToType(LHS.take(), RHSType,
6658 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006659 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006660 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006661 return ResultTy;
6662 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006663
6664 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006665 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006666 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6667 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006668 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006669 else
6670 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006671 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006672
6673 // Handle scoped enumeration types specifically, since they don't promote
6674 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006675 if (LHS.get()->getType()->isEnumeralType() &&
6676 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6677 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006678 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006679 }
Mike Stump11289f42009-09-09 15:08:12 +00006680
Steve Naroff081c7422008-09-04 15:10:53 +00006681 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006682 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006683 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006684 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6685 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006686
Steve Naroff081c7422008-09-04 15:10:53 +00006687 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006688 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006689 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006690 << LHSType << RHSType << LHS.get()->getSourceRange()
6691 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006692 }
Richard Trieub80728f2011-09-06 21:43:51 +00006693 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006694 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006695 }
John Wiegley01296292011-04-08 18:41:53 +00006696
Steve Naroffe18f94c2008-09-28 01:11:11 +00006697 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006698 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006699 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6700 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006701 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006702 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006703 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006704 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006705 ->getPointeeType()->isVoidType())))
6706 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006707 << LHSType << RHSType << LHS.get()->getSourceRange()
6708 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006709 }
John McCall7684dde2011-03-11 04:25:25 +00006710 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006711 LHS = ImpCastExprToType(LHS.take(), RHSType,
6712 RHSType->isPointerType() ? CK_BitCast
6713 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006714 else
John McCall9320b872011-09-09 05:25:32 +00006715 RHS = ImpCastExprToType(RHS.take(), LHSType,
6716 LHSType->isPointerType() ? CK_BitCast
6717 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006718 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006719 }
Steve Naroff081c7422008-09-04 15:10:53 +00006720
Richard Trieub80728f2011-09-06 21:43:51 +00006721 if (LHSType->isObjCObjectPointerType() ||
6722 RHSType->isObjCObjectPointerType()) {
6723 const PointerType *LPT = LHSType->getAs<PointerType>();
6724 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006725 if (LPT || RPT) {
6726 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6727 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006728
Steve Naroff753567f2008-11-17 19:49:16 +00006729 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006730 !Context.typesAreCompatible(LHSType, RHSType)) {
6731 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006732 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006733 }
John McCall7684dde2011-03-11 04:25:25 +00006734 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006735 LHS = ImpCastExprToType(LHS.take(), RHSType,
6736 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006737 else
John McCall9320b872011-09-09 05:25:32 +00006738 RHS = ImpCastExprToType(RHS.take(), LHSType,
6739 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006740 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006741 }
Richard Trieub80728f2011-09-06 21:43:51 +00006742 if (LHSType->isObjCObjectPointerType() &&
6743 RHSType->isObjCObjectPointerType()) {
6744 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6745 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006746 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006747 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006748 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006749 else
Richard Trieub80728f2011-09-06 21:43:51 +00006750 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006751 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006752 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006753 }
Richard Trieub80728f2011-09-06 21:43:51 +00006754 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6755 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006756 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006757 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006758 if ((LHSIsNull && LHSType->isIntegerType()) ||
6759 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006760 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006761 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006762 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006763 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006764 else if (getLangOptions().CPlusPlus) {
6765 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6766 isError = true;
6767 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006768 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006769
Chris Lattnerd99bd522009-08-23 00:03:44 +00006770 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006771 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006772 << LHSType << RHSType << LHS.get()->getSourceRange()
6773 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006774 if (isError)
6775 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006776 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006777
Richard Trieub80728f2011-09-06 21:43:51 +00006778 if (LHSType->isIntegerType())
6779 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006780 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006781 else
Richard Trieub80728f2011-09-06 21:43:51 +00006782 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006783 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006784 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006785 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006786
Steve Naroff4b191572008-09-04 16:56:14 +00006787 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006788 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006789 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6790 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006791 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006792 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006793 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006794 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6795 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006796 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006797 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006798
Richard Trieub80728f2011-09-06 21:43:51 +00006799 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006800}
6801
Tanya Lattner20248222012-01-16 21:02:28 +00006802
6803// Return a signed type that is of identical size and number of elements.
6804// For floating point vectors, return an integer type of identical size
6805// and number of elements.
6806QualType Sema::GetSignedVectorType(QualType V) {
6807 const VectorType *VTy = V->getAs<VectorType>();
6808 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6809 if (TypeSize == Context.getTypeSize(Context.CharTy))
6810 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6811 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6812 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6813 else if (TypeSize == Context.getTypeSize(Context.IntTy))
6814 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6815 else if (TypeSize == Context.getTypeSize(Context.LongTy))
6816 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6817 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6818 "Unhandled vector element size in vector compare");
6819 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6820}
6821
Nate Begeman191a6b12008-07-14 18:02:46 +00006822/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006823/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006824/// like a scalar comparison, a vector comparison produces a vector of integer
6825/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006826QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006827 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006828 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006829 // Check to make sure we're operating on vectors of the same type and width,
6830 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006831 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006832 if (vType.isNull())
6833 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006834
Richard Trieubcce2f72011-09-07 01:19:57 +00006835 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006836
Anton Yartsev530deb92011-03-27 15:36:07 +00006837 // If AltiVec, the comparison results in a numeric type, i.e.
6838 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006839 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006840 return Context.getLogicalOperationType();
6841
Nate Begeman191a6b12008-07-14 18:02:46 +00006842 // For non-floating point types, check for self-comparisons of the form
6843 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6844 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006845 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00006846 if (DeclRefExpr* DRL
6847 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
6848 if (DeclRefExpr* DRR
6849 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006850 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006851 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006852 PDiag(diag::warn_comparison_always)
6853 << 0 // self-
6854 << 2 // "a constant"
6855 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006856 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006857
Nate Begeman191a6b12008-07-14 18:02:46 +00006858 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006859 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00006860 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00006861 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006862 }
Tanya Lattner20248222012-01-16 21:02:28 +00006863
6864 // Return a signed type for the vector.
6865 return GetSignedVectorType(LHSType);
6866}
Mike Stump4e1f26a2009-02-19 03:04:26 +00006867
Tanya Lattner3dd33b22012-01-19 01:16:16 +00006868QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
6869 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00006870 // Ensure that either both operands are of the same vector type, or
6871 // one operand is of a vector type and the other is of its element type.
6872 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
6873 if (vType.isNull() || vType->isFloatingType())
6874 return InvalidOperands(Loc, LHS, RHS);
6875
6876 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00006877}
6878
Steve Naroff218bc2b2007-05-04 21:54:46 +00006879inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006880 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006881 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6882
Richard Trieubcce2f72011-09-07 01:19:57 +00006883 if (LHS.get()->getType()->isVectorType() ||
6884 RHS.get()->getType()->isVectorType()) {
6885 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6886 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006887 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006888
Richard Trieubcce2f72011-09-07 01:19:57 +00006889 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00006890 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006891
Richard Trieubcce2f72011-09-07 01:19:57 +00006892 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
6893 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00006894 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00006895 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006896 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00006897 LHS = LHSResult.take();
6898 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006899
Richard Trieubcce2f72011-09-07 01:19:57 +00006900 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
6901 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006902 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00006903 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006904}
6905
Steve Naroff218bc2b2007-05-04 21:54:46 +00006906inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00006907 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00006908
Tanya Lattner20248222012-01-16 21:02:28 +00006909 // Check vector operands differently.
6910 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
6911 return CheckVectorLogicalOperands(LHS, RHS, Loc);
6912
Chris Lattner8406c512010-07-13 19:41:32 +00006913 // Diagnose cases where the user write a logical and/or but probably meant a
6914 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
6915 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00006916 if (LHS.get()->getType()->isIntegerType() &&
6917 !LHS.get()->getType()->isBooleanType() &&
6918 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00006919 // Don't warn in macros or template instantiations.
6920 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00006921 // If the RHS can be constant folded, and if it constant folds to something
6922 // that isn't 0 or 1 (which indicate a potential logical operation that
6923 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006924 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00006925 llvm::APSInt Result;
6926 if (RHS.get()->EvaluateAsInt(Result, Context))
Richard Trieubcce2f72011-09-07 01:19:57 +00006927 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00006928 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00006929 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00006930 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006931 << (Opc == BO_LAnd ? "&&" : "||");
6932 // Suggest replacing the logical operator with the bitwise version
6933 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
6934 << (Opc == BO_LAnd ? "&" : "|")
6935 << FixItHint::CreateReplacement(SourceRange(
6936 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
6937 getLangOptions())),
6938 Opc == BO_LAnd ? "&" : "|");
6939 if (Opc == BO_LAnd)
6940 // Suggest replacing "Foo() && kNonZero" with "Foo()"
6941 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
6942 << FixItHint::CreateRemoval(
6943 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00006944 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006945 0, getSourceManager(),
6946 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00006947 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00006948 }
Chris Lattner938533d2010-07-24 01:10:11 +00006949 }
Chris Lattner8406c512010-07-13 19:41:32 +00006950
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006951 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00006952 LHS = UsualUnaryConversions(LHS.take());
6953 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006954 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006955
Richard Trieubcce2f72011-09-07 01:19:57 +00006956 RHS = UsualUnaryConversions(RHS.take());
6957 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006958 return QualType();
6959
Richard Trieubcce2f72011-09-07 01:19:57 +00006960 if (!LHS.get()->getType()->isScalarType() ||
6961 !RHS.get()->getType()->isScalarType())
6962 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006963
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006964 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00006965 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006966
John McCall4a2429a2010-06-04 00:29:51 +00006967 // The following is safe because we only use this method for
6968 // non-overloadable operands.
6969
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006970 // C++ [expr.log.and]p1
6971 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00006972 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00006973 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
6974 if (LHSRes.isInvalid())
6975 return InvalidOperands(Loc, LHS, RHS);
6976 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00006977
Richard Trieubcce2f72011-09-07 01:19:57 +00006978 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
6979 if (RHSRes.isInvalid())
6980 return InvalidOperands(Loc, LHS, RHS);
6981 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006982
Anders Carlsson2e7bc112009-11-23 21:47:44 +00006983 // C++ [expr.log.and]p2
6984 // C++ [expr.log.or]p2
6985 // The result is a bool.
6986 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00006987}
6988
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00006989/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
6990/// is a read-only property; return true if so. A readonly property expression
6991/// depends on various declarations and thus must be treated specially.
6992///
Mike Stump11289f42009-09-09 15:08:12 +00006993static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00006994 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
6995 if (!PropExpr) return false;
6996 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00006997
John McCall526ab472011-10-25 17:37:35 +00006998 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
6999 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007000 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007001 PropExpr->getBase()->getType();
7002
John McCall526ab472011-10-25 17:37:35 +00007003 if (const ObjCObjectPointerType *OPT =
7004 BaseType->getAsObjCInterfacePointerType())
7005 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7006 if (S.isPropertyReadonly(PDecl, IFace))
7007 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007008 return false;
7009}
7010
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007011static bool IsConstProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007012 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7013 if (!PropExpr) return false;
7014 if (PropExpr->isImplicitProperty()) return false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007015
John McCall526ab472011-10-25 17:37:35 +00007016 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7017 QualType T = PDecl->getType().getNonReferenceType();
7018 return T.isConstQualified();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007019}
7020
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007021static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007022 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7023 if (!ME) return false;
7024 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7025 ObjCMessageExpr *Base =
7026 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7027 if (!Base) return false;
7028 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007029}
7030
Chris Lattner30bd3272008-11-18 01:22:49 +00007031/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7032/// emit an error and return true. If so, return false.
7033static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007034 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007035 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007036 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007037 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7038 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007039 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7040 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007041 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7042 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007043 if (IsLV == Expr::MLV_Valid)
7044 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007045
Chris Lattner30bd3272008-11-18 01:22:49 +00007046 unsigned Diag = 0;
7047 bool NeedType = false;
7048 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007049 case Expr::MLV_ConstQualified:
7050 Diag = diag::err_typecheck_assign_const;
7051
John McCalld4631322011-06-17 06:42:21 +00007052 // In ARC, use some specialized diagnostics for occasions where we
7053 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007054 if (S.getLangOptions().ObjCAutoRefCount) {
7055 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7056 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7057 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7058
John McCalld4631322011-06-17 06:42:21 +00007059 // Use the normal diagnostic if it's pseudo-__strong but the
7060 // user actually wrote 'const'.
7061 if (var->isARCPseudoStrong() &&
7062 (!var->getTypeSourceInfo() ||
7063 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7064 // There are two pseudo-strong cases:
7065 // - self
John McCall31168b02011-06-15 23:02:42 +00007066 ObjCMethodDecl *method = S.getCurMethodDecl();
7067 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007068 Diag = method->isClassMethod()
7069 ? diag::err_typecheck_arc_assign_self_class_method
7070 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007071
7072 // - fast enumeration variables
7073 else
John McCall31168b02011-06-15 23:02:42 +00007074 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007075
John McCall31168b02011-06-15 23:02:42 +00007076 SourceRange Assign;
7077 if (Loc != OrigLoc)
7078 Assign = SourceRange(OrigLoc, OrigLoc);
7079 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7080 // We need to preserve the AST regardless, so migration tool
7081 // can do its job.
7082 return false;
7083 }
7084 }
7085 }
7086
7087 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007088 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007089 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7090 NeedType = true;
7091 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007092 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007093 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7094 NeedType = true;
7095 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007096 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007097 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7098 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007099 case Expr::MLV_Valid:
7100 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007101 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007102 case Expr::MLV_MemberFunction:
7103 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007104 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7105 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007106 case Expr::MLV_IncompleteType:
7107 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007108 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007109 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007110 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007111 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007112 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7113 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007114 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007115 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7116 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007117 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007118 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007119 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007120 case Expr::MLV_InvalidMessageExpression:
7121 Diag = diag::error_readonly_message_assignment;
7122 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007123 case Expr::MLV_SubObjCPropertySetting:
7124 Diag = diag::error_no_subobject_property_setting;
7125 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007126 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007127
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007128 SourceRange Assign;
7129 if (Loc != OrigLoc)
7130 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007131 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007132 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007133 else
Mike Stump11289f42009-09-09 15:08:12 +00007134 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007135 return true;
7136}
7137
7138
7139
7140// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007141QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007142 SourceLocation Loc,
7143 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007144 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7145
Chris Lattner326f7572008-11-18 01:30:42 +00007146 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007147 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007148 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007149
Richard Trieuda4f43a62011-09-07 01:33:52 +00007150 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007151 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7152 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007153 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007154 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007155 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007156 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007157 if (RHS.isInvalid())
7158 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007159 // Special case of NSObject attributes on c-style pointer types.
7160 if (ConvTy == IncompatiblePointer &&
7161 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007162 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007163 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007164 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007165 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007166
John McCall7decc9e2010-11-18 06:31:45 +00007167 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007168 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007169 Diag(Loc, diag::err_objc_object_assignment)
7170 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007171
Chris Lattnerea714382008-08-21 18:04:13 +00007172 // If the RHS is a unary plus or minus, check to see if they = and + are
7173 // right next to each other. If so, the user may have typo'd "x =+ 4"
7174 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007175 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007176 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7177 RHSCheck = ICE->getSubExpr();
7178 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007179 if ((UO->getOpcode() == UO_Plus ||
7180 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007181 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007182 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007183 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007184 // And there is a space or other character before the subexpr of the
7185 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007186 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007187 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007188 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007189 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007190 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007191 }
Chris Lattnerea714382008-08-21 18:04:13 +00007192 }
John McCall31168b02011-06-15 23:02:42 +00007193
7194 if (ConvTy == Compatible) {
7195 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007196 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007197 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007198 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007199 }
Chris Lattnerea714382008-08-21 18:04:13 +00007200 } else {
7201 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007202 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007203 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007204
Chris Lattner326f7572008-11-18 01:30:42 +00007205 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007206 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007207 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007208
Richard Trieuda4f43a62011-09-07 01:33:52 +00007209 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007210
Steve Naroff98cf3e92007-06-06 18:38:38 +00007211 // C99 6.5.16p3: The type of an assignment expression is the type of the
7212 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007213 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007214 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7215 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007216 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007217 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007218 return (getLangOptions().CPlusPlus
7219 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007220}
7221
Chris Lattner326f7572008-11-18 01:30:42 +00007222// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007223static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007224 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007225 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007226
John McCall3aef3d82011-04-10 19:13:55 +00007227 LHS = S.CheckPlaceholderExpr(LHS.take());
7228 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007229 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007230 return QualType();
7231
John McCall73d36182010-10-12 07:14:40 +00007232 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7233 // operands, but not unary promotions.
7234 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007235
John McCall34376a62010-12-04 03:47:34 +00007236 // So we treat the LHS as a ignored value, and in C++ we allow the
7237 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007238 LHS = S.IgnoredValueConversions(LHS.take());
7239 if (LHS.isInvalid())
7240 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007241
7242 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007243 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7244 if (RHS.isInvalid())
7245 return QualType();
7246 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007247 S.RequireCompleteType(Loc, RHS.get()->getType(),
7248 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007249 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007250
John Wiegley01296292011-04-08 18:41:53 +00007251 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007252}
7253
Steve Naroff7a5af782007-07-13 16:58:59 +00007254/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7255/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007256static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7257 ExprValueKind &VK,
7258 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007259 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007260 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007261 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007262
Chris Lattner6b0cf142008-11-21 07:05:48 +00007263 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007264 // Atomic types can be used for increment / decrement where the non-atomic
7265 // versions can, so ignore the _Atomic() specifier for the purpose of
7266 // checking.
7267 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7268 ResType = ResAtomicType->getValueType();
7269
Chris Lattner6b0cf142008-11-21 07:05:48 +00007270 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007271
John McCall4bc41ae2010-11-18 19:01:18 +00007272 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007273 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007274 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007275 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007276 return QualType();
7277 }
7278 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007279 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007280 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007281 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007282 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007283 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007284 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007285 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007286
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007287 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007288 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007289 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007290 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007291 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007292 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007293 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007294 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007295 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007296 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007297 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007298 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007299 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7300 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007301 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007302 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007303 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007304 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007305 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007306 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007307 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007308 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007309 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007310 // In C++, a prefix increment is the same type as the operand. Otherwise
7311 // (in C or with postfix), the increment is the unqualified type of the
7312 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007313 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007314 VK = VK_LValue;
7315 return ResType;
7316 } else {
7317 VK = VK_RValue;
7318 return ResType.getUnqualifiedType();
7319 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007320}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007321
7322
Anders Carlsson806700f2008-02-01 07:15:58 +00007323/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007324/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007325/// where the declaration is needed for type checking. We only need to
7326/// handle cases when the expression references a function designator
7327/// or is an lvalue. Here are some examples:
7328/// - &(x) => x
7329/// - &*****f => f for f a function designator.
7330/// - &s.xx => s
7331/// - &s.zz[1].yy -> s, if zz is an array
7332/// - *(x + 1) -> x, if x is an array
7333/// - &"123"[2] -> 0
7334/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007335static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007336 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007337 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007338 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007339 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007340 // If this is an arrow operator, the address is an offset from
7341 // the base's value, so the object the base refers to is
7342 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007343 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007344 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007345 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007346 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007347 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007348 // FIXME: This code shouldn't be necessary! We should catch the implicit
7349 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007350 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7351 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7352 if (ICE->getSubExpr()->getType()->isArrayType())
7353 return getPrimaryDecl(ICE->getSubExpr());
7354 }
7355 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007356 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007357 case Stmt::UnaryOperatorClass: {
7358 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007359
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007360 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007361 case UO_Real:
7362 case UO_Imag:
7363 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007364 return getPrimaryDecl(UO->getSubExpr());
7365 default:
7366 return 0;
7367 }
7368 }
Steve Naroff47500512007-04-19 23:00:49 +00007369 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007370 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007371 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007372 // If the result of an implicit cast is an l-value, we care about
7373 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007374 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007375 default:
7376 return 0;
7377 }
7378}
7379
Richard Trieu5f376f62011-09-07 21:46:33 +00007380namespace {
7381 enum {
7382 AO_Bit_Field = 0,
7383 AO_Vector_Element = 1,
7384 AO_Property_Expansion = 2,
7385 AO_Register_Variable = 3,
7386 AO_No_Error = 4
7387 };
7388}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007389/// \brief Diagnose invalid operand for address of operations.
7390///
7391/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007392static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7393 Expr *E, unsigned Type) {
7394 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7395}
7396
Steve Naroff47500512007-04-19 23:00:49 +00007397/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007398/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007399/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007400/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007401/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007402/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007403/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007404static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007405 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007406 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7407 if (PTy->getKind() == BuiltinType::Overload) {
7408 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7409 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7410 << OrigOp.get()->getSourceRange();
7411 return QualType();
7412 }
7413
7414 return S.Context.OverloadTy;
7415 }
7416
7417 if (PTy->getKind() == BuiltinType::UnknownAny)
7418 return S.Context.UnknownAnyTy;
7419
7420 if (PTy->getKind() == BuiltinType::BoundMember) {
7421 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7422 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007423 return QualType();
7424 }
John McCall526ab472011-10-25 17:37:35 +00007425
7426 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7427 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007428 }
John McCall8d08b9b2010-08-27 09:08:28 +00007429
John McCall526ab472011-10-25 17:37:35 +00007430 if (OrigOp.get()->isTypeDependent())
7431 return S.Context.DependentTy;
7432
7433 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007434
John McCall8d08b9b2010-08-27 09:08:28 +00007435 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007436 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007437
John McCall4bc41ae2010-11-18 19:01:18 +00007438 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007439 // Implement C99-only parts of addressof rules.
7440 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007441 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007442 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7443 // (assuming the deref expression is valid).
7444 return uOp->getSubExpr()->getType();
7445 }
7446 // Technically, there should be a check for array subscript
7447 // expressions here, but the result of one is always an lvalue anyway.
7448 }
John McCallf3a88602011-02-03 08:15:49 +00007449 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007450 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007451 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007452
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007453 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007454 bool sfinae = S.isSFINAEContext();
7455 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7456 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007457 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007458 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007459 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007460 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007461 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007462 } else if (lval == Expr::LV_MemberFunction) {
7463 // If it's an instance method, make a member pointer.
7464 // The expression must have exactly the form &A::foo.
7465
7466 // If the underlying expression isn't a decl ref, give up.
7467 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007468 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007469 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007470 return QualType();
7471 }
7472 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7473 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7474
7475 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007476 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007477 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007478 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007479
7480 // The method was named without a qualifier.
7481 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007482 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007483 << op->getSourceRange();
7484 }
7485
John McCall4bc41ae2010-11-18 19:01:18 +00007486 return S.Context.getMemberPointerType(op->getType(),
7487 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007488 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007489 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007490 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007491 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007492 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007493 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007494 AddressOfError = AO_Property_Expansion;
7495 } else {
7496 // FIXME: emit more specific diag...
7497 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7498 << op->getSourceRange();
7499 return QualType();
7500 }
Steve Naroff35d85152007-05-07 00:24:15 +00007501 }
John McCall086a4642010-11-24 05:12:34 +00007502 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007503 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007504 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007505 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007506 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007507 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007508 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007509 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007510 // with the register storage-class specifier.
7511 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007512 // in C++ it is not error to take address of a register
7513 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007514 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007515 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007516 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007517 }
John McCalld14a8642009-11-21 08:51:07 +00007518 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007519 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007520 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007521 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007522 // Could be a pointer to member, though, if there is an explicit
7523 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007524 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007525 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007526 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007527 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007528 S.Diag(OpLoc,
7529 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007530 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007531 return QualType();
7532 }
Mike Stump11289f42009-09-09 15:08:12 +00007533
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007534 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7535 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007536 return S.Context.getMemberPointerType(op->getType(),
7537 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007538 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007539 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007540 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007541 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007542 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007543
Richard Trieu5f376f62011-09-07 21:46:33 +00007544 if (AddressOfError != AO_No_Error) {
7545 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7546 return QualType();
7547 }
7548
Eli Friedmance7f9002009-05-16 23:27:50 +00007549 if (lval == Expr::LV_IncompleteVoidType) {
7550 // Taking the address of a void variable is technically illegal, but we
7551 // allow it in cases which are otherwise valid.
7552 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007553 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007554 }
7555
Steve Naroff47500512007-04-19 23:00:49 +00007556 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007557 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007558 return S.Context.getObjCObjectPointerType(op->getType());
7559 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007560}
7561
Chris Lattner9156f1b2010-07-05 19:17:26 +00007562/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007563static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7564 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007565 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007566 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007567
John Wiegley01296292011-04-08 18:41:53 +00007568 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7569 if (ConvResult.isInvalid())
7570 return QualType();
7571 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007572 QualType OpTy = Op->getType();
7573 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007574
7575 if (isa<CXXReinterpretCastExpr>(Op)) {
7576 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7577 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7578 Op->getSourceRange());
7579 }
7580
Chris Lattner9156f1b2010-07-05 19:17:26 +00007581 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7582 // is an incomplete type or void. It would be possible to warn about
7583 // dereferencing a void pointer, but it's completely well-defined, and such a
7584 // warning is unlikely to catch any mistakes.
7585 if (const PointerType *PT = OpTy->getAs<PointerType>())
7586 Result = PT->getPointeeType();
7587 else if (const ObjCObjectPointerType *OPT =
7588 OpTy->getAs<ObjCObjectPointerType>())
7589 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007590 else {
John McCall3aef3d82011-04-10 19:13:55 +00007591 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007592 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007593 if (PR.take() != Op)
7594 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007595 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007596
Chris Lattner9156f1b2010-07-05 19:17:26 +00007597 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007598 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007599 << OpTy << Op->getSourceRange();
7600 return QualType();
7601 }
John McCall4bc41ae2010-11-18 19:01:18 +00007602
7603 // Dereferences are usually l-values...
7604 VK = VK_LValue;
7605
7606 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007607 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007608 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007609
7610 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007611}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007612
John McCalle3027922010-08-25 11:45:40 +00007613static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007614 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007615 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007616 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007617 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007618 case tok::periodstar: Opc = BO_PtrMemD; break;
7619 case tok::arrowstar: Opc = BO_PtrMemI; break;
7620 case tok::star: Opc = BO_Mul; break;
7621 case tok::slash: Opc = BO_Div; break;
7622 case tok::percent: Opc = BO_Rem; break;
7623 case tok::plus: Opc = BO_Add; break;
7624 case tok::minus: Opc = BO_Sub; break;
7625 case tok::lessless: Opc = BO_Shl; break;
7626 case tok::greatergreater: Opc = BO_Shr; break;
7627 case tok::lessequal: Opc = BO_LE; break;
7628 case tok::less: Opc = BO_LT; break;
7629 case tok::greaterequal: Opc = BO_GE; break;
7630 case tok::greater: Opc = BO_GT; break;
7631 case tok::exclaimequal: Opc = BO_NE; break;
7632 case tok::equalequal: Opc = BO_EQ; break;
7633 case tok::amp: Opc = BO_And; break;
7634 case tok::caret: Opc = BO_Xor; break;
7635 case tok::pipe: Opc = BO_Or; break;
7636 case tok::ampamp: Opc = BO_LAnd; break;
7637 case tok::pipepipe: Opc = BO_LOr; break;
7638 case tok::equal: Opc = BO_Assign; break;
7639 case tok::starequal: Opc = BO_MulAssign; break;
7640 case tok::slashequal: Opc = BO_DivAssign; break;
7641 case tok::percentequal: Opc = BO_RemAssign; break;
7642 case tok::plusequal: Opc = BO_AddAssign; break;
7643 case tok::minusequal: Opc = BO_SubAssign; break;
7644 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7645 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7646 case tok::ampequal: Opc = BO_AndAssign; break;
7647 case tok::caretequal: Opc = BO_XorAssign; break;
7648 case tok::pipeequal: Opc = BO_OrAssign; break;
7649 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007650 }
7651 return Opc;
7652}
7653
John McCalle3027922010-08-25 11:45:40 +00007654static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007655 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007656 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007657 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007658 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007659 case tok::plusplus: Opc = UO_PreInc; break;
7660 case tok::minusminus: Opc = UO_PreDec; break;
7661 case tok::amp: Opc = UO_AddrOf; break;
7662 case tok::star: Opc = UO_Deref; break;
7663 case tok::plus: Opc = UO_Plus; break;
7664 case tok::minus: Opc = UO_Minus; break;
7665 case tok::tilde: Opc = UO_Not; break;
7666 case tok::exclaim: Opc = UO_LNot; break;
7667 case tok::kw___real: Opc = UO_Real; break;
7668 case tok::kw___imag: Opc = UO_Imag; break;
7669 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007670 }
7671 return Opc;
7672}
7673
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007674/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7675/// This warning is only emitted for builtin assignment operations. It is also
7676/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007677static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007678 SourceLocation OpLoc) {
7679 if (!S.ActiveTemplateInstantiations.empty())
7680 return;
7681 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7682 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007683 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7684 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7685 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7686 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7687 if (!LHSDeclRef || !RHSDeclRef ||
7688 LHSDeclRef->getLocation().isMacroID() ||
7689 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007690 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007691 const ValueDecl *LHSDecl =
7692 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7693 const ValueDecl *RHSDecl =
7694 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7695 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007696 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007697 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007698 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007699 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007700 if (RefTy->getPointeeType().isVolatileQualified())
7701 return;
7702
7703 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007704 << LHSDeclRef->getType()
7705 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007706}
7707
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007708/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7709/// operator @p Opc at location @c TokLoc. This routine only supports
7710/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007711ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007712 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007713 Expr *LHSExpr, Expr *RHSExpr) {
Sebastian Redl67766732012-02-27 20:34:02 +00007714 if (getLangOptions().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
7715 // The syntax only allows initializer lists on the RHS of assignment,
7716 // so we don't need to worry about accepting invalid code for
7717 // non-assignment operators.
7718 // C++11 5.17p9:
7719 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
7720 // of x = {} is x = T().
7721 InitializationKind Kind =
7722 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
7723 InitializedEntity Entity =
7724 InitializedEntity::InitializeTemporary(LHSExpr->getType());
7725 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
7726 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
7727 MultiExprArg(&RHSExpr, 1));
7728 if (Init.isInvalid())
7729 return Init;
7730 RHSExpr = Init.take();
7731 }
7732
Richard Trieu4a287fb2011-09-07 01:49:20 +00007733 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007734 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007735 // The following two variables are used for compound assignment operators
7736 QualType CompLHSTy; // Type of LHS after promotions for computation
7737 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007738 ExprValueKind VK = VK_RValue;
7739 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007740
7741 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007742 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007743 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007744 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007745 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7746 VK = LHS.get()->getValueKind();
7747 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007748 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007749 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007750 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007751 break;
John McCalle3027922010-08-25 11:45:40 +00007752 case BO_PtrMemD:
7753 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007754 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007755 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007756 break;
John McCalle3027922010-08-25 11:45:40 +00007757 case BO_Mul:
7758 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007759 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007760 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007761 break;
John McCalle3027922010-08-25 11:45:40 +00007762 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007763 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007764 break;
John McCalle3027922010-08-25 11:45:40 +00007765 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00007766 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007767 break;
John McCalle3027922010-08-25 11:45:40 +00007768 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007769 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007770 break;
John McCalle3027922010-08-25 11:45:40 +00007771 case BO_Shl:
7772 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007773 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007774 break;
John McCalle3027922010-08-25 11:45:40 +00007775 case BO_LE:
7776 case BO_LT:
7777 case BO_GE:
7778 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007779 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007780 break;
John McCalle3027922010-08-25 11:45:40 +00007781 case BO_EQ:
7782 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007783 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007784 break;
John McCalle3027922010-08-25 11:45:40 +00007785 case BO_And:
7786 case BO_Xor:
7787 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007788 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007789 break;
John McCalle3027922010-08-25 11:45:40 +00007790 case BO_LAnd:
7791 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007792 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007793 break;
John McCalle3027922010-08-25 11:45:40 +00007794 case BO_MulAssign:
7795 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007796 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007797 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007798 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007799 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7800 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007801 break;
John McCalle3027922010-08-25 11:45:40 +00007802 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007803 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007804 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007805 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7806 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007807 break;
John McCalle3027922010-08-25 11:45:40 +00007808 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00007809 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00007810 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7811 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007812 break;
John McCalle3027922010-08-25 11:45:40 +00007813 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007814 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7815 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7816 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007817 break;
John McCalle3027922010-08-25 11:45:40 +00007818 case BO_ShlAssign:
7819 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007820 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007821 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007822 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7823 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007824 break;
John McCalle3027922010-08-25 11:45:40 +00007825 case BO_AndAssign:
7826 case BO_XorAssign:
7827 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007828 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007829 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007830 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7831 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007832 break;
John McCalle3027922010-08-25 11:45:40 +00007833 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007834 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7835 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7836 VK = RHS.get()->getValueKind();
7837 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007838 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007839 break;
7840 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007841 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007842 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007843
7844 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007845 CheckArrayAccess(LHS.get());
7846 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007847
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007848 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007849 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007850 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007851 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007852 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007853 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007854 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007855 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007856 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007857 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007858 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007859}
7860
Sebastian Redl44615072009-10-27 12:10:02 +00007861/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7862/// operators are mixed in a way that suggests that the programmer forgot that
7863/// comparison operators have higher precedence. The most typical example of
7864/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007865static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007866 SourceLocation OpLoc, Expr *LHSExpr,
7867 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00007868 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007869 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
7870 RHSopc = static_cast<BinOp::Opcode>(-1);
7871 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
7872 LHSopc = BO->getOpcode();
7873 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
7874 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00007875
7876 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007877 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00007878 return;
7879
7880 // Bitwise operations are sometimes used as eager logical ops.
7881 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00007882 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
7883 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00007884 return;
7885
Richard Trieu4a287fb2011-09-07 01:49:20 +00007886 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
7887 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007888 if (!isLeftComp && !isRightComp) return;
7889
Richard Trieu4a287fb2011-09-07 01:49:20 +00007890 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
7891 OpLoc)
7892 : SourceRange(OpLoc, RHSExpr->getLocEnd());
7893 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
7894 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00007895 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00007896 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
7897 RHSExpr->getLocEnd())
7898 : SourceRange(LHSExpr->getLocStart(),
7899 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00007900
7901 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
7902 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
7903 SuggestParentheses(Self, OpLoc,
7904 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007905 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00007906 SuggestParentheses(Self, OpLoc,
7907 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
7908 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00007909}
7910
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007911/// \brief It accepts a '&' expr that is inside a '|' one.
7912/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
7913/// in parentheses.
7914static void
7915EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
7916 BinaryOperator *Bop) {
7917 assert(Bop->getOpcode() == BO_And);
7918 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
7919 << Bop->getSourceRange() << OpLoc;
7920 SuggestParentheses(Self, Bop->getOperatorLoc(),
7921 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
7922 Bop->getSourceRange());
7923}
7924
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007925/// \brief It accepts a '&&' expr that is inside a '||' one.
7926/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
7927/// in parentheses.
7928static void
7929EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007930 BinaryOperator *Bop) {
7931 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007932 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
7933 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00007934 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007935 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00007936 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007937}
7938
7939/// \brief Returns true if the given expression can be evaluated as a constant
7940/// 'true'.
7941static bool EvaluatesAsTrue(Sema &S, Expr *E) {
7942 bool Res;
7943 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
7944}
7945
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007946/// \brief Returns true if the given expression can be evaluated as a constant
7947/// 'false'.
7948static bool EvaluatesAsFalse(Sema &S, Expr *E) {
7949 bool Res;
7950 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
7951}
7952
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007953/// \brief Look for '&&' in the left hand of a '||' expr.
7954static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007955 Expr *LHSExpr, Expr *RHSExpr) {
7956 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007957 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007958 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007959 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007960 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007961 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
7962 if (!EvaluatesAsTrue(S, Bop->getLHS()))
7963 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
7964 } else if (Bop->getOpcode() == BO_LOr) {
7965 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
7966 // If it's "a || b && 1 || c" we didn't warn earlier for
7967 // "a || b && 1", but warn now.
7968 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
7969 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
7970 }
7971 }
7972 }
7973}
7974
7975/// \brief Look for '&&' in the right hand of a '||' expr.
7976static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007977 Expr *LHSExpr, Expr *RHSExpr) {
7978 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007979 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007980 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00007981 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00007982 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00007983 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
7984 if (!EvaluatesAsTrue(S, Bop->getRHS()))
7985 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00007986 }
7987 }
7988}
7989
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00007990/// \brief Look for '&' in the left or right hand of a '|' expr.
7991static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
7992 Expr *OrArg) {
7993 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
7994 if (Bop->getOpcode() == BO_And)
7995 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
7996 }
7997}
7998
Sebastian Redl43028242009-10-26 15:24:15 +00007999/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008000/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008001static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008002 SourceLocation OpLoc, Expr *LHSExpr,
8003 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008004 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008005 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008006 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008007
8008 // Diagnose "arg1 & arg2 | arg3"
8009 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008010 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8011 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008012 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008013
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008014 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8015 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008016 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008017 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8018 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008019 }
Sebastian Redl43028242009-10-26 15:24:15 +00008020}
8021
Steve Naroff218bc2b2007-05-04 21:54:46 +00008022// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008023ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008024 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008025 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008026 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008027 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8028 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008029
Sebastian Redl43028242009-10-26 15:24:15 +00008030 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008031 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008032
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008033 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008034}
8035
John McCall526ab472011-10-25 17:37:35 +00008036/// Build an overloaded binary operator expression in the given scope.
8037static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8038 BinaryOperatorKind Opc,
8039 Expr *LHS, Expr *RHS) {
8040 // Find all of the overloaded operators visible from this
8041 // point. We perform both an operator-name lookup from the local
8042 // scope and an argument-dependent lookup based on the types of
8043 // the arguments.
8044 UnresolvedSet<16> Functions;
8045 OverloadedOperatorKind OverOp
8046 = BinaryOperator::getOverloadedOperator(Opc);
8047 if (Sc && OverOp != OO_None)
8048 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8049 RHS->getType(), Functions);
8050
8051 // Build the (potentially-overloaded, potentially-dependent)
8052 // binary operation.
8053 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8054}
8055
John McCalldadc5752010-08-24 06:29:42 +00008056ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008057 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008058 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008059 // We want to end up calling one of checkPseudoObjectAssignment
8060 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8061 // both expressions are overloadable or either is type-dependent),
8062 // or CreateBuiltinBinOp (in any other case). We also want to get
8063 // any placeholder types out of the way.
8064
John McCall526ab472011-10-25 17:37:35 +00008065 // Handle pseudo-objects in the LHS.
8066 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8067 // Assignments with a pseudo-object l-value need special analysis.
8068 if (pty->getKind() == BuiltinType::PseudoObject &&
8069 BinaryOperator::isAssignmentOp(Opc))
8070 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8071
8072 // Don't resolve overloads if the other type is overloadable.
8073 if (pty->getKind() == BuiltinType::Overload) {
8074 // We can't actually test that if we still have a placeholder,
8075 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008076 // code below are valid when the LHS is an overload set. Note
8077 // that an overload set can be dependently-typed, but it never
8078 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008079 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8080 if (resolvedRHS.isInvalid()) return ExprError();
8081 RHSExpr = resolvedRHS.take();
8082
John McCall9a43e122011-10-28 01:04:34 +00008083 if (RHSExpr->isTypeDependent() ||
8084 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008085 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8086 }
8087
8088 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8089 if (LHS.isInvalid()) return ExprError();
8090 LHSExpr = LHS.take();
8091 }
8092
8093 // Handle pseudo-objects in the RHS.
8094 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8095 // An overload in the RHS can potentially be resolved by the type
8096 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008097 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8098 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8099 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8100
Eli Friedman419b1ff2012-01-17 21:27:43 +00008101 if (LHSExpr->getType()->isOverloadableType())
8102 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8103
John McCall526ab472011-10-25 17:37:35 +00008104 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008105 }
John McCall526ab472011-10-25 17:37:35 +00008106
8107 // Don't resolve overloads if the other type is overloadable.
8108 if (pty->getKind() == BuiltinType::Overload &&
8109 LHSExpr->getType()->isOverloadableType())
8110 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8111
8112 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8113 if (!resolvedRHS.isUsable()) return ExprError();
8114 RHSExpr = resolvedRHS.take();
8115 }
8116
John McCall622114c2010-12-06 05:26:58 +00008117 if (getLangOptions().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008118 // If either expression is type-dependent, always build an
8119 // overloaded op.
8120 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8121 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008122
John McCall9a43e122011-10-28 01:04:34 +00008123 // Otherwise, build an overloaded op if either expression has an
8124 // overloadable type.
8125 if (LHSExpr->getType()->isOverloadableType() ||
8126 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008127 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008128 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008129
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008130 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008131 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008132}
8133
John McCalldadc5752010-08-24 06:29:42 +00008134ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008135 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008136 Expr *InputExpr) {
8137 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008138 ExprValueKind VK = VK_RValue;
8139 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008140 QualType resultType;
8141 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008142 case UO_PreInc:
8143 case UO_PreDec:
8144 case UO_PostInc:
8145 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008146 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008147 Opc == UO_PreInc ||
8148 Opc == UO_PostInc,
8149 Opc == UO_PreInc ||
8150 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008151 break;
John McCalle3027922010-08-25 11:45:40 +00008152 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008153 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008154 break;
John McCall31996342011-04-07 08:22:57 +00008155 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008156 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8157 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008158 break;
John McCall31996342011-04-07 08:22:57 +00008159 }
John McCalle3027922010-08-25 11:45:40 +00008160 case UO_Plus:
8161 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008162 Input = UsualUnaryConversions(Input.take());
8163 if (Input.isInvalid()) return ExprError();
8164 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008165 if (resultType->isDependentType())
8166 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008167 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8168 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008169 break;
8170 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8171 resultType->isEnumeralType())
8172 break;
8173 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008174 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008175 resultType->isPointerType())
8176 break;
8177
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008178 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008179 << resultType << Input.get()->getSourceRange());
8180
John McCalle3027922010-08-25 11:45:40 +00008181 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008182 Input = UsualUnaryConversions(Input.take());
8183 if (Input.isInvalid()) return ExprError();
8184 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008185 if (resultType->isDependentType())
8186 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008187 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8188 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8189 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008190 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008191 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008192 else if (resultType->hasIntegerRepresentation())
8193 break;
John McCall526ab472011-10-25 17:37:35 +00008194 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008195 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008196 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008197 }
Steve Naroff35d85152007-05-07 00:24:15 +00008198 break;
John Wiegley01296292011-04-08 18:41:53 +00008199
John McCalle3027922010-08-25 11:45:40 +00008200 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008201 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008202 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8203 if (Input.isInvalid()) return ExprError();
8204 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008205
8206 // Though we still have to promote half FP to float...
8207 if (resultType->isHalfType()) {
8208 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8209 resultType = Context.FloatTy;
8210 }
8211
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008212 if (resultType->isDependentType())
8213 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008214 if (resultType->isScalarType()) {
8215 // C99 6.5.3.3p1: ok, fallthrough;
8216 if (Context.getLangOptions().CPlusPlus) {
8217 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8218 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008219 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8220 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008221 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008222 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008223 // Vector logical not returns the signed variant of the operand type.
8224 resultType = GetSignedVectorType(resultType);
8225 break;
John McCall36226622010-10-12 02:09:17 +00008226 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008227 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008228 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008229 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008230
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008231 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008232 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008233 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008234 break;
John McCalle3027922010-08-25 11:45:40 +00008235 case UO_Real:
8236 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008237 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008238 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8239 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008240 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008241 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8242 if (Input.get()->getValueKind() != VK_RValue &&
8243 Input.get()->getObjectKind() == OK_Ordinary)
8244 VK = Input.get()->getValueKind();
8245 } else if (!getLangOptions().CPlusPlus) {
8246 // In C, a volatile scalar is read by __imag. In C++, it is not.
8247 Input = DefaultLvalueConversion(Input.take());
8248 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008249 break;
John McCalle3027922010-08-25 11:45:40 +00008250 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008251 resultType = Input.get()->getType();
8252 VK = Input.get()->getValueKind();
8253 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008254 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008255 }
John Wiegley01296292011-04-08 18:41:53 +00008256 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008257 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008258
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008259 // Check for array bounds violations in the operand of the UnaryOperator,
8260 // except for the '*' and '&' operators that have to be handled specially
8261 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8262 // that are explicitly defined as valid by the standard).
8263 if (Opc != UO_AddrOf && Opc != UO_Deref)
8264 CheckArrayAccess(Input.get());
8265
John Wiegley01296292011-04-08 18:41:53 +00008266 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008267 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008268}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008269
Douglas Gregor72341032011-12-14 21:23:13 +00008270/// \brief Determine whether the given expression is a qualified member
8271/// access expression, of a form that could be turned into a pointer to member
8272/// with the address-of operator.
8273static bool isQualifiedMemberAccess(Expr *E) {
8274 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8275 if (!DRE->getQualifier())
8276 return false;
8277
8278 ValueDecl *VD = DRE->getDecl();
8279 if (!VD->isCXXClassMember())
8280 return false;
8281
8282 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8283 return true;
8284 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8285 return Method->isInstance();
8286
8287 return false;
8288 }
8289
8290 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8291 if (!ULE->getQualifier())
8292 return false;
8293
8294 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8295 DEnd = ULE->decls_end();
8296 D != DEnd; ++D) {
8297 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8298 if (Method->isInstance())
8299 return true;
8300 } else {
8301 // Overload set does not contain methods.
8302 break;
8303 }
8304 }
8305
8306 return false;
8307 }
8308
8309 return false;
8310}
8311
John McCalldadc5752010-08-24 06:29:42 +00008312ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008313 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008314 // First things first: handle placeholders so that the
8315 // overloaded-operator check considers the right type.
8316 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8317 // Increment and decrement of pseudo-object references.
8318 if (pty->getKind() == BuiltinType::PseudoObject &&
8319 UnaryOperator::isIncrementDecrementOp(Opc))
8320 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8321
8322 // extension is always a builtin operator.
8323 if (Opc == UO_Extension)
8324 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8325
8326 // & gets special logic for several kinds of placeholder.
8327 // The builtin code knows what to do.
8328 if (Opc == UO_AddrOf &&
8329 (pty->getKind() == BuiltinType::Overload ||
8330 pty->getKind() == BuiltinType::UnknownAny ||
8331 pty->getKind() == BuiltinType::BoundMember))
8332 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8333
8334 // Anything else needs to be handled now.
8335 ExprResult Result = CheckPlaceholderExpr(Input);
8336 if (Result.isInvalid()) return ExprError();
8337 Input = Result.take();
8338 }
8339
Anders Carlsson461a2c02009-11-14 21:26:41 +00008340 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008341 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8342 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008343 // Find all of the overloaded operators visible from this
8344 // point. We perform both an operator-name lookup from the local
8345 // scope and an argument-dependent lookup based on the types of
8346 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008347 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008348 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008349 if (S && OverOp != OO_None)
8350 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8351 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008352
John McCallb268a282010-08-23 23:25:46 +00008353 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008354 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008355
John McCallb268a282010-08-23 23:25:46 +00008356 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008357}
8358
Douglas Gregor5287f092009-11-05 00:51:44 +00008359// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008360ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008361 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008362 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008363}
8364
Steve Naroff66356bd2007-09-16 14:56:35 +00008365/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008366ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008367 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008368 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008369 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008370 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008371 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008372}
8373
John McCall31168b02011-06-15 23:02:42 +00008374/// Given the last statement in a statement-expression, check whether
8375/// the result is a producing expression (like a call to an
8376/// ns_returns_retained function) and, if so, rebuild it to hoist the
8377/// release out of the full-expression. Otherwise, return null.
8378/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008379static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008380 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008381 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008382 if (!cleanups) return 0;
8383
8384 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008385 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008386 return 0;
8387
8388 // Splice out the cast. This shouldn't modify any interesting
8389 // features of the statement.
8390 Expr *producer = cast->getSubExpr();
8391 assert(producer->getType() == cast->getType());
8392 assert(producer->getValueKind() == cast->getValueKind());
8393 cleanups->setSubExpr(producer);
8394 return cleanups;
8395}
8396
John McCalldadc5752010-08-24 06:29:42 +00008397ExprResult
John McCallb268a282010-08-23 23:25:46 +00008398Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008399 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008400 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8401 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8402
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008403 bool isFileScope
8404 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008405 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008406 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008407
Chris Lattner366727f2007-07-24 16:58:17 +00008408 // FIXME: there are a variety of strange constraints to enforce here, for
8409 // example, it is not possible to goto into a stmt expression apparently.
8410 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008411
Chris Lattner366727f2007-07-24 16:58:17 +00008412 // If there are sub stmts in the compound stmt, take the type of the last one
8413 // as the type of the stmtexpr.
8414 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008415 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008416 if (!Compound->body_empty()) {
8417 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008418 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008419 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008420 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8421 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008422 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008423 }
John McCall31168b02011-06-15 23:02:42 +00008424
John Wiegley01296292011-04-08 18:41:53 +00008425 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008426 // Do function/array conversion on the last expression, but not
8427 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008428 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8429 if (LastExpr.isInvalid())
8430 return ExprError();
8431 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008432
John Wiegley01296292011-04-08 18:41:53 +00008433 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008434 // In ARC, if the final expression ends in a consume, splice
8435 // the consume out and bind it later. In the alternate case
8436 // (when dealing with a retainable type), the result
8437 // initialization will create a produce. In both cases the
8438 // result will be +1, and we'll need to balance that out with
8439 // a bind.
8440 if (Expr *rebuiltLastStmt
8441 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8442 LastExpr = rebuiltLastStmt;
8443 } else {
8444 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008445 InitializedEntity::InitializeResult(LPLoc,
8446 Ty,
8447 false),
8448 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008449 LastExpr);
8450 }
8451
John Wiegley01296292011-04-08 18:41:53 +00008452 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008453 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008454 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008455 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008456 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008457 else
John Wiegley01296292011-04-08 18:41:53 +00008458 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008459 StmtExprMayBindToTemp = true;
8460 }
8461 }
8462 }
Chris Lattner944d3062008-07-26 19:51:01 +00008463 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008464
Eli Friedmanba961a92009-03-23 00:24:07 +00008465 // FIXME: Check that expression type is complete/non-abstract; statement
8466 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008467 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8468 if (StmtExprMayBindToTemp)
8469 return MaybeBindToTemporary(ResStmtExpr);
8470 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008471}
Steve Naroff78864672007-08-01 22:05:33 +00008472
John McCalldadc5752010-08-24 06:29:42 +00008473ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008474 TypeSourceInfo *TInfo,
8475 OffsetOfComponent *CompPtr,
8476 unsigned NumComponents,
8477 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008478 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008479 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008480 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008481
Chris Lattnerf17bd422007-08-30 17:45:32 +00008482 // We must have at least one component that refers to the type, and the first
8483 // one is known to be a field designator. Verify that the ArgTy represents
8484 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008485 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008486 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8487 << ArgTy << TypeRange);
8488
8489 // Type must be complete per C99 7.17p3 because a declaring a variable
8490 // with an incomplete type would be ill-formed.
8491 if (!Dependent
8492 && RequireCompleteType(BuiltinLoc, ArgTy,
8493 PDiag(diag::err_offsetof_incomplete_type)
8494 << TypeRange))
8495 return ExprError();
8496
Chris Lattner78502cf2007-08-31 21:49:13 +00008497 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8498 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008499 // FIXME: This diagnostic isn't actually visible because the location is in
8500 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008501 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008502 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8503 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008504
8505 bool DidWarnAboutNonPOD = false;
8506 QualType CurrentType = ArgTy;
8507 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008508 SmallVector<OffsetOfNode, 4> Comps;
8509 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008510 for (unsigned i = 0; i != NumComponents; ++i) {
8511 const OffsetOfComponent &OC = CompPtr[i];
8512 if (OC.isBrackets) {
8513 // Offset of an array sub-field. TODO: Should we allow vector elements?
8514 if (!CurrentType->isDependentType()) {
8515 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8516 if(!AT)
8517 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8518 << CurrentType);
8519 CurrentType = AT->getElementType();
8520 } else
8521 CurrentType = Context.DependentTy;
8522
Richard Smith9fcc5c32011-10-17 23:29:39 +00008523 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8524 if (IdxRval.isInvalid())
8525 return ExprError();
8526 Expr *Idx = IdxRval.take();
8527
Douglas Gregor882211c2010-04-28 22:16:22 +00008528 // The expression must be an integral expression.
8529 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008530 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8531 !Idx->getType()->isIntegerType())
8532 return ExprError(Diag(Idx->getLocStart(),
8533 diag::err_typecheck_subscript_not_integer)
8534 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008535
Douglas Gregor882211c2010-04-28 22:16:22 +00008536 // Record this array index.
8537 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008538 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008539 continue;
8540 }
8541
8542 // Offset of a field.
8543 if (CurrentType->isDependentType()) {
8544 // We have the offset of a field, but we can't look into the dependent
8545 // type. Just record the identifier of the field.
8546 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8547 CurrentType = Context.DependentTy;
8548 continue;
8549 }
8550
8551 // We need to have a complete type to look into.
8552 if (RequireCompleteType(OC.LocStart, CurrentType,
8553 diag::err_offsetof_incomplete_type))
8554 return ExprError();
8555
8556 // Look for the designated field.
8557 const RecordType *RC = CurrentType->getAs<RecordType>();
8558 if (!RC)
8559 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8560 << CurrentType);
8561 RecordDecl *RD = RC->getDecl();
8562
8563 // C++ [lib.support.types]p5:
8564 // The macro offsetof accepts a restricted set of type arguments in this
8565 // International Standard. type shall be a POD structure or a POD union
8566 // (clause 9).
8567 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8568 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008569 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008570 PDiag(diag::warn_offsetof_non_pod_type)
8571 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8572 << CurrentType))
8573 DidWarnAboutNonPOD = true;
8574 }
8575
8576 // Look for the field.
8577 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8578 LookupQualifiedName(R, RD);
8579 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008580 IndirectFieldDecl *IndirectMemberDecl = 0;
8581 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008582 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008583 MemberDecl = IndirectMemberDecl->getAnonField();
8584 }
8585
Douglas Gregor882211c2010-04-28 22:16:22 +00008586 if (!MemberDecl)
8587 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8588 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8589 OC.LocEnd));
8590
Douglas Gregor10982ea2010-04-28 22:36:06 +00008591 // C99 7.17p3:
8592 // (If the specified member is a bit-field, the behavior is undefined.)
8593 //
8594 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008595 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008596 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8597 << MemberDecl->getDeclName()
8598 << SourceRange(BuiltinLoc, RParenLoc);
8599 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8600 return ExprError();
8601 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008602
8603 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008604 if (IndirectMemberDecl)
8605 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008606
Douglas Gregord1702062010-04-29 00:18:15 +00008607 // If the member was found in a base class, introduce OffsetOfNodes for
8608 // the base class indirections.
8609 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8610 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008611 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008612 CXXBasePath &Path = Paths.front();
8613 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8614 B != BEnd; ++B)
8615 Comps.push_back(OffsetOfNode(B->Base));
8616 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008617
Francois Pichet783dd6e2010-11-21 06:08:52 +00008618 if (IndirectMemberDecl) {
8619 for (IndirectFieldDecl::chain_iterator FI =
8620 IndirectMemberDecl->chain_begin(),
8621 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8622 assert(isa<FieldDecl>(*FI));
8623 Comps.push_back(OffsetOfNode(OC.LocStart,
8624 cast<FieldDecl>(*FI), OC.LocEnd));
8625 }
8626 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008627 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008628
Douglas Gregor882211c2010-04-28 22:16:22 +00008629 CurrentType = MemberDecl->getType().getNonReferenceType();
8630 }
8631
8632 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8633 TInfo, Comps.data(), Comps.size(),
8634 Exprs.data(), Exprs.size(), RParenLoc));
8635}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008636
John McCalldadc5752010-08-24 06:29:42 +00008637ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008638 SourceLocation BuiltinLoc,
8639 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008640 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008641 OffsetOfComponent *CompPtr,
8642 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008643 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008644
Douglas Gregor882211c2010-04-28 22:16:22 +00008645 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008646 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008647 if (ArgTy.isNull())
8648 return ExprError();
8649
Eli Friedman06dcfd92010-08-05 10:15:45 +00008650 if (!ArgTInfo)
8651 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8652
8653 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008654 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008655}
8656
8657
John McCalldadc5752010-08-24 06:29:42 +00008658ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008659 Expr *CondExpr,
8660 Expr *LHSExpr, Expr *RHSExpr,
8661 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008662 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8663
John McCall7decc9e2010-11-18 06:31:45 +00008664 ExprValueKind VK = VK_RValue;
8665 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008666 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008667 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008668 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008669 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008670 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008671 } else {
8672 // The conditional expression is required to be a constant expression.
8673 llvm::APSInt condEval(32);
Richard Smithf4c51d92012-02-04 09:53:13 +00008674 ExprResult CondICE = VerifyIntegerConstantExpression(CondExpr, &condEval,
8675 PDiag(diag::err_typecheck_choose_expr_requires_constant), false);
8676 if (CondICE.isInvalid())
8677 return ExprError();
8678 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00008679
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008680 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008681 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8682
8683 resType = ActiveExpr->getType();
8684 ValueDependent = ActiveExpr->isValueDependent();
8685 VK = ActiveExpr->getValueKind();
8686 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008687 }
8688
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008689 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008690 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008691 resType->isDependentType(),
8692 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008693}
8694
Steve Naroffc540d662008-09-03 18:15:37 +00008695//===----------------------------------------------------------------------===//
8696// Clang Extensions.
8697//===----------------------------------------------------------------------===//
8698
8699/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008700void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008701 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008702 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008703 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008704 if (CurScope)
8705 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008706 else
8707 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00008708
Eli Friedman34b49062012-01-26 03:00:14 +00008709 getCurBlock()->HasImplicitReturnType = true;
8710
John McCallf1a3c2a2011-11-11 03:19:12 +00008711 // Enter a new evaluation context to insulate the block from any
8712 // cleanups from the enclosing full-expression.
8713 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008714}
8715
Mike Stump82f071f2009-02-04 22:31:32 +00008716void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008717 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008718 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008719 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008720
John McCall8cb7bdf2010-06-04 23:28:52 +00008721 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008722 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008723
John McCall3882ace2011-01-05 12:14:39 +00008724 // GetTypeForDeclarator always produces a function type for a block
8725 // literal signature. Furthermore, it is always a FunctionProtoType
8726 // unless the function was written with a typedef.
8727 assert(T->isFunctionType() &&
8728 "GetTypeForDeclarator made a non-function block signature");
8729
8730 // Look for an explicit signature in that function type.
8731 FunctionProtoTypeLoc ExplicitSignature;
8732
8733 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8734 if (isa<FunctionProtoTypeLoc>(tmp)) {
8735 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8736
8737 // Check whether that explicit signature was synthesized by
8738 // GetTypeForDeclarator. If so, don't save that as part of the
8739 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008740 if (ExplicitSignature.getLocalRangeBegin() ==
8741 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008742 // This would be much cheaper if we stored TypeLocs instead of
8743 // TypeSourceInfos.
8744 TypeLoc Result = ExplicitSignature.getResultLoc();
8745 unsigned Size = Result.getFullDataSize();
8746 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8747 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8748
8749 ExplicitSignature = FunctionProtoTypeLoc();
8750 }
John McCalla3ccba02010-06-04 11:21:44 +00008751 }
Mike Stump11289f42009-09-09 15:08:12 +00008752
John McCall3882ace2011-01-05 12:14:39 +00008753 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8754 CurBlock->FunctionType = T;
8755
8756 const FunctionType *Fn = T->getAs<FunctionType>();
8757 QualType RetTy = Fn->getResultType();
8758 bool isVariadic =
8759 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8760
John McCall8e346702010-06-04 19:02:56 +00008761 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008762
John McCalla3ccba02010-06-04 11:21:44 +00008763 // Don't allow returning a objc interface by value.
8764 if (RetTy->isObjCObjectType()) {
8765 Diag(ParamInfo.getSourceRange().getBegin(),
8766 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8767 return;
8768 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008769
John McCalla3ccba02010-06-04 11:21:44 +00008770 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008771 // return type. TODO: what should we do with declarators like:
8772 // ^ * { ... }
8773 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008774 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00008775 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008776 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00008777 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008778 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008779
John McCalla3ccba02010-06-04 11:21:44 +00008780 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008781 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008782 if (ExplicitSignature) {
8783 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8784 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008785 if (Param->getIdentifier() == 0 &&
8786 !Param->isImplicit() &&
8787 !Param->isInvalidDecl() &&
8788 !getLangOptions().CPlusPlus)
8789 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008790 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008791 }
John McCalla3ccba02010-06-04 11:21:44 +00008792
8793 // Fake up parameter variables if we have a typedef, like
8794 // ^ fntype { ... }
8795 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8796 for (FunctionProtoType::arg_type_iterator
8797 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8798 ParmVarDecl *Param =
8799 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
8800 ParamInfo.getSourceRange().getBegin(),
8801 *I);
John McCall8e346702010-06-04 19:02:56 +00008802 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008803 }
Steve Naroffc540d662008-09-03 18:15:37 +00008804 }
John McCalla3ccba02010-06-04 11:21:44 +00008805
John McCall8e346702010-06-04 19:02:56 +00008806 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008807 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008808 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008809 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8810 CurBlock->TheDecl->param_end(),
8811 /*CheckParameterNames=*/false);
8812 }
8813
John McCalla3ccba02010-06-04 11:21:44 +00008814 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008815 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008816
John McCalla3ccba02010-06-04 11:21:44 +00008817 // Put the parameter variables in scope. We can bail out immediately
8818 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008819 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008820 return;
8821
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008822 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008823 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8824 (*AI)->setOwningFunction(CurBlock->TheDecl);
8825
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008826 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008827 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008828 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008829
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008830 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008831 }
John McCallf7b2fb52010-01-22 00:28:27 +00008832 }
Steve Naroffc540d662008-09-03 18:15:37 +00008833}
8834
8835/// ActOnBlockError - If there is an error parsing a block, this callback
8836/// is invoked to pop the information about the block from the action impl.
8837void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00008838 // Leave the expression-evaluation context.
8839 DiscardCleanupsInEvaluationContext();
8840 PopExpressionEvaluationContext();
8841
Steve Naroffc540d662008-09-03 18:15:37 +00008842 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008843 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00008844 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00008845}
8846
8847/// ActOnBlockStmtExpr - This is called when the body of a block statement
8848/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008849ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008850 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008851 // If blocks are disabled, emit an error.
8852 if (!LangOpts.Blocks)
8853 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008854
John McCallf1a3c2a2011-11-11 03:19:12 +00008855 // Leave the expression-evaluation context.
8856 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
8857 PopExpressionEvaluationContext();
8858
Douglas Gregor9a28e842010-03-01 23:15:13 +00008859 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008860
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008861 PopDeclContext();
8862
Steve Naroffc540d662008-09-03 18:15:37 +00008863 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008864 if (!BSI->ReturnType.isNull())
8865 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00008866
Mike Stump3bf1ab42009-07-28 22:04:01 +00008867 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00008868 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00008869
John McCallc63de662011-02-02 13:00:07 +00008870 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00008871 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
8872 SmallVector<BlockDecl::Capture, 4> Captures;
8873 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
8874 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
8875 if (Cap.isThisCapture())
8876 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00008877 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00008878 Cap.isNested(), Cap.getCopyExpr());
8879 Captures.push_back(NewCap);
8880 }
8881 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
8882 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00008883
John McCall8e346702010-06-04 19:02:56 +00008884 // If the user wrote a function type in some form, try to use that.
8885 if (!BSI->FunctionType.isNull()) {
8886 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
8887
8888 FunctionType::ExtInfo Ext = FTy->getExtInfo();
8889 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
8890
8891 // Turn protoless block types into nullary block types.
8892 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00008893 FunctionProtoType::ExtProtoInfo EPI;
8894 EPI.ExtInfo = Ext;
8895 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008896
8897 // Otherwise, if we don't need to change anything about the function type,
8898 // preserve its sugar structure.
8899 } else if (FTy->getResultType() == RetTy &&
8900 (!NoReturn || FTy->getNoReturnAttr())) {
8901 BlockTy = BSI->FunctionType;
8902
8903 // Otherwise, make the minimal modifications to the function type.
8904 } else {
8905 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00008906 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8907 EPI.TypeQuals = 0; // FIXME: silently?
8908 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00008909 BlockTy = Context.getFunctionType(RetTy,
8910 FPT->arg_type_begin(),
8911 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00008912 EPI);
John McCall8e346702010-06-04 19:02:56 +00008913 }
8914
8915 // If we don't have a function type, just build one from nothing.
8916 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00008917 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00008918 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00008919 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00008920 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008921
John McCall8e346702010-06-04 19:02:56 +00008922 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
8923 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00008924 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00008925
Chris Lattner45542ea2009-04-19 05:28:12 +00008926 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00008927 if (getCurFunction()->NeedsScopeChecking() &&
8928 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00008929 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00008930
Chris Lattner60f84492011-02-17 23:58:47 +00008931 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008932
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00008933 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
8934 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
8935 const VarDecl *variable = ci->getVariable();
8936 QualType T = variable->getType();
8937 QualType::DestructionKind destructKind = T.isDestructedType();
8938 if (destructKind != QualType::DK_none)
8939 getCurFunction()->setHasBranchProtectedScope();
8940 }
8941
Douglas Gregor49695f02011-09-06 20:46:03 +00008942 computeNRVO(Body, getCurBlock());
8943
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008944 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
8945 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00008946 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00008947
John McCall28fc7092011-11-10 05:35:25 +00008948 // If the block isn't obviously global, i.e. it captures anything at
8949 // all, mark this full-expression as needing a cleanup.
8950 if (Result->getBlockDecl()->hasCaptures()) {
8951 ExprCleanupObjects.push_back(Result->getBlockDecl());
8952 ExprNeedsCleanups = true;
8953 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00008954
Douglas Gregor9a28e842010-03-01 23:15:13 +00008955 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00008956}
8957
John McCalldadc5752010-08-24 06:29:42 +00008958ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008959 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008960 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00008961 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008962 GetTypeFromParser(Ty, &TInfo);
8963 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00008964}
8965
John McCalldadc5752010-08-24 06:29:42 +00008966ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00008967 Expr *E, TypeSourceInfo *TInfo,
8968 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00008969 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00008970
Eli Friedman121ba0c2008-08-09 23:32:40 +00008971 // Get the va_list type
8972 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00008973 if (VaListType->isArrayType()) {
8974 // Deal with implicit array decay; for example, on x86-64,
8975 // va_list is an array, but it's supposed to decay to
8976 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00008977 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00008978 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00008979 ExprResult Result = UsualUnaryConversions(E);
8980 if (Result.isInvalid())
8981 return ExprError();
8982 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00008983 } else {
8984 // Otherwise, the va_list argument must be an l-value because
8985 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00008986 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00008987 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00008988 return ExprError();
8989 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00008990
Douglas Gregorad3150c2009-05-19 23:10:31 +00008991 if (!E->isTypeDependent() &&
8992 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008993 return ExprError(Diag(E->getLocStart(),
8994 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00008995 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00008996 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008997
David Majnemerc75d1a12011-06-14 05:17:32 +00008998 if (!TInfo->getType()->isDependentType()) {
8999 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9000 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
9001 << TInfo->getTypeLoc().getSourceRange()))
9002 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009003
David Majnemerc75d1a12011-06-14 05:17:32 +00009004 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9005 TInfo->getType(),
9006 PDiag(diag::err_second_parameter_to_va_arg_abstract)
9007 << TInfo->getTypeLoc().getSourceRange()))
9008 return ExprError();
9009
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009010 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009011 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009012 TInfo->getType()->isObjCLifetimeType()
9013 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9014 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009015 << TInfo->getType()
9016 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009017 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009018
9019 // Check for va_arg where arguments of the given type will be promoted
9020 // (i.e. this va_arg is guaranteed to have undefined behavior).
9021 QualType PromoteType;
9022 if (TInfo->getType()->isPromotableIntegerType()) {
9023 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9024 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9025 PromoteType = QualType();
9026 }
9027 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9028 PromoteType = Context.DoubleTy;
9029 if (!PromoteType.isNull())
9030 Diag(TInfo->getTypeLoc().getBeginLoc(),
9031 diag::warn_second_parameter_to_va_arg_never_compatible)
9032 << TInfo->getType()
9033 << PromoteType
9034 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009035 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009036
Abramo Bagnara27db2392010-08-10 10:06:15 +00009037 QualType T = TInfo->getType().getNonLValueExprType(Context);
9038 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009039}
9040
John McCalldadc5752010-08-24 06:29:42 +00009041ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009042 // The type of __null will be int or long, depending on the size of
9043 // pointers on the target.
9044 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009045 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9046 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009047 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009048 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009049 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009050 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009051 Ty = Context.LongLongTy;
9052 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009053 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009054 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009055
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009056 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009057}
9058
Alexis Huntc46382e2010-04-28 23:02:27 +00009059static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009060 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009061 if (!SemaRef.getLangOptions().ObjC1)
9062 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009063
Anders Carlssonace5d072009-11-10 04:46:30 +00009064 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9065 if (!PT)
9066 return;
9067
9068 // Check if the destination is of type 'id'.
9069 if (!PT->isObjCIdType()) {
9070 // Check if the destination is the 'NSString' interface.
9071 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9072 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9073 return;
9074 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009075
John McCallfe96e0b2011-11-06 09:01:30 +00009076 // Ignore any parens, implicit casts (should only be
9077 // array-to-pointer decays), and not-so-opaque values. The last is
9078 // important for making this trigger for property assignments.
9079 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9080 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9081 if (OV->getSourceExpr())
9082 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9083
9084 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009085 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009086 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009087
Douglas Gregora771f462010-03-31 17:46:05 +00009088 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009089}
9090
Chris Lattner9bad62c2008-01-04 18:04:52 +00009091bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9092 SourceLocation Loc,
9093 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009094 Expr *SrcExpr, AssignmentAction Action,
9095 bool *Complained) {
9096 if (Complained)
9097 *Complained = false;
9098
Chris Lattner9bad62c2008-01-04 18:04:52 +00009099 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009100 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009101 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009102 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009103 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009104 ConversionFixItGenerator ConvHints;
9105 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009106 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009107
Chris Lattner9bad62c2008-01-04 18:04:52 +00009108 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009109 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009110 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009111 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009112 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9113 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009114 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009115 case IntToPointer:
9116 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009117 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9118 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009119 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009120 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009121 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009122 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009123 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9124 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009125 if (Hint.isNull() && !CheckInferredResultType) {
9126 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9127 }
9128 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009129 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009130 case IncompatiblePointerSign:
9131 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9132 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009133 case FunctionVoidPointer:
9134 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9135 break;
John McCall4fff8f62011-02-01 00:10:29 +00009136 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009137 // Perform array-to-pointer decay if necessary.
9138 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9139
John McCall4fff8f62011-02-01 00:10:29 +00009140 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9141 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9142 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9143 DiagKind = diag::err_typecheck_incompatible_address_space;
9144 break;
John McCall31168b02011-06-15 23:02:42 +00009145
9146
9147 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009148 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009149 break;
John McCall4fff8f62011-02-01 00:10:29 +00009150 }
9151
9152 llvm_unreachable("unknown error case for discarding qualifiers!");
9153 // fallthrough
9154 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009155 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009156 // If the qualifiers lost were because we were applying the
9157 // (deprecated) C++ conversion from a string literal to a char*
9158 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9159 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009160 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009161 // bit of refactoring (so that the second argument is an
9162 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009163 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009164 // C++ semantics.
9165 if (getLangOptions().CPlusPlus &&
9166 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9167 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009168 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9169 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009170 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009171 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009172 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009173 case IntToBlockPointer:
9174 DiagKind = diag::err_int_to_block_pointer;
9175 break;
9176 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009177 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009178 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009179 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009180 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009181 // it can give a more specific diagnostic.
9182 DiagKind = diag::warn_incompatible_qualified_id;
9183 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009184 case IncompatibleVectors:
9185 DiagKind = diag::warn_incompatible_vectors;
9186 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009187 case IncompatibleObjCWeakRef:
9188 DiagKind = diag::err_arc_weak_unavailable_assign;
9189 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009190 case Incompatible:
9191 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009192 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9193 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009194 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009195 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009196 break;
9197 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009198
Douglas Gregorc68e1402010-04-09 00:35:39 +00009199 QualType FirstType, SecondType;
9200 switch (Action) {
9201 case AA_Assigning:
9202 case AA_Initializing:
9203 // The destination type comes first.
9204 FirstType = DstType;
9205 SecondType = SrcType;
9206 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009207
Douglas Gregorc68e1402010-04-09 00:35:39 +00009208 case AA_Returning:
9209 case AA_Passing:
9210 case AA_Converting:
9211 case AA_Sending:
9212 case AA_Casting:
9213 // The source type comes first.
9214 FirstType = SrcType;
9215 SecondType = DstType;
9216 break;
9217 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009218
Anna Zaks3b402712011-07-28 19:51:27 +00009219 PartialDiagnostic FDiag = PDiag(DiagKind);
9220 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9221
9222 // If we can fix the conversion, suggest the FixIts.
9223 assert(ConvHints.isNull() || Hint.isNull());
9224 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009225 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9226 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009227 FDiag << *HI;
9228 } else {
9229 FDiag << Hint;
9230 }
9231 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9232
Richard Trieucaff2472011-11-23 22:32:32 +00009233 if (MayHaveFunctionDiff)
9234 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9235
Anna Zaks3b402712011-07-28 19:51:27 +00009236 Diag(Loc, FDiag);
9237
Richard Trieucaff2472011-11-23 22:32:32 +00009238 if (SecondType == Context.OverloadTy)
9239 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9240 FirstType);
9241
Douglas Gregor33823722011-06-11 01:09:30 +00009242 if (CheckInferredResultType)
9243 EmitRelatedResultTypeNote(SrcExpr);
9244
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009245 if (Complained)
9246 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009247 return isInvalid;
9248}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009249
Richard Smithf4c51d92012-02-04 09:53:13 +00009250ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9251 llvm::APSInt *Result) {
9252 return VerifyIntegerConstantExpression(E, Result,
9253 PDiag(diag::err_expr_not_ice) << LangOpts.CPlusPlus);
9254}
9255
9256ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9257 PartialDiagnostic NotIceDiag,
9258 bool AllowFold,
9259 PartialDiagnostic FoldDiag) {
9260 SourceLocation DiagLoc = E->getSourceRange().getBegin();
9261
9262 if (getLangOptions().CPlusPlus0x) {
9263 // C++11 [expr.const]p5:
9264 // If an expression of literal class type is used in a context where an
9265 // integral constant expression is required, then that class type shall
9266 // have a single non-explicit conversion function to an integral or
9267 // unscoped enumeration type
9268 ExprResult Converted;
9269 if (NotIceDiag.getDiagID()) {
9270 Converted = ConvertToIntegralOrEnumerationType(
9271 DiagLoc, E,
9272 PDiag(diag::err_ice_not_integral),
9273 PDiag(diag::err_ice_incomplete_type),
9274 PDiag(diag::err_ice_explicit_conversion),
9275 PDiag(diag::note_ice_conversion_here),
9276 PDiag(diag::err_ice_ambiguous_conversion),
9277 PDiag(diag::note_ice_conversion_here),
9278 PDiag(0),
9279 /*AllowScopedEnumerations*/ false);
9280 } else {
9281 // The caller wants to silently enquire whether this is an ICE. Don't
9282 // produce any diagnostics if it isn't.
9283 Converted = ConvertToIntegralOrEnumerationType(
9284 DiagLoc, E, PDiag(), PDiag(), PDiag(), PDiag(),
9285 PDiag(), PDiag(), PDiag(), false);
9286 }
9287 if (Converted.isInvalid())
9288 return Converted;
9289 E = Converted.take();
9290 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9291 return ExprError();
9292 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9293 // An ICE must be of integral or unscoped enumeration type.
9294 if (NotIceDiag.getDiagID())
9295 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
9296 return ExprError();
9297 }
9298
Richard Smith902ca212011-12-14 23:32:26 +00009299 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9300 // in the non-ICE case.
Richard Smithf4c51d92012-02-04 09:53:13 +00009301 if (!getLangOptions().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
9302 if (Result)
9303 *Result = E->EvaluateKnownConstInt(Context);
9304 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009305 }
9306
Anders Carlssone54e8a12008-11-30 19:50:32 +00009307 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009308 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9309 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009310
Richard Smith902ca212011-12-14 23:32:26 +00009311 // Try to evaluate the expression, and produce diagnostics explaining why it's
9312 // not a constant expression as a side-effect.
9313 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9314 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9315
9316 // In C++11, we can rely on diagnostics being produced for any expression
9317 // which is not a constant expression. If no diagnostics were produced, then
9318 // this is a constant expression.
9319 if (Folded && getLangOptions().CPlusPlus0x && Notes.empty()) {
9320 if (Result)
9321 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009322 return Owned(E);
9323 }
9324
9325 // If our only note is the usual "invalid subexpression" note, just point
9326 // the caret at its location rather than producing an essentially
9327 // redundant note.
9328 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9329 diag::note_invalid_subexpr_in_const_expr) {
9330 DiagLoc = Notes[0].first;
9331 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009332 }
9333
9334 if (!Folded || !AllowFold) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009335 if (NotIceDiag.getDiagID()) {
9336 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
Richard Smith92b1ce02011-12-12 09:28:41 +00009337 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9338 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009339 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009340
Richard Smithf4c51d92012-02-04 09:53:13 +00009341 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009342 }
9343
Richard Smithf4c51d92012-02-04 09:53:13 +00009344 if (FoldDiag.getDiagID())
9345 Diag(DiagLoc, FoldDiag) << E->getSourceRange();
9346 else
9347 Diag(DiagLoc, diag::ext_expr_not_ice)
9348 << E->getSourceRange() << LangOpts.CPlusPlus;
Richard Smith2ec40612012-01-15 03:51:30 +00009349 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9350 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009351
Anders Carlssone54e8a12008-11-30 19:50:32 +00009352 if (Result)
9353 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009354 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009355}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009356
Eli Friedman456f0182012-01-20 01:26:23 +00009357namespace {
9358 // Handle the case where we conclude a expression which we speculatively
9359 // considered to be unevaluated is actually evaluated.
9360 class TransformToPE : public TreeTransform<TransformToPE> {
9361 typedef TreeTransform<TransformToPE> BaseTransform;
9362
9363 public:
9364 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9365
9366 // Make sure we redo semantic analysis
9367 bool AlwaysRebuild() { return true; }
9368
Eli Friedman5f0ca242012-02-06 23:29:57 +00009369 // Make sure we handle LabelStmts correctly.
9370 // FIXME: This does the right thing, but maybe we need a more general
9371 // fix to TreeTransform?
9372 StmtResult TransformLabelStmt(LabelStmt *S) {
9373 S->getDecl()->setStmt(0);
9374 return BaseTransform::TransformLabelStmt(S);
9375 }
9376
Eli Friedman456f0182012-01-20 01:26:23 +00009377 // We need to special-case DeclRefExprs referring to FieldDecls which
9378 // are not part of a member pointer formation; normal TreeTransforming
9379 // doesn't catch this case because of the way we represent them in the AST.
9380 // FIXME: This is a bit ugly; is it really the best way to handle this
9381 // case?
9382 //
9383 // Error on DeclRefExprs referring to FieldDecls.
9384 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9385 if (isa<FieldDecl>(E->getDecl()) &&
9386 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9387 return SemaRef.Diag(E->getLocation(),
9388 diag::err_invalid_non_static_member_use)
9389 << E->getDecl() << E->getSourceRange();
9390
9391 return BaseTransform::TransformDeclRefExpr(E);
9392 }
9393
9394 // Exception: filter out member pointer formation
9395 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9396 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9397 return E;
9398
9399 return BaseTransform::TransformUnaryOperator(E);
9400 }
9401
Douglas Gregor89625492012-02-09 08:14:43 +00009402 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9403 // Lambdas never need to be transformed.
9404 return E;
9405 }
Eli Friedman456f0182012-01-20 01:26:23 +00009406 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009407}
9408
Eli Friedman456f0182012-01-20 01:26:23 +00009409ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009410 assert(ExprEvalContexts.back().Context == Unevaluated &&
9411 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009412 ExprEvalContexts.back().Context =
9413 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9414 if (ExprEvalContexts.back().Context == Unevaluated)
9415 return E;
9416 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009417}
9418
Douglas Gregorff790f12009-11-26 00:44:06 +00009419void
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009420Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +00009421 Decl *LambdaContextDecl,
9422 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009423 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009424 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +00009425 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009426 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +00009427 LambdaContextDecl,
9428 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +00009429 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009430 if (!MaybeODRUseExprs.empty())
9431 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009432}
9433
Richard Trieucfc491d2011-08-02 04:35:43 +00009434void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009435 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009436
Douglas Gregor89625492012-02-09 08:14:43 +00009437 if (!Rec.Lambdas.empty()) {
9438 if (Rec.Context == Unevaluated) {
9439 // C++11 [expr.prim.lambda]p2:
9440 // A lambda-expression shall not appear in an unevaluated operand
9441 // (Clause 5).
9442 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
9443 Diag(Rec.Lambdas[I]->getLocStart(),
9444 diag::err_lambda_unevaluated_operand);
9445 } else {
9446 // Mark the capture expressions odr-used. This was deferred
9447 // during lambda expression creation.
9448 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
9449 LambdaExpr *Lambda = Rec.Lambdas[I];
9450 for (LambdaExpr::capture_init_iterator
9451 C = Lambda->capture_init_begin(),
9452 CEnd = Lambda->capture_init_end();
9453 C != CEnd; ++C) {
9454 MarkDeclarationsReferencedInExpr(*C);
9455 }
9456 }
9457 }
9458 }
9459
Douglas Gregorff790f12009-11-26 00:44:06 +00009460 // When are coming out of an unevaluated context, clear out any
9461 // temporaries that we may have created as part of the evaluation of
9462 // the expression in that context: they aren't relevant because they
9463 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +00009464 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +00009465 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9466 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009467 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009468 CleanupVarDeclMarking();
9469 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +00009470 // Otherwise, merge the contexts together.
9471 } else {
9472 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009473 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
9474 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +00009475 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009476
9477 // Pop the current expression evaluation context off the stack.
9478 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009479}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009480
John McCall31168b02011-06-15 23:02:42 +00009481void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +00009482 ExprCleanupObjects.erase(
9483 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9484 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009485 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009486 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +00009487}
9488
Eli Friedmane0afc982012-01-21 01:01:51 +00009489ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
9490 if (!E->getType()->isVariablyModifiedType())
9491 return E;
9492 return TranformToPotentiallyEvaluated(E);
9493}
9494
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00009495static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009496 // Do not mark anything as "used" within a dependent context; wait for
9497 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009498 if (SemaRef.CurContext->isDependentContext())
9499 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009500
Eli Friedmanfa0df832012-02-02 03:46:19 +00009501 switch (SemaRef.ExprEvalContexts.back().Context) {
9502 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009503 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +00009504 // (Depending on how you read the standard, we actually do need to do
9505 // something here for null pointer constants, but the standard's
9506 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +00009507 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009508
Eli Friedmanfa0df832012-02-02 03:46:19 +00009509 case Sema::ConstantEvaluated:
9510 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +00009511 // We are in a potentially evaluated expression (or a constant-expression
9512 // in C++03); we need to do implicit template instantiation, implicitly
9513 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009514 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009515
Eli Friedmanfa0df832012-02-02 03:46:19 +00009516 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009517 // Referenced declarations will only be used if the construct in the
9518 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009519 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009520 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +00009521 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +00009522}
9523
9524/// \brief Mark a function referenced, and check whether it is odr-used
9525/// (C++ [basic.def.odr]p2, C99 6.9p3)
9526void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
9527 assert(Func && "No function?");
9528
9529 Func->setReferenced();
9530
Richard Smith4a941e22012-02-14 22:25:15 +00009531 // Don't mark this function as used multiple times, unless it's a constexpr
9532 // function which we need to instantiate.
9533 if (Func->isUsed(false) &&
9534 !(Func->isConstexpr() && !Func->getBody() &&
9535 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +00009536 return;
9537
9538 if (!IsPotentiallyEvaluatedContext(*this))
9539 return;
Mike Stump11289f42009-09-09 15:08:12 +00009540
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009541 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009542 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009543 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009544 if (Constructor->isDefaultConstructor()) {
9545 if (Constructor->isTrivial())
9546 return;
9547 if (!Constructor->isUsed(false))
9548 DefineImplicitDefaultConstructor(Loc, Constructor);
9549 } else if (Constructor->isCopyConstructor()) {
9550 if (!Constructor->isUsed(false))
9551 DefineImplicitCopyConstructor(Loc, Constructor);
9552 } else if (Constructor->isMoveConstructor()) {
9553 if (!Constructor->isUsed(false))
9554 DefineImplicitMoveConstructor(Loc, Constructor);
9555 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009556 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009557
Douglas Gregor88d292c2010-05-13 16:44:06 +00009558 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009559 } else if (CXXDestructorDecl *Destructor =
9560 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009561 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
9562 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009563 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009564 if (Destructor->isVirtual())
9565 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009566 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009567 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
9568 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009569 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009570 if (!MethodDecl->isUsed(false)) {
9571 if (MethodDecl->isCopyAssignmentOperator())
9572 DefineImplicitCopyAssignment(Loc, MethodDecl);
9573 else
9574 DefineImplicitMoveAssignment(Loc, MethodDecl);
9575 }
Douglas Gregord3b672c2012-02-16 01:06:16 +00009576 } else if (isa<CXXConversionDecl>(MethodDecl) &&
9577 MethodDecl->getParent()->isLambda()) {
9578 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
9579 if (Conversion->isLambdaToBlockPointerConversion())
9580 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
9581 else
9582 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009583 } else if (MethodDecl->isVirtual())
9584 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009585 }
John McCall83779672011-02-19 02:53:41 +00009586
Eli Friedmanfa0df832012-02-02 03:46:19 +00009587 // Recursive functions should be marked when used from another function.
9588 // FIXME: Is this really right?
9589 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009590
Eli Friedmanfa0df832012-02-02 03:46:19 +00009591 // Implicit instantiation of function templates and member functions of
9592 // class templates.
9593 if (Func->isImplicitlyInstantiable()) {
9594 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +00009595 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009596 if (FunctionTemplateSpecializationInfo *SpecInfo
9597 = Func->getTemplateSpecializationInfo()) {
9598 if (SpecInfo->getPointOfInstantiation().isInvalid())
9599 SpecInfo->setPointOfInstantiation(Loc);
9600 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009601 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009602 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009603 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
9604 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009605 } else if (MemberSpecializationInfo *MSInfo
9606 = Func->getMemberSpecializationInfo()) {
9607 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +00009608 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009609 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009610 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009611 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009612 PointOfInstantiation = MSInfo->getPointOfInstantiation();
9613 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00009614 }
Mike Stump11289f42009-09-09 15:08:12 +00009615
Richard Smith4a941e22012-02-14 22:25:15 +00009616 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009617 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
9618 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +00009619 PendingLocalImplicitInstantiations.push_back(
9620 std::make_pair(Func, PointOfInstantiation));
9621 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +00009622 // Do not defer instantiations of constexpr functions, to avoid the
9623 // expression evaluator needing to call back into Sema if it sees a
9624 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +00009625 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009626 else {
Richard Smith4a941e22012-02-14 22:25:15 +00009627 PendingInstantiations.push_back(std::make_pair(Func,
9628 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009629 // Notify the consumer that a function was implicitly instantiated.
9630 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
9631 }
John McCall83779672011-02-19 02:53:41 +00009632 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009633 } else {
9634 // Walk redefinitions, as some of them may be instantiable.
9635 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
9636 e(Func->redecls_end()); i != e; ++i) {
9637 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9638 MarkFunctionReferenced(Loc, *i);
9639 }
Sam Weinigbae69142009-09-11 03:29:30 +00009640 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009641
9642 // Keep track of used but undefined functions.
9643 if (!Func->isPure() && !Func->hasBody() &&
9644 Func->getLinkage() != ExternalLinkage) {
9645 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
9646 if (old.isInvalid()) old = Loc;
9647 }
9648
9649 Func->setUsed(true);
9650}
9651
Eli Friedman9bb33f52012-02-03 02:04:35 +00009652static void
9653diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
9654 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +00009655 DeclContext *VarDC = var->getDeclContext();
9656
Eli Friedman9bb33f52012-02-03 02:04:35 +00009657 // If the parameter still belongs to the translation unit, then
9658 // we're actually just using one parameter in the declaration of
9659 // the next.
9660 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +00009661 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +00009662 return;
9663
Eli Friedmandd053f62012-02-07 00:15:00 +00009664 // For C code, don't diagnose about capture if we're not actually in code
9665 // right now; it's impossible to write a non-constant expression outside of
9666 // function context, so we'll get other (more useful) diagnostics later.
9667 //
9668 // For C++, things get a bit more nasty... it would be nice to suppress this
9669 // diagnostic for certain cases like using a local variable in an array bound
9670 // for a member of a local class, but the correct predicate is not obvious.
9671 if (!S.getLangOptions().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +00009672 return;
9673
Eli Friedmandd053f62012-02-07 00:15:00 +00009674 if (isa<CXXMethodDecl>(VarDC) &&
9675 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
9676 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
9677 << var->getIdentifier();
9678 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
9679 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
9680 << var->getIdentifier() << fn->getDeclName();
9681 } else if (isa<BlockDecl>(VarDC)) {
9682 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
9683 << var->getIdentifier();
9684 } else {
9685 // FIXME: Is there any other context where a local variable can be
9686 // declared?
9687 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
9688 << var->getIdentifier();
9689 }
Eli Friedman9bb33f52012-02-03 02:04:35 +00009690
Eli Friedman9bb33f52012-02-03 02:04:35 +00009691 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
9692 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +00009693
9694 // FIXME: Add additional diagnostic info about class etc. which prevents
9695 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +00009696}
9697
Douglas Gregor81495f32012-02-12 18:42:33 +00009698/// \brief Capture the given variable in the given lambda expression.
9699static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009700 VarDecl *Var, QualType FieldType,
9701 QualType DeclRefType,
9702 SourceLocation Loc) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009703 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +00009704
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009705 // Build the non-static data member.
9706 FieldDecl *Field
9707 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
9708 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
9709 0, false, false);
9710 Field->setImplicit(true);
9711 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +00009712 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009713
9714 // C++11 [expr.prim.lambda]p21:
9715 // When the lambda-expression is evaluated, the entities that
9716 // are captured by copy are used to direct-initialize each
9717 // corresponding non-static data member of the resulting closure
9718 // object. (For array members, the array elements are
9719 // direct-initialized in increasing subscript order.) These
9720 // initializations are performed in the (unspecified) order in
9721 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009722
Douglas Gregor89625492012-02-09 08:14:43 +00009723 // Introduce a new evaluation context for the initialization, so
9724 // that temporaries introduced as part of the capture are retained
9725 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009726 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9727
Douglas Gregorf02455e2012-02-10 09:26:04 +00009728 // C++ [expr.prim.labda]p12:
9729 // An entity captured by a lambda-expression is odr-used (3.2) in
9730 // the scope containing the lambda-expression.
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009731 Expr *Ref = new (S.Context) DeclRefExpr(Var, DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +00009732 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +00009733 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +00009734
9735 // When the field has array type, create index variables for each
9736 // dimension of the array. We use these index variables to subscript
9737 // the source array, and other clients (e.g., CodeGen) will perform
9738 // the necessary iteration with these index variables.
9739 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +00009740 QualType BaseType = FieldType;
9741 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +00009742 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +00009743 while (const ConstantArrayType *Array
9744 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +00009745 // Create the iteration variable for this array index.
9746 IdentifierInfo *IterationVarName = 0;
9747 {
9748 SmallString<8> Str;
9749 llvm::raw_svector_ostream OS(Str);
9750 OS << "__i" << IndexVariables.size();
9751 IterationVarName = &S.Context.Idents.get(OS.str());
9752 }
9753 VarDecl *IterationVar
9754 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9755 IterationVarName, SizeType,
9756 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9757 SC_None, SC_None);
9758 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +00009759 LSI->ArrayIndexVars.push_back(IterationVar);
9760
Douglas Gregor199cec72012-02-09 02:45:47 +00009761 // Create a reference to the iteration variable.
9762 ExprResult IterationVarRef
9763 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
9764 assert(!IterationVarRef.isInvalid() &&
9765 "Reference to invented variable cannot fail!");
9766 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
9767 assert(!IterationVarRef.isInvalid() &&
9768 "Conversion of invented variable cannot fail!");
9769
9770 // Subscript the array with this iteration variable.
9771 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
9772 Ref, Loc, IterationVarRef.take(), Loc);
9773 if (Subscript.isInvalid()) {
9774 S.CleanupVarDeclMarking();
9775 S.DiscardCleanupsInEvaluationContext();
9776 S.PopExpressionEvaluationContext();
9777 return ExprError();
9778 }
9779
9780 Ref = Subscript.take();
9781 BaseType = Array->getElementType();
9782 }
9783
9784 // Construct the entity that we will be initializing. For an array, this
9785 // will be first element in the array, which may require several levels
9786 // of array-subscript entities.
9787 SmallVector<InitializedEntity, 4> Entities;
9788 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +00009789 Entities.push_back(
9790 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +00009791 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
9792 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
9793 0,
9794 Entities.back()));
9795
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009796 InitializationKind InitKind
9797 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +00009798 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009799 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +00009800 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
9801 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009802 MultiExprArg(S, &Ref, 1));
9803
9804 // If this initialization requires any cleanups (e.g., due to a
9805 // default argument to a copy constructor), note that for the
9806 // lambda.
9807 if (S.ExprNeedsCleanups)
9808 LSI->ExprNeedsCleanups = true;
9809
9810 // Exit the expression evaluation context used for the capture.
9811 S.CleanupVarDeclMarking();
9812 S.DiscardCleanupsInEvaluationContext();
9813 S.PopExpressionEvaluationContext();
9814 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +00009815}
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009816
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009817bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
9818 TryCaptureKind Kind, SourceLocation EllipsisLoc,
9819 bool BuildAndDiagnose,
9820 QualType &CaptureType,
9821 QualType &DeclRefType) {
9822 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +00009823
Eli Friedman24af8502012-02-03 22:47:37 +00009824 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009825 if (Var->getDeclContext() == DC) return true;
9826 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009827
Douglas Gregor81495f32012-02-12 18:42:33 +00009828 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +00009829
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009830 // Walk up the stack to determine whether we can capture the variable,
9831 // performing the "simple" checks that don't depend on type. We stop when
9832 // we've either hit the declared scope of the variable or find an existing
9833 // capture of that variable.
9834 CaptureType = Var->getType();
9835 DeclRefType = CaptureType.getNonReferenceType();
9836 bool Explicit = (Kind != TryCapture_Implicit);
9837 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009838 do {
Eli Friedman24af8502012-02-03 22:47:37 +00009839 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +00009840 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +00009841 DeclContext *ParentDC;
9842 if (isa<BlockDecl>(DC))
9843 ParentDC = DC->getParent();
9844 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +00009845 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +00009846 cast<CXXRecordDecl>(DC->getParent())->isLambda())
9847 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +00009848 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009849 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +00009850 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009851 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +00009852 }
Eli Friedman9bb33f52012-02-03 02:04:35 +00009853
Eli Friedman24af8502012-02-03 22:47:37 +00009854 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +00009855 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +00009856
Eli Friedman24af8502012-02-03 22:47:37 +00009857 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +00009858 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009859 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +00009860 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009861
9862 // Retrieve the capture type for this variable.
9863 CaptureType = CSI->getCapture(Var).getCaptureType();
9864
9865 // Compute the type of an expression that refers to this variable.
9866 DeclRefType = CaptureType.getNonReferenceType();
9867
9868 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
9869 if (Cap.isCopyCapture() &&
9870 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
9871 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +00009872 break;
9873 }
9874
Douglas Gregor81495f32012-02-12 18:42:33 +00009875 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009876 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +00009877
9878 // Lambdas are not allowed to capture unnamed variables
9879 // (e.g. anonymous unions).
9880 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
9881 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +00009882 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009883 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009884 Diag(Loc, diag::err_lambda_capture_anonymous_var);
9885 Diag(Var->getLocation(), diag::note_declared_at);
9886 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009887 return true;
Eli Friedman24af8502012-02-03 22:47:37 +00009888 }
9889
9890 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009891 if (Var->getType()->isVariablyModifiedType()) {
9892 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009893 if (IsBlock)
9894 Diag(Loc, diag::err_ref_vm_type);
9895 else
9896 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
9897 Diag(Var->getLocation(), diag::note_previous_decl)
9898 << Var->getDeclName();
9899 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009900 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009901 }
9902
Eli Friedman24af8502012-02-03 22:47:37 +00009903 // Lambdas are not allowed to capture __block variables; they don't
9904 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +00009905 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009906 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009907 Diag(Loc, diag::err_lambda_capture_block)
9908 << Var->getDeclName();
9909 Diag(Var->getLocation(), diag::note_previous_decl)
9910 << Var->getDeclName();
9911 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009912 return true;
Eli Friedman24af8502012-02-03 22:47:37 +00009913 }
9914
Douglas Gregor81495f32012-02-12 18:42:33 +00009915 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
9916 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009917 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009918 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
9919 Diag(Var->getLocation(), diag::note_previous_decl)
9920 << Var->getDeclName();
9921 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
9922 diag::note_lambda_decl);
9923 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009924 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +00009925 }
9926
9927 FunctionScopesIndex--;
9928 DC = ParentDC;
9929 Explicit = false;
9930 } while (!Var->getDeclContext()->Equals(DC));
9931
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009932 // Walk back down the scope stack, computing the type of the capture at
9933 // each step, checking type-specific requirements, and adding captures if
9934 // requested.
9935 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
9936 ++I) {
9937 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +00009938
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009939 // Compute the type of the capture and of a reference to the capture within
9940 // this scope.
9941 if (isa<BlockScopeInfo>(CSI)) {
9942 Expr *CopyExpr = 0;
9943 bool ByRef = false;
9944
9945 // Blocks are not allowed to capture arrays.
9946 if (CaptureType->isArrayType()) {
9947 if (BuildAndDiagnose) {
9948 Diag(Loc, diag::err_ref_array_type);
9949 Diag(Var->getLocation(), diag::note_previous_decl)
9950 << Var->getDeclName();
9951 }
9952 return true;
9953 }
9954
9955 if (HasBlocksAttr || CaptureType->isReferenceType()) {
9956 // Block capture by reference does not change the capture or
9957 // declaration reference types.
9958 ByRef = true;
9959 } else {
9960 // Block capture by copy introduces 'const'.
9961 CaptureType = CaptureType.getNonReferenceType().withConst();
9962 DeclRefType = CaptureType;
9963
9964 if (getLangOptions().CPlusPlus && BuildAndDiagnose) {
9965 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
9966 // The capture logic needs the destructor, so make sure we mark it.
9967 // Usually this is unnecessary because most local variables have
9968 // their destructors marked at declaration time, but parameters are
9969 // an exception because it's technically only the call site that
9970 // actually requires the destructor.
9971 if (isa<ParmVarDecl>(Var))
9972 FinalizeVarWithDestructor(Var, Record);
9973
9974 // According to the blocks spec, the capture of a variable from
9975 // the stack requires a const copy constructor. This is not true
9976 // of the copy/move done to move a __block variable to the heap.
9977 Expr *DeclRef = new (Context) DeclRefExpr(Var,
9978 DeclRefType.withConst(),
9979 VK_LValue, Loc);
9980 ExprResult Result
9981 = PerformCopyInitialization(
9982 InitializedEntity::InitializeBlock(Var->getLocation(),
9983 CaptureType, false),
9984 Loc, Owned(DeclRef));
9985
9986 // Build a full-expression copy expression if initialization
9987 // succeeded and used a non-trivial constructor. Recover from
9988 // errors by pretending that the copy isn't necessary.
9989 if (!Result.isInvalid() &&
9990 !cast<CXXConstructExpr>(Result.get())->getConstructor()
9991 ->isTrivial()) {
9992 Result = MaybeCreateExprWithCleanups(Result);
9993 CopyExpr = Result.take();
9994 }
9995 }
9996 }
9997 }
9998
9999 // Actually capture the variable.
10000 if (BuildAndDiagnose)
10001 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10002 SourceLocation(), CaptureType, CopyExpr);
10003 Nested = true;
10004 continue;
10005 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010006
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010007 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10008
10009 // Determine whether we are capturing by reference or by value.
10010 bool ByRef = false;
10011 if (I == N - 1 && Kind != TryCapture_Implicit) {
10012 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010013 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010014 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010015 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010016
10017 // Compute the type of the field that will capture this variable.
10018 if (ByRef) {
10019 // C++11 [expr.prim.lambda]p15:
10020 // An entity is captured by reference if it is implicitly or
10021 // explicitly captured but not captured by copy. It is
10022 // unspecified whether additional unnamed non-static data
10023 // members are declared in the closure type for entities
10024 // captured by reference.
10025 //
10026 // FIXME: It is not clear whether we want to build an lvalue reference
10027 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10028 // to do the former, while EDG does the latter. Core issue 1249 will
10029 // clarify, but for now we follow GCC because it's a more permissive and
10030 // easily defensible position.
10031 CaptureType = Context.getLValueReferenceType(DeclRefType);
10032 } else {
10033 // C++11 [expr.prim.lambda]p14:
10034 // For each entity captured by copy, an unnamed non-static
10035 // data member is declared in the closure type. The
10036 // declaration order of these members is unspecified. The type
10037 // of such a data member is the type of the corresponding
10038 // captured entity if the entity is not a reference to an
10039 // object, or the referenced type otherwise. [Note: If the
10040 // captured entity is a reference to a function, the
10041 // corresponding data member is also a reference to a
10042 // function. - end note ]
10043 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10044 if (!RefType->getPointeeType()->isFunctionType())
10045 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010046 }
10047 }
10048
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010049 // Capture this variable in the lambda.
10050 Expr *CopyExpr = 0;
10051 if (BuildAndDiagnose) {
10052 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10053 DeclRefType, Loc);
10054 if (!Result.isInvalid())
10055 CopyExpr = Result.take();
10056 }
10057
10058 // Compute the type of a reference to this captured variable.
10059 if (ByRef)
10060 DeclRefType = CaptureType.getNonReferenceType();
10061 else {
10062 // C++ [expr.prim.lambda]p5:
10063 // The closure type for a lambda-expression has a public inline
10064 // function call operator [...]. This function call operator is
10065 // declared const (9.3.1) if and only if the lambda-expression’s
10066 // parameter-declaration-clause is not followed by mutable.
10067 DeclRefType = CaptureType.getNonReferenceType();
10068 if (!LSI->Mutable && !CaptureType->isReferenceType())
10069 DeclRefType.addConst();
10070 }
10071
10072 // Add the capture.
10073 if (BuildAndDiagnose)
10074 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10075 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010076 Nested = true;
10077 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010078
10079 return false;
10080}
10081
10082bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10083 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10084 QualType CaptureType;
10085 QualType DeclRefType;
10086 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10087 /*BuildAndDiagnose=*/true, CaptureType,
10088 DeclRefType);
10089}
10090
10091QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10092 QualType CaptureType;
10093 QualType DeclRefType;
10094
10095 // Determine whether we can capture this variable.
10096 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10097 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10098 return QualType();
10099
10100 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010101}
10102
Eli Friedman3bda6b12012-02-02 23:15:15 +000010103static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10104 SourceLocation Loc) {
10105 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010106 // FIXME: We shouldn't suppress this warning for static data members.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010107 if (Var->hasDefinition() == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010108 Var->getLinkage() != ExternalLinkage &&
10109 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010110 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10111 if (old.isInvalid()) old = Loc;
10112 }
10113
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010114 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010115
Eli Friedman3bda6b12012-02-02 23:15:15 +000010116 Var->setUsed(true);
10117}
10118
10119void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10120 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10121 // an object that satisfies the requirements for appearing in a
10122 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10123 // is immediately applied." This function handles the lvalue-to-rvalue
10124 // conversion part.
10125 MaybeODRUseExprs.erase(E->IgnoreParens());
10126}
10127
Eli Friedmanc6237c62012-02-29 03:16:56 +000010128ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10129 if (!Res.isUsable())
10130 return Res;
10131
10132 // If a constant-expression is a reference to a variable where we delay
10133 // deciding whether it is an odr-use, just assume we will apply the
10134 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10135 // (a non-type template argument), we have special handling anyway.
10136 UpdateMarkingForLValueToRValue(Res.get());
10137 return Res;
10138}
10139
Eli Friedman3bda6b12012-02-02 23:15:15 +000010140void Sema::CleanupVarDeclMarking() {
10141 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10142 e = MaybeODRUseExprs.end();
10143 i != e; ++i) {
10144 VarDecl *Var;
10145 SourceLocation Loc;
10146 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(*i)) {
10147 Var = BDRE->getDecl();
10148 Loc = BDRE->getLocation();
10149 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10150 Var = cast<VarDecl>(DRE->getDecl());
10151 Loc = DRE->getLocation();
10152 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10153 Var = cast<VarDecl>(ME->getMemberDecl());
10154 Loc = ME->getMemberLoc();
10155 } else {
10156 llvm_unreachable("Unexpcted expression");
10157 }
10158
10159 MarkVarDeclODRUsed(*this, Var, Loc);
10160 }
10161
10162 MaybeODRUseExprs.clear();
10163}
10164
10165// Mark a VarDecl referenced, and perform the necessary handling to compute
10166// odr-uses.
10167static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10168 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010169 Var->setReferenced();
10170
Eli Friedman3bda6b12012-02-02 23:15:15 +000010171 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010172 return;
10173
10174 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010175 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010176 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10177 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010178 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10179 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
10180 (!AlreadyInstantiated || Var->isUsableInConstantExpressions())) {
10181 if (!AlreadyInstantiated) {
10182 // This is a modification of an existing AST node. Notify listeners.
10183 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10184 L->StaticDataMemberInstantiated(Var);
10185 MSInfo->setPointOfInstantiation(Loc);
10186 }
10187 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Eli Friedmanfa0df832012-02-02 03:46:19 +000010188 if (Var->isUsableInConstantExpressions())
10189 // Do not defer instantiations of variables which could be used in a
10190 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010191 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010192 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010193 SemaRef.PendingInstantiations.push_back(
10194 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010195 }
10196 }
10197
Eli Friedman3bda6b12012-02-02 23:15:15 +000010198 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10199 // an object that satisfies the requirements for appearing in a
10200 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10201 // is immediately applied." We check the first part here, and
10202 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10203 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010204 // C++03 depends on whether we get the C++03 version correct. This does not
10205 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010206 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010207 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010208 Var->isUsableInConstantExpressions() &&
10209 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10210 SemaRef.MaybeODRUseExprs.insert(E);
10211 else
10212 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10213}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010214
Eli Friedman3bda6b12012-02-02 23:15:15 +000010215/// \brief Mark a variable referenced, and check whether it is odr-used
10216/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10217/// used directly for normal expressions referring to VarDecl.
10218void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10219 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010220}
10221
10222static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10223 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010224 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10225 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10226 return;
10227 }
10228
Eli Friedmanfa0df832012-02-02 03:46:19 +000010229 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010230}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010231
10232/// \brief Perform reference-marking and odr-use handling for a
10233/// BlockDeclRefExpr.
10234void Sema::MarkBlockDeclRefReferenced(BlockDeclRefExpr *E) {
10235 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10236}
10237
10238/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10239void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10240 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10241}
10242
10243/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10244void Sema::MarkMemberReferenced(MemberExpr *E) {
10245 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10246}
10247
Douglas Gregorf02455e2012-02-10 09:26:04 +000010248/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010249/// marks the declaration referenced, and performs odr-use checking for functions
10250/// and variables. This method should not be used when building an normal
10251/// expression which refers to a variable.
10252void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10253 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10254 MarkVariableReferenced(Loc, VD);
10255 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10256 MarkFunctionReferenced(Loc, FD);
10257 else
10258 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010259}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010260
Douglas Gregor5597ab42010-05-07 23:12:07 +000010261namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010262 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010263 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010264 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010265 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10266 Sema &S;
10267 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010268
Douglas Gregor5597ab42010-05-07 23:12:07 +000010269 public:
10270 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010271
Douglas Gregor5597ab42010-05-07 23:12:07 +000010272 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010273
10274 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10275 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010276 };
10277}
10278
Chandler Carruthaf80f662010-06-09 08:17:30 +000010279bool MarkReferencedDecls::TraverseTemplateArgument(
10280 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010281 if (Arg.getKind() == TemplateArgument::Declaration) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010282 S.MarkAnyDeclReferenced(Loc, Arg.getAsDecl());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010283 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010284
10285 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010286}
10287
Chandler Carruthaf80f662010-06-09 08:17:30 +000010288bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010289 if (ClassTemplateSpecializationDecl *Spec
10290 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10291 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010292 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010293 }
10294
Chandler Carruthc65667c2010-06-10 10:31:57 +000010295 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010296}
10297
10298void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10299 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010300 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010301}
10302
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010303namespace {
10304 /// \brief Helper class that marks all of the declarations referenced by
10305 /// potentially-evaluated subexpressions as "referenced".
10306 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10307 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010308 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010309
10310 public:
10311 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10312
Douglas Gregor680e9e02012-02-21 19:11:17 +000010313 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10314 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010315
10316 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010317 // If we were asked not to visit local variables, don't.
10318 if (SkipLocalVariables) {
10319 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10320 if (VD->hasLocalStorage())
10321 return;
10322 }
10323
Eli Friedmanfa0df832012-02-02 03:46:19 +000010324 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010325 }
10326
10327 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010328 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010329 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010330 }
10331
John McCall28fc7092011-11-10 05:35:25 +000010332 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010333 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010334 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10335 Visit(E->getSubExpr());
10336 }
10337
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010338 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010339 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010340 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010341 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010342 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010343 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010344 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010345
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010346 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10347 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010348 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010349 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10350 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10351 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010352 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010353 S.LookupDestructor(Record));
10354 }
10355
Douglas Gregor32b3de52010-09-11 23:32:50 +000010356 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010357 }
10358
10359 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010360 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010361 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010362 }
10363
10364 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010365 // If we were asked not to visit local variables, don't.
10366 if (SkipLocalVariables && E->getDecl()->hasLocalStorage())
10367 return;
10368
Eli Friedmanfa0df832012-02-02 03:46:19 +000010369 S.MarkBlockDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010370 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010371
10372 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10373 Visit(E->getExpr());
10374 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010375
10376 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10377 Inherited::VisitImplicitCastExpr(E);
10378
10379 if (E->getCastKind() == CK_LValueToRValue)
10380 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10381 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010382 };
10383}
10384
10385/// \brief Mark any declarations that appear within this expression or any
10386/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010387///
10388/// \param SkipLocalVariables If true, don't mark local variables as
10389/// 'referenced'.
10390void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10391 bool SkipLocalVariables) {
10392 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010393}
10394
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010395/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10396/// of the program being compiled.
10397///
10398/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010399/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010400/// possibility that the code will actually be executable. Code in sizeof()
10401/// expressions, code used only during overload resolution, etc., are not
10402/// potentially evaluated. This routine will suppress such diagnostics or,
10403/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010404/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010405/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010406///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010407/// This routine should be used for all diagnostics that describe the run-time
10408/// behavior of a program, such as passing a non-POD value through an ellipsis.
10409/// Failure to do so will likely result in spurious diagnostics or failures
10410/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000010411bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010412 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010413 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010414 case Unevaluated:
10415 // The argument will never be evaluated, so don't complain.
10416 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010417
Richard Smith764d2fe2011-12-20 02:08:33 +000010418 case ConstantEvaluated:
10419 // Relevant diagnostics should be produced by constant evaluation.
10420 break;
10421
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010422 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010423 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000010424 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000010425 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000010426 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000010427 }
10428 else
10429 Diag(Loc, PD);
10430
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010431 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010432 }
10433
10434 return false;
10435}
10436
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010437bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10438 CallExpr *CE, FunctionDecl *FD) {
10439 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10440 return false;
10441
Richard Smithfd555f62012-02-22 02:04:18 +000010442 // If we're inside a decltype's expression, don't check for a valid return
10443 // type or construct temporaries until we know whether this is the last call.
10444 if (ExprEvalContexts.back().IsDecltype) {
10445 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10446 return false;
10447 }
10448
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010449 PartialDiagnostic Note =
10450 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10451 << FD->getDeclName() : PDiag();
10452 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010453
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010454 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010455 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010456 PDiag(diag::err_call_function_incomplete_return)
10457 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010458 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010459 << CE->getSourceRange(),
10460 std::make_pair(NoteLoc, Note)))
10461 return true;
10462
10463 return false;
10464}
10465
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010466// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010467// will prevent this condition from triggering, which is what we want.
10468void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10469 SourceLocation Loc;
10470
John McCall0506e4a2009-11-11 02:41:58 +000010471 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010472 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010473
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010474 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010475 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010476 return;
10477
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010478 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10479
John McCallb0e419e2009-11-12 00:06:05 +000010480 // Greylist some idioms by putting them into a warning subcategory.
10481 if (ObjCMessageExpr *ME
10482 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10483 Selector Sel = ME->getSelector();
10484
John McCallb0e419e2009-11-12 00:06:05 +000010485 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000010486 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010487 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10488
10489 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010490 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010491 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10492 }
John McCall0506e4a2009-11-11 02:41:58 +000010493
John McCalld5707ab2009-10-12 21:59:07 +000010494 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010495 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010496 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010497 return;
10498
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010499 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010500 Loc = Op->getOperatorLoc();
10501 } else {
10502 // Not an assignment.
10503 return;
10504 }
10505
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010506 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010507
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010508 SourceLocation Open = E->getSourceRange().getBegin();
10509 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10510 Diag(Loc, diag::note_condition_assign_silence)
10511 << FixItHint::CreateInsertion(Open, "(")
10512 << FixItHint::CreateInsertion(Close, ")");
10513
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010514 if (IsOrAssign)
10515 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10516 << FixItHint::CreateReplacement(Loc, "!=");
10517 else
10518 Diag(Loc, diag::note_condition_assign_to_comparison)
10519 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010520}
10521
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010522/// \brief Redundant parentheses over an equality comparison can indicate
10523/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000010524void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010525 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000010526 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010527 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10528 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010529 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000010530 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010531 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010532
Richard Trieuba63ce62011-09-09 01:45:06 +000010533 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010534
10535 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010536 if (opE->getOpcode() == BO_EQ &&
10537 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10538 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010539 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010540
Ted Kremenekae022092011-02-02 02:20:30 +000010541 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010542 Diag(Loc, diag::note_equality_comparison_silence)
Richard Trieuba63ce62011-09-09 01:45:06 +000010543 << FixItHint::CreateRemoval(ParenE->getSourceRange().getBegin())
10544 << FixItHint::CreateRemoval(ParenE->getSourceRange().getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010545 Diag(Loc, diag::note_equality_comparison_to_assign)
10546 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010547 }
10548}
10549
John Wiegley01296292011-04-08 18:41:53 +000010550ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010551 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010552 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10553 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010554
John McCall0009fcc2011-04-26 20:42:42 +000010555 ExprResult result = CheckPlaceholderExpr(E);
10556 if (result.isInvalid()) return ExprError();
10557 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010558
John McCall0009fcc2011-04-26 20:42:42 +000010559 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010560 if (getLangOptions().CPlusPlus)
10561 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10562
John Wiegley01296292011-04-08 18:41:53 +000010563 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10564 if (ERes.isInvalid())
10565 return ExprError();
10566 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010567
10568 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010569 if (!T->isScalarType()) { // C99 6.8.4.1p1
10570 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10571 << T << E->getSourceRange();
10572 return ExprError();
10573 }
John McCalld5707ab2009-10-12 21:59:07 +000010574 }
10575
John Wiegley01296292011-04-08 18:41:53 +000010576 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010577}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010578
John McCalldadc5752010-08-24 06:29:42 +000010579ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010580 Expr *SubExpr) {
10581 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010582 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010583
Richard Trieuba63ce62011-09-09 01:45:06 +000010584 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010585}
John McCall36e7fe32010-10-12 00:20:44 +000010586
John McCall31996342011-04-07 08:22:57 +000010587namespace {
John McCall2979fe02011-04-12 00:42:48 +000010588 /// A visitor for rebuilding a call to an __unknown_any expression
10589 /// to have an appropriate type.
10590 struct RebuildUnknownAnyFunction
10591 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10592
10593 Sema &S;
10594
10595 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10596
10597 ExprResult VisitStmt(Stmt *S) {
10598 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000010599 }
10600
Richard Trieu10162ab2011-09-09 03:59:41 +000010601 ExprResult VisitExpr(Expr *E) {
10602 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
10603 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010604 return ExprError();
10605 }
10606
10607 /// Rebuild an expression which simply semantically wraps another
10608 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010609 template <class T> ExprResult rebuildSugarExpr(T *E) {
10610 ExprResult SubResult = Visit(E->getSubExpr());
10611 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010612
Richard Trieu10162ab2011-09-09 03:59:41 +000010613 Expr *SubExpr = SubResult.take();
10614 E->setSubExpr(SubExpr);
10615 E->setType(SubExpr->getType());
10616 E->setValueKind(SubExpr->getValueKind());
10617 assert(E->getObjectKind() == OK_Ordinary);
10618 return E;
John McCall2979fe02011-04-12 00:42:48 +000010619 }
10620
Richard Trieu10162ab2011-09-09 03:59:41 +000010621 ExprResult VisitParenExpr(ParenExpr *E) {
10622 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010623 }
10624
Richard Trieu10162ab2011-09-09 03:59:41 +000010625 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10626 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010627 }
10628
Richard Trieu10162ab2011-09-09 03:59:41 +000010629 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10630 ExprResult SubResult = Visit(E->getSubExpr());
10631 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010632
Richard Trieu10162ab2011-09-09 03:59:41 +000010633 Expr *SubExpr = SubResult.take();
10634 E->setSubExpr(SubExpr);
10635 E->setType(S.Context.getPointerType(SubExpr->getType()));
10636 assert(E->getValueKind() == VK_RValue);
10637 assert(E->getObjectKind() == OK_Ordinary);
10638 return E;
John McCall2979fe02011-04-12 00:42:48 +000010639 }
10640
Richard Trieu10162ab2011-09-09 03:59:41 +000010641 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
10642 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010643
Richard Trieu10162ab2011-09-09 03:59:41 +000010644 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000010645
Richard Trieu10162ab2011-09-09 03:59:41 +000010646 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +000010647 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000010648 !(isa<CXXMethodDecl>(VD) &&
10649 cast<CXXMethodDecl>(VD)->isInstance()))
10650 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000010651
Richard Trieu10162ab2011-09-09 03:59:41 +000010652 return E;
John McCall2979fe02011-04-12 00:42:48 +000010653 }
10654
Richard Trieu10162ab2011-09-09 03:59:41 +000010655 ExprResult VisitMemberExpr(MemberExpr *E) {
10656 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010657 }
10658
Richard Trieu10162ab2011-09-09 03:59:41 +000010659 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10660 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000010661 }
10662 };
10663}
10664
10665/// Given a function expression of unknown-any type, try to rebuild it
10666/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010667static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
10668 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
10669 if (Result.isInvalid()) return ExprError();
10670 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000010671}
10672
10673namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010674 /// A visitor for rebuilding an expression of type __unknown_anytype
10675 /// into one which resolves the type directly on the referring
10676 /// expression. Strict preservation of the original source
10677 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010678 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010679 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010680
10681 Sema &S;
10682
10683 /// The current destination type.
10684 QualType DestType;
10685
Richard Trieu10162ab2011-09-09 03:59:41 +000010686 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
10687 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000010688
John McCall39439732011-04-09 22:50:59 +000010689 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010690 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000010691 }
10692
Richard Trieu10162ab2011-09-09 03:59:41 +000010693 ExprResult VisitExpr(Expr *E) {
10694 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10695 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010696 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010697 }
10698
Richard Trieu10162ab2011-09-09 03:59:41 +000010699 ExprResult VisitCallExpr(CallExpr *E);
10700 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000010701
John McCall39439732011-04-09 22:50:59 +000010702 /// Rebuild an expression which simply semantically wraps another
10703 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010704 template <class T> ExprResult rebuildSugarExpr(T *E) {
10705 ExprResult SubResult = Visit(E->getSubExpr());
10706 if (SubResult.isInvalid()) return ExprError();
10707 Expr *SubExpr = SubResult.take();
10708 E->setSubExpr(SubExpr);
10709 E->setType(SubExpr->getType());
10710 E->setValueKind(SubExpr->getValueKind());
10711 assert(E->getObjectKind() == OK_Ordinary);
10712 return E;
John McCall39439732011-04-09 22:50:59 +000010713 }
John McCall31996342011-04-07 08:22:57 +000010714
Richard Trieu10162ab2011-09-09 03:59:41 +000010715 ExprResult VisitParenExpr(ParenExpr *E) {
10716 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010717 }
10718
Richard Trieu10162ab2011-09-09 03:59:41 +000010719 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10720 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010721 }
10722
Richard Trieu10162ab2011-09-09 03:59:41 +000010723 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10724 const PointerType *Ptr = DestType->getAs<PointerType>();
10725 if (!Ptr) {
10726 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
10727 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010728 return ExprError();
10729 }
Richard Trieu10162ab2011-09-09 03:59:41 +000010730 assert(E->getValueKind() == VK_RValue);
10731 assert(E->getObjectKind() == OK_Ordinary);
10732 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010733
10734 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010735 DestType = Ptr->getPointeeType();
10736 ExprResult SubResult = Visit(E->getSubExpr());
10737 if (SubResult.isInvalid()) return ExprError();
10738 E->setSubExpr(SubResult.take());
10739 return E;
John McCall2979fe02011-04-12 00:42:48 +000010740 }
10741
Richard Trieu10162ab2011-09-09 03:59:41 +000010742 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000010743
Richard Trieu10162ab2011-09-09 03:59:41 +000010744 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000010745
Richard Trieu10162ab2011-09-09 03:59:41 +000010746 ExprResult VisitMemberExpr(MemberExpr *E) {
10747 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010748 }
John McCall39439732011-04-09 22:50:59 +000010749
Richard Trieu10162ab2011-09-09 03:59:41 +000010750 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10751 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000010752 }
10753 };
10754}
10755
John McCall2d2e8702011-04-11 07:02:50 +000010756/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000010757ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
10758 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010759
10760 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010761 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010762 FK_FunctionPointer,
10763 FK_BlockPointer
10764 };
10765
Richard Trieu10162ab2011-09-09 03:59:41 +000010766 FnKind Kind;
10767 QualType CalleeType = CalleeExpr->getType();
10768 if (CalleeType == S.Context.BoundMemberTy) {
10769 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
10770 Kind = FK_MemberFunction;
10771 CalleeType = Expr::findBoundMemberType(CalleeExpr);
10772 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
10773 CalleeType = Ptr->getPointeeType();
10774 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000010775 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010776 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
10777 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000010778 }
Richard Trieu10162ab2011-09-09 03:59:41 +000010779 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000010780
10781 // Verify that this is a legal result type of a function.
10782 if (DestType->isArrayType() || DestType->isFunctionType()) {
10783 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000010784 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000010785 diagID = diag::err_block_returning_array_function;
10786
Richard Trieu10162ab2011-09-09 03:59:41 +000010787 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000010788 << DestType->isFunctionType() << DestType;
10789 return ExprError();
10790 }
10791
10792 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000010793 E->setType(DestType.getNonLValueExprType(S.Context));
10794 E->setValueKind(Expr::getValueKindForType(DestType));
10795 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010796
10797 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000010798 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000010799 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000010800 Proto->arg_type_begin(),
10801 Proto->getNumArgs(),
10802 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000010803 else
10804 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000010805 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000010806
10807 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010808 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010809 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010810 // Nothing to do.
10811 break;
10812
10813 case FK_FunctionPointer:
10814 DestType = S.Context.getPointerType(DestType);
10815 break;
10816
10817 case FK_BlockPointer:
10818 DestType = S.Context.getBlockPointerType(DestType);
10819 break;
10820 }
10821
10822 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000010823 ExprResult CalleeResult = Visit(CalleeExpr);
10824 if (!CalleeResult.isUsable()) return ExprError();
10825 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000010826
10827 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000010828 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010829}
10830
Richard Trieu10162ab2011-09-09 03:59:41 +000010831ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010832 // Verify that this is a legal result type of a call.
10833 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000010834 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000010835 << DestType->isFunctionType() << DestType;
10836 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010837 }
10838
John McCall3f4138c2011-07-13 17:56:40 +000010839 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000010840 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
10841 assert(Method->getResultType() == S.Context.UnknownAnyTy);
10842 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000010843 }
John McCall2979fe02011-04-12 00:42:48 +000010844
John McCall2d2e8702011-04-11 07:02:50 +000010845 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000010846 E->setType(DestType.getNonReferenceType());
10847 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010848
Richard Trieu10162ab2011-09-09 03:59:41 +000010849 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010850}
10851
Richard Trieu10162ab2011-09-09 03:59:41 +000010852ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010853 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000010854 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000010855 assert(E->getValueKind() == VK_RValue);
10856 assert(E->getObjectKind() == OK_Ordinary);
10857
10858 E->setType(DestType);
10859
10860 // Rebuild the sub-expression as the pointee (function) type.
10861 DestType = DestType->castAs<PointerType>()->getPointeeType();
10862
10863 ExprResult Result = Visit(E->getSubExpr());
10864 if (!Result.isUsable()) return ExprError();
10865
10866 E->setSubExpr(Result.take());
10867 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000010868 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000010869 assert(E->getValueKind() == VK_RValue);
10870 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010871
Sean Callanan12495112012-03-06 21:34:12 +000010872 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000010873
Sean Callanan12495112012-03-06 21:34:12 +000010874 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000010875
Sean Callanan12495112012-03-06 21:34:12 +000010876 // The sub-expression has to be a lvalue reference, so rebuild it as such.
10877 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000010878
Sean Callanan12495112012-03-06 21:34:12 +000010879 ExprResult Result = Visit(E->getSubExpr());
10880 if (!Result.isUsable()) return ExprError();
10881
10882 E->setSubExpr(Result.take());
10883 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000010884 } else {
Sean Callanan12495112012-03-06 21:34:12 +000010885 llvm_unreachable("Unhandled cast type!");
10886 }
John McCall2d2e8702011-04-11 07:02:50 +000010887}
10888
Richard Trieu10162ab2011-09-09 03:59:41 +000010889ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
10890 ExprValueKind ValueKind = VK_LValue;
10891 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000010892
10893 // We know how to make this work for certain kinds of decls:
10894
10895 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000010896 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
10897 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
10898 DestType = Ptr->getPointeeType();
10899 ExprResult Result = resolveDecl(E, VD);
10900 if (Result.isInvalid()) return ExprError();
10901 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000010902 CK_FunctionToPointerDecay, VK_RValue);
10903 }
10904
Richard Trieu10162ab2011-09-09 03:59:41 +000010905 if (!Type->isFunctionType()) {
10906 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
10907 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000010908 return ExprError();
10909 }
John McCall2d2e8702011-04-11 07:02:50 +000010910
Richard Trieu10162ab2011-09-09 03:59:41 +000010911 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
10912 if (MD->isInstance()) {
10913 ValueKind = VK_RValue;
10914 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000010915 }
10916
John McCall2d2e8702011-04-11 07:02:50 +000010917 // Function references aren't l-values in C.
10918 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000010919 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000010920
10921 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000010922 } else if (isa<VarDecl>(VD)) {
10923 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
10924 Type = RefTy->getPointeeType();
10925 } else if (Type->isFunctionType()) {
10926 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
10927 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010928 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010929 }
10930
10931 // - nothing else
10932 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010933 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
10934 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010935 return ExprError();
10936 }
10937
Richard Trieu10162ab2011-09-09 03:59:41 +000010938 VD->setType(DestType);
10939 E->setType(Type);
10940 E->setValueKind(ValueKind);
10941 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000010942}
10943
John McCall31996342011-04-07 08:22:57 +000010944/// Check a cast of an unknown-any type. We intentionally only
10945/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000010946ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
10947 Expr *CastExpr, CastKind &CastKind,
10948 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000010949 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000010950 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000010951 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000010952
Richard Trieuba63ce62011-09-09 01:45:06 +000010953 CastExpr = result.take();
10954 VK = CastExpr->getValueKind();
10955 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000010956
Richard Trieuba63ce62011-09-09 01:45:06 +000010957 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000010958}
10959
Douglas Gregord8fb1e32011-12-01 01:37:36 +000010960ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
10961 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
10962}
10963
Richard Trieuba63ce62011-09-09 01:45:06 +000010964static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
10965 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000010966 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000010967 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000010968 E = E->IgnoreParenImpCasts();
10969 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
10970 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010971 diagID = diag::err_uncasted_call_of_unknown_any;
10972 } else {
John McCall31996342011-04-07 08:22:57 +000010973 break;
John McCall2d2e8702011-04-11 07:02:50 +000010974 }
John McCall31996342011-04-07 08:22:57 +000010975 }
10976
John McCall2d2e8702011-04-11 07:02:50 +000010977 SourceLocation loc;
10978 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000010979 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010980 loc = ref->getLocation();
10981 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010982 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010983 loc = mem->getMemberLoc();
10984 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000010985 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000010986 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000010987 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000010988 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000010989 if (!d) {
10990 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
10991 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
10992 << orig->getSourceRange();
10993 return ExprError();
10994 }
John McCall2d2e8702011-04-11 07:02:50 +000010995 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000010996 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10997 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010998 return ExprError();
10999 }
11000
11001 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011002
11003 // Never recoverable.
11004 return ExprError();
11005}
11006
John McCall36e7fe32010-10-12 00:20:44 +000011007/// Check for operands with placeholder types and complain if found.
11008/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011009ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011010 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11011 if (!placeholderType) return Owned(E);
11012
11013 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011014
John McCall31996342011-04-07 08:22:57 +000011015 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011016 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011017 // Try to resolve a single function template specialization.
11018 // This is obligatory.
11019 ExprResult result = Owned(E);
11020 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11021 return result;
11022
11023 // If that failed, try to recover with a call.
11024 } else {
11025 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11026 /*complain*/ true);
11027 return result;
11028 }
11029 }
John McCall31996342011-04-07 08:22:57 +000011030
John McCall0009fcc2011-04-26 20:42:42 +000011031 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011032 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011033 ExprResult result = Owned(E);
11034 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11035 /*complain*/ true);
11036 return result;
John McCall4124c492011-10-17 18:40:02 +000011037 }
11038
11039 // ARC unbridged casts.
11040 case BuiltinType::ARCUnbridgedCast: {
11041 Expr *realCast = stripARCUnbridgedCast(E);
11042 diagnoseARCUnbridgedCast(realCast);
11043 return Owned(realCast);
11044 }
John McCall0009fcc2011-04-26 20:42:42 +000011045
John McCall31996342011-04-07 08:22:57 +000011046 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011047 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011048 return diagnoseUnknownAnyExpr(*this, E);
11049
John McCall526ab472011-10-25 17:37:35 +000011050 // Pseudo-objects.
11051 case BuiltinType::PseudoObject:
11052 return checkPseudoObjectRValue(E);
11053
John McCalle314e272011-10-18 21:02:43 +000011054 // Everything else should be impossible.
11055#define BUILTIN_TYPE(Id, SingletonId) \
11056 case BuiltinType::Id:
11057#define PLACEHOLDER_TYPE(Id, SingletonId)
11058#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011059 break;
11060 }
11061
11062 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011063}
Richard Trieu2c850c02011-04-21 21:44:26 +000011064
Richard Trieuba63ce62011-09-09 01:45:06 +000011065bool Sema::CheckCaseExpression(Expr *E) {
11066 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011067 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011068 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11069 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011070 return false;
11071}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011072
11073/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11074ExprResult
11075Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11076 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11077 "Unknown Objective-C Boolean value!");
11078 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11079 Context.ObjCBuiltinBoolTy, OpLoc));
11080}