blob: 85778e4a439a6a09fa4d44f7c29afa271eea74d5 [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
Richard Smithbcc22fc2012-03-09 08:00:36 +00001133/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1134/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1135static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1136 IdentifierInfo *UDSuffix,
1137 SourceLocation UDSuffixLoc,
1138 ArrayRef<Expr*> Args,
1139 SourceLocation LitEndLoc) {
1140 assert(Args.size() <= 2 && "too many arguments for literal operator");
1141
1142 QualType ArgTy[2];
1143 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1144 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1145 if (ArgTy[ArgIdx]->isArrayType())
1146 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1147 }
1148
1149 DeclarationName OpName =
1150 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1151 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1152 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1153
1154 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1155 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1156 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1157 return ExprError();
1158
1159 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1160}
1161
Steve Naroff83895f72007-09-16 03:34:24 +00001162/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001163/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1164/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1165/// multiple tokens. However, the common case is that StringToks points to one
1166/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001167///
John McCalldadc5752010-08-24 06:29:42 +00001168ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001169Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1170 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001171 assert(NumStringToks && "Must have at least one string!");
1172
Chris Lattner8a24e582009-01-16 18:51:42 +00001173 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001174 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001175 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001176
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001177 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001178 for (unsigned i = 0; i != NumStringToks; ++i)
1179 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001180
Chris Lattner36fc8792008-02-11 00:02:17 +00001181 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001182 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001183 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001184 else if (Literal.isUTF16())
1185 StrTy = Context.Char16Ty;
1186 else if (Literal.isUTF32())
1187 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001188 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001189 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001190
Douglas Gregorfb65e592011-07-27 05:40:30 +00001191 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1192 if (Literal.isWide())
1193 Kind = StringLiteral::Wide;
1194 else if (Literal.isUTF8())
1195 Kind = StringLiteral::UTF8;
1196 else if (Literal.isUTF16())
1197 Kind = StringLiteral::UTF16;
1198 else if (Literal.isUTF32())
1199 Kind = StringLiteral::UTF32;
1200
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001201 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
Chris Lattnera8687ae2010-06-15 18:05:34 +00001202 if (getLangOptions().CPlusPlus || getLangOptions().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001203 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001204
Chris Lattner36fc8792008-02-11 00:02:17 +00001205 // Get an array type for the string, according to C99 6.4.5. This includes
1206 // the nul terminator character as well as the string length for pascal
1207 // strings.
1208 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001209 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001210 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001211
Chris Lattner5b183d82006-11-10 05:03:26 +00001212 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001213 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1214 Kind, Literal.Pascal, StrTy,
1215 &StringTokLocs[0],
1216 StringTokLocs.size());
1217 if (Literal.getUDSuffix().empty())
1218 return Owned(Lit);
1219
1220 // We're building a user-defined literal.
1221 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001222 SourceLocation UDSuffixLoc =
1223 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1224 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001225
Richard Smithbcc22fc2012-03-09 08:00:36 +00001226 // Make sure we're allowed user-defined literals here.
1227 if (!UDLScope)
1228 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1229
Richard Smithc67fdd42012-03-07 08:35:16 +00001230 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1231 // operator "" X (str, len)
1232 QualType SizeType = Context.getSizeType();
1233 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1234 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1235 StringTokLocs[0]);
1236 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001237 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1238 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001239}
1240
John McCalldadc5752010-08-24 06:29:42 +00001241ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001242Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001243 SourceLocation Loc,
1244 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001245 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001246 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001247}
1248
John McCallf4cd4f92011-02-09 01:13:10 +00001249/// BuildDeclRefExpr - Build an expression that references a
1250/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001251ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001252Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001253 const DeclarationNameInfo &NameInfo,
1254 const CXXScopeSpec *SS) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001255 if (getLangOptions().CUDA)
1256 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1257 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1258 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1259 CalleeTarget = IdentifyCUDATarget(Callee);
1260 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1261 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1262 << CalleeTarget << D->getIdentifier() << CallerTarget;
1263 Diag(D->getLocation(), diag::note_previous_decl)
1264 << D->getIdentifier();
1265 return ExprError();
1266 }
1267 }
1268
Eli Friedmanfa0df832012-02-02 03:46:19 +00001269 DeclRefExpr *E = DeclRefExpr::Create(Context,
1270 SS ? SS->getWithLocInContext(Context)
1271 : NestedNameSpecifierLoc(),
1272 SourceLocation(),
1273 D, NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001274
Eli Friedmanfa0df832012-02-02 03:46:19 +00001275 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001276
1277 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001278 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1279 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001280 E->setObjectKind(OK_BitField);
1281
1282 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001283}
1284
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001285/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001286/// possibly a list of template arguments.
1287///
1288/// If this produces template arguments, it is permitted to call
1289/// DecomposeTemplateName.
1290///
1291/// This actually loses a lot of source location information for
1292/// non-standard name kinds; we should consider preserving that in
1293/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001294void
1295Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1296 TemplateArgumentListInfo &Buffer,
1297 DeclarationNameInfo &NameInfo,
1298 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001299 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1300 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1301 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1302
Douglas Gregor5476205b2011-06-23 00:49:38 +00001303 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001304 Id.TemplateId->getTemplateArgs(),
1305 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001306 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001307 TemplateArgsPtr.release();
1308
John McCall3e56fd42010-08-23 07:28:44 +00001309 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001310 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001311 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001312 TemplateArgs = &Buffer;
1313 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001314 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001315 TemplateArgs = 0;
1316 }
1317}
1318
John McCalld681c392009-12-16 08:11:27 +00001319/// Diagnose an empty lookup.
1320///
1321/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001322bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001323 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001324 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001325 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001326 DeclarationName Name = R.getLookupName();
1327
John McCalld681c392009-12-16 08:11:27 +00001328 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001329 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001330 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1331 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001332 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001333 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001334 diagnostic_suggest = diag::err_undeclared_use_suggest;
1335 }
John McCalld681c392009-12-16 08:11:27 +00001336
Douglas Gregor598b08f2009-12-31 05:20:13 +00001337 // If the original lookup was an unqualified lookup, fake an
1338 // unqualified lookup. This is useful when (for example) the
1339 // original lookup would not have found something because it was a
1340 // dependent name.
Francois Pichetde232cb2011-11-25 01:10:54 +00001341 DeclContext *DC = SS.isEmpty() ? CurContext : 0;
1342 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001343 if (isa<CXXRecordDecl>(DC)) {
1344 LookupQualifiedName(R, DC);
1345
1346 if (!R.empty()) {
1347 // Don't give errors about ambiguities in this lookup.
1348 R.suppressDiagnostics();
1349
Francois Pichet857f9d62011-11-17 03:44:24 +00001350 // During a default argument instantiation the CurContext points
1351 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1352 // function parameter list, hence add an explicit check.
1353 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1354 ActiveTemplateInstantiations.back().Kind ==
1355 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001356 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1357 bool isInstance = CurMethod &&
1358 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001359 DC == CurMethod->getParent() && !isDefaultArgument;
1360
John McCalld681c392009-12-16 08:11:27 +00001361
1362 // Give a code modification hint to insert 'this->'.
1363 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1364 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001365 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001366 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1367 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001368 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001369 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001370 if (DepMethod) {
Francois Pichet78286b22011-11-15 23:33:34 +00001371 if (getLangOptions().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001372 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001373 Diag(R.getNameLoc(), diagnostic) << Name
1374 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1375 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001376 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001377 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1378 R.getNameLoc(), DepThisType, false);
1379 TemplateArgumentListInfo TList;
1380 if (ULE->hasExplicitTemplateArgs())
1381 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001382
Douglas Gregore16af532011-02-28 18:50:33 +00001383 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001384 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001385 CXXDependentScopeMemberExpr *DepExpr =
1386 CXXDependentScopeMemberExpr::Create(
1387 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001388 SS.getWithLocInContext(Context),
1389 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001390 R.getLookupNameInfo(),
1391 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001392 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001393 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001394 // FIXME: we should be able to handle this case too. It is correct
1395 // to add this-> here. This is a workaround for PR7947.
1396 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001397 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001398 } else {
Francois Pichet78286b22011-11-15 23:33:34 +00001399 if (getLangOptions().MicrosoftMode)
1400 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001401 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001402 }
John McCalld681c392009-12-16 08:11:27 +00001403
1404 // Do we really want to note all of these?
1405 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1406 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1407
Francois Pichet857f9d62011-11-17 03:44:24 +00001408 // Return true if we are inside a default argument instantiation
1409 // and the found name refers to an instance member function, otherwise
1410 // the function calling DiagnoseEmptyLookup will try to create an
1411 // implicit member call and this is wrong for default argument.
1412 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1413 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1414 return true;
1415 }
1416
John McCalld681c392009-12-16 08:11:27 +00001417 // Tell the callee to try to recover.
1418 return false;
1419 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001420
1421 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001422 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001423
1424 // In Microsoft mode, if we are performing lookup from within a friend
1425 // function definition declared at class scope then we must set
1426 // DC to the lexical parent to be able to search into the parent
1427 // class.
Lang Hamesc8c3b402011-11-29 22:37:13 +00001428 if (getLangOptions().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001429 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1430 DC->getLexicalParent()->isRecord())
1431 DC = DC->getLexicalParent();
1432 else
1433 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001434 }
1435
Douglas Gregor598b08f2009-12-31 05:20:13 +00001436 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001437 TypoCorrection Corrected;
1438 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001439 S, &SS, CCC))) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001440 std::string CorrectedStr(Corrected.getAsString(getLangOptions()));
1441 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOptions()));
1442 R.setLookupName(Corrected.getCorrection());
1443
Hans Wennborg38198de2011-07-12 08:45:31 +00001444 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001445 if (Corrected.isOverloaded()) {
1446 OverloadCandidateSet OCS(R.getNameLoc());
1447 OverloadCandidateSet::iterator Best;
1448 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1449 CDEnd = Corrected.end();
1450 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001451 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001452 dyn_cast<FunctionTemplateDecl>(*CD))
1453 AddTemplateOverloadCandidate(
1454 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001455 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001456 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1457 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1458 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001459 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001460 }
1461 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1462 case OR_Success:
1463 ND = Best->Function;
1464 break;
1465 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001466 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001467 }
1468 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001469 R.addDecl(ND);
1470 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001471 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001472 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1473 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001474 else
1475 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001476 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001477 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001478 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1479 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001480 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001481 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001482
1483 // Tell the callee to try to recover.
1484 return false;
1485 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001486
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001487 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001488 // FIXME: If we ended up with a typo for a type name or
1489 // Objective-C class name, we're in trouble because the parser
1490 // is in the wrong place to recover. Suggest the typo
1491 // correction, but don't make it a fix-it since we're not going
1492 // to recover well anyway.
1493 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001494 Diag(R.getNameLoc(), diagnostic_suggest)
1495 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001496 else
1497 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001498 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001499 << SS.getRange();
1500
1501 // Don't try to recover; it won't work.
1502 return true;
1503 }
1504 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001505 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001506 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001507 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001508 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001509 else
Douglas Gregor25363982010-01-01 00:15:04 +00001510 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001511 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001512 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001513 return true;
1514 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001515 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001516 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001517
1518 // Emit a special diagnostic for failed member lookups.
1519 // FIXME: computing the declaration context might fail here (?)
1520 if (!SS.isEmpty()) {
1521 Diag(R.getNameLoc(), diag::err_no_member)
1522 << Name << computeDeclContext(SS, false)
1523 << SS.getRange();
1524 return true;
1525 }
1526
John McCalld681c392009-12-16 08:11:27 +00001527 // Give up, we can't recover.
1528 Diag(R.getNameLoc(), diagnostic) << Name;
1529 return true;
1530}
1531
John McCalldadc5752010-08-24 06:29:42 +00001532ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001533 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001534 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001535 UnqualifiedId &Id,
1536 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001537 bool IsAddressOfOperand,
1538 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001539 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001540 "cannot be direct & operand and have a trailing lparen");
1541
1542 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001543 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001544
John McCall10eae182009-11-30 22:42:35 +00001545 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001546
1547 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001548 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001549 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001550 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001551
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001552 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001553 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001554 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001555
John McCalle66edc12009-11-24 19:00:30 +00001556 // C++ [temp.dep.expr]p3:
1557 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001558 // -- an identifier that was declared with a dependent type,
1559 // (note: handled after lookup)
1560 // -- a template-id that is dependent,
1561 // (note: handled in BuildTemplateIdExpr)
1562 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001563 // -- a nested-name-specifier that contains a class-name that
1564 // names a dependent type.
1565 // Determine whether this is a member of an unknown specialization;
1566 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001567 bool DependentID = false;
1568 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1569 Name.getCXXNameType()->isDependentType()) {
1570 DependentID = true;
1571 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001572 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001573 if (RequireCompleteDeclContext(SS, DC))
1574 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001575 } else {
1576 DependentID = true;
1577 }
1578 }
1579
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001580 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001581 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1582 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001583
John McCalle66edc12009-11-24 19:00:30 +00001584 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001585 LookupResult R(*this, NameInfo,
1586 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1587 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001588 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001589 // Lookup the template name again to correctly establish the context in
1590 // which it was found. This is really unfortunate as we already did the
1591 // lookup to determine that it was a template name in the first place. If
1592 // this becomes a performance hit, we can work harder to preserve those
1593 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001594 bool MemberOfUnknownSpecialization;
1595 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1596 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001597
1598 if (MemberOfUnknownSpecialization ||
1599 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001600 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1601 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001602 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001603 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001604 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001605
Douglas Gregora5226932011-02-04 13:35:07 +00001606 // If the result might be in a dependent base class, this is a dependent
1607 // id-expression.
1608 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001609 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1610 IsAddressOfOperand, TemplateArgs);
1611
John McCalle66edc12009-11-24 19:00:30 +00001612 // If this reference is in an Objective-C method, then we need to do
1613 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001614 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001615 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001616 if (E.isInvalid())
1617 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001618
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001619 if (Expr *Ex = E.takeAs<Expr>())
1620 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001621 }
Chris Lattner59a25942008-03-31 00:36:02 +00001622 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001623
John McCalle66edc12009-11-24 19:00:30 +00001624 if (R.isAmbiguous())
1625 return ExprError();
1626
Douglas Gregor171c45a2009-02-18 21:56:37 +00001627 // Determine whether this name might be a candidate for
1628 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001629 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001630
John McCalle66edc12009-11-24 19:00:30 +00001631 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001632 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001633 // in C90, extension in C99, forbidden in C++).
1634 if (HasTrailingLParen && II && !getLangOptions().CPlusPlus) {
1635 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1636 if (D) R.addDecl(D);
1637 }
1638
1639 // If this name wasn't predeclared and if this is not a function
1640 // call, diagnose the problem.
1641 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001642
1643 // In Microsoft mode, if we are inside a template class member function
1644 // and we can't resolve an identifier then assume the identifier is type
1645 // dependent. The goal is to postpone name lookup to instantiation time
1646 // to be able to search into type dependent base classes.
1647 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
1648 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001649 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1650 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001651
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001652 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001653 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001654 return ExprError();
1655
1656 assert(!R.empty() &&
1657 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001658
1659 // If we found an Objective-C instance variable, let
1660 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001661 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001662 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1663 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001664 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001665 // In a hopelessly buggy code, Objective-C instance variable
1666 // lookup fails and no expression will be built to reference it.
1667 if (!E.isInvalid() && !E.get())
1668 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001669 return move(E);
1670 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001671 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001672 }
Mike Stump11289f42009-09-09 15:08:12 +00001673
John McCalle66edc12009-11-24 19:00:30 +00001674 // This is guaranteed from this point on.
1675 assert(!R.empty() || ADL);
1676
John McCall2d74de92009-12-01 22:10:20 +00001677 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001678 // C++ [class.mfct.non-static]p3:
1679 // When an id-expression that is not part of a class member access
1680 // syntax and not used to form a pointer to member is used in the
1681 // body of a non-static member function of class X, if name lookup
1682 // resolves the name in the id-expression to a non-static non-type
1683 // member of some class C, the id-expression is transformed into a
1684 // class member access expression using (*this) as the
1685 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001686 //
1687 // But we don't actually need to do this for '&' operands if R
1688 // resolved to a function or overloaded function set, because the
1689 // expression is ill-formed if it actually works out to be a
1690 // non-static member function:
1691 //
1692 // C++ [expr.ref]p4:
1693 // Otherwise, if E1.E2 refers to a non-static member function. . .
1694 // [t]he expression can be used only as the left-hand operand of a
1695 // member function call.
1696 //
1697 // There are other safeguards against such uses, but it's important
1698 // to get this right here so that we don't end up making a
1699 // spuriously dependent expression if we're inside a dependent
1700 // instance method.
John McCall57500772009-12-16 12:17:52 +00001701 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001702 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001703 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001704 MightBeImplicitMember = true;
1705 else if (!SS.isEmpty())
1706 MightBeImplicitMember = false;
1707 else if (R.isOverloadedResult())
1708 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001709 else if (R.isUnresolvableResult())
1710 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001711 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001712 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1713 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001714
1715 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001716 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1717 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001718 }
1719
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001720 if (TemplateArgs || TemplateKWLoc.isValid())
1721 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001722
John McCalle66edc12009-11-24 19:00:30 +00001723 return BuildDeclarationNameExpr(SS, R, ADL);
1724}
1725
John McCall10eae182009-11-30 22:42:35 +00001726/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1727/// declaration name, generally during template instantiation.
1728/// There's a large number of things which don't need to be done along
1729/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001730ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001731Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001732 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001733 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001734 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001735 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1736 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001737
John McCall0b66eb32010-05-01 00:40:08 +00001738 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001739 return ExprError();
1740
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001741 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001742 LookupQualifiedName(R, DC);
1743
1744 if (R.isAmbiguous())
1745 return ExprError();
1746
1747 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001748 Diag(NameInfo.getLoc(), diag::err_no_member)
1749 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001750 return ExprError();
1751 }
1752
1753 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1754}
1755
1756/// LookupInObjCMethod - The parser has read a name in, and Sema has
1757/// detected that we're currently inside an ObjC method. Perform some
1758/// additional lookup.
1759///
1760/// Ideally, most of this would be done by lookup, but there's
1761/// actually quite a lot of extra work involved.
1762///
1763/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001764ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001765Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001766 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001767 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001768 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001769
John McCalle66edc12009-11-24 19:00:30 +00001770 // There are two cases to handle here. 1) scoped lookup could have failed,
1771 // in which case we should look for an ivar. 2) scoped lookup could have
1772 // found a decl, but that decl is outside the current instance method (i.e.
1773 // a global variable). In these two cases, we do a lookup for an ivar with
1774 // this name, if the lookup sucedes, we replace it our current decl.
1775
1776 // If we're in a class method, we don't normally want to look for
1777 // ivars. But if we don't find anything else, and there's an
1778 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001779 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001780
1781 bool LookForIvars;
1782 if (Lookup.empty())
1783 LookForIvars = true;
1784 else if (IsClassMethod)
1785 LookForIvars = false;
1786 else
1787 LookForIvars = (Lookup.isSingleResult() &&
1788 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001789 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001790 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001791 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001792 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001793 ObjCIvarDecl *IV = 0;
1794 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001795 // Diagnose using an ivar in a class method.
1796 if (IsClassMethod)
1797 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1798 << IV->getDeclName());
1799
1800 // If we're referencing an invalid decl, just return this as a silent
1801 // error node. The error diagnostic was already emitted on the decl.
1802 if (IV->isInvalidDecl())
1803 return ExprError();
1804
1805 // Check if referencing a field with __attribute__((deprecated)).
1806 if (DiagnoseUseOfDecl(IV, Loc))
1807 return ExprError();
1808
1809 // Diagnose the use of an ivar outside of the declaring class.
1810 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001811 !declaresSameEntity(ClassDeclared, IFace) &&
1812 !getLangOptions().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001813 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1814
1815 // FIXME: This should use a new expr for a direct reference, don't
1816 // turn this into Self->ivar, just return a BareIVarExpr or something.
1817 IdentifierInfo &II = Context.Idents.get("self");
1818 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001819 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001820 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001821 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001822 SourceLocation TemplateKWLoc;
1823 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001824 SelfName, false, false);
1825 if (SelfExpr.isInvalid())
1826 return ExprError();
1827
John Wiegley01296292011-04-08 18:41:53 +00001828 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1829 if (SelfExpr.isInvalid())
1830 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001831
Eli Friedmanfa0df832012-02-02 03:46:19 +00001832 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001833 return Owned(new (Context)
1834 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001835 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001836 }
Chris Lattner87313662010-04-12 05:10:17 +00001837 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001838 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001839 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1840 ObjCInterfaceDecl *ClassDeclared;
1841 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1842 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001843 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001844 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1845 }
John McCalle66edc12009-11-24 19:00:30 +00001846 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001847 } else if (Lookup.isSingleResult() &&
1848 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1849 // If accessing a stand-alone ivar in a class method, this is an error.
1850 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1851 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1852 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001853 }
1854
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001855 if (Lookup.empty() && II && AllowBuiltinCreation) {
1856 // FIXME. Consolidate this with similar code in LookupName.
1857 if (unsigned BuiltinID = II->getBuiltinID()) {
1858 if (!(getLangOptions().CPlusPlus &&
1859 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1860 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1861 S, Lookup.isForRedeclaration(),
1862 Lookup.getNameLoc());
1863 if (D) Lookup.addDecl(D);
1864 }
1865 }
1866 }
John McCalle66edc12009-11-24 19:00:30 +00001867 // Sentinel value saying that we didn't do anything special.
1868 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001869}
John McCalld14a8642009-11-21 08:51:07 +00001870
John McCall16df1e52010-03-30 21:47:33 +00001871/// \brief Cast a base object to a member's actual type.
1872///
1873/// Logically this happens in three phases:
1874///
1875/// * First we cast from the base type to the naming class.
1876/// The naming class is the class into which we were looking
1877/// when we found the member; it's the qualifier type if a
1878/// qualifier was provided, and otherwise it's the base type.
1879///
1880/// * Next we cast from the naming class to the declaring class.
1881/// If the member we found was brought into a class's scope by
1882/// a using declaration, this is that class; otherwise it's
1883/// the class declaring the member.
1884///
1885/// * Finally we cast from the declaring class to the "true"
1886/// declaring class of the member. This conversion does not
1887/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001888ExprResult
1889Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001890 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001891 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001892 NamedDecl *Member) {
1893 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1894 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001895 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001896
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001897 QualType DestRecordType;
1898 QualType DestType;
1899 QualType FromRecordType;
1900 QualType FromType = From->getType();
1901 bool PointerConversions = false;
1902 if (isa<FieldDecl>(Member)) {
1903 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001904
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001905 if (FromType->getAs<PointerType>()) {
1906 DestType = Context.getPointerType(DestRecordType);
1907 FromRecordType = FromType->getPointeeType();
1908 PointerConversions = true;
1909 } else {
1910 DestType = DestRecordType;
1911 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001912 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001913 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1914 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001915 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001916
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001917 DestType = Method->getThisType(Context);
1918 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001919
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001920 if (FromType->getAs<PointerType>()) {
1921 FromRecordType = FromType->getPointeeType();
1922 PointerConversions = true;
1923 } else {
1924 FromRecordType = FromType;
1925 DestType = DestRecordType;
1926 }
1927 } else {
1928 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00001929 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001930 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001931
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001932 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00001933 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001934
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001935 // If the unqualified types are the same, no conversion is necessary.
1936 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001937 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001938
John McCall16df1e52010-03-30 21:47:33 +00001939 SourceRange FromRange = From->getSourceRange();
1940 SourceLocation FromLoc = FromRange.getBegin();
1941
Eli Friedmanbe4b3632011-09-27 21:58:52 +00001942 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001943
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001944 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001945 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001946 // class name.
1947 //
1948 // If the member was a qualified name and the qualified referred to a
1949 // specific base subobject type, we'll cast to that intermediate type
1950 // first and then to the object in which the member is declared. That allows
1951 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
1952 //
1953 // class Base { public: int x; };
1954 // class Derived1 : public Base { };
1955 // class Derived2 : public Base { };
1956 // class VeryDerived : public Derived1, public Derived2 { void f(); };
1957 //
1958 // void VeryDerived::f() {
1959 // x = 17; // error: ambiguous base subobjects
1960 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
1961 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001962 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00001963 QualType QType = QualType(Qualifier->getAsType(), 0);
1964 assert(!QType.isNull() && "lookup done with dependent qualifier?");
1965 assert(QType->isRecordType() && "lookup done with non-record type");
1966
1967 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
1968
1969 // In C++98, the qualifier type doesn't actually have to be a base
1970 // type of the object type, in which case we just ignore it.
1971 // Otherwise build the appropriate casts.
1972 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00001973 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00001974 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00001975 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00001976 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00001977
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001978 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00001979 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00001980 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
1981 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00001982
1983 FromType = QType;
1984 FromRecordType = QRecordType;
1985
1986 // If the qualifier type was the same as the destination type,
1987 // we're done.
1988 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00001989 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001990 }
1991 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001992
John McCall16df1e52010-03-30 21:47:33 +00001993 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001994
John McCall16df1e52010-03-30 21:47:33 +00001995 // If we actually found the member through a using declaration, cast
1996 // down to the using declaration's type.
1997 //
1998 // Pointer equality is fine here because only one declaration of a
1999 // class ever has member declarations.
2000 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2001 assert(isa<UsingShadowDecl>(FoundDecl));
2002 QualType URecordType = Context.getTypeDeclType(
2003 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2004
2005 // We only need to do this if the naming-class to declaring-class
2006 // conversion is non-trivial.
2007 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2008 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002009 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002010 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002011 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002012 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002013
John McCall16df1e52010-03-30 21:47:33 +00002014 QualType UType = URecordType;
2015 if (PointerConversions)
2016 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002017 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2018 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002019 FromType = UType;
2020 FromRecordType = URecordType;
2021 }
2022
2023 // We don't do access control for the conversion from the
2024 // declaring class to the true declaring class.
2025 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002026 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002027
John McCallcf142162010-08-07 06:22:56 +00002028 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002029 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2030 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002031 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002032 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002033
John Wiegley01296292011-04-08 18:41:53 +00002034 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2035 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002036}
Douglas Gregor3256d042009-06-30 15:47:41 +00002037
John McCalle66edc12009-11-24 19:00:30 +00002038bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002039 const LookupResult &R,
2040 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002041 // Only when used directly as the postfix-expression of a call.
2042 if (!HasTrailingLParen)
2043 return false;
2044
2045 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002046 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002047 return false;
2048
2049 // Only in C++ or ObjC++.
John McCallb53bbd42009-11-22 01:44:31 +00002050 if (!getLangOptions().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002051 return false;
2052
2053 // Turn off ADL when we find certain kinds of declarations during
2054 // normal lookup:
2055 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2056 NamedDecl *D = *I;
2057
2058 // C++0x [basic.lookup.argdep]p3:
2059 // -- a declaration of a class member
2060 // Since using decls preserve this property, we check this on the
2061 // original decl.
John McCall57500772009-12-16 12:17:52 +00002062 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002063 return false;
2064
2065 // C++0x [basic.lookup.argdep]p3:
2066 // -- a block-scope function declaration that is not a
2067 // using-declaration
2068 // NOTE: we also trigger this for function templates (in fact, we
2069 // don't check the decl type at all, since all other decl types
2070 // turn off ADL anyway).
2071 if (isa<UsingShadowDecl>(D))
2072 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2073 else if (D->getDeclContext()->isFunctionOrMethod())
2074 return false;
2075
2076 // C++0x [basic.lookup.argdep]p3:
2077 // -- a declaration that is neither a function or a function
2078 // template
2079 // And also for builtin functions.
2080 if (isa<FunctionDecl>(D)) {
2081 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2082
2083 // But also builtin functions.
2084 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2085 return false;
2086 } else if (!isa<FunctionTemplateDecl>(D))
2087 return false;
2088 }
2089
2090 return true;
2091}
2092
2093
John McCalld14a8642009-11-21 08:51:07 +00002094/// Diagnoses obvious problems with the use of the given declaration
2095/// as an expression. This is only actually called for lookups that
2096/// were not overloaded, and it doesn't promise that the declaration
2097/// will in fact be used.
2098static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002099 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002100 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2101 return true;
2102 }
2103
2104 if (isa<ObjCInterfaceDecl>(D)) {
2105 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2106 return true;
2107 }
2108
2109 if (isa<NamespaceDecl>(D)) {
2110 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2111 return true;
2112 }
2113
2114 return false;
2115}
2116
John McCalldadc5752010-08-24 06:29:42 +00002117ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002118Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002119 LookupResult &R,
2120 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002121 // If this is a single, fully-resolved result and we don't need ADL,
2122 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002123 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002124 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2125 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002126
2127 // We only need to check the declaration if there's exactly one
2128 // result, because in the overloaded case the results can only be
2129 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002130 if (R.isSingleResult() &&
2131 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002132 return ExprError();
2133
John McCall58cc69d2010-01-27 01:50:18 +00002134 // Otherwise, just build an unresolved lookup expression. Suppress
2135 // any lookup-related diagnostics; we'll hash these out later, when
2136 // we've picked a target.
2137 R.suppressDiagnostics();
2138
John McCalld14a8642009-11-21 08:51:07 +00002139 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002140 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002141 SS.getWithLocInContext(Context),
2142 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002143 NeedsADL, R.isOverloadedResult(),
2144 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002145
2146 return Owned(ULE);
2147}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002148
Eli Friedman9bb33f52012-02-03 02:04:35 +00002149static bool shouldBuildBlockDeclRef(ValueDecl *D, Sema &S) {
2150 // Check for a variable with local storage not from the current scope;
2151 // we need to create BlockDeclRefExprs for these.
2152 // FIXME: BlockDeclRefExpr shouldn't exist!
2153 VarDecl *var = dyn_cast<VarDecl>(D);
2154 if (!var)
2155 return false;
2156 if (var->getDeclContext() == S.CurContext)
2157 return false;
2158 if (!var->hasLocalStorage())
2159 return false;
2160 return S.getCurBlock() != 0;
2161}
2162
Eli Friedman9bb33f52012-02-03 02:04:35 +00002163static ExprResult BuildBlockDeclRefExpr(Sema &S, ValueDecl *VD,
2164 const DeclarationNameInfo &NameInfo) {
2165 VarDecl *var = cast<VarDecl>(VD);
2166 QualType exprType = var->getType().getNonReferenceType();
2167
2168 bool HasBlockAttr = var->hasAttr<BlocksAttr>();
2169 bool ConstAdded = false;
2170 if (!HasBlockAttr) {
2171 ConstAdded = !exprType.isConstQualified();
2172 exprType.addConst();
2173 }
2174
2175 BlockDeclRefExpr *BDRE =
2176 new (S.Context) BlockDeclRefExpr(var, exprType, VK_LValue,
2177 NameInfo.getLoc(), HasBlockAttr,
2178 ConstAdded);
2179
2180 S.MarkBlockDeclRefReferenced(BDRE);
2181
2182 return S.Owned(BDRE);
2183}
2184
John McCalld14a8642009-11-21 08:51:07 +00002185/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002186ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002187Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002188 const DeclarationNameInfo &NameInfo,
2189 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002190 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002191 assert(!isa<FunctionTemplateDecl>(D) &&
2192 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002193
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002194 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002195 if (CheckDeclInExpr(*this, Loc, D))
2196 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002197
Douglas Gregore7488b92009-12-01 16:58:18 +00002198 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2199 // Specifically diagnose references to class templates that are missing
2200 // a template argument list.
2201 Diag(Loc, diag::err_template_decl_ref)
2202 << Template << SS.getRange();
2203 Diag(Template->getLocation(), diag::note_template_decl_here);
2204 return ExprError();
2205 }
2206
2207 // Make sure that we're referring to a value.
2208 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2209 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002210 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002211 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002212 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002213 return ExprError();
2214 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002215
Douglas Gregor171c45a2009-02-18 21:56:37 +00002216 // Check whether this declaration can be used. Note that we suppress
2217 // this check when we're going to perform argument-dependent lookup
2218 // on this function name, because this might not be the function
2219 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002220 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002221 return ExprError();
2222
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002223 // Only create DeclRefExpr's for valid Decl's.
2224 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002225 return ExprError();
2226
John McCallf3a88602011-02-03 08:15:49 +00002227 // Handle members of anonymous structs and unions. If we got here,
2228 // and the reference is to a class member indirect field, then this
2229 // must be the subject of a pointer-to-member expression.
2230 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2231 if (!indirectField->isCXXClassMember())
2232 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2233 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002234
Eli Friedman9bb33f52012-02-03 02:04:35 +00002235 {
John McCallf4cd4f92011-02-09 01:13:10 +00002236 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002237 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002238
2239 switch (D->getKind()) {
2240 // Ignore all the non-ValueDecl kinds.
2241#define ABSTRACT_DECL(kind)
2242#define VALUE(type, base)
2243#define DECL(type, base) \
2244 case Decl::type:
2245#include "clang/AST/DeclNodes.inc"
2246 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002247
2248 // These shouldn't make it here.
2249 case Decl::ObjCAtDefsField:
2250 case Decl::ObjCIvar:
2251 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002252
2253 // Enum constants are always r-values and never references.
2254 // Unresolved using declarations are dependent.
2255 case Decl::EnumConstant:
2256 case Decl::UnresolvedUsingValue:
2257 valueKind = VK_RValue;
2258 break;
2259
2260 // Fields and indirect fields that got here must be for
2261 // pointer-to-member expressions; we just call them l-values for
2262 // internal consistency, because this subexpression doesn't really
2263 // exist in the high-level semantics.
2264 case Decl::Field:
2265 case Decl::IndirectField:
2266 assert(getLangOptions().CPlusPlus &&
2267 "building reference to field in C?");
2268
2269 // These can't have reference type in well-formed programs, but
2270 // for internal consistency we do this anyway.
2271 type = type.getNonReferenceType();
2272 valueKind = VK_LValue;
2273 break;
2274
2275 // Non-type template parameters are either l-values or r-values
2276 // depending on the type.
2277 case Decl::NonTypeTemplateParm: {
2278 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2279 type = reftype->getPointeeType();
2280 valueKind = VK_LValue; // even if the parameter is an r-value reference
2281 break;
2282 }
2283
2284 // For non-references, we need to strip qualifiers just in case
2285 // the template parameter was declared as 'const int' or whatever.
2286 valueKind = VK_RValue;
2287 type = type.getUnqualifiedType();
2288 break;
2289 }
2290
2291 case Decl::Var:
2292 // In C, "extern void blah;" is valid and is an r-value.
2293 if (!getLangOptions().CPlusPlus &&
2294 !type.hasQualifiers() &&
2295 type->isVoidType()) {
2296 valueKind = VK_RValue;
2297 break;
2298 }
2299 // fallthrough
2300
2301 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002302 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002303 // These are always l-values.
2304 valueKind = VK_LValue;
2305 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002306
2307 if (shouldBuildBlockDeclRef(VD, *this))
2308 return BuildBlockDeclRefExpr(*this, VD, NameInfo);
2309
Douglas Gregor812d8f62012-02-18 05:51:20 +00002310 // FIXME: Does the addition of const really only apply in
2311 // potentially-evaluated contexts? Since the variable isn't actually
2312 // captured in an unevaluated context, it seems that the answer is no.
2313 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2314 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2315 if (!CapturedType.isNull())
2316 type = CapturedType;
2317 }
2318
John McCallf4cd4f92011-02-09 01:13:10 +00002319 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002320 }
2321
John McCallf4cd4f92011-02-09 01:13:10 +00002322 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002323 const FunctionType *fty = type->castAs<FunctionType>();
2324
2325 // If we're referring to a function with an __unknown_anytype
2326 // result type, make the entire expression __unknown_anytype.
2327 if (fty->getResultType() == Context.UnknownAnyTy) {
2328 type = Context.UnknownAnyTy;
2329 valueKind = VK_RValue;
2330 break;
2331 }
2332
John McCallf4cd4f92011-02-09 01:13:10 +00002333 // Functions are l-values in C++.
2334 if (getLangOptions().CPlusPlus) {
2335 valueKind = VK_LValue;
2336 break;
2337 }
2338
2339 // C99 DR 316 says that, if a function type comes from a
2340 // function definition (without a prototype), that type is only
2341 // used for checking compatibility. Therefore, when referencing
2342 // the function, we pretend that we don't have the full function
2343 // type.
John McCall2979fe02011-04-12 00:42:48 +00002344 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2345 isa<FunctionProtoType>(fty))
2346 type = Context.getFunctionNoProtoType(fty->getResultType(),
2347 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002348
2349 // Functions are r-values in C.
2350 valueKind = VK_RValue;
2351 break;
2352 }
2353
2354 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002355 // If we're referring to a method with an __unknown_anytype
2356 // result type, make the entire expression __unknown_anytype.
2357 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002358 if (const FunctionProtoType *proto
2359 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002360 if (proto->getResultType() == Context.UnknownAnyTy) {
2361 type = Context.UnknownAnyTy;
2362 valueKind = VK_RValue;
2363 break;
2364 }
2365
John McCallf4cd4f92011-02-09 01:13:10 +00002366 // C++ methods are l-values if static, r-values if non-static.
2367 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2368 valueKind = VK_LValue;
2369 break;
2370 }
2371 // fallthrough
2372
2373 case Decl::CXXConversion:
2374 case Decl::CXXDestructor:
2375 case Decl::CXXConstructor:
2376 valueKind = VK_RValue;
2377 break;
2378 }
2379
2380 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2381 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002382}
Chris Lattnere168f762006-11-10 05:29:30 +00002383
John McCall2979fe02011-04-12 00:42:48 +00002384ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002385 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002386
Chris Lattnere168f762006-11-10 05:29:30 +00002387 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002388 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002389 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2390 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2391 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002392 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002393
Chris Lattnera81a0272008-01-12 08:14:25 +00002394 // Pre-defined identifiers are of type char[x], where x is the length of the
2395 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002396
Anders Carlsson2fb08242009-09-08 18:24:21 +00002397 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002398 if (!currentDecl && getCurBlock())
2399 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002400 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002401 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002402 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002403 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002404
Anders Carlsson0b209a82009-09-11 01:22:35 +00002405 QualType ResTy;
2406 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2407 ResTy = Context.DependentTy;
2408 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002409 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002410
Anders Carlsson0b209a82009-09-11 01:22:35 +00002411 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002412 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002413 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2414 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002415 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002416}
2417
Richard Smithbcc22fc2012-03-09 08:00:36 +00002418ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002419 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002420 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002421 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002422 if (Invalid)
2423 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002424
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002425 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002426 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002427 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002428 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002429
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002430 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002431 if (Literal.isWide())
2432 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002433 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002434 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002435 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002436 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
2437 else if (!getLangOptions().CPlusPlus || Literal.isMultiChar())
2438 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002439 else
2440 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002441
Douglas Gregorfb65e592011-07-27 05:40:30 +00002442 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2443 if (Literal.isWide())
2444 Kind = CharacterLiteral::Wide;
2445 else if (Literal.isUTF16())
2446 Kind = CharacterLiteral::UTF16;
2447 else if (Literal.isUTF32())
2448 Kind = CharacterLiteral::UTF32;
2449
Richard Smith75b67d62012-03-08 01:34:56 +00002450 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2451 Tok.getLocation());
2452
2453 if (Literal.getUDSuffix().empty())
2454 return Owned(Lit);
2455
2456 // We're building a user-defined literal.
2457 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2458 SourceLocation UDSuffixLoc =
2459 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2460
Richard Smithbcc22fc2012-03-09 08:00:36 +00002461 // Make sure we're allowed user-defined literals here.
2462 if (!UDLScope)
2463 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2464
Richard Smith75b67d62012-03-08 01:34:56 +00002465 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2466 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002467 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2468 llvm::makeArrayRef(&Lit, 1),
2469 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002470}
2471
Ted Kremeneke65b0862012-03-06 20:05:56 +00002472ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2473 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2474 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2475 Context.IntTy, Loc));
2476}
2477
Richard Smith39570d002012-03-08 08:45:32 +00002478static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2479 QualType Ty, SourceLocation Loc) {
2480 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2481
2482 using llvm::APFloat;
2483 APFloat Val(Format);
2484
2485 APFloat::opStatus result = Literal.GetFloatValue(Val);
2486
2487 // Overflow is always an error, but underflow is only an error if
2488 // we underflowed to zero (APFloat reports denormals as underflow).
2489 if ((result & APFloat::opOverflow) ||
2490 ((result & APFloat::opUnderflow) && Val.isZero())) {
2491 unsigned diagnostic;
2492 SmallString<20> buffer;
2493 if (result & APFloat::opOverflow) {
2494 diagnostic = diag::warn_float_overflow;
2495 APFloat::getLargest(Format).toString(buffer);
2496 } else {
2497 diagnostic = diag::warn_float_underflow;
2498 APFloat::getSmallest(Format).toString(buffer);
2499 }
2500
2501 S.Diag(Loc, diagnostic)
2502 << Ty
2503 << StringRef(buffer.data(), buffer.size());
2504 }
2505
2506 bool isExact = (result == APFloat::opOK);
2507 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2508}
2509
Richard Smithbcc22fc2012-03-09 08:00:36 +00002510ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002511 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002512 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002513 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002514 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002515 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002516 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002517
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002518 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002519 // Add padding so that NumericLiteralParser can overread by one character.
2520 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002521 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002522
Chris Lattner67ca9252007-05-21 01:08:44 +00002523 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002524 bool Invalid = false;
2525 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2526 if (Invalid)
2527 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002528
Mike Stump11289f42009-09-09 15:08:12 +00002529 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002530 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002531 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002532 return ExprError();
2533
Richard Smith39570d002012-03-08 08:45:32 +00002534 if (Literal.hasUDSuffix()) {
2535 // We're building a user-defined literal.
2536 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2537 SourceLocation UDSuffixLoc =
2538 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2539
Richard Smithbcc22fc2012-03-09 08:00:36 +00002540 // Make sure we're allowed user-defined literals here.
2541 if (!UDLScope)
2542 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002543
Richard Smithbcc22fc2012-03-09 08:00:36 +00002544 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002545 if (Literal.isFloatingLiteral()) {
2546 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2547 // long double, the literal is treated as a call of the form
2548 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002549 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002550 } else {
2551 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2552 // unsigned long long, the literal is treated as a call of the form
2553 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002554 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002555 }
2556
Richard Smithbcc22fc2012-03-09 08:00:36 +00002557 DeclarationName OpName =
2558 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2559 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2560 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2561
2562 // Perform literal operator lookup to determine if we're building a raw
2563 // literal or a cooked one.
2564 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2565 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2566 /*AllowRawAndTemplate*/true)) {
2567 case LOLR_Error:
2568 return ExprError();
2569
2570 case LOLR_Cooked: {
2571 Expr *Lit;
2572 if (Literal.isFloatingLiteral()) {
2573 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2574 } else {
2575 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2576 if (Literal.GetIntegerValue(ResultVal))
2577 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2578 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2579 Tok.getLocation());
2580 }
2581 return BuildLiteralOperatorCall(R, OpNameInfo,
2582 llvm::makeArrayRef(&Lit, 1),
2583 Tok.getLocation());
2584 }
2585
2586 case LOLR_Raw: {
2587 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2588 // literal is treated as a call of the form
2589 // operator "" X ("n")
2590 SourceLocation TokLoc = Tok.getLocation();
2591 unsigned Length = Literal.getUDSuffixOffset();
2592 QualType StrTy = Context.getConstantArrayType(
2593 Context.CharTy, llvm::APInt(32, Length + 1),
2594 ArrayType::Normal, 0);
2595 Expr *Lit = StringLiteral::Create(
2596 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2597 /*Pascal*/false, StrTy, &TokLoc, 1);
2598 return BuildLiteralOperatorCall(R, OpNameInfo,
2599 llvm::makeArrayRef(&Lit, 1), TokLoc);
2600 }
2601
2602 case LOLR_Template:
2603 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2604 // template), L is treated as a call fo the form
2605 // operator "" X <'c1', 'c2', ... 'ck'>()
2606 // where n is the source character sequence c1 c2 ... ck.
2607 TemplateArgumentListInfo ExplicitArgs;
2608 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2609 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2610 llvm::APSInt Value(CharBits, CharIsUnsigned);
2611 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2612 Value = ThisTokBegin[I];
2613 TemplateArgument Arg(Value, Context.CharTy);
2614 TemplateArgumentLocInfo ArgInfo;
2615 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2616 }
2617 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2618 Tok.getLocation(), &ExplicitArgs);
2619 }
2620
2621 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002622 }
2623
Chris Lattner1c20a172007-08-26 03:42:43 +00002624 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002625
Chris Lattner1c20a172007-08-26 03:42:43 +00002626 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002627 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002628 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002629 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002630 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002631 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002632 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002633 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002634
Richard Smith39570d002012-03-08 08:45:32 +00002635 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002636
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002637 if (Ty == Context.DoubleTy) {
2638 if (getLangOptions().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002639 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002640 } else if (getLangOptions().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
2641 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002642 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002643 }
2644 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002645 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002646 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002647 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002648 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002649
Neil Boothac582c52007-08-29 22:00:19 +00002650 // long long is a C99 feature.
Richard Smith0bf8a4922011-10-18 20:49:44 +00002651 if (!getLangOptions().C99 && Literal.isLongLong)
2652 Diag(Tok.getLocation(),
2653 getLangOptions().CPlusPlus0x ?
2654 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002655
Chris Lattner67ca9252007-05-21 01:08:44 +00002656 // Get the value in the widest-possible width.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002657 llvm::APInt ResultVal(Context.getTargetInfo().getIntMaxTWidth(), 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002658
Chris Lattner67ca9252007-05-21 01:08:44 +00002659 if (Literal.GetIntegerValue(ResultVal)) {
2660 // If this value didn't fit into uintmax_t, warn and force to ull.
2661 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002662 Ty = Context.UnsignedLongLongTy;
2663 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002664 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002665 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002666 // If this value fits into a ULL, try to figure out what else it fits into
2667 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002668
Chris Lattner67ca9252007-05-21 01:08:44 +00002669 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2670 // be an unsigned int.
2671 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2672
2673 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002674 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002675 if (!Literal.isLong && !Literal.isLongLong) {
2676 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002677 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002678
Chris Lattner67ca9252007-05-21 01:08:44 +00002679 // Does it fit in a unsigned int?
2680 if (ResultVal.isIntN(IntSize)) {
2681 // Does it fit in a signed int?
2682 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002683 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002684 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002685 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002686 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002687 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002688 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002689
Chris Lattner67ca9252007-05-21 01:08:44 +00002690 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002691 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002692 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002693
Chris Lattner67ca9252007-05-21 01:08:44 +00002694 // Does it fit in a unsigned long?
2695 if (ResultVal.isIntN(LongSize)) {
2696 // Does it fit in a signed long?
2697 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002698 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002699 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002700 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002701 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002702 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002703 }
2704
Chris Lattner67ca9252007-05-21 01:08:44 +00002705 // Finally, check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002706 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002707 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002708
Chris Lattner67ca9252007-05-21 01:08:44 +00002709 // Does it fit in a unsigned long long?
2710 if (ResultVal.isIntN(LongLongSize)) {
2711 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002712 // To be compatible with MSVC, hex integer literals ending with the
2713 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002714 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
Francois Pichet0706d202011-09-17 17:15:52 +00002715 (getLangOptions().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002716 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002717 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002718 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002719 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002720 }
2721 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002722
Chris Lattner67ca9252007-05-21 01:08:44 +00002723 // If we still couldn't decide a type, we probably have something that
2724 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002725 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002726 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002727 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002728 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002729 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002730
Chris Lattner55258cf2008-05-09 05:59:00 +00002731 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002732 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002733 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002734 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002735 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002736
Chris Lattner1c20a172007-08-26 03:42:43 +00002737 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2738 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002739 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002740 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002741
2742 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002743}
2744
Richard Trieuba63ce62011-09-09 01:45:06 +00002745ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002746 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002747 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002748}
2749
Chandler Carruth62da79c2011-05-26 08:53:12 +00002750static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2751 SourceLocation Loc,
2752 SourceRange ArgRange) {
2753 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2754 // scalar or vector data type argument..."
2755 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2756 // type (C99 6.2.5p18) or void.
2757 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2758 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2759 << T << ArgRange;
2760 return true;
2761 }
2762
2763 assert((T->isVoidType() || !T->isIncompleteType()) &&
2764 "Scalar types should always be complete");
2765 return false;
2766}
2767
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002768static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2769 SourceLocation Loc,
2770 SourceRange ArgRange,
2771 UnaryExprOrTypeTrait TraitKind) {
2772 // C99 6.5.3.4p1:
2773 if (T->isFunctionType()) {
2774 // alignof(function) is allowed as an extension.
2775 if (TraitKind == UETT_SizeOf)
2776 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2777 return false;
2778 }
2779
2780 // Allow sizeof(void)/alignof(void) as an extension.
2781 if (T->isVoidType()) {
2782 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2783 return false;
2784 }
2785
2786 return true;
2787}
2788
2789static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2790 SourceLocation Loc,
2791 SourceRange ArgRange,
2792 UnaryExprOrTypeTrait TraitKind) {
2793 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2794 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2795 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2796 << T << (TraitKind == UETT_SizeOf)
2797 << ArgRange;
2798 return true;
2799 }
2800
2801 return false;
2802}
2803
Chandler Carruth14502c22011-05-26 08:53:10 +00002804/// \brief Check the constrains on expression operands to unary type expression
2805/// and type traits.
2806///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002807/// Completes any types necessary and validates the constraints on the operand
2808/// expression. The logic mostly mirrors the type-based overload, but may modify
2809/// the expression as it completes the type for that expression through template
2810/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002811bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002812 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002813 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002814
2815 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2816 // the result is the size of the referenced type."
2817 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2818 // result shall be the alignment of the referenced type."
2819 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2820 ExprTy = Ref->getPointeeType();
2821
2822 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002823 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2824 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002825
2826 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002827 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2828 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002829 return false;
2830
Richard Trieuba63ce62011-09-09 01:45:06 +00002831 if (RequireCompleteExprType(E,
Chandler Carruth7c430c02011-05-27 01:33:31 +00002832 PDiag(diag::err_sizeof_alignof_incomplete_type)
Richard Trieuba63ce62011-09-09 01:45:06 +00002833 << ExprKind << E->getSourceRange(),
Chandler Carruth7c430c02011-05-27 01:33:31 +00002834 std::make_pair(SourceLocation(), PDiag(0))))
2835 return true;
2836
2837 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002838 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002839 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2840 ExprTy = Ref->getPointeeType();
2841
Richard Trieuba63ce62011-09-09 01:45:06 +00002842 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2843 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002844 return true;
2845
Nico Weber0870deb2011-06-15 02:47:03 +00002846 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002847 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002848 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2849 QualType OType = PVD->getOriginalType();
2850 QualType Type = PVD->getType();
2851 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002852 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002853 << Type << OType;
2854 Diag(PVD->getLocation(), diag::note_declared_at);
2855 }
2856 }
2857 }
2858 }
2859
Chandler Carruth7c430c02011-05-27 01:33:31 +00002860 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002861}
2862
2863/// \brief Check the constraints on operands to unary expression and type
2864/// traits.
2865///
2866/// This will complete any types necessary, and validate the various constraints
2867/// on those operands.
2868///
Steve Naroff71b59a92007-06-04 22:22:31 +00002869/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002870/// C99 6.3.2.1p[2-4] all state:
2871/// Except when it is the operand of the sizeof operator ...
2872///
2873/// C++ [expr.sizeof]p4
2874/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2875/// standard conversions are not applied to the operand of sizeof.
2876///
2877/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002878bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002879 SourceLocation OpLoc,
2880 SourceRange ExprRange,
2881 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002882 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002883 return false;
2884
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002885 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2886 // the result is the size of the referenced type."
2887 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2888 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002889 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2890 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002891
Chandler Carruth62da79c2011-05-26 08:53:12 +00002892 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002893 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002894
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002895 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002896 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002897 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002898 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002899
Richard Trieuba63ce62011-09-09 01:45:06 +00002900 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor906db8a2009-12-15 16:44:32 +00002901 PDiag(diag::err_sizeof_alignof_incomplete_type)
Peter Collingbournee190dee2011-03-11 19:24:49 +00002902 << ExprKind << ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002903 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002904
Richard Trieuba63ce62011-09-09 01:45:06 +00002905 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002906 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002907 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002908
Chris Lattner62975a72009-04-24 00:30:45 +00002909 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002910}
2911
Chandler Carruth14502c22011-05-26 08:53:10 +00002912static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002913 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002914
Mike Stump11289f42009-09-09 15:08:12 +00002915 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002916 if (isa<DeclRefExpr>(E))
2917 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002918
2919 // Cannot know anything else if the expression is dependent.
2920 if (E->isTypeDependent())
2921 return false;
2922
Douglas Gregor71235ec2009-05-02 02:18:30 +00002923 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002924 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2925 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002926 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002927 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002928
2929 // Alignment of a field access is always okay, so long as it isn't a
2930 // bit-field.
2931 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002932 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002933 return false;
2934
Chandler Carruth14502c22011-05-26 08:53:10 +00002935 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002936}
2937
Chandler Carruth14502c22011-05-26 08:53:10 +00002938bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002939 E = E->IgnoreParens();
2940
2941 // Cannot know anything else if the expression is dependent.
2942 if (E->isTypeDependent())
2943 return false;
2944
Chandler Carruth14502c22011-05-26 08:53:10 +00002945 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002946}
2947
Douglas Gregor0950e412009-03-13 21:01:28 +00002948/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00002949ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00002950Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
2951 SourceLocation OpLoc,
2952 UnaryExprOrTypeTrait ExprKind,
2953 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00002954 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00002955 return ExprError();
2956
John McCallbcd03502009-12-07 02:54:59 +00002957 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00002958
Douglas Gregor0950e412009-03-13 21:01:28 +00002959 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00002960 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00002961 return ExprError();
2962
2963 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002964 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
2965 Context.getSizeType(),
2966 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00002967}
2968
2969/// \brief Build a sizeof or alignof expression given an expression
2970/// operand.
John McCalldadc5752010-08-24 06:29:42 +00002971ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00002972Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
2973 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00002974 ExprResult PE = CheckPlaceholderExpr(E);
2975 if (PE.isInvalid())
2976 return ExprError();
2977
2978 E = PE.get();
2979
Douglas Gregor0950e412009-03-13 21:01:28 +00002980 // Verify that the operand is valid.
2981 bool isInvalid = false;
2982 if (E->isTypeDependent()) {
2983 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00002984 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002985 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002986 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002987 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00002988 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00002989 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00002990 isInvalid = true;
2991 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00002992 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00002993 }
2994
2995 if (isInvalid)
2996 return ExprError();
2997
Eli Friedmane0afc982012-01-21 01:01:51 +00002998 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
2999 PE = TranformToPotentiallyEvaluated(E);
3000 if (PE.isInvalid()) return ExprError();
3001 E = PE.take();
3002 }
3003
Douglas Gregor0950e412009-03-13 21:01:28 +00003004 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003005 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003006 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003007 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003008}
3009
Peter Collingbournee190dee2011-03-11 19:24:49 +00003010/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3011/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003012/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003013ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003014Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003015 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003016 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003017 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003018 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003019
Richard Trieuba63ce62011-09-09 01:45:06 +00003020 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003021 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003022 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003023 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003024 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003025
Douglas Gregor0950e412009-03-13 21:01:28 +00003026 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003027 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003028 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003029}
3030
John Wiegley01296292011-04-08 18:41:53 +00003031static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003032 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003033 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003034 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003035
John McCall34376a62010-12-04 03:47:34 +00003036 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003037 if (V.get()->getObjectKind() != OK_Ordinary) {
3038 V = S.DefaultLvalueConversion(V.take());
3039 if (V.isInvalid())
3040 return QualType();
3041 }
John McCall34376a62010-12-04 03:47:34 +00003042
Chris Lattnere267f5d2007-08-26 05:39:26 +00003043 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003044 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003045 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003046
Chris Lattnere267f5d2007-08-26 05:39:26 +00003047 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003048 if (V.get()->getType()->isArithmeticType())
3049 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003050
John McCall36226622010-10-12 02:09:17 +00003051 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003052 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003053 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003054 if (PR.get() != V.get()) {
3055 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003056 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003057 }
3058
Chris Lattnere267f5d2007-08-26 05:39:26 +00003059 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003060 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003061 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003062 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003063}
3064
3065
Chris Lattnere168f762006-11-10 05:29:30 +00003066
John McCalldadc5752010-08-24 06:29:42 +00003067ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003068Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003069 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003070 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003071 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003072 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003073 case tok::plusplus: Opc = UO_PostInc; break;
3074 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003075 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003076
Sebastian Redla9351792012-02-11 23:51:47 +00003077 // Since this might is a postfix expression, get rid of ParenListExprs.
3078 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3079 if (Result.isInvalid()) return ExprError();
3080 Input = Result.take();
3081
John McCallb268a282010-08-23 23:25:46 +00003082 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003083}
3084
John McCalldadc5752010-08-24 06:29:42 +00003085ExprResult
John McCallb268a282010-08-23 23:25:46 +00003086Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3087 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003088 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003089 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003090 if (Result.isInvalid()) return ExprError();
3091 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003092
John McCallb268a282010-08-23 23:25:46 +00003093 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003094
Douglas Gregor40412ac2008-11-19 17:17:41 +00003095 if (getLangOptions().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003096 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003097 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003098 Context.DependentTy,
3099 VK_LValue, OK_Ordinary,
3100 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003101 }
3102
Mike Stump11289f42009-09-09 15:08:12 +00003103 if (getLangOptions().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003104 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003105 LHSExp->getType()->isEnumeralType() ||
3106 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003107 RHSExp->getType()->isEnumeralType()) &&
3108 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003109 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003110 }
3111
John McCallb268a282010-08-23 23:25:46 +00003112 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003113}
3114
3115
John McCalldadc5752010-08-24 06:29:42 +00003116ExprResult
John McCallb268a282010-08-23 23:25:46 +00003117Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003118 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003119 Expr *LHSExp = Base;
3120 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003121
Chris Lattner36d572b2007-07-16 00:14:47 +00003122 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003123 if (!LHSExp->getType()->getAs<VectorType>()) {
3124 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3125 if (Result.isInvalid())
3126 return ExprError();
3127 LHSExp = Result.take();
3128 }
3129 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3130 if (Result.isInvalid())
3131 return ExprError();
3132 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003133
Chris Lattner36d572b2007-07-16 00:14:47 +00003134 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003135 ExprValueKind VK = VK_LValue;
3136 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003137
Steve Naroffc1aadb12007-03-28 21:49:40 +00003138 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003139 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003140 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003141 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003142 Expr *BaseExpr, *IndexExpr;
3143 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003144 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3145 BaseExpr = LHSExp;
3146 IndexExpr = RHSExp;
3147 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003148 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003149 BaseExpr = LHSExp;
3150 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003151 ResultType = PTy->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003152 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
Chris Lattneraee0cfd2007-07-16 00:23:25 +00003153 // Handle the uncommon case of "123[Ptr]".
Chris Lattner36d572b2007-07-16 00:14:47 +00003154 BaseExpr = RHSExp;
3155 IndexExpr = LHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003156 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003157 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003158 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003159 BaseExpr = LHSExp;
3160 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003161 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3162 if (!Result.isInvalid())
3163 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003164 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003165 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003166 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003167 // Handle the uncommon case of "123[Ptr]".
3168 BaseExpr = RHSExp;
3169 IndexExpr = LHSExp;
3170 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003171 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003172 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003173 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003174 VK = LHSExp->getValueKind();
3175 if (VK != VK_RValue)
3176 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003177
Chris Lattner36d572b2007-07-16 00:14:47 +00003178 // FIXME: need to deal with const...
3179 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003180 } else if (LHSTy->isArrayType()) {
3181 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003182 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003183 // wasn't promoted because of the C90 rule that doesn't
3184 // allow promoting non-lvalue arrays. Warn, then
3185 // force the promotion here.
3186 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3187 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003188 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3189 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003190 LHSTy = LHSExp->getType();
3191
3192 BaseExpr = LHSExp;
3193 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003194 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003195 } else if (RHSTy->isArrayType()) {
3196 // Same as previous, except for 123[f().a] case
3197 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3198 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003199 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3200 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003201 RHSTy = RHSExp->getType();
3202
3203 BaseExpr = RHSExp;
3204 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003205 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003206 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003207 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3208 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003209 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003210 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003211 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003212 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3213 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003214
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003215 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003216 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3217 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003218 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3219
Douglas Gregorac1fb652009-03-24 19:52:54 +00003220 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003221 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3222 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003223 // incomplete types are not object types.
3224 if (ResultType->isFunctionType()) {
3225 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3226 << ResultType << BaseExpr->getSourceRange();
3227 return ExprError();
3228 }
Mike Stump11289f42009-09-09 15:08:12 +00003229
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003230 if (ResultType->isVoidType() && !getLangOptions().CPlusPlus) {
3231 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003232 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3233 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003234
3235 // C forbids expressions of unqualified void type from being l-values.
3236 // See IsCForbiddenLValueType.
3237 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003238 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003239 RequireCompleteType(LLoc, ResultType,
Anders Carlssond624e162009-08-26 23:45:07 +00003240 PDiag(diag::err_subscript_incomplete_type)
3241 << BaseExpr->getSourceRange()))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003242 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003243
Chris Lattner62975a72009-04-24 00:30:45 +00003244 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003245 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003246 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3247 << ResultType << BaseExpr->getSourceRange();
3248 return ExprError();
3249 }
Mike Stump11289f42009-09-09 15:08:12 +00003250
John McCall4bc41ae2010-11-18 19:01:18 +00003251 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003252 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003253
Mike Stump4e1f26a2009-02-19 03:04:26 +00003254 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003255 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003256}
3257
John McCalldadc5752010-08-24 06:29:42 +00003258ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003259 FunctionDecl *FD,
3260 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003261 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003262 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003263 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003264 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003265 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003266 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003267 return ExprError();
3268 }
3269
3270 if (Param->hasUninstantiatedDefaultArg()) {
3271 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003272
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003273 // Instantiate the expression.
3274 MultiLevelTemplateArgumentList ArgList
3275 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003276
Nico Weber44887f62010-11-29 18:19:25 +00003277 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003278 = ArgList.getInnermost();
3279 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3280 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003281
Nico Weber44887f62010-11-29 18:19:25 +00003282 ExprResult Result;
3283 {
3284 // C++ [dcl.fct.default]p5:
3285 // The names in the [default argument] expression are bound, and
3286 // the semantic constraints are checked, at the point where the
3287 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003288 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003289 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003290 Result = SubstExpr(UninstExpr, ArgList);
3291 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003292 if (Result.isInvalid())
3293 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003294
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003295 // Check the expression as an initializer for the parameter.
3296 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003297 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003298 InitializationKind Kind
3299 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003300 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003301 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003302
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003303 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3304 Result = InitSeq.Perform(*this, Entity, Kind,
3305 MultiExprArg(*this, &ResultE, 1));
3306 if (Result.isInvalid())
3307 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003308
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003309 // Build the default argument expression.
3310 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param,
3311 Result.takeAs<Expr>()));
Anders Carlsson355933d2009-08-25 03:49:14 +00003312 }
3313
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003314 // If the default expression creates temporaries, we need to
3315 // push them to the current stack of expression temporaries so they'll
3316 // be properly destroyed.
3317 // FIXME: We should really be rebuilding the default argument with new
3318 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003319 // We don't need to do that with block decls, though, because
3320 // blocks in default argument expression can never capture anything.
3321 if (isa<ExprWithCleanups>(Param->getInit())) {
3322 // Set the "needs cleanups" bit regardless of whether there are
3323 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003324 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003325
3326 // Append all the objects to the cleanup list. Right now, this
3327 // should always be a no-op, because blocks in default argument
3328 // expressions should never be able to capture anything.
3329 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3330 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003331 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003332
3333 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003334 // Just mark all of the declarations in this potentially-evaluated expression
3335 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003336 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3337 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003338 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003339}
3340
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003341/// ConvertArgumentsForCall - Converts the arguments specified in
3342/// Args/NumArgs to the parameter types of the function FDecl with
3343/// function prototype Proto. Call is the call expression itself, and
3344/// Fn is the function expression. For a C++ member function, this
3345/// routine does not attempt to convert the object argument. Returns
3346/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003347bool
3348Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003349 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003350 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003351 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003352 SourceLocation RParenLoc,
3353 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003354 // Bail out early if calling a builtin with custom typechecking.
3355 // We don't need to do this in the
3356 if (FDecl)
3357 if (unsigned ID = FDecl->getBuiltinID())
3358 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3359 return false;
3360
Mike Stump4e1f26a2009-02-19 03:04:26 +00003361 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003362 // assignment, to the types of the corresponding parameter, ...
3363 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003364 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003365 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003366 unsigned FnKind = Fn->getType()->isBlockPointerType()
3367 ? 1 /* block */
3368 : (IsExecConfig ? 3 /* kernel function (exec config) */
3369 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003370
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003371 // If too few arguments are available (and we don't have default
3372 // arguments for the remaining parameters), don't make the call.
3373 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003374 if (NumArgs < MinArgs) {
3375 Diag(RParenLoc, MinArgs == NumArgsInProto
3376 ? diag::err_typecheck_call_too_few_args
3377 : diag::err_typecheck_call_too_few_args_at_least)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003378 << FnKind
Peter Collingbourne740afe22011-10-02 23:49:20 +00003379 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003380
3381 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003382 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003383 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3384 << FDecl;
3385
3386 return true;
3387 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003388 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003389 }
3390
3391 // If too many are passed and not variadic, error on the extras and drop
3392 // them.
3393 if (NumArgs > NumArgsInProto) {
3394 if (!Proto->isVariadic()) {
3395 Diag(Args[NumArgsInProto]->getLocStart(),
Peter Collingbourne740afe22011-10-02 23:49:20 +00003396 MinArgs == NumArgsInProto
3397 ? diag::err_typecheck_call_too_many_args
3398 : diag::err_typecheck_call_too_many_args_at_most)
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003399 << FnKind
Eric Christopher2a5aaff2010-04-16 04:56:46 +00003400 << NumArgsInProto << NumArgs << Fn->getSourceRange()
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003401 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3402 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003403
3404 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003405 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003406 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3407 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003408
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003409 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003410 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003411 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003412 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003413 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003414 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003415 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003416 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3417 if (Fn->getType()->isBlockPointerType())
3418 CallType = VariadicBlock; // Block
3419 else if (isa<MemberExpr>(Fn))
3420 CallType = VariadicMethod;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003421 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003422 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003423 if (Invalid)
3424 return true;
3425 unsigned TotalNumArgs = AllArgs.size();
3426 for (unsigned i = 0; i < TotalNumArgs; ++i)
3427 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003428
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003429 return false;
3430}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003431
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003432bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3433 FunctionDecl *FDecl,
3434 const FunctionProtoType *Proto,
3435 unsigned FirstProtoArg,
3436 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003437 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003438 VariadicCallType CallType,
3439 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003440 unsigned NumArgsInProto = Proto->getNumArgs();
3441 unsigned NumArgsToCheck = NumArgs;
3442 bool Invalid = false;
3443 if (NumArgs != NumArgsInProto)
3444 // Use default arguments for missing arguments
3445 NumArgsToCheck = NumArgsInProto;
3446 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003447 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003448 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003449 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003450
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003451 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003452 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003453 if (ArgIx < NumArgs) {
3454 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003455
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003456 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003457 ProtoArgType,
Anders Carlssond624e162009-08-26 23:45:07 +00003458 PDiag(diag::err_call_incomplete_argument)
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003459 << Arg->getSourceRange()))
Eli Friedman3164fb12009-03-22 22:00:50 +00003460 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003461
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003462 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003463 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003464 if (FDecl && i < FDecl->getNumParams())
3465 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003466
John McCall4124c492011-10-17 18:40:02 +00003467 // Strip the unbridged-cast placeholder expression off, if applicable.
3468 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3469 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3470 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3471 Arg = stripARCUnbridgedCast(Arg);
3472
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003473 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003474 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003475 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3476 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003477 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003478 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003479 Owned(Arg),
3480 /*TopLevelOfInitList=*/false,
3481 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003482 if (ArgE.isInvalid())
3483 return true;
3484
3485 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003486 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003487 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003488
John McCalldadc5752010-08-24 06:29:42 +00003489 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003490 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003491 if (ArgExpr.isInvalid())
3492 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003493
Anders Carlsson355933d2009-08-25 03:49:14 +00003494 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003495 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003496
3497 // Check for array bounds violations for each argument to the call. This
3498 // check only triggers warnings when the argument isn't a more complex Expr
3499 // with its own checking, such as a BinaryOperator.
3500 CheckArrayAccess(Arg);
3501
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003502 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3503 CheckStaticArrayArgument(CallLoc, Param, Arg);
3504
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003505 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003506 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003507
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003508 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003509 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003510
3511 // Assume that extern "C" functions with variadic arguments that
3512 // return __unknown_anytype aren't *really* variadic.
3513 if (Proto->getResultType() == Context.UnknownAnyTy &&
3514 FDecl && FDecl->isExternC()) {
3515 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3516 ExprResult arg;
3517 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3518 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3519 else
3520 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3521 Invalid |= arg.isInvalid();
3522 AllArgs.push_back(arg.take());
3523 }
3524
3525 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3526 } else {
3527 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003528 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3529 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003530 Invalid |= Arg.isInvalid();
3531 AllArgs.push_back(Arg.take());
3532 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003533 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003534
3535 // Check for array bounds violations.
3536 for (unsigned i = ArgIx; i != NumArgs; ++i)
3537 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003538 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003539 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003540}
3541
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003542static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3543 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3544 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3545 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3546 << ATL->getLocalSourceRange();
3547}
3548
3549/// CheckStaticArrayArgument - If the given argument corresponds to a static
3550/// array parameter, check that it is non-null, and that if it is formed by
3551/// array-to-pointer decay, the underlying array is sufficiently large.
3552///
3553/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3554/// array type derivation, then for each call to the function, the value of the
3555/// corresponding actual argument shall provide access to the first element of
3556/// an array with at least as many elements as specified by the size expression.
3557void
3558Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3559 ParmVarDecl *Param,
3560 const Expr *ArgExpr) {
3561 // Static array parameters are not supported in C++.
3562 if (!Param || getLangOptions().CPlusPlus)
3563 return;
3564
3565 QualType OrigTy = Param->getOriginalType();
3566
3567 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3568 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3569 return;
3570
3571 if (ArgExpr->isNullPointerConstant(Context,
3572 Expr::NPC_NeverValueDependent)) {
3573 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3574 DiagnoseCalleeStaticArrayParam(*this, Param);
3575 return;
3576 }
3577
3578 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3579 if (!CAT)
3580 return;
3581
3582 const ConstantArrayType *ArgCAT =
3583 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3584 if (!ArgCAT)
3585 return;
3586
3587 if (ArgCAT->getSize().ult(CAT->getSize())) {
3588 Diag(CallLoc, diag::warn_static_array_too_small)
3589 << ArgExpr->getSourceRange()
3590 << (unsigned) ArgCAT->getSize().getZExtValue()
3591 << (unsigned) CAT->getSize().getZExtValue();
3592 DiagnoseCalleeStaticArrayParam(*this, Param);
3593 }
3594}
3595
John McCall2979fe02011-04-12 00:42:48 +00003596/// Given a function expression of unknown-any type, try to rebuild it
3597/// to have a function type.
3598static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3599
Steve Naroff83895f72007-09-16 03:34:24 +00003600/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003601/// This provides the location of the left/right parens and a list of comma
3602/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003603ExprResult
John McCallb268a282010-08-23 23:25:46 +00003604Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003605 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003606 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003607 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003608
3609 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003610 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003611 if (Result.isInvalid()) return ExprError();
3612 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003613
Richard Trieuba63ce62011-09-09 01:45:06 +00003614 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003615
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003616 if (getLangOptions().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003617 // If this is a pseudo-destructor expression, build the call immediately.
3618 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3619 if (NumArgs > 0) {
3620 // Pseudo-destructor calls should not have any arguments.
3621 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003622 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003623 SourceRange(Args[0]->getLocStart(),
3624 Args[NumArgs-1]->getLocEnd()));
Mike Stump11289f42009-09-09 15:08:12 +00003625
Douglas Gregorad8a3362009-09-04 17:36:40 +00003626 NumArgs = 0;
3627 }
Mike Stump11289f42009-09-09 15:08:12 +00003628
Douglas Gregorad8a3362009-09-04 17:36:40 +00003629 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003630 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003631 }
Mike Stump11289f42009-09-09 15:08:12 +00003632
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003633 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003634 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003635 // FIXME: Will need to cache the results of name lookup (including ADL) in
3636 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003637 bool Dependent = false;
3638 if (Fn->isTypeDependent())
3639 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003640 else if (Expr::hasAnyTypeDependentArguments(
3641 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003642 Dependent = true;
3643
Peter Collingbourne41f85462011-02-09 21:07:24 +00003644 if (Dependent) {
3645 if (ExecConfig) {
3646 return Owned(new (Context) CUDAKernelCallExpr(
3647 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3648 Context.DependentTy, VK_RValue, RParenLoc));
3649 } else {
3650 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3651 Context.DependentTy, VK_RValue,
3652 RParenLoc));
3653 }
3654 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003655
3656 // Determine whether this is a call to an object (C++ [over.call.object]).
3657 if (Fn->getType()->isRecordType())
3658 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003659 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003660
John McCall2979fe02011-04-12 00:42:48 +00003661 if (Fn->getType() == Context.UnknownAnyTy) {
3662 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3663 if (result.isInvalid()) return ExprError();
3664 Fn = result.take();
3665 }
3666
John McCall0009fcc2011-04-26 20:42:42 +00003667 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003668 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003669 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003670 }
John McCall0009fcc2011-04-26 20:42:42 +00003671 }
John McCall10eae182009-11-30 22:42:35 +00003672
John McCall0009fcc2011-04-26 20:42:42 +00003673 // Check for overloaded calls. This can happen even in C due to extensions.
3674 if (Fn->getType() == Context.OverloadTy) {
3675 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3676
Douglas Gregorcda22702011-10-13 18:10:35 +00003677 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003678 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003679 OverloadExpr *ovl = find.Expression;
3680 if (isa<UnresolvedLookupExpr>(ovl)) {
3681 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3682 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3683 RParenLoc, ExecConfig);
3684 } else {
John McCall2d74de92009-12-01 22:10:20 +00003685 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003686 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003687 }
3688 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003689 }
3690
Douglas Gregore254f902009-02-04 00:32:51 +00003691 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003692 if (Fn->getType() == Context.UnknownAnyTy) {
3693 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3694 if (result.isInvalid()) return ExprError();
3695 Fn = result.take();
3696 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003697
Eli Friedmane14b1992009-12-26 03:35:45 +00003698 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003699
John McCall57500772009-12-16 12:17:52 +00003700 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003701 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3702 if (UnOp->getOpcode() == UO_AddrOf)
3703 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3704
John McCall57500772009-12-16 12:17:52 +00003705 if (isa<DeclRefExpr>(NakedFn))
3706 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003707 else if (isa<MemberExpr>(NakedFn))
3708 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003709
Peter Collingbourne41f85462011-02-09 21:07:24 +00003710 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003711 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003712}
3713
3714ExprResult
3715Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003716 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003717 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3718 if (!ConfigDecl)
3719 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3720 << "cudaConfigureCall");
3721 QualType ConfigQTy = ConfigDecl->getType();
3722
3723 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
3724 ConfigDecl, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003725 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003726
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003727 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3728 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003729}
3730
Tanya Lattner55808c12011-06-04 00:47:47 +00003731/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3732///
3733/// __builtin_astype( value, dst type )
3734///
Richard Trieuba63ce62011-09-09 01:45:06 +00003735ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003736 SourceLocation BuiltinLoc,
3737 SourceLocation RParenLoc) {
3738 ExprValueKind VK = VK_RValue;
3739 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003740 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3741 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003742 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3743 return ExprError(Diag(BuiltinLoc,
3744 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003745 << DstTy
3746 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003747 << E->getSourceRange());
3748 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003749 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003750}
3751
John McCall57500772009-12-16 12:17:52 +00003752/// BuildResolvedCallExpr - Build a call to a resolved expression,
3753/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003754/// unary-convert to an expression of function-pointer or
3755/// block-pointer type.
3756///
3757/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003758ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003759Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3760 SourceLocation LParenLoc,
3761 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003762 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003763 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003764 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3765
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003766 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003767 ExprResult Result = UsualUnaryConversions(Fn);
3768 if (Result.isInvalid())
3769 return ExprError();
3770 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003771
Chris Lattner08464942007-12-28 05:29:59 +00003772 // Make the call expr early, before semantic checks. This guarantees cleanup
3773 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003774 CallExpr *TheCall;
3775 if (Config) {
3776 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3777 cast<CallExpr>(Config),
3778 Args, NumArgs,
3779 Context.BoolTy,
3780 VK_RValue,
3781 RParenLoc);
3782 } else {
3783 TheCall = new (Context) CallExpr(Context, Fn,
3784 Args, NumArgs,
3785 Context.BoolTy,
3786 VK_RValue,
3787 RParenLoc);
3788 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003789
John McCallbebede42011-02-26 05:39:39 +00003790 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3791
3792 // Bail out early if calling a builtin with custom typechecking.
3793 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3794 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3795
John McCall31996342011-04-07 08:22:57 +00003796 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003797 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003798 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003799 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3800 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003801 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003802 if (FuncT == 0)
3803 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3804 << Fn->getType() << Fn->getSourceRange());
3805 } else if (const BlockPointerType *BPT =
3806 Fn->getType()->getAs<BlockPointerType>()) {
3807 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3808 } else {
John McCall31996342011-04-07 08:22:57 +00003809 // Handle calls to expressions of unknown-any type.
3810 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003811 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003812 if (rewrite.isInvalid()) return ExprError();
3813 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003814 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003815 goto retry;
3816 }
3817
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003818 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3819 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003820 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003821
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003822 if (getLangOptions().CUDA) {
3823 if (Config) {
3824 // CUDA: Kernel calls must be to global functions
3825 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3826 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3827 << FDecl->getName() << Fn->getSourceRange());
3828
3829 // CUDA: Kernel function must have 'void' return type
3830 if (!FuncT->getResultType()->isVoidType())
3831 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3832 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003833 } else {
3834 // CUDA: Calls to global functions must be configured
3835 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3836 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3837 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003838 }
3839 }
3840
Eli Friedman3164fb12009-03-22 22:00:50 +00003841 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003842 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003843 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003844 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003845 return ExprError();
3846
Chris Lattner08464942007-12-28 05:29:59 +00003847 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003848 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003849 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003850
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003851 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003852 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003853 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003854 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003855 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003856 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003857
Douglas Gregord8e97de2009-04-02 15:37:10 +00003858 if (FDecl) {
3859 // Check if we have too few/too many template arguments, based
3860 // on our knowledge of the function definition.
3861 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003862 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003863 const FunctionProtoType *Proto
3864 = Def->getType()->getAs<FunctionProtoType>();
3865 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003866 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3867 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003868 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003869
3870 // If the function we're calling isn't a function prototype, but we have
3871 // a function prototype from a prior declaratiom, use that prototype.
3872 if (!FDecl->hasPrototype())
3873 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003874 }
3875
Steve Naroff0b661582007-08-28 23:30:39 +00003876 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003877 for (unsigned i = 0; i != NumArgs; i++) {
3878 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003879
3880 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003881 InitializedEntity Entity
3882 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003883 Proto->getArgType(i),
3884 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003885 ExprResult ArgE = PerformCopyInitialization(Entity,
3886 SourceLocation(),
3887 Owned(Arg));
3888 if (ArgE.isInvalid())
3889 return true;
3890
3891 Arg = ArgE.takeAs<Expr>();
3892
3893 } else {
John Wiegley01296292011-04-08 18:41:53 +00003894 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3895
3896 if (ArgE.isInvalid())
3897 return true;
3898
3899 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003900 }
3901
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003902 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00003903 Arg->getType(),
3904 PDiag(diag::err_call_incomplete_argument)
3905 << Arg->getSourceRange()))
3906 return ExprError();
3907
Chris Lattner08464942007-12-28 05:29:59 +00003908 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003909 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003910 }
Chris Lattner08464942007-12-28 05:29:59 +00003911
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003912 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3913 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003914 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3915 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003916
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003917 // Check for sentinels
3918 if (NDecl)
3919 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003920
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003921 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003922 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003923 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003924 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003925
John McCallbebede42011-02-26 05:39:39 +00003926 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003927 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003928 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003929 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003930 return ExprError();
3931 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003932
John McCallb268a282010-08-23 23:25:46 +00003933 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003934}
3935
John McCalldadc5752010-08-24 06:29:42 +00003936ExprResult
John McCallba7bf592010-08-24 05:47:05 +00003937Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00003938 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00003939 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00003940 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00003941 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00003942
3943 TypeSourceInfo *TInfo;
3944 QualType literalType = GetTypeFromParser(Ty, &TInfo);
3945 if (!TInfo)
3946 TInfo = Context.getTrivialTypeSourceInfo(literalType);
3947
John McCallb268a282010-08-23 23:25:46 +00003948 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00003949}
3950
John McCalldadc5752010-08-24 06:29:42 +00003951ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00003952Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00003953 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00003954 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00003955
Eli Friedman37a186d2008-05-20 05:22:08 +00003956 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003957 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
3958 PDiag(diag::err_illegal_decl_array_incomplete_type)
3959 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003960 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00003961 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00003962 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003963 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00003964 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00003965 } else if (!literalType->isDependentType() &&
3966 RequireCompleteType(LParenLoc, literalType,
Anders Carlssond624e162009-08-26 23:45:07 +00003967 PDiag(diag::err_typecheck_decl_incomplete_type)
Mike Stump11289f42009-09-09 15:08:12 +00003968 << SourceRange(LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003969 LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003970 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00003971
Douglas Gregor85dabae2009-12-16 01:38:02 +00003972 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00003973 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00003974 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00003975 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00003976 SourceRange(LParenLoc, RParenLoc),
3977 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00003978 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00003979 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00003980 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00003981 &literalType);
3982 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00003983 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00003984 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00003985
Chris Lattner79413952008-12-04 23:50:19 +00003986 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00003987 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00003988 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00003989 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00003990 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00003991
John McCall7decc9e2010-11-18 06:31:45 +00003992 // In C, compound literals are l-values for some reason.
3993 ExprValueKind VK = getLangOptions().CPlusPlus ? VK_RValue : VK_LValue;
3994
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00003995 return MaybeBindToTemporary(
3996 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00003997 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00003998}
3999
John McCalldadc5752010-08-24 06:29:42 +00004000ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004001Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004002 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004003 unsigned NumInit = InitArgList.size();
4004 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004005
John McCall526ab472011-10-25 17:37:35 +00004006 // Immediately handle non-overload placeholders. Overloads can be
4007 // resolved contextually, but everything else here can't.
4008 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00004009 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00004010 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4011
4012 // Ignore failures; dropping the entire initializer list because
4013 // of one failure would be terrible for indexing/etc.
4014 if (result.isInvalid()) continue;
4015
4016 InitList[I] = result.take();
4017 }
4018 }
4019
Steve Naroff30d242c2007-09-15 18:49:24 +00004020 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004021 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004022
Ted Kremenekac034612010-04-13 23:39:13 +00004023 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4024 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004025 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004026 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004027}
4028
John McCallcd78e802011-09-10 01:16:55 +00004029/// Do an explicit extend of the given block pointer if we're in ARC.
4030static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4031 assert(E.get()->getType()->isBlockPointerType());
4032 assert(E.get()->isRValue());
4033
4034 // Only do this in an r-value context.
4035 if (!S.getLangOptions().ObjCAutoRefCount) return;
4036
4037 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004038 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004039 /*base path*/ 0, VK_RValue);
4040 S.ExprNeedsCleanups = true;
4041}
4042
4043/// Prepare a conversion of the given expression to an ObjC object
4044/// pointer type.
4045CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4046 QualType type = E.get()->getType();
4047 if (type->isObjCObjectPointerType()) {
4048 return CK_BitCast;
4049 } else if (type->isBlockPointerType()) {
4050 maybeExtendBlockObject(*this, E);
4051 return CK_BlockPointerToObjCPointerCast;
4052 } else {
4053 assert(type->isPointerType());
4054 return CK_CPointerToObjCPointerCast;
4055 }
4056}
4057
John McCalld7646252010-11-14 08:17:51 +00004058/// Prepares for a scalar cast, performing all the necessary stages
4059/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004060CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004061 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4062 // Also, callers should have filtered out the invalid cases with
4063 // pointers. Everything else should be possible.
4064
John Wiegley01296292011-04-08 18:41:53 +00004065 QualType SrcTy = Src.get()->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00004066 if (const AtomicType *SrcAtomicTy = SrcTy->getAs<AtomicType>())
4067 SrcTy = SrcAtomicTy->getValueType();
4068 if (const AtomicType *DestAtomicTy = DestTy->getAs<AtomicType>())
4069 DestTy = DestAtomicTy->getValueType();
4070
John McCall9776e432011-10-06 23:25:11 +00004071 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004072 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004073
John McCall9320b872011-09-09 05:25:32 +00004074 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004075 case Type::STK_MemberPointer:
4076 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004077
John McCall9320b872011-09-09 05:25:32 +00004078 case Type::STK_CPointer:
4079 case Type::STK_BlockPointer:
4080 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004081 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004082 case Type::STK_CPointer:
4083 return CK_BitCast;
4084 case Type::STK_BlockPointer:
4085 return (SrcKind == Type::STK_BlockPointer
4086 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4087 case Type::STK_ObjCObjectPointer:
4088 if (SrcKind == Type::STK_ObjCObjectPointer)
4089 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004090 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004091 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004092 maybeExtendBlockObject(*this, Src);
4093 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004094 case Type::STK_Bool:
4095 return CK_PointerToBoolean;
4096 case Type::STK_Integral:
4097 return CK_PointerToIntegral;
4098 case Type::STK_Floating:
4099 case Type::STK_FloatingComplex:
4100 case Type::STK_IntegralComplex:
4101 case Type::STK_MemberPointer:
4102 llvm_unreachable("illegal cast from pointer");
4103 }
David Blaikie8a40f702012-01-17 06:56:22 +00004104 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004105
John McCall8cb679e2010-11-15 09:13:47 +00004106 case Type::STK_Bool: // casting from bool is like casting from an integer
4107 case Type::STK_Integral:
4108 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004109 case Type::STK_CPointer:
4110 case Type::STK_ObjCObjectPointer:
4111 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004112 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004113 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004114 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004115 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004116 case Type::STK_Bool:
4117 return CK_IntegralToBoolean;
4118 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004119 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004120 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004121 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004122 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004123 Src = ImpCastExprToType(Src.take(),
4124 DestTy->castAs<ComplexType>()->getElementType(),
4125 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004126 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004127 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004128 Src = ImpCastExprToType(Src.take(),
4129 DestTy->castAs<ComplexType>()->getElementType(),
4130 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004131 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004132 case Type::STK_MemberPointer:
4133 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004134 }
David Blaikie8a40f702012-01-17 06:56:22 +00004135 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004136
John McCall8cb679e2010-11-15 09:13:47 +00004137 case Type::STK_Floating:
4138 switch (DestTy->getScalarTypeKind()) {
4139 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004140 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004141 case Type::STK_Bool:
4142 return CK_FloatingToBoolean;
4143 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004144 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004145 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004146 Src = ImpCastExprToType(Src.take(),
4147 DestTy->castAs<ComplexType>()->getElementType(),
4148 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004149 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004150 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004151 Src = ImpCastExprToType(Src.take(),
4152 DestTy->castAs<ComplexType>()->getElementType(),
4153 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004154 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004155 case Type::STK_CPointer:
4156 case Type::STK_ObjCObjectPointer:
4157 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004158 llvm_unreachable("valid float->pointer cast?");
4159 case Type::STK_MemberPointer:
4160 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004161 }
David Blaikie8a40f702012-01-17 06:56:22 +00004162 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004163
John McCall8cb679e2010-11-15 09:13:47 +00004164 case Type::STK_FloatingComplex:
4165 switch (DestTy->getScalarTypeKind()) {
4166 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004167 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004168 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004169 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004170 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004171 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4172 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004173 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004174 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004175 return CK_FloatingCast;
4176 }
John McCall8cb679e2010-11-15 09:13:47 +00004177 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004178 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004179 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004180 Src = ImpCastExprToType(Src.take(),
4181 SrcTy->castAs<ComplexType>()->getElementType(),
4182 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004183 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004184 case Type::STK_CPointer:
4185 case Type::STK_ObjCObjectPointer:
4186 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004187 llvm_unreachable("valid complex float->pointer cast?");
4188 case Type::STK_MemberPointer:
4189 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004190 }
David Blaikie8a40f702012-01-17 06:56:22 +00004191 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004192
John McCall8cb679e2010-11-15 09:13:47 +00004193 case Type::STK_IntegralComplex:
4194 switch (DestTy->getScalarTypeKind()) {
4195 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004196 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004197 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004198 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004199 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004200 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4201 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004202 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004203 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004204 return CK_IntegralCast;
4205 }
John McCall8cb679e2010-11-15 09:13:47 +00004206 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004207 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004208 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004209 Src = ImpCastExprToType(Src.take(),
4210 SrcTy->castAs<ComplexType>()->getElementType(),
4211 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004212 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004213 case Type::STK_CPointer:
4214 case Type::STK_ObjCObjectPointer:
4215 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004216 llvm_unreachable("valid complex int->pointer cast?");
4217 case Type::STK_MemberPointer:
4218 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004219 }
David Blaikie8a40f702012-01-17 06:56:22 +00004220 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004221 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004222
John McCalld7646252010-11-14 08:17:51 +00004223 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004224}
4225
Anders Carlsson525b76b2009-10-16 02:48:28 +00004226bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004227 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004228 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004229
Anders Carlssonde71adf2007-11-27 05:51:55 +00004230 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004231 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004232 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004233 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004234 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004235 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004236 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004237 } else
4238 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004239 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004240 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004241
John McCalle3027922010-08-25 11:45:40 +00004242 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004243 return false;
4244}
4245
John Wiegley01296292011-04-08 18:41:53 +00004246ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4247 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004248 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004249
Anders Carlsson43d70f82009-10-16 05:23:41 +00004250 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004251
Nate Begemanc8961a42009-06-27 22:05:55 +00004252 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4253 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004254 // In OpenCL, casts between vectors of different types are not allowed.
4255 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004256 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004257 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
4258 || (getLangOptions().OpenCL &&
4259 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004260 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004261 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004262 return ExprError();
4263 }
John McCalle3027922010-08-25 11:45:40 +00004264 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004265 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004266 }
4267
Nate Begemanbd956c42009-06-28 02:36:38 +00004268 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004269 // conversion will take place first from scalar to elt type, and then
4270 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004271 if (SrcTy->isPointerType())
4272 return Diag(R.getBegin(),
4273 diag::err_invalid_conversion_between_vector_and_scalar)
4274 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004275
4276 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004277 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004278 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004279 if (CastExprRes.isInvalid())
4280 return ExprError();
4281 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004282
John McCalle3027922010-08-25 11:45:40 +00004283 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004284 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004285}
4286
John McCalldadc5752010-08-24 06:29:42 +00004287ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004288Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4289 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004290 SourceLocation RParenLoc, Expr *CastExpr) {
4291 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004292 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004293
Richard Trieuba63ce62011-09-09 01:45:06 +00004294 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004295 if (D.isInvalidType())
4296 return ExprError();
4297
4298 if (getLangOptions().CPlusPlus) {
4299 // Check that there are no default arguments (C++ only).
4300 CheckExtraCXXDefaultArguments(D);
4301 }
4302
John McCall42856de2011-10-01 05:17:03 +00004303 checkUnusedDeclAttributes(D);
4304
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004305 QualType castType = castTInfo->getType();
4306 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004307
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004308 bool isVectorLiteral = false;
4309
4310 // Check for an altivec or OpenCL literal,
4311 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004312 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4313 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004314 if ((getLangOptions().AltiVec || getLangOptions().OpenCL)
4315 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004316 if (PLE && PLE->getNumExprs() == 0) {
4317 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4318 return ExprError();
4319 }
4320 if (PE || PLE->getNumExprs() == 1) {
4321 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4322 if (!E->getType()->isVectorType())
4323 isVectorLiteral = true;
4324 }
4325 else
4326 isVectorLiteral = true;
4327 }
4328
4329 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4330 // then handle it as such.
4331 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004332 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004333
Nate Begeman5ec4b312009-08-10 23:49:36 +00004334 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004335 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4336 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004337 if (isa<ParenListExpr>(CastExpr)) {
4338 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004339 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004340 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004341 }
John McCallebe54742010-01-15 18:56:44 +00004342
Richard Trieuba63ce62011-09-09 01:45:06 +00004343 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004344}
4345
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004346ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4347 SourceLocation RParenLoc, Expr *E,
4348 TypeSourceInfo *TInfo) {
4349 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4350 "Expected paren or paren list expression");
4351
4352 Expr **exprs;
4353 unsigned numExprs;
4354 Expr *subExpr;
4355 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4356 exprs = PE->getExprs();
4357 numExprs = PE->getNumExprs();
4358 } else {
4359 subExpr = cast<ParenExpr>(E)->getSubExpr();
4360 exprs = &subExpr;
4361 numExprs = 1;
4362 }
4363
4364 QualType Ty = TInfo->getType();
4365 assert(Ty->isVectorType() && "Expected vector type");
4366
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004367 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004368 const VectorType *VTy = Ty->getAs<VectorType>();
4369 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4370
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004371 // '(...)' form of vector initialization in AltiVec: the number of
4372 // initializers must be one or must match the size of the vector.
4373 // If a single value is specified in the initializer then it will be
4374 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004375 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004376 // The number of initializers must be one or must match the size of the
4377 // vector. If a single value is specified in the initializer then it will
4378 // be replicated to all the components of the vector
4379 if (numExprs == 1) {
4380 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004381 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4382 if (Literal.isInvalid())
4383 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004384 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004385 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004386 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4387 }
4388 else if (numExprs < numElems) {
4389 Diag(E->getExprLoc(),
4390 diag::err_incorrect_number_of_vector_initializers);
4391 return ExprError();
4392 }
4393 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004394 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004395 }
Tanya Lattner83559382011-07-15 23:07:01 +00004396 else {
4397 // For OpenCL, when the number of initializers is a single value,
4398 // it will be replicated to all components of the vector.
4399 if (getLangOptions().OpenCL &&
4400 VTy->getVectorKind() == VectorType::GenericVector &&
4401 numExprs == 1) {
4402 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004403 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4404 if (Literal.isInvalid())
4405 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004406 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004407 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004408 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4409 }
4410
Benjamin Kramer8001f742012-02-14 12:06:21 +00004411 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004412 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004413 // FIXME: This means that pretty-printing the final AST will produce curly
4414 // braces instead of the original commas.
4415 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4416 &initExprs[0],
4417 initExprs.size(), RParenLoc);
4418 initE->setType(Ty);
4419 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4420}
4421
Sebastian Redla9351792012-02-11 23:51:47 +00004422/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4423/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004424ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004425Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4426 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004427 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004428 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004429
John McCalldadc5752010-08-24 06:29:42 +00004430 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004431
Nate Begeman5ec4b312009-08-10 23:49:36 +00004432 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004433 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4434 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004435
John McCallb268a282010-08-23 23:25:46 +00004436 if (Result.isInvalid()) return ExprError();
4437
4438 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004439}
4440
Sebastian Redla9351792012-02-11 23:51:47 +00004441ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4442 SourceLocation R,
4443 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004444 unsigned nexprs = Val.size();
4445 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004446 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004447 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004448 return Owned(expr);
4449}
4450
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004451/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004452/// constant and the other is not a pointer. Returns true if a diagnostic is
4453/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004454bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004455 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004456 Expr *NullExpr = LHSExpr;
4457 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004458 Expr::NullPointerConstantKind NullKind =
4459 NullExpr->isNullPointerConstant(Context,
4460 Expr::NPC_ValueDependentIsNotNull);
4461
4462 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004463 NullExpr = RHSExpr;
4464 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004465 NullKind =
4466 NullExpr->isNullPointerConstant(Context,
4467 Expr::NPC_ValueDependentIsNotNull);
4468 }
4469
4470 if (NullKind == Expr::NPCK_NotNull)
4471 return false;
4472
4473 if (NullKind == Expr::NPCK_ZeroInteger) {
4474 // In this case, check to make sure that we got here from a "NULL"
4475 // string in the source code.
4476 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004477 SourceLocation loc = NullExpr->getExprLoc();
4478 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004479 return false;
4480 }
4481
4482 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4483 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4484 << NonPointerExpr->getType() << DiagType
4485 << NonPointerExpr->getSourceRange();
4486 return true;
4487}
4488
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004489/// \brief Return false if the condition expression is valid, true otherwise.
4490static bool checkCondition(Sema &S, Expr *Cond) {
4491 QualType CondTy = Cond->getType();
4492
4493 // C99 6.5.15p2
4494 if (CondTy->isScalarType()) return false;
4495
4496 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
4497 if (S.getLangOptions().OpenCL && CondTy->isVectorType())
4498 return false;
4499
4500 // Emit the proper error message.
4501 S.Diag(Cond->getLocStart(), S.getLangOptions().OpenCL ?
4502 diag::err_typecheck_cond_expect_scalar :
4503 diag::err_typecheck_cond_expect_scalar_or_vector)
4504 << CondTy;
4505 return true;
4506}
4507
4508/// \brief Return false if the two expressions can be converted to a vector,
4509/// true otherwise
4510static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4511 ExprResult &RHS,
4512 QualType CondTy) {
4513 // Both operands should be of scalar type.
4514 if (!LHS.get()->getType()->isScalarType()) {
4515 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4516 << CondTy;
4517 return true;
4518 }
4519 if (!RHS.get()->getType()->isScalarType()) {
4520 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4521 << CondTy;
4522 return true;
4523 }
4524
4525 // Implicity convert these scalars to the type of the condition.
4526 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4527 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4528 return false;
4529}
4530
4531/// \brief Handle when one or both operands are void type.
4532static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4533 ExprResult &RHS) {
4534 Expr *LHSExpr = LHS.get();
4535 Expr *RHSExpr = RHS.get();
4536
4537 if (!LHSExpr->getType()->isVoidType())
4538 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4539 << RHSExpr->getSourceRange();
4540 if (!RHSExpr->getType()->isVoidType())
4541 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4542 << LHSExpr->getSourceRange();
4543 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4544 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4545 return S.Context.VoidTy;
4546}
4547
4548/// \brief Return false if the NullExpr can be promoted to PointerTy,
4549/// true otherwise.
4550static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4551 QualType PointerTy) {
4552 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4553 !NullExpr.get()->isNullPointerConstant(S.Context,
4554 Expr::NPC_ValueDependentIsNull))
4555 return true;
4556
4557 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4558 return false;
4559}
4560
4561/// \brief Checks compatibility between two pointers and return the resulting
4562/// type.
4563static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4564 ExprResult &RHS,
4565 SourceLocation Loc) {
4566 QualType LHSTy = LHS.get()->getType();
4567 QualType RHSTy = RHS.get()->getType();
4568
4569 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4570 // Two identical pointers types are always compatible.
4571 return LHSTy;
4572 }
4573
4574 QualType lhptee, rhptee;
4575
4576 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004577 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4578 lhptee = LHSBTy->getPointeeType();
4579 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004580 } else {
John McCall9320b872011-09-09 05:25:32 +00004581 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4582 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004583 }
4584
4585 if (!S.Context.typesAreCompatible(lhptee.getUnqualifiedType(),
4586 rhptee.getUnqualifiedType())) {
4587 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4588 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4589 << RHS.get()->getSourceRange();
4590 // In this situation, we assume void* type. No especially good
4591 // reason, but this is what gcc does, and we do have to pick
4592 // to get a consistent AST.
4593 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4594 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4595 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4596 return incompatTy;
4597 }
4598
4599 // The pointer types are compatible.
4600 // C99 6.5.15p6: If both operands are pointers to compatible types *or* to
4601 // differently qualified versions of compatible types, the result type is
4602 // a pointer to an appropriately qualified version of the *composite*
4603 // type.
4604 // FIXME: Need to calculate the composite type.
4605 // FIXME: Need to add qualifiers
4606
4607 LHS = S.ImpCastExprToType(LHS.take(), LHSTy, CK_BitCast);
4608 RHS = S.ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
4609 return LHSTy;
4610}
4611
4612/// \brief Return the resulting type when the operands are both block pointers.
4613static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4614 ExprResult &LHS,
4615 ExprResult &RHS,
4616 SourceLocation Loc) {
4617 QualType LHSTy = LHS.get()->getType();
4618 QualType RHSTy = RHS.get()->getType();
4619
4620 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4621 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4622 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4623 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4624 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4625 return destType;
4626 }
4627 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4628 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4629 << RHS.get()->getSourceRange();
4630 return QualType();
4631 }
4632
4633 // We have 2 block pointer types.
4634 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4635}
4636
4637/// \brief Return the resulting type when the operands are both pointers.
4638static QualType
4639checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4640 ExprResult &RHS,
4641 SourceLocation Loc) {
4642 // get the pointer types
4643 QualType LHSTy = LHS.get()->getType();
4644 QualType RHSTy = RHS.get()->getType();
4645
4646 // get the "pointed to" types
4647 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4648 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4649
4650 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4651 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4652 // Figure out necessary qualifiers (C99 6.5.15p6)
4653 QualType destPointee
4654 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4655 QualType destType = S.Context.getPointerType(destPointee);
4656 // Add qualifiers if necessary.
4657 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4658 // Promote to void*.
4659 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4660 return destType;
4661 }
4662 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4663 QualType destPointee
4664 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4665 QualType destType = S.Context.getPointerType(destPointee);
4666 // Add qualifiers if necessary.
4667 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4668 // Promote to void*.
4669 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4670 return destType;
4671 }
4672
4673 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4674}
4675
4676/// \brief Return false if the first expression is not an integer and the second
4677/// expression is not a pointer, true otherwise.
4678static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4679 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004680 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004681 if (!PointerExpr->getType()->isPointerType() ||
4682 !Int.get()->getType()->isIntegerType())
4683 return false;
4684
Richard Trieuba63ce62011-09-09 01:45:06 +00004685 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4686 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004687
4688 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4689 << Expr1->getType() << Expr2->getType()
4690 << Expr1->getSourceRange() << Expr2->getSourceRange();
4691 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4692 CK_IntegralToPointer);
4693 return true;
4694}
4695
Richard Trieud33e46e2011-09-06 20:06:39 +00004696/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4697/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004698/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004699QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4700 ExprResult &RHS, ExprValueKind &VK,
4701 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004702 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004703
Richard Trieud33e46e2011-09-06 20:06:39 +00004704 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4705 if (!LHSResult.isUsable()) return QualType();
4706 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004707
Richard Trieud33e46e2011-09-06 20:06:39 +00004708 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4709 if (!RHSResult.isUsable()) return QualType();
4710 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004711
Sebastian Redl1a99f442009-04-16 17:51:27 +00004712 // C++ is sufficiently different to merit its own checker.
4713 if (getLangOptions().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004714 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004715
4716 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004717 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004718
John Wiegley01296292011-04-08 18:41:53 +00004719 Cond = UsualUnaryConversions(Cond.take());
4720 if (Cond.isInvalid())
4721 return QualType();
4722 LHS = UsualUnaryConversions(LHS.take());
4723 if (LHS.isInvalid())
4724 return QualType();
4725 RHS = UsualUnaryConversions(RHS.take());
4726 if (RHS.isInvalid())
4727 return QualType();
4728
4729 QualType CondTy = Cond.get()->getType();
4730 QualType LHSTy = LHS.get()->getType();
4731 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004732
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004733 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004734 if (checkCondition(*this, Cond.get()))
4735 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004736
Chris Lattnere2949f42008-01-06 22:42:25 +00004737 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004738 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004739 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004740
Nate Begemanabb5a732010-09-20 22:41:17 +00004741 // OpenCL: If the condition is a vector, and both operands are scalar,
4742 // attempt to implicity convert them to the vector type to act like the
4743 // built in select.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004744 if (getLangOptions().OpenCL && CondTy->isVectorType())
4745 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004746 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004747
Chris Lattnere2949f42008-01-06 22:42:25 +00004748 // If both operands have arithmetic type, do the usual arithmetic conversions
4749 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004750 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4751 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004752 if (LHS.isInvalid() || RHS.isInvalid())
4753 return QualType();
4754 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004755 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004756
Chris Lattnere2949f42008-01-06 22:42:25 +00004757 // If both operands are the same structure or union type, the result is that
4758 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004759 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4760 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004761 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004762 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004763 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004764 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004765 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004766 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004767
Chris Lattnere2949f42008-01-06 22:42:25 +00004768 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004769 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004770 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004771 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004772 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004773
Steve Naroff039ad3c2008-01-08 01:11:38 +00004774 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4775 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004776 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4777 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004778
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004779 // All objective-c pointer type analysis is done here.
4780 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4781 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004782 if (LHS.isInvalid() || RHS.isInvalid())
4783 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004784 if (!compositeType.isNull())
4785 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004786
4787
Steve Naroff05efa972009-07-01 14:36:47 +00004788 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004789 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4790 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4791 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004792
Steve Naroff05efa972009-07-01 14:36:47 +00004793 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004794 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4795 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4796 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004797
John McCalle84af4e2010-11-13 01:35:44 +00004798 // GCC compatibility: soften pointer/integer mismatch. Note that
4799 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004800 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4801 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004802 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004803 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4804 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004805 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004806
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004807 // Emit a better diagnostic if one of the expressions is a null pointer
4808 // constant and the other is not a pointer type. In this case, the user most
4809 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004810 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004811 return QualType();
4812
Chris Lattnere2949f42008-01-06 22:42:25 +00004813 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004814 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004815 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4816 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004817 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004818}
4819
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004820/// FindCompositeObjCPointerType - Helper method to find composite type of
4821/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004822QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004823 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004824 QualType LHSTy = LHS.get()->getType();
4825 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004826
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004827 // Handle things like Class and struct objc_class*. Here we case the result
4828 // to the pseudo-builtin, because that will be implicitly cast back to the
4829 // redefinition type if an attempt is made to access its fields.
4830 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004831 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004832 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004833 return LHSTy;
4834 }
4835 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004836 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004837 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004838 return RHSTy;
4839 }
4840 // And the same for struct objc_object* / id
4841 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004842 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004843 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004844 return LHSTy;
4845 }
4846 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004847 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004848 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004849 return RHSTy;
4850 }
4851 // And the same for struct objc_selector* / SEL
4852 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004853 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004854 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004855 return LHSTy;
4856 }
4857 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004858 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004859 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004860 return RHSTy;
4861 }
4862 // Check constraints for Objective-C object pointers types.
4863 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004864
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004865 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4866 // Two identical object pointer types are always compatible.
4867 return LHSTy;
4868 }
John McCall9320b872011-09-09 05:25:32 +00004869 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4870 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004871 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004872
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004873 // If both operands are interfaces and either operand can be
4874 // assigned to the other, use that type as the composite
4875 // type. This allows
4876 // xxx ? (A*) a : (B*) b
4877 // where B is a subclass of A.
4878 //
4879 // Additionally, as for assignment, if either type is 'id'
4880 // allow silent coercion. Finally, if the types are
4881 // incompatible then make sure to use 'id' as the composite
4882 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004883
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004884 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4885 // It could return the composite type.
4886 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4887 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4888 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4889 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4890 } else if ((LHSTy->isObjCQualifiedIdType() ||
4891 RHSTy->isObjCQualifiedIdType()) &&
4892 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4893 // Need to handle "id<xx>" explicitly.
4894 // GCC allows qualified id and any Objective-C type to devolve to
4895 // id. Currently localizing to here until clear this should be
4896 // part of ObjCQualifiedIdTypesAreCompatible.
4897 compositeType = Context.getObjCIdType();
4898 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4899 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004900 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004901 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4902 ;
4903 else {
4904 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4905 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004906 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004907 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004908 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4909 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004910 return incompatTy;
4911 }
4912 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004913 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4914 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004915 return compositeType;
4916 }
4917 // Check Objective-C object pointer types and 'void *'
4918 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004919 if (getLangOptions().ObjCAutoRefCount) {
4920 // ARC forbids the implicit conversion of object pointers to 'void *',
4921 // so these types are not compatible.
4922 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4923 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4924 LHS = RHS = true;
4925 return QualType();
4926 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004927 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4928 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4929 QualType destPointee
4930 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4931 QualType destType = Context.getPointerType(destPointee);
4932 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004933 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004934 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004935 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004936 return destType;
4937 }
4938 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004939 if (getLangOptions().ObjCAutoRefCount) {
4940 // ARC forbids the implicit conversion of object pointers to 'void *',
4941 // so these types are not compatible.
4942 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4943 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4944 LHS = RHS = true;
4945 return QualType();
4946 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004947 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
4948 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4949 QualType destPointee
4950 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4951 QualType destType = Context.getPointerType(destPointee);
4952 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00004953 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004954 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00004955 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004956 return destType;
4957 }
4958 return QualType();
4959}
4960
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004961/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004962/// ParenRange in parentheses.
4963static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00004964 const PartialDiagnostic &Note,
4965 SourceRange ParenRange) {
4966 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
4967 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
4968 EndLoc.isValid()) {
4969 Self.Diag(Loc, Note)
4970 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
4971 << FixItHint::CreateInsertion(EndLoc, ")");
4972 } else {
4973 // We can't display the parentheses, so just show the bare note.
4974 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004975 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00004976}
4977
4978static bool IsArithmeticOp(BinaryOperatorKind Opc) {
4979 return Opc >= BO_Mul && Opc <= BO_Shr;
4980}
4981
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004982/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
4983/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00004984/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
4985/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004986static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00004987 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00004988 // Don't strip parenthesis: we should not warn if E is in parenthesis.
4989 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004990 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00004991 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004992
4993 // Built-in binary operator.
4994 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
4995 if (IsArithmeticOp(OP->getOpcode())) {
4996 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00004997 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00004998 return true;
4999 }
5000 }
5001
5002 // Overloaded operator.
5003 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5004 if (Call->getNumArgs() != 2)
5005 return false;
5006
5007 // Make sure this is really a binary operator that is safe to pass into
5008 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5009 OverloadedOperatorKind OO = Call->getOperator();
5010 if (OO < OO_Plus || OO > OO_Arrow)
5011 return false;
5012
5013 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5014 if (IsArithmeticOp(OpKind)) {
5015 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005016 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005017 return true;
5018 }
5019 }
5020
5021 return false;
5022}
5023
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005024static bool IsLogicOp(BinaryOperatorKind Opc) {
5025 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5026}
5027
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005028/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5029/// or is a logical expression such as (x==y) which has int type, but is
5030/// commonly interpreted as boolean.
5031static bool ExprLooksBoolean(Expr *E) {
5032 E = E->IgnoreParenImpCasts();
5033
5034 if (E->getType()->isBooleanType())
5035 return true;
5036 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5037 return IsLogicOp(OP->getOpcode());
5038 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5039 return OP->getOpcode() == UO_LNot;
5040
5041 return false;
5042}
5043
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005044/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5045/// and binary operator are mixed in a way that suggests the programmer assumed
5046/// the conditional operator has higher precedence, for example:
5047/// "int x = a + someBinaryCondition ? 1 : 2".
5048static void DiagnoseConditionalPrecedence(Sema &Self,
5049 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005050 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005051 Expr *LHSExpr,
5052 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005053 BinaryOperatorKind CondOpcode;
5054 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005055
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005056 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005057 return;
5058 if (!ExprLooksBoolean(CondRHS))
5059 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005060
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005061 // The condition is an arithmetic binary expression, with a right-
5062 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005063
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005064 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005065 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005066 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005067
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005068 SuggestParentheses(Self, OpLoc,
5069 Self.PDiag(diag::note_precedence_conditional_silence)
5070 << BinaryOperator::getOpcodeStr(CondOpcode),
5071 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005072
5073 SuggestParentheses(Self, OpLoc,
5074 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005075 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005076}
5077
Steve Naroff83895f72007-09-16 03:34:24 +00005078/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005079/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005080ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005081 SourceLocation ColonLoc,
5082 Expr *CondExpr, Expr *LHSExpr,
5083 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005084 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5085 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005086 OpaqueValueExpr *opaqueValue = 0;
5087 Expr *commonExpr = 0;
5088 if (LHSExpr == 0) {
5089 commonExpr = CondExpr;
5090
5091 // We usually want to apply unary conversions *before* saving, except
5092 // in the special case of a C++ l-value conditional.
5093 if (!(getLangOptions().CPlusPlus
5094 && !commonExpr->isTypeDependent()
5095 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5096 && commonExpr->isGLValue()
5097 && commonExpr->isOrdinaryOrBitFieldObject()
5098 && RHSExpr->isOrdinaryOrBitFieldObject()
5099 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005100 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5101 if (commonRes.isInvalid())
5102 return ExprError();
5103 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005104 }
5105
5106 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5107 commonExpr->getType(),
5108 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005109 commonExpr->getObjectKind(),
5110 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005111 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005112 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005113
John McCall7decc9e2010-11-18 06:31:45 +00005114 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005115 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005116 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5117 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005118 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005119 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5120 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005121 return ExprError();
5122
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005123 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5124 RHS.get());
5125
John McCallc07a0c72011-02-17 10:25:35 +00005126 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005127 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5128 LHS.take(), ColonLoc,
5129 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005130
5131 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005132 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005133 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5134 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005135}
5136
John McCallaba90822011-01-31 23:13:11 +00005137// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005138// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005139// routine is it effectively iqnores the qualifiers on the top level pointee.
5140// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5141// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005142static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005143checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5144 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5145 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005146
Steve Naroff1f4d7272007-05-11 04:00:31 +00005147 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005148 const Type *lhptee, *rhptee;
5149 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005150 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5151 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005152
John McCallaba90822011-01-31 23:13:11 +00005153 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005154
5155 // C99 6.5.16.1p1: This following citation is common to constraints
5156 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5157 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005158 Qualifiers lq;
5159
John McCall31168b02011-06-15 23:02:42 +00005160 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5161 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5162 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5163 // Ignore lifetime for further calculation.
5164 lhq.removeObjCLifetime();
5165 rhq.removeObjCLifetime();
5166 }
5167
John McCall4fff8f62011-02-01 00:10:29 +00005168 if (!lhq.compatiblyIncludes(rhq)) {
5169 // Treat address-space mismatches as fatal. TODO: address subspaces
5170 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5171 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5172
John McCall31168b02011-06-15 23:02:42 +00005173 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005174 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005175 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005176 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005177 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005178 && (lhptee->isVoidType() || rhptee->isVoidType()))
5179 ; // keep old
5180
John McCall31168b02011-06-15 23:02:42 +00005181 // Treat lifetime mismatches as fatal.
5182 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5183 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5184
John McCall4fff8f62011-02-01 00:10:29 +00005185 // For GCC compatibility, other qualifier mismatches are treated
5186 // as still compatible in C.
5187 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5188 }
Steve Naroff3f597292007-05-11 22:18:03 +00005189
Mike Stump4e1f26a2009-02-19 03:04:26 +00005190 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5191 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005192 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005193 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005194 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005195 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005196
Chris Lattner0a788432008-01-03 22:56:36 +00005197 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005198 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005199 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005200 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005201
Chris Lattner0a788432008-01-03 22:56:36 +00005202 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005203 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005204 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005205
5206 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005207 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005208 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005209 }
John McCall4fff8f62011-02-01 00:10:29 +00005210
Mike Stump4e1f26a2009-02-19 03:04:26 +00005211 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005212 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005213 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5214 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005215 // Check if the pointee types are compatible ignoring the sign.
5216 // We explicitly check for char so that we catch "char" vs
5217 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005218 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005219 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005220 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005221 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005222
Chris Lattnerec3a1562009-10-17 20:33:28 +00005223 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005224 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005225 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005226 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005227
John McCall4fff8f62011-02-01 00:10:29 +00005228 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005229 // Types are compatible ignoring the sign. Qualifier incompatibility
5230 // takes priority over sign incompatibility because the sign
5231 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005232 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005233 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005234
John McCallaba90822011-01-31 23:13:11 +00005235 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005236 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005237
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005238 // If we are a multi-level pointer, it's possible that our issue is simply
5239 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5240 // the eventual target type is the same and the pointers have the same
5241 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005242 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005243 do {
John McCall4fff8f62011-02-01 00:10:29 +00005244 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5245 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005246 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005247
John McCall4fff8f62011-02-01 00:10:29 +00005248 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005249 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005250 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005251
Eli Friedman80160bd2009-03-22 23:59:44 +00005252 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005253 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005254 }
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005255 if (!S.getLangOptions().CPlusPlus &&
5256 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5257 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005258 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005259}
5260
John McCallaba90822011-01-31 23:13:11 +00005261/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005262/// block pointer types are compatible or whether a block and normal pointer
5263/// are compatible. It is more restrict than comparing two function pointer
5264// types.
John McCallaba90822011-01-31 23:13:11 +00005265static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005266checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5267 QualType RHSType) {
5268 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5269 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005270
Steve Naroff081c7422008-09-04 15:10:53 +00005271 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005272
Steve Naroff081c7422008-09-04 15:10:53 +00005273 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005274 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5275 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005276
John McCallaba90822011-01-31 23:13:11 +00005277 // In C++, the types have to match exactly.
5278 if (S.getLangOptions().CPlusPlus)
5279 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005280
John McCallaba90822011-01-31 23:13:11 +00005281 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005282
Steve Naroff081c7422008-09-04 15:10:53 +00005283 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005284 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5285 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005286
Richard Trieua871b972011-09-06 20:21:22 +00005287 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005288 return Sema::IncompatibleBlockPointer;
5289
Steve Naroff081c7422008-09-04 15:10:53 +00005290 return ConvTy;
5291}
5292
John McCallaba90822011-01-31 23:13:11 +00005293/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005294/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005295static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005296checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5297 QualType RHSType) {
5298 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5299 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005300
Richard Trieua871b972011-09-06 20:21:22 +00005301 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005302 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005303 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5304 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005305 return Sema::IncompatiblePointer;
5306 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005307 }
Richard Trieua871b972011-09-06 20:21:22 +00005308 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005309 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5310 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005311 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005312 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005313 }
Richard Trieua871b972011-09-06 20:21:22 +00005314 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5315 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005316
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005317 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5318 // make an exception for id<P>
5319 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005320 return Sema::CompatiblePointerDiscardsQualifiers;
5321
Richard Trieua871b972011-09-06 20:21:22 +00005322 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005323 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005324 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005325 return Sema::IncompatibleObjCQualifiedId;
5326 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005327}
5328
John McCall29600e12010-11-16 02:32:08 +00005329Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005330Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005331 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005332 // Fake up an opaque expression. We don't actually care about what
5333 // cast operations are required, so if CheckAssignmentConstraints
5334 // adds casts to this they'll be wasted, but fortunately that doesn't
5335 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005336 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5337 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005338 CastKind K = CK_Invalid;
5339
Richard Trieua871b972011-09-06 20:21:22 +00005340 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005341}
5342
Mike Stump4e1f26a2009-02-19 03:04:26 +00005343/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5344/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005345/// pointers. Here are some objectionable examples that GCC considers warnings:
5346///
5347/// int a, *pint;
5348/// short *pshort;
5349/// struct foo *pfoo;
5350///
5351/// pint = pshort; // warning: assignment from incompatible pointer type
5352/// a = pint; // warning: assignment makes integer from pointer without a cast
5353/// pint = a; // warning: assignment makes pointer from integer without a cast
5354/// pint = pfoo; // warning: assignment from incompatible pointer type
5355///
5356/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005357/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005358///
John McCall8cb679e2010-11-15 09:13:47 +00005359/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005360Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005361Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005362 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005363 QualType RHSType = RHS.get()->getType();
5364 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005365
Chris Lattnera52c2f22008-01-04 23:18:45 +00005366 // Get canonical types. We're not formatting these types, just comparing
5367 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005368 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5369 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005370
Eli Friedman0dfb8892011-10-06 23:00:33 +00005371
John McCalle5255932011-01-31 22:28:28 +00005372 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005373 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005374 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005375 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005376 }
5377
David Chisnallfa35df62012-01-16 17:27:18 +00005378 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
5379 if (AtomicTy->getValueType() == RHSType) {
5380 Kind = CK_NonAtomicToAtomic;
5381 return Compatible;
5382 }
5383 }
5384
5385 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(RHSType)) {
5386 if (AtomicTy->getValueType() == LHSType) {
5387 Kind = CK_AtomicToNonAtomic;
5388 return Compatible;
5389 }
5390 }
5391
5392
Douglas Gregor6b754842008-10-28 00:22:11 +00005393 // If the left-hand side is a reference type, then we are in a
5394 // (rare!) case where we've allowed the use of references in C,
5395 // e.g., as a parameter type in a built-in function. In this case,
5396 // just make sure that the type referenced is compatible with the
5397 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005398 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005399 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005400 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5401 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005402 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005403 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005404 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005405 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005406 }
John McCalle5255932011-01-31 22:28:28 +00005407
Nate Begemanbd956c42009-06-28 02:36:38 +00005408 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5409 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005410 if (LHSType->isExtVectorType()) {
5411 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005412 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005413 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005414 // CK_VectorSplat does T -> vector T, so first cast to the
5415 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005416 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5417 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005418 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005419 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005420 }
5421 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005422 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005423 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005424 }
Mike Stump11289f42009-09-09 15:08:12 +00005425
John McCalle5255932011-01-31 22:28:28 +00005426 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005427 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5428 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005429 // Allow assignments of an AltiVec vector type to an equivalent GCC
5430 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005431 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005432 Kind = CK_BitCast;
5433 return Compatible;
5434 }
5435
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005436 // If we are allowing lax vector conversions, and LHS and RHS are both
5437 // vectors, the total size only needs to be the same. This is a bitcast;
5438 // no bits are changed but the result type is different.
5439 if (getLangOptions().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005440 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005441 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005442 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005443 }
Chris Lattner881a2122008-01-04 23:32:24 +00005444 }
5445 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005446 }
Eli Friedman3360d892008-05-30 18:07:22 +00005447
John McCalle5255932011-01-31 22:28:28 +00005448 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005449 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
5450 !(getLangOptions().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005451 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005452 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005453 }
Eli Friedman3360d892008-05-30 18:07:22 +00005454
John McCalle5255932011-01-31 22:28:28 +00005455 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005456 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005457 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005458 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005459 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005460 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005461 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005462
John McCalle5255932011-01-31 22:28:28 +00005463 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005464 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005465 Kind = CK_IntegralToPointer; // FIXME: null?
5466 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005467 }
John McCalle5255932011-01-31 22:28:28 +00005468
5469 // C pointers are not compatible with ObjC object pointers,
5470 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005471 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005472 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005473 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005474 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005475 return Compatible;
5476 }
5477
5478 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005479 if (RHSType->isObjCClassType() &&
5480 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005481 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005482 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005483 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005484 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005485
John McCalle5255932011-01-31 22:28:28 +00005486 Kind = CK_BitCast;
5487 return IncompatiblePointer;
5488 }
5489
5490 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005491 if (RHSType->getAs<BlockPointerType>()) {
5492 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005493 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005494 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005495 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005496 }
John McCalle5255932011-01-31 22:28:28 +00005497
Steve Naroff081c7422008-09-04 15:10:53 +00005498 return Incompatible;
5499 }
5500
John McCalle5255932011-01-31 22:28:28 +00005501 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005502 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005503 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005504 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005505 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005506 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005507 }
5508
5509 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005510 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005511 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005512 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005513 }
5514
John McCalle5255932011-01-31 22:28:28 +00005515 // id -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005516 if (getLangOptions().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005517 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005518 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005519 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005520
John McCalle5255932011-01-31 22:28:28 +00005521 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005522 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005523 if (RHSPT->getPointeeType()->isVoidType()) {
5524 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005525 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005526 }
John McCall8cb679e2010-11-15 09:13:47 +00005527
Chris Lattnera52c2f22008-01-04 23:18:45 +00005528 return Incompatible;
5529 }
5530
John McCalle5255932011-01-31 22:28:28 +00005531 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005532 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005533 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005534 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005535 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005536 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005537 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005538 if (getLangOptions().ObjCAutoRefCount &&
5539 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005540 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005541 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005542 return result;
John McCalle5255932011-01-31 22:28:28 +00005543 }
5544
5545 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005546 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005547 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005548 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005549 }
5550
John McCalle5255932011-01-31 22:28:28 +00005551 // In general, C pointers are not compatible with ObjC object pointers,
5552 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005553 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005554 Kind = CK_CPointerToObjCPointerCast;
5555
John McCalle5255932011-01-31 22:28:28 +00005556 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005557 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005558 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005559 }
5560
5561 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005562 if (LHSType->isObjCClassType() &&
5563 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005564 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005565 return Compatible;
5566 }
5567
Steve Naroffaccc4882009-07-20 17:56:53 +00005568 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005569 }
John McCalle5255932011-01-31 22:28:28 +00005570
5571 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005572 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005573 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005574 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005575 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005576 }
5577
Steve Naroff7cae42b2009-07-10 23:34:53 +00005578 return Incompatible;
5579 }
John McCalle5255932011-01-31 22:28:28 +00005580
5581 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005582 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005583 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005584 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005585 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005586 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005587 }
Eli Friedman3360d892008-05-30 18:07:22 +00005588
John McCalle5255932011-01-31 22:28:28 +00005589 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005590 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005591 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005592 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005593 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005594
Chris Lattnera52c2f22008-01-04 23:18:45 +00005595 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005596 }
John McCalle5255932011-01-31 22:28:28 +00005597
5598 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005599 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005600 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005601 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005602 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005603 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005604 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005605
John McCalle5255932011-01-31 22:28:28 +00005606 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005607 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005608 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005609 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005610 }
5611
Steve Naroff7cae42b2009-07-10 23:34:53 +00005612 return Incompatible;
5613 }
Eli Friedman3360d892008-05-30 18:07:22 +00005614
John McCalle5255932011-01-31 22:28:28 +00005615 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005616 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5617 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005618 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005619 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005620 }
Bill Wendling216423b2007-05-30 06:30:29 +00005621 }
John McCalle5255932011-01-31 22:28:28 +00005622
Steve Naroff98cf3e92007-06-06 18:38:38 +00005623 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005624}
5625
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005626/// \brief Constructs a transparent union from an expression that is
5627/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005628static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5629 ExprResult &EResult, QualType UnionType,
5630 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005631 // Build an initializer list that designates the appropriate member
5632 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005633 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005634 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005635 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005636 SourceLocation());
5637 Initializer->setType(UnionType);
5638 Initializer->setInitializedFieldInUnion(Field);
5639
5640 // Build a compound literal constructing a value of the transparent
5641 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005642 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005643 EResult = S.Owned(
5644 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5645 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005646}
5647
5648Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005649Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005650 ExprResult &RHS) {
5651 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005652
Mike Stump11289f42009-09-09 15:08:12 +00005653 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005654 // transparent_union GCC extension.
5655 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005656 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005657 return Incompatible;
5658
5659 // The field to initialize within the transparent union.
5660 RecordDecl *UD = UT->getDecl();
5661 FieldDecl *InitField = 0;
5662 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005663 for (RecordDecl::field_iterator it = UD->field_begin(),
5664 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005665 it != itend; ++it) {
5666 if (it->getType()->isPointerType()) {
5667 // If the transparent union contains a pointer type, we allow:
5668 // 1) void pointer
5669 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005670 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005671 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005672 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005673 InitField = *it;
5674 break;
5675 }
Mike Stump11289f42009-09-09 15:08:12 +00005676
Richard Trieueb299142011-09-06 20:40:12 +00005677 if (RHS.get()->isNullPointerConstant(Context,
5678 Expr::NPC_ValueDependentIsNull)) {
5679 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5680 CK_NullToPointer);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005681 InitField = *it;
5682 break;
5683 }
5684 }
5685
John McCall8cb679e2010-11-15 09:13:47 +00005686 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005687 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005688 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005689 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005690 InitField = *it;
5691 break;
5692 }
5693 }
5694
5695 if (!InitField)
5696 return Incompatible;
5697
Richard Trieueb299142011-09-06 20:40:12 +00005698 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005699 return Compatible;
5700}
5701
Chris Lattner9bad62c2008-01-04 18:04:52 +00005702Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005703Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5704 bool Diagnose) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005705 if (getLangOptions().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005706 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005707 // C++ 5.17p3: If the left operand is not of class type, the
5708 // expression is implicitly converted (C++ 4) to the
5709 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005710 ExprResult Res;
5711 if (Diagnose) {
5712 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5713 AA_Assigning);
5714 } else {
5715 ImplicitConversionSequence ICS =
5716 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5717 /*SuppressUserConversions=*/false,
5718 /*AllowExplicit=*/false,
5719 /*InOverloadResolution=*/false,
5720 /*CStyle=*/false,
5721 /*AllowObjCWritebackConversion=*/false);
5722 if (ICS.isFailure())
5723 return Incompatible;
5724 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5725 ICS, AA_Assigning);
5726 }
John Wiegley01296292011-04-08 18:41:53 +00005727 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005728 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005729 Sema::AssignConvertType result = Compatible;
5730 if (getLangOptions().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005731 !CheckObjCARCUnavailableWeakConversion(LHSType,
5732 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005733 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005734 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005735 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005736 }
5737
5738 // FIXME: Currently, we fall through and treat C++ classes like C
5739 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005740 // FIXME: We also fall through for atomics; not sure what should
5741 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005742 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005743
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005744 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5745 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005746 if ((LHSType->isPointerType() ||
5747 LHSType->isObjCObjectPointerType() ||
5748 LHSType->isBlockPointerType())
5749 && RHS.get()->isNullPointerConstant(Context,
5750 Expr::NPC_ValueDependentIsNull)) {
5751 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005752 return Compatible;
5753 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005754
Chris Lattnere6dcd502007-10-16 02:55:40 +00005755 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005756 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005757 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005758 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005759 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005760 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005761 if (!LHSType->isReferenceType()) {
5762 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5763 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005764 return Incompatible;
5765 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005766
John McCall8cb679e2010-11-15 09:13:47 +00005767 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005768 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005769 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005770
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005771 // C99 6.5.16.1p2: The value of the right operand is converted to the
5772 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005773 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5774 // so that we can use references in built-in functions even in C.
5775 // The getNonReferenceType() call makes sure that the resulting expression
5776 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005777 if (result != Incompatible && RHS.get()->getType() != LHSType)
5778 RHS = ImpCastExprToType(RHS.take(),
5779 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005780 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005781}
5782
Richard Trieueb299142011-09-06 20:40:12 +00005783QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5784 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005785 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005786 << LHS.get()->getType() << RHS.get()->getType()
5787 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005788 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005789}
5790
Richard Trieu859d23f2011-09-06 21:01:04 +00005791QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005792 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005793 if (!IsCompAssign) {
5794 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5795 if (LHS.isInvalid())
5796 return QualType();
5797 }
5798 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5799 if (RHS.isInvalid())
5800 return QualType();
5801
Mike Stump4e1f26a2009-02-19 03:04:26 +00005802 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005803 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005804 QualType LHSType =
5805 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5806 QualType RHSType =
5807 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005808
Nate Begeman191a6b12008-07-14 18:02:46 +00005809 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005810 if (LHSType == RHSType)
5811 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005812
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005813 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005814 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5815 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5816 if (LHSType->isExtVectorType()) {
5817 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5818 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005819 }
5820
Richard Trieuba63ce62011-09-09 01:45:06 +00005821 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005822 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5823 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005824 }
5825
Eli Friedman1408bc92011-06-23 18:10:35 +00005826 if (getLangOptions().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005827 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005828 // If we are allowing lax vector conversions, and LHS and RHS are both
5829 // vectors, the total size only needs to be the same. This is a
5830 // bitcast; no bits are changed but the result type is different.
5831 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005832 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5833 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005834 }
5835
Nate Begemanbd956c42009-06-28 02:36:38 +00005836 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5837 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5838 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005839 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005840 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005841 std::swap(RHS, LHS);
5842 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005843 }
Mike Stump11289f42009-09-09 15:08:12 +00005844
Nate Begeman886448d2009-06-28 19:12:57 +00005845 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005846 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005847 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005848 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5849 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005850 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005851 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005852 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005853 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5854 if (swapped) std::swap(RHS, LHS);
5855 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005856 }
5857 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005858 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5859 RHSType->isRealFloatingType()) {
5860 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005861 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005862 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005863 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005864 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5865 if (swapped) std::swap(RHS, LHS);
5866 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005867 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005868 }
5869 }
Mike Stump11289f42009-09-09 15:08:12 +00005870
Nate Begeman886448d2009-06-28 19:12:57 +00005871 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005872 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005873 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005874 << LHS.get()->getType() << RHS.get()->getType()
5875 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005876 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005877}
5878
Richard Trieuf8916e12011-09-16 00:53:10 +00005879// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5880// expression. These are mainly cases where the null pointer is used as an
5881// integer instead of a pointer.
5882static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5883 SourceLocation Loc, bool IsCompare) {
5884 // The canonical way to check for a GNU null is with isNullPointerConstant,
5885 // but we use a bit of a hack here for speed; this is a relatively
5886 // hot path, and isNullPointerConstant is slow.
5887 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5888 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5889
5890 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5891
5892 // Avoid analyzing cases where the result will either be invalid (and
5893 // diagnosed as such) or entirely valid and not something to warn about.
5894 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5895 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5896 return;
5897
5898 // Comparison operations would not make sense with a null pointer no matter
5899 // what the other expression is.
5900 if (!IsCompare) {
5901 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5902 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5903 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5904 return;
5905 }
5906
5907 // The rest of the operations only make sense with a null pointer
5908 // if the other expression is a pointer.
5909 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5910 NonNullType->canDecayToPointerType())
5911 return;
5912
5913 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5914 << LHSNull /* LHS is NULL */ << NonNullType
5915 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5916}
5917
Richard Trieu859d23f2011-09-06 21:01:04 +00005918QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005919 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005920 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005921 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5922
Richard Trieu859d23f2011-09-06 21:01:04 +00005923 if (LHS.get()->getType()->isVectorType() ||
5924 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005925 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005926
Richard Trieuba63ce62011-09-09 01:45:06 +00005927 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005928 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005929 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005930
David Chisnallfa35df62012-01-16 17:27:18 +00005931
Richard Trieu859d23f2011-09-06 21:01:04 +00005932 if (!LHS.get()->getType()->isArithmeticType() ||
David Chisnallfa35df62012-01-16 17:27:18 +00005933 !RHS.get()->getType()->isArithmeticType()) {
5934 if (IsCompAssign &&
5935 LHS.get()->getType()->isAtomicType() &&
5936 RHS.get()->getType()->isArithmeticType())
5937 return compType;
Richard Trieu859d23f2011-09-06 21:01:04 +00005938 return InvalidOperands(Loc, LHS, RHS);
David Chisnallfa35df62012-01-16 17:27:18 +00005939 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005940
Chris Lattnerfaa54172010-01-12 21:23:57 +00005941 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00005942 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005943 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005944 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005945 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
5946 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005947
Chris Lattnerfaa54172010-01-12 21:23:57 +00005948 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00005949}
5950
Chris Lattnerfaa54172010-01-12 21:23:57 +00005951QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00005952 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005953 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5954
Richard Trieu859d23f2011-09-06 21:01:04 +00005955 if (LHS.get()->getType()->isVectorType() ||
5956 RHS.get()->getType()->isVectorType()) {
5957 if (LHS.get()->getType()->hasIntegerRepresentation() &&
5958 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00005959 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005960 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00005961 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005962
Richard Trieuba63ce62011-09-09 01:45:06 +00005963 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005964 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005965 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005966
Richard Trieu859d23f2011-09-06 21:01:04 +00005967 if (!LHS.get()->getType()->isIntegerType() ||
5968 !RHS.get()->getType()->isIntegerType())
5969 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005970
Chris Lattnerfaa54172010-01-12 21:23:57 +00005971 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00005972 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00005973 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00005974 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
5975 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005976
Chris Lattnerfaa54172010-01-12 21:23:57 +00005977 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00005978}
5979
Chandler Carruthc9332212011-06-27 08:02:19 +00005980/// \brief Diagnose invalid arithmetic on two void pointers.
5981static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00005982 Expr *LHSExpr, Expr *RHSExpr) {
Chandler Carruthc9332212011-06-27 08:02:19 +00005983 S.Diag(Loc, S.getLangOptions().CPlusPlus
5984 ? diag::err_typecheck_pointer_arith_void_type
5985 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00005986 << 1 /* two pointers */ << LHSExpr->getSourceRange()
5987 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00005988}
5989
5990/// \brief Diagnose invalid arithmetic on a void pointer.
5991static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
5992 Expr *Pointer) {
5993 S.Diag(Loc, S.getLangOptions().CPlusPlus
5994 ? diag::err_typecheck_pointer_arith_void_type
5995 : diag::ext_gnu_void_ptr)
5996 << 0 /* one pointer */ << Pointer->getSourceRange();
5997}
5998
5999/// \brief Diagnose invalid arithmetic on two function pointers.
6000static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6001 Expr *LHS, Expr *RHS) {
6002 assert(LHS->getType()->isAnyPointerType());
6003 assert(RHS->getType()->isAnyPointerType());
6004 S.Diag(Loc, S.getLangOptions().CPlusPlus
6005 ? diag::err_typecheck_pointer_arith_function_type
6006 : diag::ext_gnu_ptr_func_arith)
6007 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6008 // We only show the second type if it differs from the first.
6009 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6010 RHS->getType())
6011 << RHS->getType()->getPointeeType()
6012 << LHS->getSourceRange() << RHS->getSourceRange();
6013}
6014
6015/// \brief Diagnose invalid arithmetic on a function pointer.
6016static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6017 Expr *Pointer) {
6018 assert(Pointer->getType()->isAnyPointerType());
6019 S.Diag(Loc, S.getLangOptions().CPlusPlus
6020 ? diag::err_typecheck_pointer_arith_function_type
6021 : diag::ext_gnu_ptr_func_arith)
6022 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6023 << 0 /* one pointer, so only one type */
6024 << Pointer->getSourceRange();
6025}
6026
Richard Trieu993f3ab2011-09-12 18:08:02 +00006027/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006028///
6029/// \returns True if pointer has incomplete type
6030static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6031 Expr *Operand) {
6032 if ((Operand->getType()->isPointerType() &&
6033 !Operand->getType()->isDependentType()) ||
6034 Operand->getType()->isObjCObjectPointerType()) {
6035 QualType PointeeTy = Operand->getType()->getPointeeType();
6036 if (S.RequireCompleteType(
6037 Loc, PointeeTy,
6038 S.PDiag(diag::err_typecheck_arithmetic_incomplete_type)
6039 << PointeeTy << Operand->getSourceRange()))
6040 return true;
6041 }
6042 return false;
6043}
6044
Chandler Carruthc9332212011-06-27 08:02:19 +00006045/// \brief Check the validity of an arithmetic pointer operand.
6046///
6047/// If the operand has pointer type, this code will check for pointer types
6048/// which are invalid in arithmetic operations. These will be diagnosed
6049/// appropriately, including whether or not the use is supported as an
6050/// extension.
6051///
6052/// \returns True when the operand is valid to use (even if as an extension).
6053static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6054 Expr *Operand) {
6055 if (!Operand->getType()->isAnyPointerType()) return true;
6056
6057 QualType PointeeTy = Operand->getType()->getPointeeType();
6058 if (PointeeTy->isVoidType()) {
6059 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
6060 return !S.getLangOptions().CPlusPlus;
6061 }
6062 if (PointeeTy->isFunctionType()) {
6063 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
6064 return !S.getLangOptions().CPlusPlus;
6065 }
6066
Richard Trieuaba22802011-09-02 02:15:37 +00006067 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006068
6069 return true;
6070}
6071
6072/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6073/// operands.
6074///
6075/// This routine will diagnose any invalid arithmetic on pointer operands much
6076/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6077/// for emitting a single diagnostic even for operations where both LHS and RHS
6078/// are (potentially problematic) pointers.
6079///
6080/// \returns True when the operand is valid to use (even if as an extension).
6081static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006082 Expr *LHSExpr, Expr *RHSExpr) {
6083 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6084 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006085 if (!isLHSPointer && !isRHSPointer) return true;
6086
6087 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006088 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6089 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006090
6091 // Check for arithmetic on pointers to incomplete types.
6092 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6093 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6094 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006095 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6096 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6097 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006098
6099 return !S.getLangOptions().CPlusPlus;
6100 }
6101
6102 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6103 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6104 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006105 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6106 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6107 RHSExpr);
6108 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006109
6110 return !S.getLangOptions().CPlusPlus;
6111 }
6112
Richard Trieu4ae7e972011-09-06 21:13:51 +00006113 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6114 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006115
Chandler Carruthc9332212011-06-27 08:02:19 +00006116 return true;
6117}
6118
Richard Trieub10c6312011-09-01 22:53:23 +00006119/// \brief Check bad cases where we step over interface counts.
6120static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6121 SourceLocation OpLoc,
6122 Expr *Op) {
6123 assert(Op->getType()->isAnyPointerType());
6124 QualType PointeeTy = Op->getType()->getPointeeType();
6125 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6126 return true;
6127
6128 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6129 << PointeeTy << Op->getSourceRange();
6130 return false;
6131}
6132
Nico Weberccec40d2012-03-02 22:01:22 +00006133/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6134/// literal.
6135static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6136 Expr *LHSExpr, Expr *RHSExpr) {
6137 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6138 Expr* IndexExpr = RHSExpr;
6139 if (!StrExpr) {
6140 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6141 IndexExpr = LHSExpr;
6142 }
6143
6144 bool IsStringPlusInt = StrExpr &&
6145 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6146 if (!IsStringPlusInt)
6147 return;
6148
6149 llvm::APSInt index;
6150 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6151 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6152 if (index.isNonNegative() &&
6153 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6154 index.isUnsigned()))
6155 return;
6156 }
6157
6158 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6159 Self.Diag(OpLoc, diag::warn_string_plus_int)
6160 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6161
6162 // Only print a fixit for "str" + int, not for int + "str".
6163 if (IndexExpr == RHSExpr) {
6164 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6165 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6166 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6167 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6168 << FixItHint::CreateInsertion(EndLoc, "]");
6169 } else
6170 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6171}
6172
Richard Trieu993f3ab2011-09-12 18:08:02 +00006173/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006174static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006175 Expr *LHSExpr, Expr *RHSExpr) {
6176 assert(LHSExpr->getType()->isAnyPointerType());
6177 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006178 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006179 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6180 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006181}
6182
Chris Lattnerfaa54172010-01-12 21:23:57 +00006183QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006184 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6185 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006186 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6187
Richard Trieu4ae7e972011-09-06 21:13:51 +00006188 if (LHS.get()->getType()->isVectorType() ||
6189 RHS.get()->getType()->isVectorType()) {
6190 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006191 if (CompLHSTy) *CompLHSTy = compType;
6192 return compType;
6193 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006194
Richard Trieu4ae7e972011-09-06 21:13:51 +00006195 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6196 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006197 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006198
Nico Weberccec40d2012-03-02 22:01:22 +00006199 // Diagnose "string literal" '+' int.
6200 if (Opc == BO_Add)
6201 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6202
Steve Naroffe4718892007-04-27 18:30:00 +00006203 // handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006204 if (LHS.get()->getType()->isArithmeticType() &&
6205 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006206 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006207 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006208 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006209
David Chisnallfa35df62012-01-16 17:27:18 +00006210 if (LHS.get()->getType()->isAtomicType() &&
6211 RHS.get()->getType()->isArithmeticType()) {
6212 *CompLHSTy = LHS.get()->getType();
6213 return compType;
6214 }
6215
Eli Friedman8e122982008-05-18 18:08:51 +00006216 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006217 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006218 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006219 std::swap(PExp, IExp);
6220
Richard Trieub420bca2011-09-12 18:37:54 +00006221 if (!PExp->getType()->isAnyPointerType())
6222 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006223
Richard Trieub420bca2011-09-12 18:37:54 +00006224 if (!IExp->getType()->isIntegerType())
6225 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006226
Richard Trieub420bca2011-09-12 18:37:54 +00006227 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6228 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006229
Richard Trieub420bca2011-09-12 18:37:54 +00006230 // Diagnose bad cases where we step over interface counts.
6231 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6232 return QualType();
6233
6234 // Check array bounds for pointer arithemtic
6235 CheckArrayAccess(PExp, IExp);
6236
6237 if (CompLHSTy) {
6238 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6239 if (LHSTy.isNull()) {
6240 LHSTy = LHS.get()->getType();
6241 if (LHSTy->isPromotableIntegerType())
6242 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006243 }
Richard Trieub420bca2011-09-12 18:37:54 +00006244 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006245 }
6246
Richard Trieub420bca2011-09-12 18:37:54 +00006247 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006248}
6249
Chris Lattner2a3569b2008-04-07 05:30:13 +00006250// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006251QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006252 SourceLocation Loc,
6253 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006254 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6255
Richard Trieu4ae7e972011-09-06 21:13:51 +00006256 if (LHS.get()->getType()->isVectorType() ||
6257 RHS.get()->getType()->isVectorType()) {
6258 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006259 if (CompLHSTy) *CompLHSTy = compType;
6260 return compType;
6261 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006262
Richard Trieu4ae7e972011-09-06 21:13:51 +00006263 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6264 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006265 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006266
Chris Lattner4d62f422007-12-09 21:53:25 +00006267 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006268
Chris Lattner4d62f422007-12-09 21:53:25 +00006269 // Handle the common case first (both operands are arithmetic).
Richard Trieu4ae7e972011-09-06 21:13:51 +00006270 if (LHS.get()->getType()->isArithmeticType() &&
6271 RHS.get()->getType()->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006272 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006273 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006274 }
Mike Stump11289f42009-09-09 15:08:12 +00006275
David Chisnallfa35df62012-01-16 17:27:18 +00006276 if (LHS.get()->getType()->isAtomicType() &&
6277 RHS.get()->getType()->isArithmeticType()) {
6278 *CompLHSTy = LHS.get()->getType();
6279 return compType;
6280 }
6281
Chris Lattner4d62f422007-12-09 21:53:25 +00006282 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006283 if (LHS.get()->getType()->isAnyPointerType()) {
6284 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006285
Chris Lattner12bdebb2009-04-24 23:50:08 +00006286 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006287 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006288 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006289
Chris Lattner4d62f422007-12-09 21:53:25 +00006290 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006291 if (RHS.get()->getType()->isIntegerType()) {
6292 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006293 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006294
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006295 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006296 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6297 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006298
Richard Trieu4ae7e972011-09-06 21:13:51 +00006299 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6300 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006301 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006302
Chris Lattner4d62f422007-12-09 21:53:25 +00006303 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006304 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006305 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006306 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006307
Eli Friedman168fe152009-05-16 13:54:38 +00006308 if (getLangOptions().CPlusPlus) {
6309 // Pointee types must be the same: C++ [expr.add]
6310 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006311 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006312 }
6313 } else {
6314 // Pointee types must be compatible C99 6.5.6p3
6315 if (!Context.typesAreCompatible(
6316 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6317 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006318 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006319 return QualType();
6320 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006321 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006322
Chandler Carruthc9332212011-06-27 08:02:19 +00006323 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006324 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006325 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006326
Richard Trieu4ae7e972011-09-06 21:13:51 +00006327 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006328 return Context.getPointerDiffType();
6329 }
6330 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006331
Richard Trieu4ae7e972011-09-06 21:13:51 +00006332 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006333}
6334
Douglas Gregor0bf31402010-10-08 23:50:27 +00006335static bool isScopedEnumerationType(QualType T) {
6336 if (const EnumType *ET = dyn_cast<EnumType>(T))
6337 return ET->getDecl()->isScoped();
6338 return false;
6339}
6340
Richard Trieue4a19fb2011-09-06 21:21:28 +00006341static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006342 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006343 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006344 llvm::APSInt Right;
6345 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006346 if (RHS.get()->isValueDependent() ||
6347 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006348 return;
6349
6350 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006351 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006352 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006353 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006354 return;
6355 }
6356 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006357 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006358 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006359 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006360 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006361 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006362 return;
6363 }
6364 if (Opc != BO_Shl)
6365 return;
6366
6367 // When left shifting an ICE which is signed, we can check for overflow which
6368 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6369 // integers have defined behavior modulo one more than the maximum value
6370 // representable in the result type, so never warn for those.
6371 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006372 if (LHS.get()->isValueDependent() ||
6373 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6374 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006375 return;
6376 llvm::APInt ResultBits =
6377 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6378 if (LeftBits.uge(ResultBits))
6379 return;
6380 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6381 Result = Result.shl(Right);
6382
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006383 // Print the bit representation of the signed integer as an unsigned
6384 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006385 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006386 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6387
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006388 // If we are only missing a sign bit, this is less likely to result in actual
6389 // bugs -- if the result is cast back to an unsigned type, it will have the
6390 // expected value. Thus we place this behind a different warning that can be
6391 // turned off separately if needed.
6392 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006393 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006394 << HexResult.str() << LHSType
6395 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006396 return;
6397 }
6398
6399 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006400 << HexResult.str() << Result.getMinSignedBits() << LHSType
6401 << Left.getBitWidth() << LHS.get()->getSourceRange()
6402 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006403}
6404
Chris Lattner2a3569b2008-04-07 05:30:13 +00006405// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006406QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006407 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006408 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006409 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6410
Chris Lattner5c11c412007-12-12 05:47:28 +00006411 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006412 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6413 !RHS.get()->getType()->hasIntegerRepresentation())
6414 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006415
Douglas Gregor0bf31402010-10-08 23:50:27 +00006416 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6417 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006418 if (isScopedEnumerationType(LHS.get()->getType()) ||
6419 isScopedEnumerationType(RHS.get()->getType())) {
6420 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006421 }
6422
Nate Begemane46ee9a2009-10-25 02:26:48 +00006423 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006424 if (LHS.get()->getType()->isVectorType() ||
6425 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006426 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006427
Chris Lattner5c11c412007-12-12 05:47:28 +00006428 // Shifts don't perform usual arithmetic conversions, they just do integer
6429 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006430
John McCall57cdd882010-12-16 19:28:59 +00006431 // For the LHS, do usual unary conversions, but then reset them away
6432 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006433 ExprResult OldLHS = LHS;
6434 LHS = UsualUnaryConversions(LHS.take());
6435 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006436 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006437 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006438 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006439
6440 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006441 RHS = UsualUnaryConversions(RHS.take());
6442 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006443 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006444
Ryan Flynnf53fab82009-08-07 16:20:20 +00006445 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006446 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006447
Chris Lattner5c11c412007-12-12 05:47:28 +00006448 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006449 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006450}
6451
Chandler Carruth17773fc2010-07-10 12:30:03 +00006452static bool IsWithinTemplateSpecialization(Decl *D) {
6453 if (DeclContext *DC = D->getDeclContext()) {
6454 if (isa<ClassTemplateSpecializationDecl>(DC))
6455 return true;
6456 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6457 return FD->isFunctionTemplateSpecialization();
6458 }
6459 return false;
6460}
6461
Richard Trieueea56f72011-09-02 03:48:46 +00006462/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006463static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6464 ExprResult &RHS) {
6465 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6466 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006467
6468 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6469 if (!LHSEnumType)
6470 return;
6471 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6472 if (!RHSEnumType)
6473 return;
6474
6475 // Ignore anonymous enums.
6476 if (!LHSEnumType->getDecl()->getIdentifier())
6477 return;
6478 if (!RHSEnumType->getDecl()->getIdentifier())
6479 return;
6480
6481 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6482 return;
6483
6484 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6485 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006486 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006487}
6488
Richard Trieudd82a5c2011-09-02 02:55:45 +00006489/// \brief Diagnose bad pointer comparisons.
6490static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006491 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006492 bool IsError) {
6493 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006494 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006495 << LHS.get()->getType() << RHS.get()->getType()
6496 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006497}
6498
6499/// \brief Returns false if the pointers are converted to a composite type,
6500/// true otherwise.
6501static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006502 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006503 // C++ [expr.rel]p2:
6504 // [...] Pointer conversions (4.10) and qualification
6505 // conversions (4.4) are performed on pointer operands (or on
6506 // a pointer operand and a null pointer constant) to bring
6507 // them to their composite pointer type. [...]
6508 //
6509 // C++ [expr.eq]p1 uses the same notion for (in)equality
6510 // comparisons of pointers.
6511
6512 // C++ [expr.eq]p2:
6513 // In addition, pointers to members can be compared, or a pointer to
6514 // member and a null pointer constant. Pointer to member conversions
6515 // (4.11) and qualification conversions (4.4) are performed to bring
6516 // them to a common type. If one operand is a null pointer constant,
6517 // the common type is the type of the other operand. Otherwise, the
6518 // common type is a pointer to member type similar (4.4) to the type
6519 // of one of the operands, with a cv-qualification signature (4.4)
6520 // that is the union of the cv-qualification signatures of the operand
6521 // types.
6522
Richard Trieu1762d7c2011-09-06 21:27:33 +00006523 QualType LHSType = LHS.get()->getType();
6524 QualType RHSType = RHS.get()->getType();
6525 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6526 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006527
6528 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006529 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006530 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006531 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006532 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006533 return true;
6534 }
6535
6536 if (NonStandardCompositeType)
6537 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006538 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6539 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006540
Richard Trieu1762d7c2011-09-06 21:27:33 +00006541 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6542 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006543 return false;
6544}
6545
6546static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006547 ExprResult &LHS,
6548 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006549 bool IsError) {
6550 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6551 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006552 << LHS.get()->getType() << RHS.get()->getType()
6553 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006554}
6555
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006556// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006557QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006558 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006559 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006560 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6561
John McCalle3027922010-08-25 11:45:40 +00006562 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006563
Chris Lattner9a152e22009-12-05 05:40:13 +00006564 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006565 if (LHS.get()->getType()->isVectorType() ||
6566 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006567 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006568
Richard Trieub80728f2011-09-06 21:43:51 +00006569 QualType LHSType = LHS.get()->getType();
6570 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006571
Richard Trieub80728f2011-09-06 21:43:51 +00006572 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6573 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006574
Richard Trieub80728f2011-09-06 21:43:51 +00006575 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006576
Richard Trieub80728f2011-09-06 21:43:51 +00006577 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006578 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006579 !LHS.get()->getLocStart().isMacroID() &&
6580 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006581 // For non-floating point types, check for self-comparisons of the form
6582 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6583 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006584 //
6585 // NOTE: Don't warn about comparison expressions resulting from macro
6586 // expansion. Also don't warn about comparisons which are only self
6587 // comparisons within a template specialization. The warnings should catch
6588 // obvious cases in the definition of the template anyways. The idea is to
6589 // warn when the typed comparison operator will always evaluate to the same
6590 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006591 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006592 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006593 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006594 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006595 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006596 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006597 << (Opc == BO_EQ
6598 || Opc == BO_LE
6599 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006600 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006601 !DRL->getDecl()->getType()->isReferenceType() &&
6602 !DRR->getDecl()->getType()->isReferenceType()) {
6603 // what is it always going to eval to?
6604 char always_evals_to;
6605 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006606 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006607 always_evals_to = 0; // false
6608 break;
John McCalle3027922010-08-25 11:45:40 +00006609 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006610 always_evals_to = 1; // true
6611 break;
6612 default:
6613 // best we can say is 'a constant'
6614 always_evals_to = 2; // e.g. array1 <= array2
6615 break;
6616 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006617 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006618 << 1 // array
6619 << always_evals_to);
6620 }
6621 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006622 }
Mike Stump11289f42009-09-09 15:08:12 +00006623
Chris Lattner222b8bd2009-03-08 19:39:53 +00006624 if (isa<CastExpr>(LHSStripped))
6625 LHSStripped = LHSStripped->IgnoreParenCasts();
6626 if (isa<CastExpr>(RHSStripped))
6627 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006628
Chris Lattner222b8bd2009-03-08 19:39:53 +00006629 // Warn about comparisons against a string constant (unless the other
6630 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006631 Expr *literalString = 0;
6632 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006633 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006634 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006635 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006636 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006637 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006638 } else if ((isa<StringLiteral>(RHSStripped) ||
6639 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006640 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006641 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006642 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006643 literalStringStripped = RHSStripped;
6644 }
6645
6646 if (literalString) {
6647 std::string resultComparison;
6648 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006649 case BO_LT: resultComparison = ") < 0"; break;
6650 case BO_GT: resultComparison = ") > 0"; break;
6651 case BO_LE: resultComparison = ") <= 0"; break;
6652 case BO_GE: resultComparison = ") >= 0"; break;
6653 case BO_EQ: resultComparison = ") == 0"; break;
6654 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006655 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006656 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006657
Ted Kremenek3427fac2011-02-23 01:52:04 +00006658 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006659 PDiag(diag::warn_stringcompare)
6660 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006661 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006662 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006663 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006664
Douglas Gregorec170db2010-06-08 19:50:34 +00006665 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006666 if (LHS.get()->getType()->isArithmeticType() &&
6667 RHS.get()->getType()->isArithmeticType()) {
6668 UsualArithmeticConversions(LHS, RHS);
6669 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006670 return QualType();
6671 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006672 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006673 LHS = UsualUnaryConversions(LHS.take());
6674 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006675 return QualType();
6676
Richard Trieub80728f2011-09-06 21:43:51 +00006677 RHS = UsualUnaryConversions(RHS.take());
6678 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006679 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006680 }
6681
Richard Trieub80728f2011-09-06 21:43:51 +00006682 LHSType = LHS.get()->getType();
6683 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006684
Douglas Gregorca63811b2008-11-19 03:25:36 +00006685 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006686 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006687
Richard Trieuba63ce62011-09-09 01:45:06 +00006688 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006689 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006690 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006691 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006692 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006693 if (LHSType->hasFloatingRepresentation())
6694 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006695
Richard Trieub80728f2011-09-06 21:43:51 +00006696 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006697 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006698 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006699
Richard Trieub80728f2011-09-06 21:43:51 +00006700 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006701 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006702 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006703 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006704
Douglas Gregorf267edd2010-06-15 21:38:40 +00006705 // All of the following pointer-related warnings are GCC extensions, except
6706 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006707 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006708 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006709 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006710 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006711 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006712
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006713 if (getLangOptions().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006714 if (LCanPointeeTy == RCanPointeeTy)
6715 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006716 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006717 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6718 // Valid unless comparison between non-null pointer and function pointer
6719 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006720 // In a SFINAE context, we treat this as a hard error to maintain
6721 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006722 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6723 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006724 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006725 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006726
6727 if (isSFINAEContext())
6728 return QualType();
6729
Richard Trieub80728f2011-09-06 21:43:51 +00006730 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006731 return ResultTy;
6732 }
6733 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006734
Richard Trieub80728f2011-09-06 21:43:51 +00006735 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006736 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006737 else
6738 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006739 }
Eli Friedman16c209612009-08-23 00:27:47 +00006740 // C99 6.5.9p2 and C99 6.5.8p2
6741 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6742 RCanPointeeTy.getUnqualifiedType())) {
6743 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006744 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006745 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006746 << LHSType << RHSType << LHS.get()->getSourceRange()
6747 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006748 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006749 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006750 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6751 // Valid unless comparison between non-null pointer and function pointer
6752 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006753 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006754 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006755 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006756 } else {
6757 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006758 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006759 }
John McCall7684dde2011-03-11 04:25:25 +00006760 if (LCanPointeeTy != RCanPointeeTy) {
6761 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006762 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006763 else
Richard Trieub80728f2011-09-06 21:43:51 +00006764 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006765 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006766 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006767 }
Mike Stump11289f42009-09-09 15:08:12 +00006768
Sebastian Redl576fd422009-05-10 18:38:11 +00006769 if (getLangOptions().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006770 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006771 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006772 return ResultTy;
6773
Mike Stump11289f42009-09-09 15:08:12 +00006774 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006775 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006776 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006777 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006778 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006779 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6780 RHS = ImpCastExprToType(RHS.take(), LHSType,
6781 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006782 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006783 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006784 return ResultTy;
6785 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006786 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006787 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006788 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006789 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6790 LHS = ImpCastExprToType(LHS.take(), RHSType,
6791 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006792 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006793 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006794 return ResultTy;
6795 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006796
6797 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006798 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006799 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6800 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006801 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006802 else
6803 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006804 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006805
6806 // Handle scoped enumeration types specifically, since they don't promote
6807 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00006808 if (LHS.get()->getType()->isEnumeralType() &&
6809 Context.hasSameUnqualifiedType(LHS.get()->getType(),
6810 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006811 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00006812 }
Mike Stump11289f42009-09-09 15:08:12 +00006813
Steve Naroff081c7422008-09-04 15:10:53 +00006814 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00006815 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00006816 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00006817 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
6818 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006819
Steve Naroff081c7422008-09-04 15:10:53 +00006820 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00006821 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00006822 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006823 << LHSType << RHSType << LHS.get()->getSourceRange()
6824 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00006825 }
Richard Trieub80728f2011-09-06 21:43:51 +00006826 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006827 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00006828 }
John Wiegley01296292011-04-08 18:41:53 +00006829
Steve Naroffe18f94c2008-09-28 01:11:11 +00006830 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00006831 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00006832 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
6833 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00006834 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00006835 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006836 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00006837 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00006838 ->getPointeeType()->isVoidType())))
6839 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00006840 << LHSType << RHSType << LHS.get()->getSourceRange()
6841 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00006842 }
John McCall7684dde2011-03-11 04:25:25 +00006843 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006844 LHS = ImpCastExprToType(LHS.take(), RHSType,
6845 RHSType->isPointerType() ? CK_BitCast
6846 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006847 else
John McCall9320b872011-09-09 05:25:32 +00006848 RHS = ImpCastExprToType(RHS.take(), LHSType,
6849 LHSType->isPointerType() ? CK_BitCast
6850 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006851 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00006852 }
Steve Naroff081c7422008-09-04 15:10:53 +00006853
Richard Trieub80728f2011-09-06 21:43:51 +00006854 if (LHSType->isObjCObjectPointerType() ||
6855 RHSType->isObjCObjectPointerType()) {
6856 const PointerType *LPT = LHSType->getAs<PointerType>();
6857 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00006858 if (LPT || RPT) {
6859 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
6860 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006861
Steve Naroff753567f2008-11-17 19:49:16 +00006862 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00006863 !Context.typesAreCompatible(LHSType, RHSType)) {
6864 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006865 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00006866 }
John McCall7684dde2011-03-11 04:25:25 +00006867 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00006868 LHS = ImpCastExprToType(LHS.take(), RHSType,
6869 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00006870 else
John McCall9320b872011-09-09 05:25:32 +00006871 RHS = ImpCastExprToType(RHS.take(), LHSType,
6872 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006873 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00006874 }
Richard Trieub80728f2011-09-06 21:43:51 +00006875 if (LHSType->isObjCObjectPointerType() &&
6876 RHSType->isObjCObjectPointerType()) {
6877 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
6878 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006879 /*isError*/false);
John McCall7684dde2011-03-11 04:25:25 +00006880 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006881 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006882 else
Richard Trieub80728f2011-09-06 21:43:51 +00006883 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006884 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00006885 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00006886 }
Richard Trieub80728f2011-09-06 21:43:51 +00006887 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
6888 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00006889 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006890 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00006891 if ((LHSIsNull && LHSType->isIntegerType()) ||
6892 (RHSIsNull && RHSType->isIntegerType())) {
Richard Trieuba63ce62011-09-09 01:45:06 +00006893 if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006894 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
Richard Trieuba63ce62011-09-09 01:45:06 +00006895 } else if (IsRelational && !getLangOptions().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00006896 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
Douglas Gregorf267edd2010-06-15 21:38:40 +00006897 else if (getLangOptions().CPlusPlus) {
6898 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
6899 isError = true;
6900 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00006901 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00006902
Chris Lattnerd99bd522009-08-23 00:03:44 +00006903 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00006904 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00006905 << LHSType << RHSType << LHS.get()->getSourceRange()
6906 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00006907 if (isError)
6908 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00006909 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006910
Richard Trieub80728f2011-09-06 21:43:51 +00006911 if (LHSType->isIntegerType())
6912 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006913 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00006914 else
Richard Trieub80728f2011-09-06 21:43:51 +00006915 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00006916 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006917 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00006918 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00006919
Steve Naroff4b191572008-09-04 16:56:14 +00006920 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006921 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006922 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
6923 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006924 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006925 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006926 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00006927 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
6928 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00006929 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00006930 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00006931
Richard Trieub80728f2011-09-06 21:43:51 +00006932 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00006933}
6934
Tanya Lattner20248222012-01-16 21:02:28 +00006935
6936// Return a signed type that is of identical size and number of elements.
6937// For floating point vectors, return an integer type of identical size
6938// and number of elements.
6939QualType Sema::GetSignedVectorType(QualType V) {
6940 const VectorType *VTy = V->getAs<VectorType>();
6941 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
6942 if (TypeSize == Context.getTypeSize(Context.CharTy))
6943 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
6944 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
6945 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
6946 else if (TypeSize == Context.getTypeSize(Context.IntTy))
6947 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
6948 else if (TypeSize == Context.getTypeSize(Context.LongTy))
6949 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
6950 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
6951 "Unhandled vector element size in vector compare");
6952 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
6953}
6954
Nate Begeman191a6b12008-07-14 18:02:46 +00006955/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00006956/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00006957/// like a scalar comparison, a vector comparison produces a vector of integer
6958/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00006959QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00006960 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006961 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00006962 // Check to make sure we're operating on vectors of the same type and width,
6963 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00006964 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00006965 if (vType.isNull())
6966 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00006967
Richard Trieubcce2f72011-09-07 01:19:57 +00006968 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006969
Anton Yartsev530deb92011-03-27 15:36:07 +00006970 // If AltiVec, the comparison results in a numeric type, i.e.
6971 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00006972 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00006973 return Context.getLogicalOperationType();
6974
Nate Begeman191a6b12008-07-14 18:02:46 +00006975 // For non-floating point types, check for self-comparisons of the form
6976 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6977 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00006978 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00006979 if (DeclRefExpr* DRL
6980 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
6981 if (DeclRefExpr* DRR
6982 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00006983 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00006984 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00006985 PDiag(diag::warn_comparison_always)
6986 << 0 // self-
6987 << 2 // "a constant"
6988 );
Nate Begeman191a6b12008-07-14 18:02:46 +00006989 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006990
Nate Begeman191a6b12008-07-14 18:02:46 +00006991 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00006992 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00006993 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00006994 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00006995 }
Tanya Lattner20248222012-01-16 21:02:28 +00006996
6997 // Return a signed type for the vector.
6998 return GetSignedVectorType(LHSType);
6999}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007000
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007001QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7002 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007003 // Ensure that either both operands are of the same vector type, or
7004 // one operand is of a vector type and the other is of its element type.
7005 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7006 if (vType.isNull() || vType->isFloatingType())
7007 return InvalidOperands(Loc, LHS, RHS);
7008
7009 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007010}
7011
Steve Naroff218bc2b2007-05-04 21:54:46 +00007012inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007013 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007014 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7015
Richard Trieubcce2f72011-09-07 01:19:57 +00007016 if (LHS.get()->getType()->isVectorType() ||
7017 RHS.get()->getType()->isVectorType()) {
7018 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7019 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007020 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007021
Richard Trieubcce2f72011-09-07 01:19:57 +00007022 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007023 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007024
Richard Trieubcce2f72011-09-07 01:19:57 +00007025 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7026 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007027 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007028 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007029 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007030 LHS = LHSResult.take();
7031 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007032
Richard Trieubcce2f72011-09-07 01:19:57 +00007033 if (LHS.get()->getType()->isIntegralOrUnscopedEnumerationType() &&
7034 RHS.get()->getType()->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007035 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007036 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007037}
7038
Steve Naroff218bc2b2007-05-04 21:54:46 +00007039inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007040 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007041
Tanya Lattner20248222012-01-16 21:02:28 +00007042 // Check vector operands differently.
7043 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7044 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7045
Chris Lattner8406c512010-07-13 19:41:32 +00007046 // Diagnose cases where the user write a logical and/or but probably meant a
7047 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7048 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007049 if (LHS.get()->getType()->isIntegerType() &&
7050 !LHS.get()->getType()->isBooleanType() &&
7051 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007052 // Don't warn in macros or template instantiations.
7053 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007054 // If the RHS can be constant folded, and if it constant folds to something
7055 // that isn't 0 or 1 (which indicate a potential logical operation that
7056 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007057 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007058 llvm::APSInt Result;
7059 if (RHS.get()->EvaluateAsInt(Result, Context))
Richard Trieubcce2f72011-09-07 01:19:57 +00007060 if ((getLangOptions().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007061 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007062 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007063 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007064 << (Opc == BO_LAnd ? "&&" : "||");
7065 // Suggest replacing the logical operator with the bitwise version
7066 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7067 << (Opc == BO_LAnd ? "&" : "|")
7068 << FixItHint::CreateReplacement(SourceRange(
7069 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
7070 getLangOptions())),
7071 Opc == BO_LAnd ? "&" : "|");
7072 if (Opc == BO_LAnd)
7073 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7074 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7075 << FixItHint::CreateRemoval(
7076 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007077 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007078 0, getSourceManager(),
7079 getLangOptions()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007080 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007081 }
Chris Lattner938533d2010-07-24 01:10:11 +00007082 }
Chris Lattner8406c512010-07-13 19:41:32 +00007083
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007084 if (!Context.getLangOptions().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007085 LHS = UsualUnaryConversions(LHS.take());
7086 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007087 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007088
Richard Trieubcce2f72011-09-07 01:19:57 +00007089 RHS = UsualUnaryConversions(RHS.take());
7090 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007091 return QualType();
7092
Richard Trieubcce2f72011-09-07 01:19:57 +00007093 if (!LHS.get()->getType()->isScalarType() ||
7094 !RHS.get()->getType()->isScalarType())
7095 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007096
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007097 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007098 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007099
John McCall4a2429a2010-06-04 00:29:51 +00007100 // The following is safe because we only use this method for
7101 // non-overloadable operands.
7102
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007103 // C++ [expr.log.and]p1
7104 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007105 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007106 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7107 if (LHSRes.isInvalid())
7108 return InvalidOperands(Loc, LHS, RHS);
7109 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007110
Richard Trieubcce2f72011-09-07 01:19:57 +00007111 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7112 if (RHSRes.isInvalid())
7113 return InvalidOperands(Loc, LHS, RHS);
7114 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007115
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007116 // C++ [expr.log.and]p2
7117 // C++ [expr.log.or]p2
7118 // The result is a bool.
7119 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007120}
7121
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007122/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7123/// is a read-only property; return true if so. A readonly property expression
7124/// depends on various declarations and thus must be treated specially.
7125///
Mike Stump11289f42009-09-09 15:08:12 +00007126static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007127 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7128 if (!PropExpr) return false;
7129 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007130
John McCall526ab472011-10-25 17:37:35 +00007131 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7132 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007133 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007134 PropExpr->getBase()->getType();
7135
John McCall526ab472011-10-25 17:37:35 +00007136 if (const ObjCObjectPointerType *OPT =
7137 BaseType->getAsObjCInterfacePointerType())
7138 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7139 if (S.isPropertyReadonly(PDecl, IFace))
7140 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007141 return false;
7142}
7143
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007144static bool IsConstProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007145 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7146 if (!PropExpr) return false;
7147 if (PropExpr->isImplicitProperty()) return false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007148
John McCall526ab472011-10-25 17:37:35 +00007149 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7150 QualType T = PDecl->getType().getNonReferenceType();
7151 return T.isConstQualified();
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007152}
7153
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007154static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007155 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7156 if (!ME) return false;
7157 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7158 ObjCMessageExpr *Base =
7159 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7160 if (!Base) return false;
7161 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007162}
7163
Chris Lattner30bd3272008-11-18 01:22:49 +00007164/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7165/// emit an error and return true. If so, return false.
7166static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007167 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007168 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007169 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007170 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7171 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +00007172 else if (Expr::MLV_ConstQualified && IsConstProperty(E, S))
7173 IsLV = Expr::MLV_Valid;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007174 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7175 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007176 if (IsLV == Expr::MLV_Valid)
7177 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007178
Chris Lattner30bd3272008-11-18 01:22:49 +00007179 unsigned Diag = 0;
7180 bool NeedType = false;
7181 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007182 case Expr::MLV_ConstQualified:
7183 Diag = diag::err_typecheck_assign_const;
7184
John McCalld4631322011-06-17 06:42:21 +00007185 // In ARC, use some specialized diagnostics for occasions where we
7186 // infer 'const'. These are always pseudo-strong variables.
John McCall31168b02011-06-15 23:02:42 +00007187 if (S.getLangOptions().ObjCAutoRefCount) {
7188 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7189 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7190 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7191
John McCalld4631322011-06-17 06:42:21 +00007192 // Use the normal diagnostic if it's pseudo-__strong but the
7193 // user actually wrote 'const'.
7194 if (var->isARCPseudoStrong() &&
7195 (!var->getTypeSourceInfo() ||
7196 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7197 // There are two pseudo-strong cases:
7198 // - self
John McCall31168b02011-06-15 23:02:42 +00007199 ObjCMethodDecl *method = S.getCurMethodDecl();
7200 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007201 Diag = method->isClassMethod()
7202 ? diag::err_typecheck_arc_assign_self_class_method
7203 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007204
7205 // - fast enumeration variables
7206 else
John McCall31168b02011-06-15 23:02:42 +00007207 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007208
John McCall31168b02011-06-15 23:02:42 +00007209 SourceRange Assign;
7210 if (Loc != OrigLoc)
7211 Assign = SourceRange(OrigLoc, OrigLoc);
7212 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7213 // We need to preserve the AST regardless, so migration tool
7214 // can do its job.
7215 return false;
7216 }
7217 }
7218 }
7219
7220 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007221 case Expr::MLV_ArrayType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007222 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7223 NeedType = true;
7224 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007225 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007226 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7227 NeedType = true;
7228 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007229 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007230 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7231 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007232 case Expr::MLV_Valid:
7233 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007234 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007235 case Expr::MLV_MemberFunction:
7236 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007237 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7238 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007239 case Expr::MLV_IncompleteType:
7240 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007241 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007242 S.PDiag(diag::err_typecheck_incomplete_type_not_modifiable_lvalue)
Anders Carlssond624e162009-08-26 23:45:07 +00007243 << E->getSourceRange());
Chris Lattner9bad62c2008-01-04 18:04:52 +00007244 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007245 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7246 break;
Steve Naroffba756cb2008-09-26 14:41:28 +00007247 case Expr::MLV_NotBlockQualified:
Chris Lattner30bd3272008-11-18 01:22:49 +00007248 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7249 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007250 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007251 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007252 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007253 case Expr::MLV_InvalidMessageExpression:
7254 Diag = diag::error_readonly_message_assignment;
7255 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007256 case Expr::MLV_SubObjCPropertySetting:
7257 Diag = diag::error_no_subobject_property_setting;
7258 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007259 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007260
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007261 SourceRange Assign;
7262 if (Loc != OrigLoc)
7263 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007264 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007265 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007266 else
Mike Stump11289f42009-09-09 15:08:12 +00007267 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007268 return true;
7269}
7270
7271
7272
7273// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007274QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007275 SourceLocation Loc,
7276 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007277 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7278
Chris Lattner326f7572008-11-18 01:30:42 +00007279 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007280 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007281 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007282
Richard Trieuda4f43a62011-09-07 01:33:52 +00007283 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007284 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7285 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007286 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007287 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007288 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007289 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007290 if (RHS.isInvalid())
7291 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007292 // Special case of NSObject attributes on c-style pointer types.
7293 if (ConvTy == IncompatiblePointer &&
7294 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007295 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007296 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007297 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007298 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007299
John McCall7decc9e2010-11-18 06:31:45 +00007300 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007301 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007302 Diag(Loc, diag::err_objc_object_assignment)
7303 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007304
Chris Lattnerea714382008-08-21 18:04:13 +00007305 // If the RHS is a unary plus or minus, check to see if they = and + are
7306 // right next to each other. If so, the user may have typo'd "x =+ 4"
7307 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007308 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007309 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7310 RHSCheck = ICE->getSubExpr();
7311 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007312 if ((UO->getOpcode() == UO_Plus ||
7313 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007314 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007315 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007316 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007317 // And there is a space or other character before the subexpr of the
7318 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007319 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007320 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007321 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007322 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007323 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007324 }
Chris Lattnerea714382008-08-21 18:04:13 +00007325 }
John McCall31168b02011-06-15 23:02:42 +00007326
7327 if (ConvTy == Compatible) {
7328 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007329 checkRetainCycles(LHSExpr, RHS.get());
Fariborz Jahanian5f98da02011-06-24 18:25:34 +00007330 else if (getLangOptions().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007331 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007332 }
Chris Lattnerea714382008-08-21 18:04:13 +00007333 } else {
7334 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007335 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007336 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007337
Chris Lattner326f7572008-11-18 01:30:42 +00007338 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007339 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007340 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007341
Richard Trieuda4f43a62011-09-07 01:33:52 +00007342 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007343
Steve Naroff98cf3e92007-06-06 18:38:38 +00007344 // C99 6.5.16p3: The type of an assignment expression is the type of the
7345 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007346 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007347 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7348 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007349 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007350 // operand.
John McCall01cbf2d2010-10-12 02:19:57 +00007351 return (getLangOptions().CPlusPlus
7352 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007353}
7354
Chris Lattner326f7572008-11-18 01:30:42 +00007355// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007356static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007357 SourceLocation Loc) {
John Wiegley01296292011-04-08 18:41:53 +00007358 S.DiagnoseUnusedExprResult(LHS.get());
Argyrios Kyrtzidis639ffb02010-06-30 10:53:14 +00007359
John McCall3aef3d82011-04-10 19:13:55 +00007360 LHS = S.CheckPlaceholderExpr(LHS.take());
7361 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007362 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007363 return QualType();
7364
John McCall73d36182010-10-12 07:14:40 +00007365 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7366 // operands, but not unary promotions.
7367 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007368
John McCall34376a62010-12-04 03:47:34 +00007369 // So we treat the LHS as a ignored value, and in C++ we allow the
7370 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007371 LHS = S.IgnoredValueConversions(LHS.take());
7372 if (LHS.isInvalid())
7373 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007374
7375 if (!S.getLangOptions().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007376 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7377 if (RHS.isInvalid())
7378 return QualType();
7379 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007380 S.RequireCompleteType(Loc, RHS.get()->getType(),
7381 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007382 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007383
John Wiegley01296292011-04-08 18:41:53 +00007384 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007385}
7386
Steve Naroff7a5af782007-07-13 16:58:59 +00007387/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7388/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007389static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7390 ExprValueKind &VK,
7391 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007392 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007393 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007394 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007395
Chris Lattner6b0cf142008-11-21 07:05:48 +00007396 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007397 // Atomic types can be used for increment / decrement where the non-atomic
7398 // versions can, so ignore the _Atomic() specifier for the purpose of
7399 // checking.
7400 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7401 ResType = ResAtomicType->getValueType();
7402
Chris Lattner6b0cf142008-11-21 07:05:48 +00007403 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007404
John McCall4bc41ae2010-11-18 19:01:18 +00007405 if (S.getLangOptions().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007406 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007407 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007408 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007409 return QualType();
7410 }
7411 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007412 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007413 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007414 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007415 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007416 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007417 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007418 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007419
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007420 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007421 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007422 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007423 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007424 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007425 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007426 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007427 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007428 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007429 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007430 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007431 IsInc, IsPrefix);
Anton Yartsev85129b82011-02-07 02:17:30 +00007432 } else if (S.getLangOptions().AltiVec && ResType->isVectorType()) {
7433 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007434 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007435 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007436 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007437 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007438 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007439 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007440 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007441 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007442 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007443 // In C++, a prefix increment is the same type as the operand. Otherwise
7444 // (in C or with postfix), the increment is the unqualified type of the
7445 // operand.
Richard Trieuba63ce62011-09-09 01:45:06 +00007446 if (IsPrefix && S.getLangOptions().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007447 VK = VK_LValue;
7448 return ResType;
7449 } else {
7450 VK = VK_RValue;
7451 return ResType.getUnqualifiedType();
7452 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007453}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007454
7455
Anders Carlsson806700f2008-02-01 07:15:58 +00007456/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007457/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007458/// where the declaration is needed for type checking. We only need to
7459/// handle cases when the expression references a function designator
7460/// or is an lvalue. Here are some examples:
7461/// - &(x) => x
7462/// - &*****f => f for f a function designator.
7463/// - &s.xx => s
7464/// - &s.zz[1].yy -> s, if zz is an array
7465/// - *(x + 1) -> x, if x is an array
7466/// - &"123"[2] -> 0
7467/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007468static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007469 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007470 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007471 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007472 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007473 // If this is an arrow operator, the address is an offset from
7474 // the base's value, so the object the base refers to is
7475 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007476 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007477 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007478 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007479 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007480 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007481 // FIXME: This code shouldn't be necessary! We should catch the implicit
7482 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007483 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7484 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7485 if (ICE->getSubExpr()->getType()->isArrayType())
7486 return getPrimaryDecl(ICE->getSubExpr());
7487 }
7488 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007489 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007490 case Stmt::UnaryOperatorClass: {
7491 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007492
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007493 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007494 case UO_Real:
7495 case UO_Imag:
7496 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007497 return getPrimaryDecl(UO->getSubExpr());
7498 default:
7499 return 0;
7500 }
7501 }
Steve Naroff47500512007-04-19 23:00:49 +00007502 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007503 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007504 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007505 // If the result of an implicit cast is an l-value, we care about
7506 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007507 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007508 default:
7509 return 0;
7510 }
7511}
7512
Richard Trieu5f376f62011-09-07 21:46:33 +00007513namespace {
7514 enum {
7515 AO_Bit_Field = 0,
7516 AO_Vector_Element = 1,
7517 AO_Property_Expansion = 2,
7518 AO_Register_Variable = 3,
7519 AO_No_Error = 4
7520 };
7521}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007522/// \brief Diagnose invalid operand for address of operations.
7523///
7524/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007525static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7526 Expr *E, unsigned Type) {
7527 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7528}
7529
Steve Naroff47500512007-04-19 23:00:49 +00007530/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007531/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007532/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007533/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007534/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007535/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007536/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007537static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007538 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007539 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7540 if (PTy->getKind() == BuiltinType::Overload) {
7541 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7542 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7543 << OrigOp.get()->getSourceRange();
7544 return QualType();
7545 }
7546
7547 return S.Context.OverloadTy;
7548 }
7549
7550 if (PTy->getKind() == BuiltinType::UnknownAny)
7551 return S.Context.UnknownAnyTy;
7552
7553 if (PTy->getKind() == BuiltinType::BoundMember) {
7554 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7555 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007556 return QualType();
7557 }
John McCall526ab472011-10-25 17:37:35 +00007558
7559 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7560 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007561 }
John McCall8d08b9b2010-08-27 09:08:28 +00007562
John McCall526ab472011-10-25 17:37:35 +00007563 if (OrigOp.get()->isTypeDependent())
7564 return S.Context.DependentTy;
7565
7566 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007567
John McCall8d08b9b2010-08-27 09:08:28 +00007568 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007569 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007570
John McCall4bc41ae2010-11-18 19:01:18 +00007571 if (S.getLangOptions().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007572 // Implement C99-only parts of addressof rules.
7573 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007574 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007575 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7576 // (assuming the deref expression is valid).
7577 return uOp->getSubExpr()->getType();
7578 }
7579 // Technically, there should be a check for array subscript
7580 // expressions here, but the result of one is always an lvalue anyway.
7581 }
John McCallf3a88602011-02-03 08:15:49 +00007582 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007583 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007584 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007585
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007586 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007587 bool sfinae = S.isSFINAEContext();
7588 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7589 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007590 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007591 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007592 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007593 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007594 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007595 } else if (lval == Expr::LV_MemberFunction) {
7596 // If it's an instance method, make a member pointer.
7597 // The expression must have exactly the form &A::foo.
7598
7599 // If the underlying expression isn't a decl ref, give up.
7600 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007601 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007602 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007603 return QualType();
7604 }
7605 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7606 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7607
7608 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007609 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007610 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007611 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007612
7613 // The method was named without a qualifier.
7614 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007615 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007616 << op->getSourceRange();
7617 }
7618
John McCall4bc41ae2010-11-18 19:01:18 +00007619 return S.Context.getMemberPointerType(op->getType(),
7620 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007621 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007622 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007623 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007624 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007625 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007626 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007627 AddressOfError = AO_Property_Expansion;
7628 } else {
7629 // FIXME: emit more specific diag...
7630 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7631 << op->getSourceRange();
7632 return QualType();
7633 }
Steve Naroff35d85152007-05-07 00:24:15 +00007634 }
John McCall086a4642010-11-24 05:12:34 +00007635 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007636 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007637 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007638 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007639 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007640 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007641 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007642 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007643 // with the register storage-class specifier.
7644 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007645 // in C++ it is not error to take address of a register
7646 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007647 if (vd->getStorageClass() == SC_Register &&
John McCall4bc41ae2010-11-18 19:01:18 +00007648 !S.getLangOptions().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007649 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007650 }
John McCalld14a8642009-11-21 08:51:07 +00007651 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007652 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007653 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007654 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007655 // Could be a pointer to member, though, if there is an explicit
7656 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007657 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007658 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007659 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007660 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007661 S.Diag(OpLoc,
7662 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007663 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007664 return QualType();
7665 }
Mike Stump11289f42009-09-09 15:08:12 +00007666
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007667 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7668 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007669 return S.Context.getMemberPointerType(op->getType(),
7670 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007671 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007672 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007673 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007674 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007675 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007676
Richard Trieu5f376f62011-09-07 21:46:33 +00007677 if (AddressOfError != AO_No_Error) {
7678 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7679 return QualType();
7680 }
7681
Eli Friedmance7f9002009-05-16 23:27:50 +00007682 if (lval == Expr::LV_IncompleteVoidType) {
7683 // Taking the address of a void variable is technically illegal, but we
7684 // allow it in cases which are otherwise valid.
7685 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007686 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007687 }
7688
Steve Naroff47500512007-04-19 23:00:49 +00007689 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007690 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007691 return S.Context.getObjCObjectPointerType(op->getType());
7692 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007693}
7694
Chris Lattner9156f1b2010-07-05 19:17:26 +00007695/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007696static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7697 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007698 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007699 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007700
John Wiegley01296292011-04-08 18:41:53 +00007701 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7702 if (ConvResult.isInvalid())
7703 return QualType();
7704 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007705 QualType OpTy = Op->getType();
7706 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007707
7708 if (isa<CXXReinterpretCastExpr>(Op)) {
7709 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7710 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7711 Op->getSourceRange());
7712 }
7713
Chris Lattner9156f1b2010-07-05 19:17:26 +00007714 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7715 // is an incomplete type or void. It would be possible to warn about
7716 // dereferencing a void pointer, but it's completely well-defined, and such a
7717 // warning is unlikely to catch any mistakes.
7718 if (const PointerType *PT = OpTy->getAs<PointerType>())
7719 Result = PT->getPointeeType();
7720 else if (const ObjCObjectPointerType *OPT =
7721 OpTy->getAs<ObjCObjectPointerType>())
7722 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007723 else {
John McCall3aef3d82011-04-10 19:13:55 +00007724 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007725 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007726 if (PR.take() != Op)
7727 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007728 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007729
Chris Lattner9156f1b2010-07-05 19:17:26 +00007730 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007731 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007732 << OpTy << Op->getSourceRange();
7733 return QualType();
7734 }
John McCall4bc41ae2010-11-18 19:01:18 +00007735
7736 // Dereferences are usually l-values...
7737 VK = VK_LValue;
7738
7739 // ...except that certain expressions are never l-values in C.
Douglas Gregor5476205b2011-06-23 00:49:38 +00007740 if (!S.getLangOptions().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007741 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007742
7743 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007744}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007745
John McCalle3027922010-08-25 11:45:40 +00007746static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007747 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007748 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007749 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007750 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007751 case tok::periodstar: Opc = BO_PtrMemD; break;
7752 case tok::arrowstar: Opc = BO_PtrMemI; break;
7753 case tok::star: Opc = BO_Mul; break;
7754 case tok::slash: Opc = BO_Div; break;
7755 case tok::percent: Opc = BO_Rem; break;
7756 case tok::plus: Opc = BO_Add; break;
7757 case tok::minus: Opc = BO_Sub; break;
7758 case tok::lessless: Opc = BO_Shl; break;
7759 case tok::greatergreater: Opc = BO_Shr; break;
7760 case tok::lessequal: Opc = BO_LE; break;
7761 case tok::less: Opc = BO_LT; break;
7762 case tok::greaterequal: Opc = BO_GE; break;
7763 case tok::greater: Opc = BO_GT; break;
7764 case tok::exclaimequal: Opc = BO_NE; break;
7765 case tok::equalequal: Opc = BO_EQ; break;
7766 case tok::amp: Opc = BO_And; break;
7767 case tok::caret: Opc = BO_Xor; break;
7768 case tok::pipe: Opc = BO_Or; break;
7769 case tok::ampamp: Opc = BO_LAnd; break;
7770 case tok::pipepipe: Opc = BO_LOr; break;
7771 case tok::equal: Opc = BO_Assign; break;
7772 case tok::starequal: Opc = BO_MulAssign; break;
7773 case tok::slashequal: Opc = BO_DivAssign; break;
7774 case tok::percentequal: Opc = BO_RemAssign; break;
7775 case tok::plusequal: Opc = BO_AddAssign; break;
7776 case tok::minusequal: Opc = BO_SubAssign; break;
7777 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7778 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
7779 case tok::ampequal: Opc = BO_AndAssign; break;
7780 case tok::caretequal: Opc = BO_XorAssign; break;
7781 case tok::pipeequal: Opc = BO_OrAssign; break;
7782 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007783 }
7784 return Opc;
7785}
7786
John McCalle3027922010-08-25 11:45:40 +00007787static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00007788 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007789 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00007790 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007791 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00007792 case tok::plusplus: Opc = UO_PreInc; break;
7793 case tok::minusminus: Opc = UO_PreDec; break;
7794 case tok::amp: Opc = UO_AddrOf; break;
7795 case tok::star: Opc = UO_Deref; break;
7796 case tok::plus: Opc = UO_Plus; break;
7797 case tok::minus: Opc = UO_Minus; break;
7798 case tok::tilde: Opc = UO_Not; break;
7799 case tok::exclaim: Opc = UO_LNot; break;
7800 case tok::kw___real: Opc = UO_Real; break;
7801 case tok::kw___imag: Opc = UO_Imag; break;
7802 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00007803 }
7804 return Opc;
7805}
7806
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007807/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
7808/// This warning is only emitted for builtin assignment operations. It is also
7809/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007810static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007811 SourceLocation OpLoc) {
7812 if (!S.ActiveTemplateInstantiations.empty())
7813 return;
7814 if (OpLoc.isInvalid() || OpLoc.isMacroID())
7815 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007816 LHSExpr = LHSExpr->IgnoreParenImpCasts();
7817 RHSExpr = RHSExpr->IgnoreParenImpCasts();
7818 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
7819 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
7820 if (!LHSDeclRef || !RHSDeclRef ||
7821 LHSDeclRef->getLocation().isMacroID() ||
7822 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007823 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007824 const ValueDecl *LHSDecl =
7825 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
7826 const ValueDecl *RHSDecl =
7827 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
7828 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007829 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007830 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007831 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00007832 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007833 if (RefTy->getPointeeType().isVolatileQualified())
7834 return;
7835
7836 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007837 << LHSDeclRef->getType()
7838 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007839}
7840
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007841/// CreateBuiltinBinOp - Creates a new built-in binary operation with
7842/// operator @p Opc at location @c TokLoc. This routine only supports
7843/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00007844ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00007845 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007846 Expr *LHSExpr, Expr *RHSExpr) {
Sebastian Redl67766732012-02-27 20:34:02 +00007847 if (getLangOptions().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
7848 // The syntax only allows initializer lists on the RHS of assignment,
7849 // so we don't need to worry about accepting invalid code for
7850 // non-assignment operators.
7851 // C++11 5.17p9:
7852 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
7853 // of x = {} is x = T().
7854 InitializationKind Kind =
7855 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
7856 InitializedEntity Entity =
7857 InitializedEntity::InitializeTemporary(LHSExpr->getType());
7858 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
7859 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
7860 MultiExprArg(&RHSExpr, 1));
7861 if (Init.isInvalid())
7862 return Init;
7863 RHSExpr = Init.take();
7864 }
7865
Richard Trieu4a287fb2011-09-07 01:49:20 +00007866 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007867 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007868 // The following two variables are used for compound assignment operators
7869 QualType CompLHSTy; // Type of LHS after promotions for computation
7870 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00007871 ExprValueKind VK = VK_RValue;
7872 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007873
7874 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00007875 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007876 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
John McCall34376a62010-12-04 03:47:34 +00007877 if (getLangOptions().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00007878 LHS.get()->getObjectKind() != OK_ObjCProperty) {
7879 VK = LHS.get()->getValueKind();
7880 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007881 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00007882 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007883 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007884 break;
John McCalle3027922010-08-25 11:45:40 +00007885 case BO_PtrMemD:
7886 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007887 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00007888 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00007889 break;
John McCalle3027922010-08-25 11:45:40 +00007890 case BO_Mul:
7891 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007892 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00007893 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007894 break;
John McCalle3027922010-08-25 11:45:40 +00007895 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007896 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007897 break;
John McCalle3027922010-08-25 11:45:40 +00007898 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00007899 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007900 break;
John McCalle3027922010-08-25 11:45:40 +00007901 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007902 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007903 break;
John McCalle3027922010-08-25 11:45:40 +00007904 case BO_Shl:
7905 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007906 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007907 break;
John McCalle3027922010-08-25 11:45:40 +00007908 case BO_LE:
7909 case BO_LT:
7910 case BO_GE:
7911 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007912 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007913 break;
John McCalle3027922010-08-25 11:45:40 +00007914 case BO_EQ:
7915 case BO_NE:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007916 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007917 break;
John McCalle3027922010-08-25 11:45:40 +00007918 case BO_And:
7919 case BO_Xor:
7920 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007921 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007922 break;
John McCalle3027922010-08-25 11:45:40 +00007923 case BO_LAnd:
7924 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007925 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007926 break;
John McCalle3027922010-08-25 11:45:40 +00007927 case BO_MulAssign:
7928 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007929 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00007930 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007931 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007932 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7933 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007934 break;
John McCalle3027922010-08-25 11:45:40 +00007935 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007936 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007937 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007938 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7939 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007940 break;
John McCalle3027922010-08-25 11:45:40 +00007941 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00007942 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00007943 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7944 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007945 break;
John McCalle3027922010-08-25 11:45:40 +00007946 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007947 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
7948 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7949 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007950 break;
John McCalle3027922010-08-25 11:45:40 +00007951 case BO_ShlAssign:
7952 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007953 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007954 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007955 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7956 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007957 break;
John McCalle3027922010-08-25 11:45:40 +00007958 case BO_AndAssign:
7959 case BO_XorAssign:
7960 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007961 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007962 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007963 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
7964 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007965 break;
John McCalle3027922010-08-25 11:45:40 +00007966 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00007967 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
7968 if (getLangOptions().CPlusPlus && !RHS.isInvalid()) {
7969 VK = RHS.get()->getValueKind();
7970 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007971 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007972 break;
7973 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007974 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00007975 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007976
7977 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00007978 CheckArrayAccess(LHS.get());
7979 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007980
Eli Friedman8b7b1b12009-03-28 01:22:36 +00007981 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00007982 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007983 ResultTy, VK, OK, OpLoc));
Richard Trieu4a287fb2011-09-07 01:49:20 +00007984 if (getLangOptions().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00007985 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00007986 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00007987 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00007988 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00007989 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00007990 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00007991 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00007992}
7993
Sebastian Redl44615072009-10-27 12:10:02 +00007994/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
7995/// operators are mixed in a way that suggests that the programmer forgot that
7996/// comparison operators have higher precedence. The most typical example of
7997/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00007998static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00007999 SourceLocation OpLoc, Expr *LHSExpr,
8000 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008001 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008002 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8003 RHSopc = static_cast<BinOp::Opcode>(-1);
8004 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8005 LHSopc = BO->getOpcode();
8006 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8007 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008008
8009 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008010 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008011 return;
8012
8013 // Bitwise operations are sometimes used as eager logical ops.
8014 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008015 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8016 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008017 return;
8018
Richard Trieu4a287fb2011-09-07 01:49:20 +00008019 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8020 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008021 if (!isLeftComp && !isRightComp) return;
8022
Richard Trieu4a287fb2011-09-07 01:49:20 +00008023 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8024 OpLoc)
8025 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8026 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8027 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008028 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008029 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8030 RHSExpr->getLocEnd())
8031 : SourceRange(LHSExpr->getLocStart(),
8032 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008033
8034 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8035 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8036 SuggestParentheses(Self, OpLoc,
8037 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008038 RHSExpr->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008039 SuggestParentheses(Self, OpLoc,
8040 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8041 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008042}
8043
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008044/// \brief It accepts a '&' expr that is inside a '|' one.
8045/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8046/// in parentheses.
8047static void
8048EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8049 BinaryOperator *Bop) {
8050 assert(Bop->getOpcode() == BO_And);
8051 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8052 << Bop->getSourceRange() << OpLoc;
8053 SuggestParentheses(Self, Bop->getOperatorLoc(),
8054 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8055 Bop->getSourceRange());
8056}
8057
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008058/// \brief It accepts a '&&' expr that is inside a '||' one.
8059/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8060/// in parentheses.
8061static void
8062EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008063 BinaryOperator *Bop) {
8064 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008065 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8066 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008067 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008068 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008069 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008070}
8071
8072/// \brief Returns true if the given expression can be evaluated as a constant
8073/// 'true'.
8074static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8075 bool Res;
8076 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8077}
8078
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008079/// \brief Returns true if the given expression can be evaluated as a constant
8080/// 'false'.
8081static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8082 bool Res;
8083 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8084}
8085
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008086/// \brief Look for '&&' in the left hand of a '||' expr.
8087static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008088 Expr *LHSExpr, Expr *RHSExpr) {
8089 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008090 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008091 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008092 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008093 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008094 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8095 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8096 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8097 } else if (Bop->getOpcode() == BO_LOr) {
8098 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8099 // If it's "a || b && 1 || c" we didn't warn earlier for
8100 // "a || b && 1", but warn now.
8101 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8102 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8103 }
8104 }
8105 }
8106}
8107
8108/// \brief Look for '&&' in the right hand of a '||' expr.
8109static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008110 Expr *LHSExpr, Expr *RHSExpr) {
8111 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008112 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008113 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008114 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008115 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008116 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8117 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8118 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008119 }
8120 }
8121}
8122
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008123/// \brief Look for '&' in the left or right hand of a '|' expr.
8124static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8125 Expr *OrArg) {
8126 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8127 if (Bop->getOpcode() == BO_And)
8128 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8129 }
8130}
8131
Sebastian Redl43028242009-10-26 15:24:15 +00008132/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008133/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008134static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008135 SourceLocation OpLoc, Expr *LHSExpr,
8136 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008137 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008138 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008139 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008140
8141 // Diagnose "arg1 & arg2 | arg3"
8142 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008143 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8144 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008145 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008146
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008147 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8148 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008149 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008150 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8151 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008152 }
Sebastian Redl43028242009-10-26 15:24:15 +00008153}
8154
Steve Naroff218bc2b2007-05-04 21:54:46 +00008155// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008156ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008157 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008158 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008159 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008160 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8161 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008162
Sebastian Redl43028242009-10-26 15:24:15 +00008163 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008164 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008165
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008166 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008167}
8168
John McCall526ab472011-10-25 17:37:35 +00008169/// Build an overloaded binary operator expression in the given scope.
8170static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8171 BinaryOperatorKind Opc,
8172 Expr *LHS, Expr *RHS) {
8173 // Find all of the overloaded operators visible from this
8174 // point. We perform both an operator-name lookup from the local
8175 // scope and an argument-dependent lookup based on the types of
8176 // the arguments.
8177 UnresolvedSet<16> Functions;
8178 OverloadedOperatorKind OverOp
8179 = BinaryOperator::getOverloadedOperator(Opc);
8180 if (Sc && OverOp != OO_None)
8181 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8182 RHS->getType(), Functions);
8183
8184 // Build the (potentially-overloaded, potentially-dependent)
8185 // binary operation.
8186 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8187}
8188
John McCalldadc5752010-08-24 06:29:42 +00008189ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008190 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008191 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008192 // We want to end up calling one of checkPseudoObjectAssignment
8193 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8194 // both expressions are overloadable or either is type-dependent),
8195 // or CreateBuiltinBinOp (in any other case). We also want to get
8196 // any placeholder types out of the way.
8197
John McCall526ab472011-10-25 17:37:35 +00008198 // Handle pseudo-objects in the LHS.
8199 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8200 // Assignments with a pseudo-object l-value need special analysis.
8201 if (pty->getKind() == BuiltinType::PseudoObject &&
8202 BinaryOperator::isAssignmentOp(Opc))
8203 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8204
8205 // Don't resolve overloads if the other type is overloadable.
8206 if (pty->getKind() == BuiltinType::Overload) {
8207 // We can't actually test that if we still have a placeholder,
8208 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008209 // code below are valid when the LHS is an overload set. Note
8210 // that an overload set can be dependently-typed, but it never
8211 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008212 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8213 if (resolvedRHS.isInvalid()) return ExprError();
8214 RHSExpr = resolvedRHS.take();
8215
John McCall9a43e122011-10-28 01:04:34 +00008216 if (RHSExpr->isTypeDependent() ||
8217 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008218 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8219 }
8220
8221 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8222 if (LHS.isInvalid()) return ExprError();
8223 LHSExpr = LHS.take();
8224 }
8225
8226 // Handle pseudo-objects in the RHS.
8227 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8228 // An overload in the RHS can potentially be resolved by the type
8229 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008230 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8231 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8232 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8233
Eli Friedman419b1ff2012-01-17 21:27:43 +00008234 if (LHSExpr->getType()->isOverloadableType())
8235 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8236
John McCall526ab472011-10-25 17:37:35 +00008237 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008238 }
John McCall526ab472011-10-25 17:37:35 +00008239
8240 // Don't resolve overloads if the other type is overloadable.
8241 if (pty->getKind() == BuiltinType::Overload &&
8242 LHSExpr->getType()->isOverloadableType())
8243 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8244
8245 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8246 if (!resolvedRHS.isUsable()) return ExprError();
8247 RHSExpr = resolvedRHS.take();
8248 }
8249
John McCall622114c2010-12-06 05:26:58 +00008250 if (getLangOptions().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008251 // If either expression is type-dependent, always build an
8252 // overloaded op.
8253 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8254 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008255
John McCall9a43e122011-10-28 01:04:34 +00008256 // Otherwise, build an overloaded op if either expression has an
8257 // overloadable type.
8258 if (LHSExpr->getType()->isOverloadableType() ||
8259 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008260 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008261 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008262
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008263 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008264 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008265}
8266
John McCalldadc5752010-08-24 06:29:42 +00008267ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008268 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008269 Expr *InputExpr) {
8270 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008271 ExprValueKind VK = VK_RValue;
8272 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008273 QualType resultType;
8274 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008275 case UO_PreInc:
8276 case UO_PreDec:
8277 case UO_PostInc:
8278 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008279 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008280 Opc == UO_PreInc ||
8281 Opc == UO_PostInc,
8282 Opc == UO_PreInc ||
8283 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008284 break;
John McCalle3027922010-08-25 11:45:40 +00008285 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008286 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008287 break;
John McCall31996342011-04-07 08:22:57 +00008288 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008289 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8290 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008291 break;
John McCall31996342011-04-07 08:22:57 +00008292 }
John McCalle3027922010-08-25 11:45:40 +00008293 case UO_Plus:
8294 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008295 Input = UsualUnaryConversions(Input.take());
8296 if (Input.isInvalid()) return ExprError();
8297 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008298 if (resultType->isDependentType())
8299 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008300 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8301 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008302 break;
8303 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6-7
8304 resultType->isEnumeralType())
8305 break;
8306 else if (getLangOptions().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008307 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008308 resultType->isPointerType())
8309 break;
8310
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008311 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008312 << resultType << Input.get()->getSourceRange());
8313
John McCalle3027922010-08-25 11:45:40 +00008314 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008315 Input = UsualUnaryConversions(Input.take());
8316 if (Input.isInvalid()) return ExprError();
8317 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008318 if (resultType->isDependentType())
8319 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008320 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8321 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8322 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008323 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008324 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008325 else if (resultType->hasIntegerRepresentation())
8326 break;
John McCall526ab472011-10-25 17:37:35 +00008327 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008328 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008329 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008330 }
Steve Naroff35d85152007-05-07 00:24:15 +00008331 break;
John Wiegley01296292011-04-08 18:41:53 +00008332
John McCalle3027922010-08-25 11:45:40 +00008333 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008334 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008335 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8336 if (Input.isInvalid()) return ExprError();
8337 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008338
8339 // Though we still have to promote half FP to float...
8340 if (resultType->isHalfType()) {
8341 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8342 resultType = Context.FloatTy;
8343 }
8344
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008345 if (resultType->isDependentType())
8346 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008347 if (resultType->isScalarType()) {
8348 // C99 6.5.3.3p1: ok, fallthrough;
8349 if (Context.getLangOptions().CPlusPlus) {
8350 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8351 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008352 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8353 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008354 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008355 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008356 // Vector logical not returns the signed variant of the operand type.
8357 resultType = GetSignedVectorType(resultType);
8358 break;
John McCall36226622010-10-12 02:09:17 +00008359 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008360 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008361 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008362 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008363
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008364 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008365 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008366 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008367 break;
John McCalle3027922010-08-25 11:45:40 +00008368 case UO_Real:
8369 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008370 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008371 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8372 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008373 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008374 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8375 if (Input.get()->getValueKind() != VK_RValue &&
8376 Input.get()->getObjectKind() == OK_Ordinary)
8377 VK = Input.get()->getValueKind();
8378 } else if (!getLangOptions().CPlusPlus) {
8379 // In C, a volatile scalar is read by __imag. In C++, it is not.
8380 Input = DefaultLvalueConversion(Input.take());
8381 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008382 break;
John McCalle3027922010-08-25 11:45:40 +00008383 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008384 resultType = Input.get()->getType();
8385 VK = Input.get()->getValueKind();
8386 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008387 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008388 }
John Wiegley01296292011-04-08 18:41:53 +00008389 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008390 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008391
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008392 // Check for array bounds violations in the operand of the UnaryOperator,
8393 // except for the '*' and '&' operators that have to be handled specially
8394 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8395 // that are explicitly defined as valid by the standard).
8396 if (Opc != UO_AddrOf && Opc != UO_Deref)
8397 CheckArrayAccess(Input.get());
8398
John Wiegley01296292011-04-08 18:41:53 +00008399 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008400 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008401}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008402
Douglas Gregor72341032011-12-14 21:23:13 +00008403/// \brief Determine whether the given expression is a qualified member
8404/// access expression, of a form that could be turned into a pointer to member
8405/// with the address-of operator.
8406static bool isQualifiedMemberAccess(Expr *E) {
8407 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8408 if (!DRE->getQualifier())
8409 return false;
8410
8411 ValueDecl *VD = DRE->getDecl();
8412 if (!VD->isCXXClassMember())
8413 return false;
8414
8415 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8416 return true;
8417 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8418 return Method->isInstance();
8419
8420 return false;
8421 }
8422
8423 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8424 if (!ULE->getQualifier())
8425 return false;
8426
8427 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8428 DEnd = ULE->decls_end();
8429 D != DEnd; ++D) {
8430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8431 if (Method->isInstance())
8432 return true;
8433 } else {
8434 // Overload set does not contain methods.
8435 break;
8436 }
8437 }
8438
8439 return false;
8440 }
8441
8442 return false;
8443}
8444
John McCalldadc5752010-08-24 06:29:42 +00008445ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008446 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008447 // First things first: handle placeholders so that the
8448 // overloaded-operator check considers the right type.
8449 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8450 // Increment and decrement of pseudo-object references.
8451 if (pty->getKind() == BuiltinType::PseudoObject &&
8452 UnaryOperator::isIncrementDecrementOp(Opc))
8453 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8454
8455 // extension is always a builtin operator.
8456 if (Opc == UO_Extension)
8457 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8458
8459 // & gets special logic for several kinds of placeholder.
8460 // The builtin code knows what to do.
8461 if (Opc == UO_AddrOf &&
8462 (pty->getKind() == BuiltinType::Overload ||
8463 pty->getKind() == BuiltinType::UnknownAny ||
8464 pty->getKind() == BuiltinType::BoundMember))
8465 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8466
8467 // Anything else needs to be handled now.
8468 ExprResult Result = CheckPlaceholderExpr(Input);
8469 if (Result.isInvalid()) return ExprError();
8470 Input = Result.take();
8471 }
8472
Anders Carlsson461a2c02009-11-14 21:26:41 +00008473 if (getLangOptions().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008474 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8475 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008476 // Find all of the overloaded operators visible from this
8477 // point. We perform both an operator-name lookup from the local
8478 // scope and an argument-dependent lookup based on the types of
8479 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008480 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008481 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008482 if (S && OverOp != OO_None)
8483 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8484 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008485
John McCallb268a282010-08-23 23:25:46 +00008486 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008487 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008488
John McCallb268a282010-08-23 23:25:46 +00008489 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008490}
8491
Douglas Gregor5287f092009-11-05 00:51:44 +00008492// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008493ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008494 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008495 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008496}
8497
Steve Naroff66356bd2007-09-16 14:56:35 +00008498/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008499ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008500 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008501 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008502 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008503 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008504 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008505}
8506
John McCall31168b02011-06-15 23:02:42 +00008507/// Given the last statement in a statement-expression, check whether
8508/// the result is a producing expression (like a call to an
8509/// ns_returns_retained function) and, if so, rebuild it to hoist the
8510/// release out of the full-expression. Otherwise, return null.
8511/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008512static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008513 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008514 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008515 if (!cleanups) return 0;
8516
8517 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008518 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008519 return 0;
8520
8521 // Splice out the cast. This shouldn't modify any interesting
8522 // features of the statement.
8523 Expr *producer = cast->getSubExpr();
8524 assert(producer->getType() == cast->getType());
8525 assert(producer->getValueKind() == cast->getValueKind());
8526 cleanups->setSubExpr(producer);
8527 return cleanups;
8528}
8529
John McCalldadc5752010-08-24 06:29:42 +00008530ExprResult
John McCallb268a282010-08-23 23:25:46 +00008531Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008532 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008533 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8534 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8535
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008536 bool isFileScope
8537 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008538 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008539 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008540
Chris Lattner366727f2007-07-24 16:58:17 +00008541 // FIXME: there are a variety of strange constraints to enforce here, for
8542 // example, it is not possible to goto into a stmt expression apparently.
8543 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008544
Chris Lattner366727f2007-07-24 16:58:17 +00008545 // If there are sub stmts in the compound stmt, take the type of the last one
8546 // as the type of the stmtexpr.
8547 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008548 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008549 if (!Compound->body_empty()) {
8550 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008551 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008552 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008553 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8554 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008555 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008556 }
John McCall31168b02011-06-15 23:02:42 +00008557
John Wiegley01296292011-04-08 18:41:53 +00008558 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008559 // Do function/array conversion on the last expression, but not
8560 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008561 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8562 if (LastExpr.isInvalid())
8563 return ExprError();
8564 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008565
John Wiegley01296292011-04-08 18:41:53 +00008566 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008567 // In ARC, if the final expression ends in a consume, splice
8568 // the consume out and bind it later. In the alternate case
8569 // (when dealing with a retainable type), the result
8570 // initialization will create a produce. In both cases the
8571 // result will be +1, and we'll need to balance that out with
8572 // a bind.
8573 if (Expr *rebuiltLastStmt
8574 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8575 LastExpr = rebuiltLastStmt;
8576 } else {
8577 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008578 InitializedEntity::InitializeResult(LPLoc,
8579 Ty,
8580 false),
8581 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008582 LastExpr);
8583 }
8584
John Wiegley01296292011-04-08 18:41:53 +00008585 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008586 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008587 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008588 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008589 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008590 else
John Wiegley01296292011-04-08 18:41:53 +00008591 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008592 StmtExprMayBindToTemp = true;
8593 }
8594 }
8595 }
Chris Lattner944d3062008-07-26 19:51:01 +00008596 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008597
Eli Friedmanba961a92009-03-23 00:24:07 +00008598 // FIXME: Check that expression type is complete/non-abstract; statement
8599 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008600 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8601 if (StmtExprMayBindToTemp)
8602 return MaybeBindToTemporary(ResStmtExpr);
8603 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008604}
Steve Naroff78864672007-08-01 22:05:33 +00008605
John McCalldadc5752010-08-24 06:29:42 +00008606ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008607 TypeSourceInfo *TInfo,
8608 OffsetOfComponent *CompPtr,
8609 unsigned NumComponents,
8610 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008611 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008612 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008613 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008614
Chris Lattnerf17bd422007-08-30 17:45:32 +00008615 // We must have at least one component that refers to the type, and the first
8616 // one is known to be a field designator. Verify that the ArgTy represents
8617 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008618 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008619 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8620 << ArgTy << TypeRange);
8621
8622 // Type must be complete per C99 7.17p3 because a declaring a variable
8623 // with an incomplete type would be ill-formed.
8624 if (!Dependent
8625 && RequireCompleteType(BuiltinLoc, ArgTy,
8626 PDiag(diag::err_offsetof_incomplete_type)
8627 << TypeRange))
8628 return ExprError();
8629
Chris Lattner78502cf2007-08-31 21:49:13 +00008630 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8631 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008632 // FIXME: This diagnostic isn't actually visible because the location is in
8633 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008634 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008635 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8636 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008637
8638 bool DidWarnAboutNonPOD = false;
8639 QualType CurrentType = ArgTy;
8640 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008641 SmallVector<OffsetOfNode, 4> Comps;
8642 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008643 for (unsigned i = 0; i != NumComponents; ++i) {
8644 const OffsetOfComponent &OC = CompPtr[i];
8645 if (OC.isBrackets) {
8646 // Offset of an array sub-field. TODO: Should we allow vector elements?
8647 if (!CurrentType->isDependentType()) {
8648 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8649 if(!AT)
8650 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8651 << CurrentType);
8652 CurrentType = AT->getElementType();
8653 } else
8654 CurrentType = Context.DependentTy;
8655
Richard Smith9fcc5c32011-10-17 23:29:39 +00008656 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8657 if (IdxRval.isInvalid())
8658 return ExprError();
8659 Expr *Idx = IdxRval.take();
8660
Douglas Gregor882211c2010-04-28 22:16:22 +00008661 // The expression must be an integral expression.
8662 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008663 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8664 !Idx->getType()->isIntegerType())
8665 return ExprError(Diag(Idx->getLocStart(),
8666 diag::err_typecheck_subscript_not_integer)
8667 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008668
Douglas Gregor882211c2010-04-28 22:16:22 +00008669 // Record this array index.
8670 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008671 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008672 continue;
8673 }
8674
8675 // Offset of a field.
8676 if (CurrentType->isDependentType()) {
8677 // We have the offset of a field, but we can't look into the dependent
8678 // type. Just record the identifier of the field.
8679 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8680 CurrentType = Context.DependentTy;
8681 continue;
8682 }
8683
8684 // We need to have a complete type to look into.
8685 if (RequireCompleteType(OC.LocStart, CurrentType,
8686 diag::err_offsetof_incomplete_type))
8687 return ExprError();
8688
8689 // Look for the designated field.
8690 const RecordType *RC = CurrentType->getAs<RecordType>();
8691 if (!RC)
8692 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8693 << CurrentType);
8694 RecordDecl *RD = RC->getDecl();
8695
8696 // C++ [lib.support.types]p5:
8697 // The macro offsetof accepts a restricted set of type arguments in this
8698 // International Standard. type shall be a POD structure or a POD union
8699 // (clause 9).
8700 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8701 if (!CRD->isPOD() && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008702 DiagRuntimeBehavior(BuiltinLoc, 0,
Douglas Gregor882211c2010-04-28 22:16:22 +00008703 PDiag(diag::warn_offsetof_non_pod_type)
8704 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8705 << CurrentType))
8706 DidWarnAboutNonPOD = true;
8707 }
8708
8709 // Look for the field.
8710 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8711 LookupQualifiedName(R, RD);
8712 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008713 IndirectFieldDecl *IndirectMemberDecl = 0;
8714 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008715 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008716 MemberDecl = IndirectMemberDecl->getAnonField();
8717 }
8718
Douglas Gregor882211c2010-04-28 22:16:22 +00008719 if (!MemberDecl)
8720 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8721 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8722 OC.LocEnd));
8723
Douglas Gregor10982ea2010-04-28 22:36:06 +00008724 // C99 7.17p3:
8725 // (If the specified member is a bit-field, the behavior is undefined.)
8726 //
8727 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008728 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008729 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8730 << MemberDecl->getDeclName()
8731 << SourceRange(BuiltinLoc, RParenLoc);
8732 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8733 return ExprError();
8734 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008735
8736 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008737 if (IndirectMemberDecl)
8738 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008739
Douglas Gregord1702062010-04-29 00:18:15 +00008740 // If the member was found in a base class, introduce OffsetOfNodes for
8741 // the base class indirections.
8742 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8743 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008744 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008745 CXXBasePath &Path = Paths.front();
8746 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8747 B != BEnd; ++B)
8748 Comps.push_back(OffsetOfNode(B->Base));
8749 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008750
Francois Pichet783dd6e2010-11-21 06:08:52 +00008751 if (IndirectMemberDecl) {
8752 for (IndirectFieldDecl::chain_iterator FI =
8753 IndirectMemberDecl->chain_begin(),
8754 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
8755 assert(isa<FieldDecl>(*FI));
8756 Comps.push_back(OffsetOfNode(OC.LocStart,
8757 cast<FieldDecl>(*FI), OC.LocEnd));
8758 }
8759 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00008760 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00008761
Douglas Gregor882211c2010-04-28 22:16:22 +00008762 CurrentType = MemberDecl->getType().getNonReferenceType();
8763 }
8764
8765 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
8766 TInfo, Comps.data(), Comps.size(),
8767 Exprs.data(), Exprs.size(), RParenLoc));
8768}
Mike Stump4e1f26a2009-02-19 03:04:26 +00008769
John McCalldadc5752010-08-24 06:29:42 +00008770ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00008771 SourceLocation BuiltinLoc,
8772 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008773 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00008774 OffsetOfComponent *CompPtr,
8775 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008776 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00008777
Douglas Gregor882211c2010-04-28 22:16:22 +00008778 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00008779 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00008780 if (ArgTy.isNull())
8781 return ExprError();
8782
Eli Friedman06dcfd92010-08-05 10:15:45 +00008783 if (!ArgTInfo)
8784 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
8785
8786 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00008787 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00008788}
8789
8790
John McCalldadc5752010-08-24 06:29:42 +00008791ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008792 Expr *CondExpr,
8793 Expr *LHSExpr, Expr *RHSExpr,
8794 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00008795 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
8796
John McCall7decc9e2010-11-18 06:31:45 +00008797 ExprValueKind VK = VK_RValue;
8798 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008799 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00008800 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00008801 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008802 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00008803 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008804 } else {
8805 // The conditional expression is required to be a constant expression.
8806 llvm::APSInt condEval(32);
Richard Smithf4c51d92012-02-04 09:53:13 +00008807 ExprResult CondICE = VerifyIntegerConstantExpression(CondExpr, &condEval,
8808 PDiag(diag::err_typecheck_choose_expr_requires_constant), false);
8809 if (CondICE.isInvalid())
8810 return ExprError();
8811 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00008812
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008813 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00008814 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
8815
8816 resType = ActiveExpr->getType();
8817 ValueDependent = ActiveExpr->isValueDependent();
8818 VK = ActiveExpr->getValueKind();
8819 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008820 }
8821
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008822 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008823 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00008824 resType->isDependentType(),
8825 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00008826}
8827
Steve Naroffc540d662008-09-03 18:15:37 +00008828//===----------------------------------------------------------------------===//
8829// Clang Extensions.
8830//===----------------------------------------------------------------------===//
8831
8832/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00008833void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00008834 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00008835 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008836 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00008837 if (CurScope)
8838 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008839 else
8840 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00008841
Eli Friedman34b49062012-01-26 03:00:14 +00008842 getCurBlock()->HasImplicitReturnType = true;
8843
John McCallf1a3c2a2011-11-11 03:19:12 +00008844 // Enter a new evaluation context to insulate the block from any
8845 // cleanups from the enclosing full-expression.
8846 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008847}
8848
Mike Stump82f071f2009-02-04 22:31:32 +00008849void Sema::ActOnBlockArguments(Declarator &ParamInfo, Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00008850 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00008851 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00008852 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008853
John McCall8cb7bdf2010-06-04 23:28:52 +00008854 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00008855 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00008856
John McCall3882ace2011-01-05 12:14:39 +00008857 // GetTypeForDeclarator always produces a function type for a block
8858 // literal signature. Furthermore, it is always a FunctionProtoType
8859 // unless the function was written with a typedef.
8860 assert(T->isFunctionType() &&
8861 "GetTypeForDeclarator made a non-function block signature");
8862
8863 // Look for an explicit signature in that function type.
8864 FunctionProtoTypeLoc ExplicitSignature;
8865
8866 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
8867 if (isa<FunctionProtoTypeLoc>(tmp)) {
8868 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
8869
8870 // Check whether that explicit signature was synthesized by
8871 // GetTypeForDeclarator. If so, don't save that as part of the
8872 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00008873 if (ExplicitSignature.getLocalRangeBegin() ==
8874 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00008875 // This would be much cheaper if we stored TypeLocs instead of
8876 // TypeSourceInfos.
8877 TypeLoc Result = ExplicitSignature.getResultLoc();
8878 unsigned Size = Result.getFullDataSize();
8879 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
8880 Sig->getTypeLoc().initializeFullCopy(Result, Size);
8881
8882 ExplicitSignature = FunctionProtoTypeLoc();
8883 }
John McCalla3ccba02010-06-04 11:21:44 +00008884 }
Mike Stump11289f42009-09-09 15:08:12 +00008885
John McCall3882ace2011-01-05 12:14:39 +00008886 CurBlock->TheDecl->setSignatureAsWritten(Sig);
8887 CurBlock->FunctionType = T;
8888
8889 const FunctionType *Fn = T->getAs<FunctionType>();
8890 QualType RetTy = Fn->getResultType();
8891 bool isVariadic =
8892 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
8893
John McCall8e346702010-06-04 19:02:56 +00008894 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00008895
John McCalla3ccba02010-06-04 11:21:44 +00008896 // Don't allow returning a objc interface by value.
8897 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008898 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00008899 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
8900 return;
8901 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008902
John McCalla3ccba02010-06-04 11:21:44 +00008903 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00008904 // return type. TODO: what should we do with declarators like:
8905 // ^ * { ... }
8906 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008907 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00008908 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008909 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00008910 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00008911 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008912
John McCalla3ccba02010-06-04 11:21:44 +00008913 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008914 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00008915 if (ExplicitSignature) {
8916 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
8917 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008918 if (Param->getIdentifier() == 0 &&
8919 !Param->isImplicit() &&
8920 !Param->isInvalidDecl() &&
8921 !getLangOptions().CPlusPlus)
8922 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00008923 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00008924 }
John McCalla3ccba02010-06-04 11:21:44 +00008925
8926 // Fake up parameter variables if we have a typedef, like
8927 // ^ fntype { ... }
8928 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
8929 for (FunctionProtoType::arg_type_iterator
8930 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
8931 ParmVarDecl *Param =
8932 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00008933 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00008934 *I);
John McCall8e346702010-06-04 19:02:56 +00008935 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00008936 }
Steve Naroffc540d662008-09-03 18:15:37 +00008937 }
John McCalla3ccba02010-06-04 11:21:44 +00008938
John McCall8e346702010-06-04 19:02:56 +00008939 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00008940 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00008941 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00008942 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
8943 CurBlock->TheDecl->param_end(),
8944 /*CheckParameterNames=*/false);
8945 }
8946
John McCalla3ccba02010-06-04 11:21:44 +00008947 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00008948 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00008949
John McCalla3ccba02010-06-04 11:21:44 +00008950 // Put the parameter variables in scope. We can bail out immediately
8951 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00008952 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00008953 return;
8954
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008955 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00008956 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
8957 (*AI)->setOwningFunction(CurBlock->TheDecl);
8958
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008959 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00008960 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00008961 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00008962
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008963 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00008964 }
John McCallf7b2fb52010-01-22 00:28:27 +00008965 }
Steve Naroffc540d662008-09-03 18:15:37 +00008966}
8967
8968/// ActOnBlockError - If there is an error parsing a block, this callback
8969/// is invoked to pop the information about the block from the action impl.
8970void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00008971 // Leave the expression-evaluation context.
8972 DiscardCleanupsInEvaluationContext();
8973 PopExpressionEvaluationContext();
8974
Steve Naroffc540d662008-09-03 18:15:37 +00008975 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00008976 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00008977 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00008978}
8979
8980/// ActOnBlockStmtExpr - This is called when the body of a block statement
8981/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00008982ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00008983 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00008984 // If blocks are disabled, emit an error.
8985 if (!LangOpts.Blocks)
8986 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00008987
John McCallf1a3c2a2011-11-11 03:19:12 +00008988 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00008989 if (hasAnyUnrecoverableErrorsInThisFunction())
8990 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00008991 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
8992 PopExpressionEvaluationContext();
8993
Douglas Gregor9a28e842010-03-01 23:15:13 +00008994 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00008995
Steve Naroff1d95e5a2008-10-10 01:28:17 +00008996 PopDeclContext();
8997
Steve Naroffc540d662008-09-03 18:15:37 +00008998 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00008999 if (!BSI->ReturnType.isNull())
9000 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009001
Mike Stump3bf1ab42009-07-28 22:04:01 +00009002 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009003 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009004
John McCallc63de662011-02-02 13:00:07 +00009005 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009006 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9007 SmallVector<BlockDecl::Capture, 4> Captures;
9008 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9009 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9010 if (Cap.isThisCapture())
9011 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009012 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009013 Cap.isNested(), Cap.getCopyExpr());
9014 Captures.push_back(NewCap);
9015 }
9016 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9017 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009018
John McCall8e346702010-06-04 19:02:56 +00009019 // If the user wrote a function type in some form, try to use that.
9020 if (!BSI->FunctionType.isNull()) {
9021 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9022
9023 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9024 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9025
9026 // Turn protoless block types into nullary block types.
9027 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009028 FunctionProtoType::ExtProtoInfo EPI;
9029 EPI.ExtInfo = Ext;
9030 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009031
9032 // Otherwise, if we don't need to change anything about the function type,
9033 // preserve its sugar structure.
9034 } else if (FTy->getResultType() == RetTy &&
9035 (!NoReturn || FTy->getNoReturnAttr())) {
9036 BlockTy = BSI->FunctionType;
9037
9038 // Otherwise, make the minimal modifications to the function type.
9039 } else {
9040 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009041 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9042 EPI.TypeQuals = 0; // FIXME: silently?
9043 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009044 BlockTy = Context.getFunctionType(RetTy,
9045 FPT->arg_type_begin(),
9046 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009047 EPI);
John McCall8e346702010-06-04 19:02:56 +00009048 }
9049
9050 // If we don't have a function type, just build one from nothing.
9051 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009052 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009053 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009054 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009055 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009056
John McCall8e346702010-06-04 19:02:56 +00009057 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9058 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009059 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009060
Chris Lattner45542ea2009-04-19 05:28:12 +00009061 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009062 if (getCurFunction()->NeedsScopeChecking() &&
9063 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009064 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009065
Chris Lattner60f84492011-02-17 23:58:47 +00009066 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009067
Fariborz Jahanian256d39d2011-07-11 18:04:54 +00009068 for (BlockDecl::capture_const_iterator ci = BSI->TheDecl->capture_begin(),
9069 ce = BSI->TheDecl->capture_end(); ci != ce; ++ci) {
9070 const VarDecl *variable = ci->getVariable();
9071 QualType T = variable->getType();
9072 QualType::DestructionKind destructKind = T.isDestructedType();
9073 if (destructKind != QualType::DK_none)
9074 getCurFunction()->setHasBranchProtectedScope();
9075 }
9076
Douglas Gregor49695f02011-09-06 20:46:03 +00009077 computeNRVO(Body, getCurBlock());
9078
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009079 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9080 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009081 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009082
John McCall28fc7092011-11-10 05:35:25 +00009083 // If the block isn't obviously global, i.e. it captures anything at
9084 // all, mark this full-expression as needing a cleanup.
9085 if (Result->getBlockDecl()->hasCaptures()) {
9086 ExprCleanupObjects.push_back(Result->getBlockDecl());
9087 ExprNeedsCleanups = true;
9088 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009089
Douglas Gregor9a28e842010-03-01 23:15:13 +00009090 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009091}
9092
John McCalldadc5752010-08-24 06:29:42 +00009093ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009094 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009095 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009096 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009097 GetTypeFromParser(Ty, &TInfo);
9098 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009099}
9100
John McCalldadc5752010-08-24 06:29:42 +00009101ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009102 Expr *E, TypeSourceInfo *TInfo,
9103 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009104 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009105
Eli Friedman121ba0c2008-08-09 23:32:40 +00009106 // Get the va_list type
9107 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009108 if (VaListType->isArrayType()) {
9109 // Deal with implicit array decay; for example, on x86-64,
9110 // va_list is an array, but it's supposed to decay to
9111 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009112 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009113 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009114 ExprResult Result = UsualUnaryConversions(E);
9115 if (Result.isInvalid())
9116 return ExprError();
9117 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009118 } else {
9119 // Otherwise, the va_list argument must be an l-value because
9120 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009121 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009122 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009123 return ExprError();
9124 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009125
Douglas Gregorad3150c2009-05-19 23:10:31 +00009126 if (!E->isTypeDependent() &&
9127 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009128 return ExprError(Diag(E->getLocStart(),
9129 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009130 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009131 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009132
David Majnemerc75d1a12011-06-14 05:17:32 +00009133 if (!TInfo->getType()->isDependentType()) {
9134 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
9135 PDiag(diag::err_second_parameter_to_va_arg_incomplete)
9136 << TInfo->getTypeLoc().getSourceRange()))
9137 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009138
David Majnemerc75d1a12011-06-14 05:17:32 +00009139 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
9140 TInfo->getType(),
9141 PDiag(diag::err_second_parameter_to_va_arg_abstract)
9142 << TInfo->getTypeLoc().getSourceRange()))
9143 return ExprError();
9144
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009145 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009146 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009147 TInfo->getType()->isObjCLifetimeType()
9148 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9149 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009150 << TInfo->getType()
9151 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009152 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009153
9154 // Check for va_arg where arguments of the given type will be promoted
9155 // (i.e. this va_arg is guaranteed to have undefined behavior).
9156 QualType PromoteType;
9157 if (TInfo->getType()->isPromotableIntegerType()) {
9158 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9159 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9160 PromoteType = QualType();
9161 }
9162 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9163 PromoteType = Context.DoubleTy;
9164 if (!PromoteType.isNull())
9165 Diag(TInfo->getTypeLoc().getBeginLoc(),
9166 diag::warn_second_parameter_to_va_arg_never_compatible)
9167 << TInfo->getType()
9168 << PromoteType
9169 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009170 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009171
Abramo Bagnara27db2392010-08-10 10:06:15 +00009172 QualType T = TInfo->getType().getNonLValueExprType(Context);
9173 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009174}
9175
John McCalldadc5752010-08-24 06:29:42 +00009176ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009177 // The type of __null will be int or long, depending on the size of
9178 // pointers on the target.
9179 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009180 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9181 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009182 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009183 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009184 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009185 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009186 Ty = Context.LongLongTy;
9187 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009188 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009189 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009190
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009191 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009192}
9193
Alexis Huntc46382e2010-04-28 23:02:27 +00009194static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009195 Expr *SrcExpr, FixItHint &Hint) {
Anders Carlssonace5d072009-11-10 04:46:30 +00009196 if (!SemaRef.getLangOptions().ObjC1)
9197 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009198
Anders Carlssonace5d072009-11-10 04:46:30 +00009199 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9200 if (!PT)
9201 return;
9202
9203 // Check if the destination is of type 'id'.
9204 if (!PT->isObjCIdType()) {
9205 // Check if the destination is the 'NSString' interface.
9206 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9207 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9208 return;
9209 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009210
John McCallfe96e0b2011-11-06 09:01:30 +00009211 // Ignore any parens, implicit casts (should only be
9212 // array-to-pointer decays), and not-so-opaque values. The last is
9213 // important for making this trigger for property assignments.
9214 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9215 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9216 if (OV->getSourceExpr())
9217 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9218
9219 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009220 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009221 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009222
Douglas Gregora771f462010-03-31 17:46:05 +00009223 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009224}
9225
Chris Lattner9bad62c2008-01-04 18:04:52 +00009226bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9227 SourceLocation Loc,
9228 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009229 Expr *SrcExpr, AssignmentAction Action,
9230 bool *Complained) {
9231 if (Complained)
9232 *Complained = false;
9233
Chris Lattner9bad62c2008-01-04 18:04:52 +00009234 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009235 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009236 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009237 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009238 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009239 ConversionFixItGenerator ConvHints;
9240 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009241 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009242
Chris Lattner9bad62c2008-01-04 18:04:52 +00009243 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009244 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009245 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009246 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009247 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9248 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009249 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009250 case IntToPointer:
9251 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009252 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9253 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009254 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009255 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009256 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009257 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009258 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9259 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009260 if (Hint.isNull() && !CheckInferredResultType) {
9261 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9262 }
9263 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009264 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009265 case IncompatiblePointerSign:
9266 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9267 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009268 case FunctionVoidPointer:
9269 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9270 break;
John McCall4fff8f62011-02-01 00:10:29 +00009271 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009272 // Perform array-to-pointer decay if necessary.
9273 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9274
John McCall4fff8f62011-02-01 00:10:29 +00009275 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9276 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9277 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9278 DiagKind = diag::err_typecheck_incompatible_address_space;
9279 break;
John McCall31168b02011-06-15 23:02:42 +00009280
9281
9282 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009283 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009284 break;
John McCall4fff8f62011-02-01 00:10:29 +00009285 }
9286
9287 llvm_unreachable("unknown error case for discarding qualifiers!");
9288 // fallthrough
9289 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009290 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009291 // If the qualifiers lost were because we were applying the
9292 // (deprecated) C++ conversion from a string literal to a char*
9293 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9294 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009295 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009296 // bit of refactoring (so that the second argument is an
9297 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009298 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009299 // C++ semantics.
9300 if (getLangOptions().CPlusPlus &&
9301 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9302 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009303 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9304 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009305 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009306 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009307 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009308 case IntToBlockPointer:
9309 DiagKind = diag::err_int_to_block_pointer;
9310 break;
9311 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009312 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009313 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009314 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009315 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009316 // it can give a more specific diagnostic.
9317 DiagKind = diag::warn_incompatible_qualified_id;
9318 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009319 case IncompatibleVectors:
9320 DiagKind = diag::warn_incompatible_vectors;
9321 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009322 case IncompatibleObjCWeakRef:
9323 DiagKind = diag::err_arc_weak_unavailable_assign;
9324 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009325 case Incompatible:
9326 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009327 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9328 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009329 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009330 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009331 break;
9332 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009333
Douglas Gregorc68e1402010-04-09 00:35:39 +00009334 QualType FirstType, SecondType;
9335 switch (Action) {
9336 case AA_Assigning:
9337 case AA_Initializing:
9338 // The destination type comes first.
9339 FirstType = DstType;
9340 SecondType = SrcType;
9341 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009342
Douglas Gregorc68e1402010-04-09 00:35:39 +00009343 case AA_Returning:
9344 case AA_Passing:
9345 case AA_Converting:
9346 case AA_Sending:
9347 case AA_Casting:
9348 // The source type comes first.
9349 FirstType = SrcType;
9350 SecondType = DstType;
9351 break;
9352 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009353
Anna Zaks3b402712011-07-28 19:51:27 +00009354 PartialDiagnostic FDiag = PDiag(DiagKind);
9355 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9356
9357 // If we can fix the conversion, suggest the FixIts.
9358 assert(ConvHints.isNull() || Hint.isNull());
9359 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009360 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9361 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009362 FDiag << *HI;
9363 } else {
9364 FDiag << Hint;
9365 }
9366 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9367
Richard Trieucaff2472011-11-23 22:32:32 +00009368 if (MayHaveFunctionDiff)
9369 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9370
Anna Zaks3b402712011-07-28 19:51:27 +00009371 Diag(Loc, FDiag);
9372
Richard Trieucaff2472011-11-23 22:32:32 +00009373 if (SecondType == Context.OverloadTy)
9374 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9375 FirstType);
9376
Douglas Gregor33823722011-06-11 01:09:30 +00009377 if (CheckInferredResultType)
9378 EmitRelatedResultTypeNote(SrcExpr);
9379
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009380 if (Complained)
9381 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009382 return isInvalid;
9383}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009384
Richard Smithf4c51d92012-02-04 09:53:13 +00009385ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9386 llvm::APSInt *Result) {
9387 return VerifyIntegerConstantExpression(E, Result,
9388 PDiag(diag::err_expr_not_ice) << LangOpts.CPlusPlus);
9389}
9390
9391ExprResult Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
9392 PartialDiagnostic NotIceDiag,
9393 bool AllowFold,
9394 PartialDiagnostic FoldDiag) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009395 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009396
9397 if (getLangOptions().CPlusPlus0x) {
9398 // C++11 [expr.const]p5:
9399 // If an expression of literal class type is used in a context where an
9400 // integral constant expression is required, then that class type shall
9401 // have a single non-explicit conversion function to an integral or
9402 // unscoped enumeration type
9403 ExprResult Converted;
9404 if (NotIceDiag.getDiagID()) {
9405 Converted = ConvertToIntegralOrEnumerationType(
9406 DiagLoc, E,
9407 PDiag(diag::err_ice_not_integral),
9408 PDiag(diag::err_ice_incomplete_type),
9409 PDiag(diag::err_ice_explicit_conversion),
9410 PDiag(diag::note_ice_conversion_here),
9411 PDiag(diag::err_ice_ambiguous_conversion),
9412 PDiag(diag::note_ice_conversion_here),
9413 PDiag(0),
9414 /*AllowScopedEnumerations*/ false);
9415 } else {
9416 // The caller wants to silently enquire whether this is an ICE. Don't
9417 // produce any diagnostics if it isn't.
9418 Converted = ConvertToIntegralOrEnumerationType(
9419 DiagLoc, E, PDiag(), PDiag(), PDiag(), PDiag(),
9420 PDiag(), PDiag(), PDiag(), false);
9421 }
9422 if (Converted.isInvalid())
9423 return Converted;
9424 E = Converted.take();
9425 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9426 return ExprError();
9427 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9428 // An ICE must be of integral or unscoped enumeration type.
9429 if (NotIceDiag.getDiagID())
9430 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
9431 return ExprError();
9432 }
9433
Richard Smith902ca212011-12-14 23:32:26 +00009434 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9435 // in the non-ICE case.
Richard Smithf4c51d92012-02-04 09:53:13 +00009436 if (!getLangOptions().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
9437 if (Result)
9438 *Result = E->EvaluateKnownConstInt(Context);
9439 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009440 }
9441
Anders Carlssone54e8a12008-11-30 19:50:32 +00009442 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009443 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9444 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009445
Richard Smith902ca212011-12-14 23:32:26 +00009446 // Try to evaluate the expression, and produce diagnostics explaining why it's
9447 // not a constant expression as a side-effect.
9448 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9449 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9450
9451 // In C++11, we can rely on diagnostics being produced for any expression
9452 // which is not a constant expression. If no diagnostics were produced, then
9453 // this is a constant expression.
9454 if (Folded && getLangOptions().CPlusPlus0x && Notes.empty()) {
9455 if (Result)
9456 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009457 return Owned(E);
9458 }
9459
9460 // If our only note is the usual "invalid subexpression" note, just point
9461 // the caret at its location rather than producing an essentially
9462 // redundant note.
9463 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9464 diag::note_invalid_subexpr_in_const_expr) {
9465 DiagLoc = Notes[0].first;
9466 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009467 }
9468
9469 if (!Folded || !AllowFold) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009470 if (NotIceDiag.getDiagID()) {
9471 Diag(DiagLoc, NotIceDiag) << E->getSourceRange();
Richard Smith92b1ce02011-12-12 09:28:41 +00009472 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9473 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009474 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009475
Richard Smithf4c51d92012-02-04 09:53:13 +00009476 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009477 }
9478
Richard Smithf4c51d92012-02-04 09:53:13 +00009479 if (FoldDiag.getDiagID())
9480 Diag(DiagLoc, FoldDiag) << E->getSourceRange();
9481 else
9482 Diag(DiagLoc, diag::ext_expr_not_ice)
9483 << E->getSourceRange() << LangOpts.CPlusPlus;
Richard Smith2ec40612012-01-15 03:51:30 +00009484 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9485 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009486
Anders Carlssone54e8a12008-11-30 19:50:32 +00009487 if (Result)
9488 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009489 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009490}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009491
Eli Friedman456f0182012-01-20 01:26:23 +00009492namespace {
9493 // Handle the case where we conclude a expression which we speculatively
9494 // considered to be unevaluated is actually evaluated.
9495 class TransformToPE : public TreeTransform<TransformToPE> {
9496 typedef TreeTransform<TransformToPE> BaseTransform;
9497
9498 public:
9499 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9500
9501 // Make sure we redo semantic analysis
9502 bool AlwaysRebuild() { return true; }
9503
Eli Friedman5f0ca242012-02-06 23:29:57 +00009504 // Make sure we handle LabelStmts correctly.
9505 // FIXME: This does the right thing, but maybe we need a more general
9506 // fix to TreeTransform?
9507 StmtResult TransformLabelStmt(LabelStmt *S) {
9508 S->getDecl()->setStmt(0);
9509 return BaseTransform::TransformLabelStmt(S);
9510 }
9511
Eli Friedman456f0182012-01-20 01:26:23 +00009512 // We need to special-case DeclRefExprs referring to FieldDecls which
9513 // are not part of a member pointer formation; normal TreeTransforming
9514 // doesn't catch this case because of the way we represent them in the AST.
9515 // FIXME: This is a bit ugly; is it really the best way to handle this
9516 // case?
9517 //
9518 // Error on DeclRefExprs referring to FieldDecls.
9519 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9520 if (isa<FieldDecl>(E->getDecl()) &&
9521 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9522 return SemaRef.Diag(E->getLocation(),
9523 diag::err_invalid_non_static_member_use)
9524 << E->getDecl() << E->getSourceRange();
9525
9526 return BaseTransform::TransformDeclRefExpr(E);
9527 }
9528
9529 // Exception: filter out member pointer formation
9530 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9531 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9532 return E;
9533
9534 return BaseTransform::TransformUnaryOperator(E);
9535 }
9536
Douglas Gregor89625492012-02-09 08:14:43 +00009537 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9538 // Lambdas never need to be transformed.
9539 return E;
9540 }
Eli Friedman456f0182012-01-20 01:26:23 +00009541 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009542}
9543
Eli Friedman456f0182012-01-20 01:26:23 +00009544ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009545 assert(ExprEvalContexts.back().Context == Unevaluated &&
9546 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009547 ExprEvalContexts.back().Context =
9548 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9549 if (ExprEvalContexts.back().Context == Unevaluated)
9550 return E;
9551 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009552}
9553
Douglas Gregorff790f12009-11-26 00:44:06 +00009554void
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009555Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +00009556 Decl *LambdaContextDecl,
9557 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009558 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009559 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +00009560 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009561 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +00009562 LambdaContextDecl,
9563 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +00009564 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009565 if (!MaybeODRUseExprs.empty())
9566 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009567}
9568
Richard Trieucfc491d2011-08-02 04:35:43 +00009569void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009570 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009571
Douglas Gregor89625492012-02-09 08:14:43 +00009572 if (!Rec.Lambdas.empty()) {
9573 if (Rec.Context == Unevaluated) {
9574 // C++11 [expr.prim.lambda]p2:
9575 // A lambda-expression shall not appear in an unevaluated operand
9576 // (Clause 5).
9577 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
9578 Diag(Rec.Lambdas[I]->getLocStart(),
9579 diag::err_lambda_unevaluated_operand);
9580 } else {
9581 // Mark the capture expressions odr-used. This was deferred
9582 // during lambda expression creation.
9583 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
9584 LambdaExpr *Lambda = Rec.Lambdas[I];
9585 for (LambdaExpr::capture_init_iterator
9586 C = Lambda->capture_init_begin(),
9587 CEnd = Lambda->capture_init_end();
9588 C != CEnd; ++C) {
9589 MarkDeclarationsReferencedInExpr(*C);
9590 }
9591 }
9592 }
9593 }
9594
Douglas Gregorff790f12009-11-26 00:44:06 +00009595 // When are coming out of an unevaluated context, clear out any
9596 // temporaries that we may have created as part of the evaluation of
9597 // the expression in that context: they aren't relevant because they
9598 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +00009599 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +00009600 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9601 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009602 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009603 CleanupVarDeclMarking();
9604 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +00009605 // Otherwise, merge the contexts together.
9606 } else {
9607 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009608 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
9609 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +00009610 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009611
9612 // Pop the current expression evaluation context off the stack.
9613 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009614}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009615
John McCall31168b02011-06-15 23:02:42 +00009616void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +00009617 ExprCleanupObjects.erase(
9618 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
9619 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009620 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009621 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +00009622}
9623
Eli Friedmane0afc982012-01-21 01:01:51 +00009624ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
9625 if (!E->getType()->isVariablyModifiedType())
9626 return E;
9627 return TranformToPotentiallyEvaluated(E);
9628}
9629
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +00009630static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009631 // Do not mark anything as "used" within a dependent context; wait for
9632 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009633 if (SemaRef.CurContext->isDependentContext())
9634 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009635
Eli Friedmanfa0df832012-02-02 03:46:19 +00009636 switch (SemaRef.ExprEvalContexts.back().Context) {
9637 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009638 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +00009639 // (Depending on how you read the standard, we actually do need to do
9640 // something here for null pointer constants, but the standard's
9641 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +00009642 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009643
Eli Friedmanfa0df832012-02-02 03:46:19 +00009644 case Sema::ConstantEvaluated:
9645 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +00009646 // We are in a potentially evaluated expression (or a constant-expression
9647 // in C++03); we need to do implicit template instantiation, implicitly
9648 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009649 return true;
Mike Stump11289f42009-09-09 15:08:12 +00009650
Eli Friedmanfa0df832012-02-02 03:46:19 +00009651 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00009652 // Referenced declarations will only be used if the construct in the
9653 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009654 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009655 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +00009656 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +00009657}
9658
9659/// \brief Mark a function referenced, and check whether it is odr-used
9660/// (C++ [basic.def.odr]p2, C99 6.9p3)
9661void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
9662 assert(Func && "No function?");
9663
9664 Func->setReferenced();
9665
Richard Smith4a941e22012-02-14 22:25:15 +00009666 // Don't mark this function as used multiple times, unless it's a constexpr
9667 // function which we need to instantiate.
9668 if (Func->isUsed(false) &&
9669 !(Func->isConstexpr() && !Func->getBody() &&
9670 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +00009671 return;
9672
9673 if (!IsPotentiallyEvaluatedContext(*this))
9674 return;
Mike Stump11289f42009-09-09 15:08:12 +00009675
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009676 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +00009677 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009678 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009679 if (Constructor->isDefaultConstructor()) {
9680 if (Constructor->isTrivial())
9681 return;
9682 if (!Constructor->isUsed(false))
9683 DefineImplicitDefaultConstructor(Loc, Constructor);
9684 } else if (Constructor->isCopyConstructor()) {
9685 if (!Constructor->isUsed(false))
9686 DefineImplicitCopyConstructor(Loc, Constructor);
9687 } else if (Constructor->isMoveConstructor()) {
9688 if (!Constructor->isUsed(false))
9689 DefineImplicitMoveConstructor(Loc, Constructor);
9690 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +00009691 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009692
Douglas Gregor88d292c2010-05-13 16:44:06 +00009693 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009694 } else if (CXXDestructorDecl *Destructor =
9695 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009696 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
9697 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +00009698 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009699 if (Destructor->isVirtual())
9700 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +00009701 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +00009702 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
9703 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009704 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +00009705 if (!MethodDecl->isUsed(false)) {
9706 if (MethodDecl->isCopyAssignmentOperator())
9707 DefineImplicitCopyAssignment(Loc, MethodDecl);
9708 else
9709 DefineImplicitMoveAssignment(Loc, MethodDecl);
9710 }
Douglas Gregord3b672c2012-02-16 01:06:16 +00009711 } else if (isa<CXXConversionDecl>(MethodDecl) &&
9712 MethodDecl->getParent()->isLambda()) {
9713 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
9714 if (Conversion->isLambdaToBlockPointerConversion())
9715 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
9716 else
9717 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +00009718 } else if (MethodDecl->isVirtual())
9719 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +00009720 }
John McCall83779672011-02-19 02:53:41 +00009721
Eli Friedmanfa0df832012-02-02 03:46:19 +00009722 // Recursive functions should be marked when used from another function.
9723 // FIXME: Is this really right?
9724 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009725
Eli Friedmanfa0df832012-02-02 03:46:19 +00009726 // Implicit instantiation of function templates and member functions of
9727 // class templates.
9728 if (Func->isImplicitlyInstantiable()) {
9729 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +00009730 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +00009731 if (FunctionTemplateSpecializationInfo *SpecInfo
9732 = Func->getTemplateSpecializationInfo()) {
9733 if (SpecInfo->getPointOfInstantiation().isInvalid())
9734 SpecInfo->setPointOfInstantiation(Loc);
9735 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009736 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009737 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009738 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
9739 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009740 } else if (MemberSpecializationInfo *MSInfo
9741 = Func->getMemberSpecializationInfo()) {
9742 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +00009743 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00009744 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +00009745 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009746 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +00009747 PointOfInstantiation = MSInfo->getPointOfInstantiation();
9748 }
Douglas Gregor06db9f52009-10-12 20:18:28 +00009749 }
Mike Stump11289f42009-09-09 15:08:12 +00009750
Richard Smith4a941e22012-02-14 22:25:15 +00009751 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009752 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
9753 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +00009754 PendingLocalImplicitInstantiations.push_back(
9755 std::make_pair(Func, PointOfInstantiation));
9756 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +00009757 // Do not defer instantiations of constexpr functions, to avoid the
9758 // expression evaluator needing to call back into Sema if it sees a
9759 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +00009760 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009761 else {
Richard Smith4a941e22012-02-14 22:25:15 +00009762 PendingInstantiations.push_back(std::make_pair(Func,
9763 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +00009764 // Notify the consumer that a function was implicitly instantiated.
9765 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
9766 }
John McCall83779672011-02-19 02:53:41 +00009767 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009768 } else {
9769 // Walk redefinitions, as some of them may be instantiable.
9770 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
9771 e(Func->redecls_end()); i != e; ++i) {
9772 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
9773 MarkFunctionReferenced(Loc, *i);
9774 }
Sam Weinigbae69142009-09-11 03:29:30 +00009775 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009776
9777 // Keep track of used but undefined functions.
9778 if (!Func->isPure() && !Func->hasBody() &&
9779 Func->getLinkage() != ExternalLinkage) {
9780 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
9781 if (old.isInvalid()) old = Loc;
9782 }
9783
9784 Func->setUsed(true);
9785}
9786
Eli Friedman9bb33f52012-02-03 02:04:35 +00009787static void
9788diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
9789 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +00009790 DeclContext *VarDC = var->getDeclContext();
9791
Eli Friedman9bb33f52012-02-03 02:04:35 +00009792 // If the parameter still belongs to the translation unit, then
9793 // we're actually just using one parameter in the declaration of
9794 // the next.
9795 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +00009796 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +00009797 return;
9798
Eli Friedmandd053f62012-02-07 00:15:00 +00009799 // For C code, don't diagnose about capture if we're not actually in code
9800 // right now; it's impossible to write a non-constant expression outside of
9801 // function context, so we'll get other (more useful) diagnostics later.
9802 //
9803 // For C++, things get a bit more nasty... it would be nice to suppress this
9804 // diagnostic for certain cases like using a local variable in an array bound
9805 // for a member of a local class, but the correct predicate is not obvious.
9806 if (!S.getLangOptions().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +00009807 return;
9808
Eli Friedmandd053f62012-02-07 00:15:00 +00009809 if (isa<CXXMethodDecl>(VarDC) &&
9810 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
9811 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
9812 << var->getIdentifier();
9813 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
9814 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
9815 << var->getIdentifier() << fn->getDeclName();
9816 } else if (isa<BlockDecl>(VarDC)) {
9817 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
9818 << var->getIdentifier();
9819 } else {
9820 // FIXME: Is there any other context where a local variable can be
9821 // declared?
9822 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
9823 << var->getIdentifier();
9824 }
Eli Friedman9bb33f52012-02-03 02:04:35 +00009825
Eli Friedman9bb33f52012-02-03 02:04:35 +00009826 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
9827 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +00009828
9829 // FIXME: Add additional diagnostic info about class etc. which prevents
9830 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +00009831}
9832
Douglas Gregor81495f32012-02-12 18:42:33 +00009833/// \brief Capture the given variable in the given lambda expression.
9834static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009835 VarDecl *Var, QualType FieldType,
9836 QualType DeclRefType,
9837 SourceLocation Loc) {
Douglas Gregor81495f32012-02-12 18:42:33 +00009838 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +00009839
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009840 // Build the non-static data member.
9841 FieldDecl *Field
9842 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
9843 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
9844 0, false, false);
9845 Field->setImplicit(true);
9846 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +00009847 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009848
9849 // C++11 [expr.prim.lambda]p21:
9850 // When the lambda-expression is evaluated, the entities that
9851 // are captured by copy are used to direct-initialize each
9852 // corresponding non-static data member of the resulting closure
9853 // object. (For array members, the array elements are
9854 // direct-initialized in increasing subscript order.) These
9855 // initializations are performed in the (unspecified) order in
9856 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009857
Douglas Gregor89625492012-02-09 08:14:43 +00009858 // Introduce a new evaluation context for the initialization, so
9859 // that temporaries introduced as part of the capture are retained
9860 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009861 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
9862
Douglas Gregorf02455e2012-02-10 09:26:04 +00009863 // C++ [expr.prim.labda]p12:
9864 // An entity captured by a lambda-expression is odr-used (3.2) in
9865 // the scope containing the lambda-expression.
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009866 Expr *Ref = new (S.Context) DeclRefExpr(Var, DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +00009867 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +00009868 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +00009869
9870 // When the field has array type, create index variables for each
9871 // dimension of the array. We use these index variables to subscript
9872 // the source array, and other clients (e.g., CodeGen) will perform
9873 // the necessary iteration with these index variables.
9874 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +00009875 QualType BaseType = FieldType;
9876 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +00009877 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +00009878 while (const ConstantArrayType *Array
9879 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +00009880 // Create the iteration variable for this array index.
9881 IdentifierInfo *IterationVarName = 0;
9882 {
9883 SmallString<8> Str;
9884 llvm::raw_svector_ostream OS(Str);
9885 OS << "__i" << IndexVariables.size();
9886 IterationVarName = &S.Context.Idents.get(OS.str());
9887 }
9888 VarDecl *IterationVar
9889 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
9890 IterationVarName, SizeType,
9891 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
9892 SC_None, SC_None);
9893 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +00009894 LSI->ArrayIndexVars.push_back(IterationVar);
9895
Douglas Gregor199cec72012-02-09 02:45:47 +00009896 // Create a reference to the iteration variable.
9897 ExprResult IterationVarRef
9898 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
9899 assert(!IterationVarRef.isInvalid() &&
9900 "Reference to invented variable cannot fail!");
9901 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
9902 assert(!IterationVarRef.isInvalid() &&
9903 "Conversion of invented variable cannot fail!");
9904
9905 // Subscript the array with this iteration variable.
9906 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
9907 Ref, Loc, IterationVarRef.take(), Loc);
9908 if (Subscript.isInvalid()) {
9909 S.CleanupVarDeclMarking();
9910 S.DiscardCleanupsInEvaluationContext();
9911 S.PopExpressionEvaluationContext();
9912 return ExprError();
9913 }
9914
9915 Ref = Subscript.take();
9916 BaseType = Array->getElementType();
9917 }
9918
9919 // Construct the entity that we will be initializing. For an array, this
9920 // will be first element in the array, which may require several levels
9921 // of array-subscript entities.
9922 SmallVector<InitializedEntity, 4> Entities;
9923 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +00009924 Entities.push_back(
9925 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +00009926 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
9927 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
9928 0,
9929 Entities.back()));
9930
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009931 InitializationKind InitKind
9932 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +00009933 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009934 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +00009935 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
9936 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009937 MultiExprArg(S, &Ref, 1));
9938
9939 // If this initialization requires any cleanups (e.g., due to a
9940 // default argument to a copy constructor), note that for the
9941 // lambda.
9942 if (S.ExprNeedsCleanups)
9943 LSI->ExprNeedsCleanups = true;
9944
9945 // Exit the expression evaluation context used for the capture.
9946 S.CleanupVarDeclMarking();
9947 S.DiscardCleanupsInEvaluationContext();
9948 S.PopExpressionEvaluationContext();
9949 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +00009950}
Douglas Gregorabecb9c2012-02-09 01:56:40 +00009951
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009952bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
9953 TryCaptureKind Kind, SourceLocation EllipsisLoc,
9954 bool BuildAndDiagnose,
9955 QualType &CaptureType,
9956 QualType &DeclRefType) {
9957 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +00009958
Eli Friedman24af8502012-02-03 22:47:37 +00009959 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009960 if (Var->getDeclContext() == DC) return true;
9961 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009962
Douglas Gregor81495f32012-02-12 18:42:33 +00009963 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +00009964
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009965 // Walk up the stack to determine whether we can capture the variable,
9966 // performing the "simple" checks that don't depend on type. We stop when
9967 // we've either hit the declared scope of the variable or find an existing
9968 // capture of that variable.
9969 CaptureType = Var->getType();
9970 DeclRefType = CaptureType.getNonReferenceType();
9971 bool Explicit = (Kind != TryCapture_Implicit);
9972 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +00009973 do {
Eli Friedman24af8502012-02-03 22:47:37 +00009974 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +00009975 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +00009976 DeclContext *ParentDC;
9977 if (isa<BlockDecl>(DC))
9978 ParentDC = DC->getParent();
9979 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +00009980 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +00009981 cast<CXXRecordDecl>(DC->getParent())->isLambda())
9982 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +00009983 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009984 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +00009985 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009986 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +00009987 }
Eli Friedman9bb33f52012-02-03 02:04:35 +00009988
Eli Friedman24af8502012-02-03 22:47:37 +00009989 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +00009990 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +00009991
Eli Friedman24af8502012-02-03 22:47:37 +00009992 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +00009993 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009994 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +00009995 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +00009996
9997 // Retrieve the capture type for this variable.
9998 CaptureType = CSI->getCapture(Var).getCaptureType();
9999
10000 // Compute the type of an expression that refers to this variable.
10001 DeclRefType = CaptureType.getNonReferenceType();
10002
10003 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10004 if (Cap.isCopyCapture() &&
10005 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10006 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010007 break;
10008 }
10009
Douglas Gregor81495f32012-02-12 18:42:33 +000010010 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010011 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010012
10013 // Lambdas are not allowed to capture unnamed variables
10014 // (e.g. anonymous unions).
10015 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10016 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010017 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010018 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010019 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10020 Diag(Var->getLocation(), diag::note_declared_at);
10021 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010022 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010023 }
10024
10025 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010026 if (Var->getType()->isVariablyModifiedType()) {
10027 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010028 if (IsBlock)
10029 Diag(Loc, diag::err_ref_vm_type);
10030 else
10031 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10032 Diag(Var->getLocation(), diag::note_previous_decl)
10033 << Var->getDeclName();
10034 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010035 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010036 }
10037
Eli Friedman24af8502012-02-03 22:47:37 +000010038 // Lambdas are not allowed to capture __block variables; they don't
10039 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010040 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010041 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010042 Diag(Loc, diag::err_lambda_capture_block)
10043 << Var->getDeclName();
10044 Diag(Var->getLocation(), diag::note_previous_decl)
10045 << Var->getDeclName();
10046 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010047 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010048 }
10049
Douglas Gregor81495f32012-02-12 18:42:33 +000010050 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10051 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010052 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010053 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10054 Diag(Var->getLocation(), diag::note_previous_decl)
10055 << Var->getDeclName();
10056 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10057 diag::note_lambda_decl);
10058 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010059 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010060 }
10061
10062 FunctionScopesIndex--;
10063 DC = ParentDC;
10064 Explicit = false;
10065 } while (!Var->getDeclContext()->Equals(DC));
10066
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010067 // Walk back down the scope stack, computing the type of the capture at
10068 // each step, checking type-specific requirements, and adding captures if
10069 // requested.
10070 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10071 ++I) {
10072 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010073
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010074 // Compute the type of the capture and of a reference to the capture within
10075 // this scope.
10076 if (isa<BlockScopeInfo>(CSI)) {
10077 Expr *CopyExpr = 0;
10078 bool ByRef = false;
10079
10080 // Blocks are not allowed to capture arrays.
10081 if (CaptureType->isArrayType()) {
10082 if (BuildAndDiagnose) {
10083 Diag(Loc, diag::err_ref_array_type);
10084 Diag(Var->getLocation(), diag::note_previous_decl)
10085 << Var->getDeclName();
10086 }
10087 return true;
10088 }
10089
10090 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10091 // Block capture by reference does not change the capture or
10092 // declaration reference types.
10093 ByRef = true;
10094 } else {
10095 // Block capture by copy introduces 'const'.
10096 CaptureType = CaptureType.getNonReferenceType().withConst();
10097 DeclRefType = CaptureType;
10098
10099 if (getLangOptions().CPlusPlus && BuildAndDiagnose) {
10100 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10101 // The capture logic needs the destructor, so make sure we mark it.
10102 // Usually this is unnecessary because most local variables have
10103 // their destructors marked at declaration time, but parameters are
10104 // an exception because it's technically only the call site that
10105 // actually requires the destructor.
10106 if (isa<ParmVarDecl>(Var))
10107 FinalizeVarWithDestructor(Var, Record);
10108
10109 // According to the blocks spec, the capture of a variable from
10110 // the stack requires a const copy constructor. This is not true
10111 // of the copy/move done to move a __block variable to the heap.
10112 Expr *DeclRef = new (Context) DeclRefExpr(Var,
10113 DeclRefType.withConst(),
10114 VK_LValue, Loc);
10115 ExprResult Result
10116 = PerformCopyInitialization(
10117 InitializedEntity::InitializeBlock(Var->getLocation(),
10118 CaptureType, false),
10119 Loc, Owned(DeclRef));
10120
10121 // Build a full-expression copy expression if initialization
10122 // succeeded and used a non-trivial constructor. Recover from
10123 // errors by pretending that the copy isn't necessary.
10124 if (!Result.isInvalid() &&
10125 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10126 ->isTrivial()) {
10127 Result = MaybeCreateExprWithCleanups(Result);
10128 CopyExpr = Result.take();
10129 }
10130 }
10131 }
10132 }
10133
10134 // Actually capture the variable.
10135 if (BuildAndDiagnose)
10136 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10137 SourceLocation(), CaptureType, CopyExpr);
10138 Nested = true;
10139 continue;
10140 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010141
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010142 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10143
10144 // Determine whether we are capturing by reference or by value.
10145 bool ByRef = false;
10146 if (I == N - 1 && Kind != TryCapture_Implicit) {
10147 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010148 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010149 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010150 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010151
10152 // Compute the type of the field that will capture this variable.
10153 if (ByRef) {
10154 // C++11 [expr.prim.lambda]p15:
10155 // An entity is captured by reference if it is implicitly or
10156 // explicitly captured but not captured by copy. It is
10157 // unspecified whether additional unnamed non-static data
10158 // members are declared in the closure type for entities
10159 // captured by reference.
10160 //
10161 // FIXME: It is not clear whether we want to build an lvalue reference
10162 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10163 // to do the former, while EDG does the latter. Core issue 1249 will
10164 // clarify, but for now we follow GCC because it's a more permissive and
10165 // easily defensible position.
10166 CaptureType = Context.getLValueReferenceType(DeclRefType);
10167 } else {
10168 // C++11 [expr.prim.lambda]p14:
10169 // For each entity captured by copy, an unnamed non-static
10170 // data member is declared in the closure type. The
10171 // declaration order of these members is unspecified. The type
10172 // of such a data member is the type of the corresponding
10173 // captured entity if the entity is not a reference to an
10174 // object, or the referenced type otherwise. [Note: If the
10175 // captured entity is a reference to a function, the
10176 // corresponding data member is also a reference to a
10177 // function. - end note ]
10178 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10179 if (!RefType->getPointeeType()->isFunctionType())
10180 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010181 }
10182 }
10183
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010184 // Capture this variable in the lambda.
10185 Expr *CopyExpr = 0;
10186 if (BuildAndDiagnose) {
10187 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
10188 DeclRefType, Loc);
10189 if (!Result.isInvalid())
10190 CopyExpr = Result.take();
10191 }
10192
10193 // Compute the type of a reference to this captured variable.
10194 if (ByRef)
10195 DeclRefType = CaptureType.getNonReferenceType();
10196 else {
10197 // C++ [expr.prim.lambda]p5:
10198 // The closure type for a lambda-expression has a public inline
10199 // function call operator [...]. This function call operator is
10200 // declared const (9.3.1) if and only if the lambda-expression’s
10201 // parameter-declaration-clause is not followed by mutable.
10202 DeclRefType = CaptureType.getNonReferenceType();
10203 if (!LSI->Mutable && !CaptureType->isReferenceType())
10204 DeclRefType.addConst();
10205 }
10206
10207 // Add the capture.
10208 if (BuildAndDiagnose)
10209 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10210 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010211 Nested = true;
10212 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010213
10214 return false;
10215}
10216
10217bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10218 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10219 QualType CaptureType;
10220 QualType DeclRefType;
10221 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10222 /*BuildAndDiagnose=*/true, CaptureType,
10223 DeclRefType);
10224}
10225
10226QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10227 QualType CaptureType;
10228 QualType DeclRefType;
10229
10230 // Determine whether we can capture this variable.
10231 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10232 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10233 return QualType();
10234
10235 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010236}
10237
Eli Friedman3bda6b12012-02-02 23:15:15 +000010238static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10239 SourceLocation Loc) {
10240 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010241 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010242 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010243 Var->getLinkage() != ExternalLinkage &&
10244 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010245 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10246 if (old.isInvalid()) old = Loc;
10247 }
10248
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010249 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010250
Eli Friedman3bda6b12012-02-02 23:15:15 +000010251 Var->setUsed(true);
10252}
10253
10254void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10255 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10256 // an object that satisfies the requirements for appearing in a
10257 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10258 // is immediately applied." This function handles the lvalue-to-rvalue
10259 // conversion part.
10260 MaybeODRUseExprs.erase(E->IgnoreParens());
10261}
10262
Eli Friedmanc6237c62012-02-29 03:16:56 +000010263ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10264 if (!Res.isUsable())
10265 return Res;
10266
10267 // If a constant-expression is a reference to a variable where we delay
10268 // deciding whether it is an odr-use, just assume we will apply the
10269 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10270 // (a non-type template argument), we have special handling anyway.
10271 UpdateMarkingForLValueToRValue(Res.get());
10272 return Res;
10273}
10274
Eli Friedman3bda6b12012-02-02 23:15:15 +000010275void Sema::CleanupVarDeclMarking() {
10276 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10277 e = MaybeODRUseExprs.end();
10278 i != e; ++i) {
10279 VarDecl *Var;
10280 SourceLocation Loc;
10281 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(*i)) {
10282 Var = BDRE->getDecl();
10283 Loc = BDRE->getLocation();
10284 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
10285 Var = cast<VarDecl>(DRE->getDecl());
10286 Loc = DRE->getLocation();
10287 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10288 Var = cast<VarDecl>(ME->getMemberDecl());
10289 Loc = ME->getMemberLoc();
10290 } else {
10291 llvm_unreachable("Unexpcted expression");
10292 }
10293
10294 MarkVarDeclODRUsed(*this, Var, Loc);
10295 }
10296
10297 MaybeODRUseExprs.clear();
10298}
10299
10300// Mark a VarDecl referenced, and perform the necessary handling to compute
10301// odr-uses.
10302static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10303 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010304 Var->setReferenced();
10305
Eli Friedman3bda6b12012-02-02 23:15:15 +000010306 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010307 return;
10308
10309 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010310 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010311 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10312 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010313 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10314 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010315 (!AlreadyInstantiated ||
10316 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010317 if (!AlreadyInstantiated) {
10318 // This is a modification of an existing AST node. Notify listeners.
10319 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10320 L->StaticDataMemberInstantiated(Var);
10321 MSInfo->setPointOfInstantiation(Loc);
10322 }
10323 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010324 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010325 // Do not defer instantiations of variables which could be used in a
10326 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010327 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010328 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010329 SemaRef.PendingInstantiations.push_back(
10330 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010331 }
10332 }
10333
Eli Friedman3bda6b12012-02-02 23:15:15 +000010334 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10335 // an object that satisfies the requirements for appearing in a
10336 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10337 // is immediately applied." We check the first part here, and
10338 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10339 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010340 // C++03 depends on whether we get the C++03 version correct. This does not
10341 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010342 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010343 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010344 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010345 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10346 SemaRef.MaybeODRUseExprs.insert(E);
10347 else
10348 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10349}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010350
Eli Friedman3bda6b12012-02-02 23:15:15 +000010351/// \brief Mark a variable referenced, and check whether it is odr-used
10352/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10353/// used directly for normal expressions referring to VarDecl.
10354void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10355 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010356}
10357
10358static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10359 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010360 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10361 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10362 return;
10363 }
10364
Eli Friedmanfa0df832012-02-02 03:46:19 +000010365 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010366}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010367
10368/// \brief Perform reference-marking and odr-use handling for a
10369/// BlockDeclRefExpr.
10370void Sema::MarkBlockDeclRefReferenced(BlockDeclRefExpr *E) {
10371 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10372}
10373
10374/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10375void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10376 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10377}
10378
10379/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10380void Sema::MarkMemberReferenced(MemberExpr *E) {
10381 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10382}
10383
Douglas Gregorf02455e2012-02-10 09:26:04 +000010384/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010385/// marks the declaration referenced, and performs odr-use checking for functions
10386/// and variables. This method should not be used when building an normal
10387/// expression which refers to a variable.
10388void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10389 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10390 MarkVariableReferenced(Loc, VD);
10391 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10392 MarkFunctionReferenced(Loc, FD);
10393 else
10394 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010395}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010396
Douglas Gregor5597ab42010-05-07 23:12:07 +000010397namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010398 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010399 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010400 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010401 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10402 Sema &S;
10403 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010404
Douglas Gregor5597ab42010-05-07 23:12:07 +000010405 public:
10406 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010407
Douglas Gregor5597ab42010-05-07 23:12:07 +000010408 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010409
10410 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10411 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010412 };
10413}
10414
Chandler Carruthaf80f662010-06-09 08:17:30 +000010415bool MarkReferencedDecls::TraverseTemplateArgument(
10416 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010417 if (Arg.getKind() == TemplateArgument::Declaration) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010418 S.MarkAnyDeclReferenced(Loc, Arg.getAsDecl());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010419 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010420
10421 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010422}
10423
Chandler Carruthaf80f662010-06-09 08:17:30 +000010424bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010425 if (ClassTemplateSpecializationDecl *Spec
10426 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10427 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010428 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010429 }
10430
Chandler Carruthc65667c2010-06-10 10:31:57 +000010431 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010432}
10433
10434void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10435 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010436 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010437}
10438
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010439namespace {
10440 /// \brief Helper class that marks all of the declarations referenced by
10441 /// potentially-evaluated subexpressions as "referenced".
10442 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10443 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010444 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010445
10446 public:
10447 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10448
Douglas Gregor680e9e02012-02-21 19:11:17 +000010449 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10450 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010451
10452 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010453 // If we were asked not to visit local variables, don't.
10454 if (SkipLocalVariables) {
10455 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10456 if (VD->hasLocalStorage())
10457 return;
10458 }
10459
Eli Friedmanfa0df832012-02-02 03:46:19 +000010460 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010461 }
10462
10463 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010464 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010465 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010466 }
10467
John McCall28fc7092011-11-10 05:35:25 +000010468 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010469 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010470 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10471 Visit(E->getSubExpr());
10472 }
10473
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010474 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010475 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010476 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010477 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010478 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010479 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010480 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010481
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010482 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10483 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010484 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010485 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10486 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10487 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010488 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010489 S.LookupDestructor(Record));
10490 }
10491
Douglas Gregor32b3de52010-09-11 23:32:50 +000010492 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010493 }
10494
10495 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010496 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010497 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010498 }
10499
10500 void VisitBlockDeclRefExpr(BlockDeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010501 // If we were asked not to visit local variables, don't.
10502 if (SkipLocalVariables && E->getDecl()->hasLocalStorage())
10503 return;
10504
Eli Friedmanfa0df832012-02-02 03:46:19 +000010505 S.MarkBlockDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010506 }
Douglas Gregorf0873f42010-10-19 17:17:35 +000010507
10508 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10509 Visit(E->getExpr());
10510 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010511
10512 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10513 Inherited::VisitImplicitCastExpr(E);
10514
10515 if (E->getCastKind() == CK_LValueToRValue)
10516 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10517 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010518 };
10519}
10520
10521/// \brief Mark any declarations that appear within this expression or any
10522/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010523///
10524/// \param SkipLocalVariables If true, don't mark local variables as
10525/// 'referenced'.
10526void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10527 bool SkipLocalVariables) {
10528 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010529}
10530
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010531/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10532/// of the program being compiled.
10533///
10534/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010535/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010536/// possibility that the code will actually be executable. Code in sizeof()
10537/// expressions, code used only during overload resolution, etc., are not
10538/// potentially evaluated. This routine will suppress such diagnostics or,
10539/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010540/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010541/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010542///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010543/// This routine should be used for all diagnostics that describe the run-time
10544/// behavior of a program, such as passing a non-POD value through an ellipsis.
10545/// Failure to do so will likely result in spurious diagnostics or failures
10546/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000010547bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010548 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010549 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010550 case Unevaluated:
10551 // The argument will never be evaluated, so don't complain.
10552 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010553
Richard Smith764d2fe2011-12-20 02:08:33 +000010554 case ConstantEvaluated:
10555 // Relevant diagnostics should be produced by constant evaluation.
10556 break;
10557
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010558 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010559 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000010560 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000010561 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000010562 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000010563 }
10564 else
10565 Diag(Loc, PD);
10566
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010567 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010568 }
10569
10570 return false;
10571}
10572
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010573bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10574 CallExpr *CE, FunctionDecl *FD) {
10575 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10576 return false;
10577
Richard Smithfd555f62012-02-22 02:04:18 +000010578 // If we're inside a decltype's expression, don't check for a valid return
10579 // type or construct temporaries until we know whether this is the last call.
10580 if (ExprEvalContexts.back().IsDecltype) {
10581 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10582 return false;
10583 }
10584
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010585 PartialDiagnostic Note =
10586 FD ? PDiag(diag::note_function_with_incomplete_return_type_declared_here)
10587 << FD->getDeclName() : PDiag();
10588 SourceLocation NoteLoc = FD ? FD->getLocation() : SourceLocation();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010589
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010590 if (RequireCompleteType(Loc, ReturnType,
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010591 FD ?
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010592 PDiag(diag::err_call_function_incomplete_return)
10593 << CE->getSourceRange() << FD->getDeclName() :
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010594 PDiag(diag::err_call_incomplete_return)
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010595 << CE->getSourceRange(),
10596 std::make_pair(NoteLoc, Note)))
10597 return true;
10598
10599 return false;
10600}
10601
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010602// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000010603// will prevent this condition from triggering, which is what we want.
10604void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
10605 SourceLocation Loc;
10606
John McCall0506e4a2009-11-11 02:41:58 +000010607 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010608 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000010609
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010610 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010611 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000010612 return;
10613
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010614 IsOrAssign = Op->getOpcode() == BO_OrAssign;
10615
John McCallb0e419e2009-11-12 00:06:05 +000010616 // Greylist some idioms by putting them into a warning subcategory.
10617 if (ObjCMessageExpr *ME
10618 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
10619 Selector Sel = ME->getSelector();
10620
John McCallb0e419e2009-11-12 00:06:05 +000010621 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000010622 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000010623 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10624
10625 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000010626 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000010627 diagnostic = diag::warn_condition_is_idiomatic_assignment;
10628 }
John McCall0506e4a2009-11-11 02:41:58 +000010629
John McCalld5707ab2009-10-12 21:59:07 +000010630 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000010631 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010632 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000010633 return;
10634
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010635 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000010636 Loc = Op->getOperatorLoc();
10637 } else {
10638 // Not an assignment.
10639 return;
10640 }
10641
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000010642 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010643
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010644 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010645 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
10646 Diag(Loc, diag::note_condition_assign_silence)
10647 << FixItHint::CreateInsertion(Open, "(")
10648 << FixItHint::CreateInsertion(Close, ")");
10649
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000010650 if (IsOrAssign)
10651 Diag(Loc, diag::note_condition_or_assign_to_comparison)
10652 << FixItHint::CreateReplacement(Loc, "!=");
10653 else
10654 Diag(Loc, diag::note_condition_assign_to_comparison)
10655 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000010656}
10657
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010658/// \brief Redundant parentheses over an equality comparison can indicate
10659/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000010660void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010661 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000010662 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010663 if (parenLoc.isInvalid() || parenLoc.isMacroID())
10664 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010665 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000010666 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000010667 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000010668
Richard Trieuba63ce62011-09-09 01:45:06 +000010669 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010670
10671 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000010672 if (opE->getOpcode() == BO_EQ &&
10673 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
10674 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010675 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000010676
Ted Kremenekae022092011-02-02 02:20:30 +000010677 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010678 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000010679 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010680 << FixItHint::CreateRemoval(ParenERange.getBegin())
10681 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000010682 Diag(Loc, diag::note_equality_comparison_to_assign)
10683 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010684 }
10685}
10686
John Wiegley01296292011-04-08 18:41:53 +000010687ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000010688 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000010689 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
10690 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000010691
John McCall0009fcc2011-04-26 20:42:42 +000010692 ExprResult result = CheckPlaceholderExpr(E);
10693 if (result.isInvalid()) return ExprError();
10694 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000010695
John McCall0009fcc2011-04-26 20:42:42 +000010696 if (!E->isTypeDependent()) {
John McCall34376a62010-12-04 03:47:34 +000010697 if (getLangOptions().CPlusPlus)
10698 return CheckCXXBooleanCondition(E); // C++ 6.4p4
10699
John Wiegley01296292011-04-08 18:41:53 +000010700 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
10701 if (ERes.isInvalid())
10702 return ExprError();
10703 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000010704
10705 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000010706 if (!T->isScalarType()) { // C99 6.8.4.1p1
10707 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
10708 << T << E->getSourceRange();
10709 return ExprError();
10710 }
John McCalld5707ab2009-10-12 21:59:07 +000010711 }
10712
John Wiegley01296292011-04-08 18:41:53 +000010713 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000010714}
Douglas Gregore60e41a2010-05-06 17:25:47 +000010715
John McCalldadc5752010-08-24 06:29:42 +000010716ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000010717 Expr *SubExpr) {
10718 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000010719 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010720
Richard Trieuba63ce62011-09-09 01:45:06 +000010721 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000010722}
John McCall36e7fe32010-10-12 00:20:44 +000010723
John McCall31996342011-04-07 08:22:57 +000010724namespace {
John McCall2979fe02011-04-12 00:42:48 +000010725 /// A visitor for rebuilding a call to an __unknown_any expression
10726 /// to have an appropriate type.
10727 struct RebuildUnknownAnyFunction
10728 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
10729
10730 Sema &S;
10731
10732 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
10733
10734 ExprResult VisitStmt(Stmt *S) {
10735 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000010736 }
10737
Richard Trieu10162ab2011-09-09 03:59:41 +000010738 ExprResult VisitExpr(Expr *E) {
10739 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
10740 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010741 return ExprError();
10742 }
10743
10744 /// Rebuild an expression which simply semantically wraps another
10745 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010746 template <class T> ExprResult rebuildSugarExpr(T *E) {
10747 ExprResult SubResult = Visit(E->getSubExpr());
10748 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010749
Richard Trieu10162ab2011-09-09 03:59:41 +000010750 Expr *SubExpr = SubResult.take();
10751 E->setSubExpr(SubExpr);
10752 E->setType(SubExpr->getType());
10753 E->setValueKind(SubExpr->getValueKind());
10754 assert(E->getObjectKind() == OK_Ordinary);
10755 return E;
John McCall2979fe02011-04-12 00:42:48 +000010756 }
10757
Richard Trieu10162ab2011-09-09 03:59:41 +000010758 ExprResult VisitParenExpr(ParenExpr *E) {
10759 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010760 }
10761
Richard Trieu10162ab2011-09-09 03:59:41 +000010762 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10763 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010764 }
10765
Richard Trieu10162ab2011-09-09 03:59:41 +000010766 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10767 ExprResult SubResult = Visit(E->getSubExpr());
10768 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000010769
Richard Trieu10162ab2011-09-09 03:59:41 +000010770 Expr *SubExpr = SubResult.take();
10771 E->setSubExpr(SubExpr);
10772 E->setType(S.Context.getPointerType(SubExpr->getType()));
10773 assert(E->getValueKind() == VK_RValue);
10774 assert(E->getObjectKind() == OK_Ordinary);
10775 return E;
John McCall2979fe02011-04-12 00:42:48 +000010776 }
10777
Richard Trieu10162ab2011-09-09 03:59:41 +000010778 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
10779 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000010780
Richard Trieu10162ab2011-09-09 03:59:41 +000010781 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000010782
Richard Trieu10162ab2011-09-09 03:59:41 +000010783 assert(E->getValueKind() == VK_RValue);
John McCall2979fe02011-04-12 00:42:48 +000010784 if (S.getLangOptions().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000010785 !(isa<CXXMethodDecl>(VD) &&
10786 cast<CXXMethodDecl>(VD)->isInstance()))
10787 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000010788
Richard Trieu10162ab2011-09-09 03:59:41 +000010789 return E;
John McCall2979fe02011-04-12 00:42:48 +000010790 }
10791
Richard Trieu10162ab2011-09-09 03:59:41 +000010792 ExprResult VisitMemberExpr(MemberExpr *E) {
10793 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010794 }
10795
Richard Trieu10162ab2011-09-09 03:59:41 +000010796 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10797 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000010798 }
10799 };
10800}
10801
10802/// Given a function expression of unknown-any type, try to rebuild it
10803/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010804static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
10805 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
10806 if (Result.isInvalid()) return ExprError();
10807 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000010808}
10809
10810namespace {
John McCall2d2e8702011-04-11 07:02:50 +000010811 /// A visitor for rebuilding an expression of type __unknown_anytype
10812 /// into one which resolves the type directly on the referring
10813 /// expression. Strict preservation of the original source
10814 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000010815 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000010816 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000010817
10818 Sema &S;
10819
10820 /// The current destination type.
10821 QualType DestType;
10822
Richard Trieu10162ab2011-09-09 03:59:41 +000010823 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
10824 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000010825
John McCall39439732011-04-09 22:50:59 +000010826 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000010827 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000010828 }
10829
Richard Trieu10162ab2011-09-09 03:59:41 +000010830 ExprResult VisitExpr(Expr *E) {
10831 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
10832 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000010833 return ExprError();
John McCall31996342011-04-07 08:22:57 +000010834 }
10835
Richard Trieu10162ab2011-09-09 03:59:41 +000010836 ExprResult VisitCallExpr(CallExpr *E);
10837 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000010838
John McCall39439732011-04-09 22:50:59 +000010839 /// Rebuild an expression which simply semantically wraps another
10840 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000010841 template <class T> ExprResult rebuildSugarExpr(T *E) {
10842 ExprResult SubResult = Visit(E->getSubExpr());
10843 if (SubResult.isInvalid()) return ExprError();
10844 Expr *SubExpr = SubResult.take();
10845 E->setSubExpr(SubExpr);
10846 E->setType(SubExpr->getType());
10847 E->setValueKind(SubExpr->getValueKind());
10848 assert(E->getObjectKind() == OK_Ordinary);
10849 return E;
John McCall39439732011-04-09 22:50:59 +000010850 }
John McCall31996342011-04-07 08:22:57 +000010851
Richard Trieu10162ab2011-09-09 03:59:41 +000010852 ExprResult VisitParenExpr(ParenExpr *E) {
10853 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010854 }
10855
Richard Trieu10162ab2011-09-09 03:59:41 +000010856 ExprResult VisitUnaryExtension(UnaryOperator *E) {
10857 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000010858 }
10859
Richard Trieu10162ab2011-09-09 03:59:41 +000010860 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
10861 const PointerType *Ptr = DestType->getAs<PointerType>();
10862 if (!Ptr) {
10863 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
10864 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000010865 return ExprError();
10866 }
Richard Trieu10162ab2011-09-09 03:59:41 +000010867 assert(E->getValueKind() == VK_RValue);
10868 assert(E->getObjectKind() == OK_Ordinary);
10869 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000010870
10871 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010872 DestType = Ptr->getPointeeType();
10873 ExprResult SubResult = Visit(E->getSubExpr());
10874 if (SubResult.isInvalid()) return ExprError();
10875 E->setSubExpr(SubResult.take());
10876 return E;
John McCall2979fe02011-04-12 00:42:48 +000010877 }
10878
Richard Trieu10162ab2011-09-09 03:59:41 +000010879 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000010880
Richard Trieu10162ab2011-09-09 03:59:41 +000010881 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000010882
Richard Trieu10162ab2011-09-09 03:59:41 +000010883 ExprResult VisitMemberExpr(MemberExpr *E) {
10884 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000010885 }
John McCall39439732011-04-09 22:50:59 +000010886
Richard Trieu10162ab2011-09-09 03:59:41 +000010887 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
10888 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000010889 }
10890 };
10891}
10892
John McCall2d2e8702011-04-11 07:02:50 +000010893/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000010894ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
10895 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000010896
10897 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000010898 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000010899 FK_FunctionPointer,
10900 FK_BlockPointer
10901 };
10902
Richard Trieu10162ab2011-09-09 03:59:41 +000010903 FnKind Kind;
10904 QualType CalleeType = CalleeExpr->getType();
10905 if (CalleeType == S.Context.BoundMemberTy) {
10906 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
10907 Kind = FK_MemberFunction;
10908 CalleeType = Expr::findBoundMemberType(CalleeExpr);
10909 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
10910 CalleeType = Ptr->getPointeeType();
10911 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000010912 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000010913 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
10914 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000010915 }
Richard Trieu10162ab2011-09-09 03:59:41 +000010916 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000010917
10918 // Verify that this is a legal result type of a function.
10919 if (DestType->isArrayType() || DestType->isFunctionType()) {
10920 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000010921 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000010922 diagID = diag::err_block_returning_array_function;
10923
Richard Trieu10162ab2011-09-09 03:59:41 +000010924 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000010925 << DestType->isFunctionType() << DestType;
10926 return ExprError();
10927 }
10928
10929 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000010930 E->setType(DestType.getNonLValueExprType(S.Context));
10931 E->setValueKind(Expr::getValueKindForType(DestType));
10932 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000010933
10934 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000010935 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000010936 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000010937 Proto->arg_type_begin(),
10938 Proto->getNumArgs(),
10939 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000010940 else
10941 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000010942 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000010943
10944 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000010945 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000010946 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000010947 // Nothing to do.
10948 break;
10949
10950 case FK_FunctionPointer:
10951 DestType = S.Context.getPointerType(DestType);
10952 break;
10953
10954 case FK_BlockPointer:
10955 DestType = S.Context.getBlockPointerType(DestType);
10956 break;
10957 }
10958
10959 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000010960 ExprResult CalleeResult = Visit(CalleeExpr);
10961 if (!CalleeResult.isUsable()) return ExprError();
10962 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000010963
10964 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000010965 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010966}
10967
Richard Trieu10162ab2011-09-09 03:59:41 +000010968ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010969 // Verify that this is a legal result type of a call.
10970 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000010971 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000010972 << DestType->isFunctionType() << DestType;
10973 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000010974 }
10975
John McCall3f4138c2011-07-13 17:56:40 +000010976 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000010977 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
10978 assert(Method->getResultType() == S.Context.UnknownAnyTy);
10979 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000010980 }
John McCall2979fe02011-04-12 00:42:48 +000010981
John McCall2d2e8702011-04-11 07:02:50 +000010982 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000010983 E->setType(DestType.getNonReferenceType());
10984 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000010985
Richard Trieu10162ab2011-09-09 03:59:41 +000010986 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000010987}
10988
Richard Trieu10162ab2011-09-09 03:59:41 +000010989ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000010990 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000010991 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000010992 assert(E->getValueKind() == VK_RValue);
10993 assert(E->getObjectKind() == OK_Ordinary);
10994
10995 E->setType(DestType);
10996
10997 // Rebuild the sub-expression as the pointee (function) type.
10998 DestType = DestType->castAs<PointerType>()->getPointeeType();
10999
11000 ExprResult Result = Visit(E->getSubExpr());
11001 if (!Result.isUsable()) return ExprError();
11002
11003 E->setSubExpr(Result.take());
11004 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011005 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011006 assert(E->getValueKind() == VK_RValue);
11007 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011008
Sean Callanan12495112012-03-06 21:34:12 +000011009 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011010
Sean Callanan12495112012-03-06 21:34:12 +000011011 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011012
Sean Callanan12495112012-03-06 21:34:12 +000011013 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11014 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011015
Sean Callanan12495112012-03-06 21:34:12 +000011016 ExprResult Result = Visit(E->getSubExpr());
11017 if (!Result.isUsable()) return ExprError();
11018
11019 E->setSubExpr(Result.take());
11020 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011021 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011022 llvm_unreachable("Unhandled cast type!");
11023 }
John McCall2d2e8702011-04-11 07:02:50 +000011024}
11025
Richard Trieu10162ab2011-09-09 03:59:41 +000011026ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11027 ExprValueKind ValueKind = VK_LValue;
11028 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011029
11030 // We know how to make this work for certain kinds of decls:
11031
11032 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011033 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11034 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11035 DestType = Ptr->getPointeeType();
11036 ExprResult Result = resolveDecl(E, VD);
11037 if (Result.isInvalid()) return ExprError();
11038 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011039 CK_FunctionToPointerDecay, VK_RValue);
11040 }
11041
Richard Trieu10162ab2011-09-09 03:59:41 +000011042 if (!Type->isFunctionType()) {
11043 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11044 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011045 return ExprError();
11046 }
John McCall2d2e8702011-04-11 07:02:50 +000011047
Richard Trieu10162ab2011-09-09 03:59:41 +000011048 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11049 if (MD->isInstance()) {
11050 ValueKind = VK_RValue;
11051 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011052 }
11053
John McCall2d2e8702011-04-11 07:02:50 +000011054 // Function references aren't l-values in C.
11055 if (!S.getLangOptions().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011056 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011057
11058 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011059 } else if (isa<VarDecl>(VD)) {
11060 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11061 Type = RefTy->getPointeeType();
11062 } else if (Type->isFunctionType()) {
11063 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11064 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011065 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011066 }
11067
11068 // - nothing else
11069 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011070 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11071 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011072 return ExprError();
11073 }
11074
Richard Trieu10162ab2011-09-09 03:59:41 +000011075 VD->setType(DestType);
11076 E->setType(Type);
11077 E->setValueKind(ValueKind);
11078 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011079}
11080
John McCall31996342011-04-07 08:22:57 +000011081/// Check a cast of an unknown-any type. We intentionally only
11082/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011083ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11084 Expr *CastExpr, CastKind &CastKind,
11085 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011086 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011087 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011088 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011089
Richard Trieuba63ce62011-09-09 01:45:06 +000011090 CastExpr = result.take();
11091 VK = CastExpr->getValueKind();
11092 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011093
Richard Trieuba63ce62011-09-09 01:45:06 +000011094 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011095}
11096
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011097ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11098 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11099}
11100
Richard Trieuba63ce62011-09-09 01:45:06 +000011101static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11102 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011103 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011104 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011105 E = E->IgnoreParenImpCasts();
11106 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11107 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011108 diagID = diag::err_uncasted_call_of_unknown_any;
11109 } else {
John McCall31996342011-04-07 08:22:57 +000011110 break;
John McCall2d2e8702011-04-11 07:02:50 +000011111 }
John McCall31996342011-04-07 08:22:57 +000011112 }
11113
John McCall2d2e8702011-04-11 07:02:50 +000011114 SourceLocation loc;
11115 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011116 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011117 loc = ref->getLocation();
11118 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011119 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011120 loc = mem->getMemberLoc();
11121 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011122 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011123 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011124 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011125 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011126 if (!d) {
11127 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11128 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11129 << orig->getSourceRange();
11130 return ExprError();
11131 }
John McCall2d2e8702011-04-11 07:02:50 +000011132 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011133 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11134 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011135 return ExprError();
11136 }
11137
11138 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011139
11140 // Never recoverable.
11141 return ExprError();
11142}
11143
John McCall36e7fe32010-10-12 00:20:44 +000011144/// Check for operands with placeholder types and complain if found.
11145/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011146ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011147 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11148 if (!placeholderType) return Owned(E);
11149
11150 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011151
John McCall31996342011-04-07 08:22:57 +000011152 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011153 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011154 // Try to resolve a single function template specialization.
11155 // This is obligatory.
11156 ExprResult result = Owned(E);
11157 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11158 return result;
11159
11160 // If that failed, try to recover with a call.
11161 } else {
11162 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11163 /*complain*/ true);
11164 return result;
11165 }
11166 }
John McCall31996342011-04-07 08:22:57 +000011167
John McCall0009fcc2011-04-26 20:42:42 +000011168 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011169 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011170 ExprResult result = Owned(E);
11171 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11172 /*complain*/ true);
11173 return result;
John McCall4124c492011-10-17 18:40:02 +000011174 }
11175
11176 // ARC unbridged casts.
11177 case BuiltinType::ARCUnbridgedCast: {
11178 Expr *realCast = stripARCUnbridgedCast(E);
11179 diagnoseARCUnbridgedCast(realCast);
11180 return Owned(realCast);
11181 }
John McCall0009fcc2011-04-26 20:42:42 +000011182
John McCall31996342011-04-07 08:22:57 +000011183 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011184 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011185 return diagnoseUnknownAnyExpr(*this, E);
11186
John McCall526ab472011-10-25 17:37:35 +000011187 // Pseudo-objects.
11188 case BuiltinType::PseudoObject:
11189 return checkPseudoObjectRValue(E);
11190
John McCalle314e272011-10-18 21:02:43 +000011191 // Everything else should be impossible.
11192#define BUILTIN_TYPE(Id, SingletonId) \
11193 case BuiltinType::Id:
11194#define PLACEHOLDER_TYPE(Id, SingletonId)
11195#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011196 break;
11197 }
11198
11199 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011200}
Richard Trieu2c850c02011-04-21 21:44:26 +000011201
Richard Trieuba63ce62011-09-09 01:45:06 +000011202bool Sema::CheckCaseExpression(Expr *E) {
11203 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011204 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011205 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11206 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011207 return false;
11208}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011209
11210/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11211ExprResult
11212Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11213 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11214 "Unknown Objective-C Boolean value!");
11215 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
11216 Context.ObjCBuiltinBoolTy, OpLoc));
11217}