blob: d9950949ea85d9303892ccf044b21a6621fc53da [file] [log] [blame]
Chris Lattner5b183d82006-11-10 05:03:26 +00001//===--- SemaExpr.cpp - Semantic Analysis for Expressions -----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner5b183d82006-11-10 05:03:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Eli Friedmanfbc0dff2012-01-18 01:05:54 +000018#include "clang/Sema/ScopeInfo.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000019#include "clang/Sema/AnalysisBasedWarnings.h"
Chris Lattnercb6a3822006-11-10 06:20:45 +000020#include "clang/AST/ASTContext.h"
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000021#include "clang/AST/ASTConsumer.h"
Sebastian Redl2ac2c722011-04-29 08:19:30 +000022#include "clang/AST/ASTMutationListener.h"
Douglas Gregord1702062010-04-29 00:18:15 +000023#include "clang/AST/CXXInheritance.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000024#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000025#include "clang/AST/DeclTemplate.h"
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000026#include "clang/AST/EvaluatedExprVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000027#include "clang/AST/Expr.h"
Chris Lattneraa9c7ae2008-04-08 04:40:51 +000028#include "clang/AST/ExprCXX.h"
Steve Naroff021ca182008-05-29 21:12:08 +000029#include "clang/AST/ExprObjC.h"
Douglas Gregor5597ab42010-05-07 23:12:07 +000030#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000031#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000032#include "clang/Basic/PartialDiagnostic.h"
Steve Narofff2fb89e2007-03-13 20:29:44 +000033#include "clang/Basic/SourceManager.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000034#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000035#include "clang/Lex/LiteralSupport.h"
36#include "clang/Lex/Preprocessor.h"
John McCall8b0666c2010-08-20 18:27:03 +000037#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/Designator.h"
39#include "clang/Sema/Scope.h"
John McCallaab3e412010-08-25 08:40:02 +000040#include "clang/Sema/ScopeInfo.h"
John McCall8b0666c2010-08-20 18:27:03 +000041#include "clang/Sema/ParsedTemplate.h"
Anna Zaks3b402712011-07-28 19:51:27 +000042#include "clang/Sema/SemaFixItUtils.h"
John McCallde6836a2010-08-24 07:21:54 +000043#include "clang/Sema/Template.h"
Eli Friedman456f0182012-01-20 01:26:23 +000044#include "TreeTransform.h"
Chris Lattner5b183d82006-11-10 05:03:26 +000045using namespace clang;
John McCallaab3e412010-08-25 08:40:02 +000046using namespace sema;
Chris Lattner5b183d82006-11-10 05:03:26 +000047
Sebastian Redlb49c46c2011-09-24 17:48:00 +000048/// \brief Determine whether the use of this declaration is valid, without
49/// emitting diagnostics.
50bool Sema::CanUseDecl(NamedDecl *D) {
51 // See if this is an auto-typed variable whose initializer we are parsing.
52 if (ParsingInitForAutoVars.count(D))
53 return false;
54
55 // See if this is a deleted function.
56 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
57 if (FD->isDeleted())
58 return false;
59 }
Sebastian Redl5999aec2011-10-16 18:19:16 +000060
61 // See if this function is unavailable.
62 if (D->getAvailability() == AR_Unavailable &&
63 cast<Decl>(CurContext)->getAvailability() != AR_Unavailable)
64 return false;
65
Sebastian Redlb49c46c2011-09-24 17:48:00 +000066 return true;
67}
David Chisnall9f57c292009-08-17 16:35:33 +000068
Ted Kremenek6eb25622012-02-10 02:45:47 +000069static AvailabilityResult DiagnoseAvailabilityOfDecl(Sema &S,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000070 NamedDecl *D, SourceLocation Loc,
71 const ObjCInterfaceDecl *UnknownObjCClass) {
72 // See if this declaration is unavailable or deprecated.
73 std::string Message;
74 AvailabilityResult Result = D->getAvailability(&Message);
Fariborz Jahanian25d09c22011-11-28 19:45:58 +000075 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
76 if (Result == AR_Available) {
77 const DeclContext *DC = ECD->getDeclContext();
78 if (const EnumDecl *TheEnumDecl = dyn_cast<EnumDecl>(DC))
79 Result = TheEnumDecl->getAvailability(&Message);
80 }
81
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000082 switch (Result) {
83 case AR_Available:
84 case AR_NotYetIntroduced:
85 break;
86
87 case AR_Deprecated:
Ted Kremenek6eb25622012-02-10 02:45:47 +000088 S.EmitDeprecationWarning(D, Message, Loc, UnknownObjCClass);
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000089 break;
90
91 case AR_Unavailable:
Ted Kremenek6eb25622012-02-10 02:45:47 +000092 if (S.getCurContextAvailability() != AR_Unavailable) {
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000093 if (Message.empty()) {
94 if (!UnknownObjCClass)
Ted Kremenek6eb25622012-02-10 02:45:47 +000095 S.Diag(Loc, diag::err_unavailable) << D->getDeclName();
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000096 else
Ted Kremenek6eb25622012-02-10 02:45:47 +000097 S.Diag(Loc, diag::warn_unavailable_fwdclass_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +000098 << D->getDeclName();
99 }
100 else
Ted Kremenek6eb25622012-02-10 02:45:47 +0000101 S.Diag(Loc, diag::err_unavailable_message)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000102 << D->getDeclName() << Message;
Ted Kremenek6eb25622012-02-10 02:45:47 +0000103 S.Diag(D->getLocation(), diag::note_unavailable_here)
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000104 << isa<FunctionDecl>(D) << false;
105 }
106 break;
107 }
108 return Result;
109}
110
Richard Smith852265f2012-03-30 20:53:28 +0000111/// \brief Emit a note explaining that this function is deleted or unavailable.
112void Sema::NoteDeletedFunction(FunctionDecl *Decl) {
113 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Decl);
114
Richard Smith6f1e2c62012-04-02 20:59:25 +0000115 if (Method && Method->isDeleted() && !Method->isDeletedAsWritten()) {
116 // If the method was explicitly defaulted, point at that declaration.
117 if (!Method->isImplicit())
118 Diag(Decl->getLocation(), diag::note_implicitly_deleted);
119
120 // Try to diagnose why this special member function was implicitly
121 // deleted. This might fail, if that reason no longer applies.
Richard Smith852265f2012-03-30 20:53:28 +0000122 CXXSpecialMember CSM = getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +0000123 if (CSM != CXXInvalid)
124 ShouldDeleteSpecialMember(Method, CSM, /*Diagnose=*/true);
125
126 return;
Richard Smith852265f2012-03-30 20:53:28 +0000127 }
128
129 Diag(Decl->getLocation(), diag::note_unavailable_here)
130 << 1 << Decl->isDeleted();
131}
132
Douglas Gregor171c45a2009-02-18 21:56:37 +0000133/// \brief Determine whether the use of this declaration is valid, and
134/// emit any corresponding diagnostics.
135///
136/// This routine diagnoses various problems with referencing
137/// declarations that can occur when using a declaration. For example,
138/// it might warn if a deprecated or unavailable declaration is being
139/// used, or produce an error (and return true) if a C++0x deleted
140/// function is being used.
141///
142/// \returns true if there was an error (this declaration cannot be
143/// referenced), false otherwise.
Chris Lattnerb7df3c62009-10-25 22:31:57 +0000144///
Fariborz Jahanian7d6e11a2010-12-21 00:44:01 +0000145bool Sema::DiagnoseUseOfDecl(NamedDecl *D, SourceLocation Loc,
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000146 const ObjCInterfaceDecl *UnknownObjCClass) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000147 if (getLangOpts().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000148 // If there were any diagnostics suppressed by template argument deduction,
149 // emit them now.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000150 llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> >::iterator
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000151 Pos = SuppressedDiagnostics.find(D->getCanonicalDecl());
152 if (Pos != SuppressedDiagnostics.end()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000153 SmallVectorImpl<PartialDiagnosticAt> &Suppressed = Pos->second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000154 for (unsigned I = 0, N = Suppressed.size(); I != N; ++I)
155 Diag(Suppressed[I].first, Suppressed[I].second);
156
157 // Clear out the list of suppressed diagnostics, so that we don't emit
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000158 // them again for this specialization. However, we don't obsolete this
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +0000159 // entry from the table, because we want to avoid ever emitting these
160 // diagnostics again.
161 Suppressed.clear();
162 }
163 }
164
Richard Smith30482bc2011-02-20 03:19:35 +0000165 // See if this is an auto-typed variable whose initializer we are parsing.
Richard Smithb2bc2e62011-02-21 20:05:19 +0000166 if (ParsingInitForAutoVars.count(D)) {
167 Diag(Loc, diag::err_auto_variable_cannot_appear_in_own_initializer)
168 << D->getDeclName();
169 return true;
Richard Smith30482bc2011-02-20 03:19:35 +0000170 }
171
Douglas Gregor171c45a2009-02-18 21:56:37 +0000172 // See if this is a deleted function.
Douglas Gregorde681d42009-02-24 04:26:15 +0000173 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor171c45a2009-02-18 21:56:37 +0000174 if (FD->isDeleted()) {
175 Diag(Loc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +0000176 NoteDeletedFunction(FD);
Douglas Gregor171c45a2009-02-18 21:56:37 +0000177 return true;
178 }
Douglas Gregorde681d42009-02-24 04:26:15 +0000179 }
Ted Kremenek6eb25622012-02-10 02:45:47 +0000180 DiagnoseAvailabilityOfDecl(*this, D, Loc, UnknownObjCClass);
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000181
Anders Carlsson73067a02010-10-22 23:37:08 +0000182 // Warn if this is used but marked unused.
Fariborz Jahanian6b854c52011-09-29 22:45:21 +0000183 if (D->hasAttr<UnusedAttr>())
Anders Carlsson73067a02010-10-22 23:37:08 +0000184 Diag(Loc, diag::warn_used_but_marked_unused) << D->getDeclName();
Jordan Rose2684c682012-06-15 18:19:48 +0000185
186 // Warn if we're in an extern inline function referring to a decl
187 // with internal linkage. (C99 6.7.4p3)
188 // FIXME: This is not explicitly forbidden in C++, but it's not clear
189 // what the correct behavior is. We should probably still have a warning.
190 // (However, in C++ const variables have internal linkage by default, while
191 // functions still have external linkage by default, so this warning becomes
192 // very noisy.)
193 if (!getLangOpts().CPlusPlus) {
194 if (FunctionDecl *Current = getCurFunctionDecl()) {
195 if (Current->isInlined() && Current->getLinkage() > InternalLinkage) {
196 if (D->getLinkage() == InternalLinkage) {
Jordan Roseedff0202012-06-18 17:49:58 +0000197 // We won't warn by default if the inline function is in the main
198 // source file; in these cases it is almost certain that the inlining
199 // will only occur in this file, even if there is an external
200 // declaration as well.
201 bool IsFromMainFile = getSourceManager().isFromMainFile(Loc);
202 Diag(Loc, IsFromMainFile ? diag::ext_internal_in_extern_inline
203 : diag::warn_internal_in_extern_inline)
Jordan Rose2684c682012-06-15 18:19:48 +0000204 << !isa<FunctionDecl>(D) << D << isa<CXXMethodDecl>(Current);
205
206 // If the user didn't explicitly specify a storage class,
207 // suggest adding "static" to fix the problem.
208 const FunctionDecl *FirstDecl = Current->getCanonicalDecl();
209 if (FirstDecl->getStorageClassAsWritten() == SC_None) {
210 SourceLocation DeclBegin = FirstDecl->getSourceRange().getBegin();
211 Diag(DeclBegin, diag::note_convert_inline_to_static)
212 << Current << FixItHint::CreateInsertion(DeclBegin, "static ");
213 }
214
215 Diag(D->getCanonicalDecl()->getLocation(),
216 diag::note_internal_decl_declared_here)
217 << D;
218 }
219 }
220 }
221 }
222
Douglas Gregor171c45a2009-02-18 21:56:37 +0000223 return false;
Chris Lattner4bf74fd2009-02-15 22:43:40 +0000224}
225
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000226/// \brief Retrieve the message suffix that should be added to a
227/// diagnostic complaining about the given function being deleted or
228/// unavailable.
229std::string Sema::getDeletedOrUnavailableSuffix(const FunctionDecl *FD) {
230 // FIXME: C++0x implicitly-deleted special member functions could be
231 // detected here so that we could improve diagnostics to say, e.g.,
232 // "base class 'A' had a deleted copy constructor".
233 if (FD->isDeleted())
234 return std::string();
235
236 std::string Message;
237 if (FD->getAvailability(&Message))
238 return ": " + Message;
239
240 return std::string();
241}
242
John McCallb46f2872011-09-09 07:56:05 +0000243/// DiagnoseSentinelCalls - This routine checks whether a call or
244/// message-send is to a declaration with the sentinel attribute, and
245/// if so, it checks that the requirements of the sentinel are
246/// satisfied.
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000247void Sema::DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc,
John McCallb46f2872011-09-09 07:56:05 +0000248 Expr **args, unsigned numArgs) {
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +0000249 const SentinelAttr *attr = D->getAttr<SentinelAttr>();
Mike Stump11289f42009-09-09 15:08:12 +0000250 if (!attr)
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000251 return;
Douglas Gregorc298ffc2010-04-22 16:44:27 +0000252
John McCallb46f2872011-09-09 07:56:05 +0000253 // The number of formal parameters of the declaration.
254 unsigned numFormalParams;
Mike Stump11289f42009-09-09 15:08:12 +0000255
John McCallb46f2872011-09-09 07:56:05 +0000256 // The kind of declaration. This is also an index into a %select in
257 // the diagnostic.
258 enum CalleeType { CT_Function, CT_Method, CT_Block } calleeType;
259
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000260 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000261 numFormalParams = MD->param_size();
262 calleeType = CT_Method;
Mike Stump12b8ce12009-08-04 21:02:39 +0000263 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
John McCallb46f2872011-09-09 07:56:05 +0000264 numFormalParams = FD->param_size();
265 calleeType = CT_Function;
266 } else if (isa<VarDecl>(D)) {
267 QualType type = cast<ValueDecl>(D)->getType();
268 const FunctionType *fn = 0;
269 if (const PointerType *ptr = type->getAs<PointerType>()) {
270 fn = ptr->getPointeeType()->getAs<FunctionType>();
271 if (!fn) return;
272 calleeType = CT_Function;
273 } else if (const BlockPointerType *ptr = type->getAs<BlockPointerType>()) {
274 fn = ptr->getPointeeType()->castAs<FunctionType>();
275 calleeType = CT_Block;
276 } else {
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +0000277 return;
John McCallb46f2872011-09-09 07:56:05 +0000278 }
Fariborz Jahanian4a528032009-05-14 18:00:00 +0000279
John McCallb46f2872011-09-09 07:56:05 +0000280 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fn)) {
281 numFormalParams = proto->getNumArgs();
282 } else {
283 numFormalParams = 0;
284 }
285 } else {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000286 return;
287 }
John McCallb46f2872011-09-09 07:56:05 +0000288
289 // "nullPos" is the number of formal parameters at the end which
290 // effectively count as part of the variadic arguments. This is
291 // useful if you would prefer to not have *any* formal parameters,
292 // but the language forces you to have at least one.
293 unsigned nullPos = attr->getNullPos();
294 assert((nullPos == 0 || nullPos == 1) && "invalid null position on sentinel");
295 numFormalParams = (nullPos > numFormalParams ? 0 : numFormalParams - nullPos);
296
297 // The number of arguments which should follow the sentinel.
298 unsigned numArgsAfterSentinel = attr->getSentinel();
299
300 // If there aren't enough arguments for all the formal parameters,
301 // the sentinel, and the args after the sentinel, complain.
302 if (numArgs < numFormalParams + numArgsAfterSentinel + 1) {
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000303 Diag(Loc, diag::warn_not_enough_argument) << D->getDeclName();
John McCallb46f2872011-09-09 07:56:05 +0000304 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian9e877212009-05-13 23:20:50 +0000305 return;
306 }
John McCallb46f2872011-09-09 07:56:05 +0000307
308 // Otherwise, find the sentinel expression.
309 Expr *sentinelExpr = args[numArgs - numArgsAfterSentinel - 1];
John McCall7ddbcf42010-05-06 23:53:00 +0000310 if (!sentinelExpr) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000311 if (sentinelExpr->isValueDependent()) return;
Argyrios Kyrtzidis2e809ce2012-02-03 05:58:16 +0000312 if (Context.isSentinelNullExpr(sentinelExpr)) return;
John McCall7ddbcf42010-05-06 23:53:00 +0000313
John McCallb46f2872011-09-09 07:56:05 +0000314 // Pick a reasonable string to insert. Optimistically use 'nil' or
315 // 'NULL' if those are actually defined in the context. Only use
316 // 'nil' for ObjC methods, where it's much more likely that the
317 // variadic arguments form a list of object pointers.
318 SourceLocation MissingNilLoc
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000319 = PP.getLocForEndOfToken(sentinelExpr->getLocEnd());
320 std::string NullValue;
John McCallb46f2872011-09-09 07:56:05 +0000321 if (calleeType == CT_Method &&
322 PP.getIdentifierInfo("nil")->hasMacroDefinition())
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000323 NullValue = "nil";
324 else if (PP.getIdentifierInfo("NULL")->hasMacroDefinition())
325 NullValue = "NULL";
Douglas Gregor5ff4e982011-07-30 08:57:03 +0000326 else
John McCallb46f2872011-09-09 07:56:05 +0000327 NullValue = "(void*) 0";
Eli Friedman9ab36372011-09-27 23:46:37 +0000328
329 if (MissingNilLoc.isInvalid())
330 Diag(Loc, diag::warn_missing_sentinel) << calleeType;
331 else
332 Diag(MissingNilLoc, diag::warn_missing_sentinel)
333 << calleeType
334 << FixItHint::CreateInsertion(MissingNilLoc, ", " + NullValue);
John McCallb46f2872011-09-09 07:56:05 +0000335 Diag(D->getLocation(), diag::note_sentinel_here) << calleeType;
Fariborz Jahanian027b8862009-05-13 18:09:35 +0000336}
337
Richard Trieuba63ce62011-09-09 01:45:06 +0000338SourceRange Sema::getExprRange(Expr *E) const {
339 return E ? E->getSourceRange() : SourceRange();
Douglas Gregor87f95b02009-02-26 21:00:50 +0000340}
341
Chris Lattner513165e2008-07-25 21:10:04 +0000342//===----------------------------------------------------------------------===//
343// Standard Promotions and Conversions
344//===----------------------------------------------------------------------===//
345
Chris Lattner513165e2008-07-25 21:10:04 +0000346/// DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
John Wiegley01296292011-04-08 18:41:53 +0000347ExprResult Sema::DefaultFunctionArrayConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000348 // Handle any placeholder expressions which made it here.
349 if (E->getType()->isPlaceholderType()) {
350 ExprResult result = CheckPlaceholderExpr(E);
351 if (result.isInvalid()) return ExprError();
352 E = result.take();
353 }
354
Chris Lattner513165e2008-07-25 21:10:04 +0000355 QualType Ty = E->getType();
356 assert(!Ty.isNull() && "DefaultFunctionArrayConversion - missing type");
357
Chris Lattner513165e2008-07-25 21:10:04 +0000358 if (Ty->isFunctionType())
John Wiegley01296292011-04-08 18:41:53 +0000359 E = ImpCastExprToType(E, Context.getPointerType(Ty),
360 CK_FunctionToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000361 else if (Ty->isArrayType()) {
362 // In C90 mode, arrays only promote to pointers if the array expression is
363 // an lvalue. The relevant legalese is C90 6.2.2.1p3: "an lvalue that has
364 // type 'array of type' is converted to an expression that has type 'pointer
365 // to type'...". In C99 this was changed to: C99 6.3.2.1p3: "an expression
366 // that has type 'array of type' ...". The relevant change is "an lvalue"
367 // (C90) to "an expression" (C99).
Argyrios Kyrtzidis9321c742008-09-11 04:25:59 +0000368 //
369 // C++ 4.2p1:
370 // An lvalue or rvalue of type "array of N T" or "array of unknown bound of
371 // T" can be converted to an rvalue of type "pointer to T".
372 //
David Blaikiebbafb8a2012-03-11 07:00:24 +0000373 if (getLangOpts().C99 || getLangOpts().CPlusPlus || E->isLValue())
John Wiegley01296292011-04-08 18:41:53 +0000374 E = ImpCastExprToType(E, Context.getArrayDecayedType(Ty),
375 CK_ArrayToPointerDecay).take();
Chris Lattner61f60a02008-07-25 21:33:13 +0000376 }
John Wiegley01296292011-04-08 18:41:53 +0000377 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000378}
379
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000380static void CheckForNullPointerDereference(Sema &S, Expr *E) {
381 // Check to see if we are dereferencing a null pointer. If so,
382 // and if not volatile-qualified, this is undefined behavior that the
383 // optimizer will delete, so warn about it. People sometimes try to use this
384 // to get a deterministic trap and are surprised by clang's behavior. This
385 // only handles the pattern "*null", which is a very syntactic check.
386 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParenCasts()))
387 if (UO->getOpcode() == UO_Deref &&
388 UO->getSubExpr()->IgnoreParenCasts()->
389 isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull) &&
390 !UO->getType().isVolatileQualified()) {
391 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
392 S.PDiag(diag::warn_indirection_through_null)
393 << UO->getSubExpr()->getSourceRange());
394 S.DiagRuntimeBehavior(UO->getOperatorLoc(), UO,
395 S.PDiag(diag::note_indirection_through_null));
396 }
397}
398
John Wiegley01296292011-04-08 18:41:53 +0000399ExprResult Sema::DefaultLvalueConversion(Expr *E) {
John McCall50a2c2c2011-10-11 23:14:30 +0000400 // Handle any placeholder expressions which made it here.
401 if (E->getType()->isPlaceholderType()) {
402 ExprResult result = CheckPlaceholderExpr(E);
403 if (result.isInvalid()) return ExprError();
404 E = result.take();
405 }
406
John McCallf3735e02010-12-01 04:43:34 +0000407 // C++ [conv.lval]p1:
408 // A glvalue of a non-function, non-array type T can be
409 // converted to a prvalue.
John Wiegley01296292011-04-08 18:41:53 +0000410 if (!E->isGLValue()) return Owned(E);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +0000411
John McCall27584242010-12-06 20:48:59 +0000412 QualType T = E->getType();
413 assert(!T.isNull() && "r-value conversion on typeless expression?");
John McCall34376a62010-12-04 03:47:34 +0000414
John McCall27584242010-12-06 20:48:59 +0000415 // We don't want to throw lvalue-to-rvalue casts on top of
416 // expressions of certain types in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000417 if (getLangOpts().CPlusPlus &&
John McCall27584242010-12-06 20:48:59 +0000418 (E->getType() == Context.OverloadTy ||
419 T->isDependentType() ||
420 T->isRecordType()))
John Wiegley01296292011-04-08 18:41:53 +0000421 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000422
423 // The C standard is actually really unclear on this point, and
424 // DR106 tells us what the result should be but not why. It's
425 // generally best to say that void types just doesn't undergo
426 // lvalue-to-rvalue at all. Note that expressions of unqualified
427 // 'void' type are never l-values, but qualified void can be.
428 if (T->isVoidType())
John Wiegley01296292011-04-08 18:41:53 +0000429 return Owned(E);
John McCall27584242010-12-06 20:48:59 +0000430
Argyrios Kyrtzidisa9b630e2011-04-26 17:41:22 +0000431 CheckForNullPointerDereference(*this, E);
432
John McCall27584242010-12-06 20:48:59 +0000433 // C++ [conv.lval]p1:
434 // [...] If T is a non-class type, the type of the prvalue is the
435 // cv-unqualified version of T. Otherwise, the type of the
436 // rvalue is T.
437 //
438 // C99 6.3.2.1p2:
439 // If the lvalue has qualified type, the value has the unqualified
440 // version of the type of the lvalue; otherwise, the value has the
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000441 // type of the lvalue.
John McCall27584242010-12-06 20:48:59 +0000442 if (T.hasQualifiers())
443 T = T.getUnqualifiedType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000444
Eli Friedman3bda6b12012-02-02 23:15:15 +0000445 UpdateMarkingForLValueToRValue(E);
446
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000447 ExprResult Res = Owned(ImplicitCastExpr::Create(Context, T, CK_LValueToRValue,
448 E, 0, VK_RValue));
449
Douglas Gregorc79862f2012-04-12 17:51:55 +0000450 // C11 6.3.2.1p2:
451 // ... if the lvalue has atomic type, the value has the non-atomic version
452 // of the type of the lvalue ...
453 if (const AtomicType *Atomic = T->getAs<AtomicType>()) {
454 T = Atomic->getValueType().getUnqualifiedType();
455 Res = Owned(ImplicitCastExpr::Create(Context, T, CK_AtomicToNonAtomic,
456 Res.get(), 0, VK_RValue));
457 }
458
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000459 return Res;
John McCall27584242010-12-06 20:48:59 +0000460}
461
John Wiegley01296292011-04-08 18:41:53 +0000462ExprResult Sema::DefaultFunctionArrayLvalueConversion(Expr *E) {
463 ExprResult Res = DefaultFunctionArrayConversion(E);
464 if (Res.isInvalid())
465 return ExprError();
466 Res = DefaultLvalueConversion(Res.take());
467 if (Res.isInvalid())
468 return ExprError();
469 return move(Res);
Douglas Gregorb92a1562010-02-03 00:27:59 +0000470}
471
472
Chris Lattner513165e2008-07-25 21:10:04 +0000473/// UsualUnaryConversions - Performs various conversions that are common to most
Mike Stump11289f42009-09-09 15:08:12 +0000474/// operators (C99 6.3). The conversions of array and function types are
Chris Lattner57540c52011-04-15 05:22:18 +0000475/// sometimes suppressed. For example, the array->pointer conversion doesn't
Chris Lattner513165e2008-07-25 21:10:04 +0000476/// apply if the array is an argument to the sizeof or address (&) operators.
477/// In these instances, this routine should *not* be called.
John Wiegley01296292011-04-08 18:41:53 +0000478ExprResult Sema::UsualUnaryConversions(Expr *E) {
John McCallf3735e02010-12-01 04:43:34 +0000479 // First, convert to an r-value.
John Wiegley01296292011-04-08 18:41:53 +0000480 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
481 if (Res.isInvalid())
482 return Owned(E);
483 E = Res.take();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000484
John McCallf3735e02010-12-01 04:43:34 +0000485 QualType Ty = E->getType();
Chris Lattner513165e2008-07-25 21:10:04 +0000486 assert(!Ty.isNull() && "UsualUnaryConversions - missing type");
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000487
488 // Half FP is a bit different: it's a storage-only type, meaning that any
489 // "use" of it should be promoted to float.
490 if (Ty->isHalfType())
491 return ImpCastExprToType(Res.take(), Context.FloatTy, CK_FloatingCast);
492
John McCallf3735e02010-12-01 04:43:34 +0000493 // Try to perform integral promotions if the object has a theoretically
494 // promotable type.
495 if (Ty->isIntegralOrUnscopedEnumerationType()) {
496 // C99 6.3.1.1p2:
497 //
498 // The following may be used in an expression wherever an int or
499 // unsigned int may be used:
500 // - an object or expression with an integer type whose integer
501 // conversion rank is less than or equal to the rank of int
502 // and unsigned int.
503 // - A bit-field of type _Bool, int, signed int, or unsigned int.
504 //
505 // If an int can represent all values of the original type, the
506 // value is converted to an int; otherwise, it is converted to an
507 // unsigned int. These are called the integer promotions. All
508 // other types are unchanged by the integer promotions.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000509
John McCallf3735e02010-12-01 04:43:34 +0000510 QualType PTy = Context.isPromotableBitField(E);
511 if (!PTy.isNull()) {
John Wiegley01296292011-04-08 18:41:53 +0000512 E = ImpCastExprToType(E, PTy, CK_IntegralCast).take();
513 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000514 }
515 if (Ty->isPromotableIntegerType()) {
516 QualType PT = Context.getPromotedIntegerType(Ty);
John Wiegley01296292011-04-08 18:41:53 +0000517 E = ImpCastExprToType(E, PT, CK_IntegralCast).take();
518 return Owned(E);
John McCallf3735e02010-12-01 04:43:34 +0000519 }
Eli Friedman629ffb92009-08-20 04:21:42 +0000520 }
John Wiegley01296292011-04-08 18:41:53 +0000521 return Owned(E);
Chris Lattner513165e2008-07-25 21:10:04 +0000522}
523
Chris Lattner2ce500f2008-07-25 22:25:12 +0000524/// DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that
Mike Stump11289f42009-09-09 15:08:12 +0000525/// do not have a prototype. Arguments that have type float are promoted to
Chris Lattner2ce500f2008-07-25 22:25:12 +0000526/// double. All other argument types are converted by UsualUnaryConversions().
John Wiegley01296292011-04-08 18:41:53 +0000527ExprResult Sema::DefaultArgumentPromotion(Expr *E) {
528 QualType Ty = E->getType();
Chris Lattner2ce500f2008-07-25 22:25:12 +0000529 assert(!Ty.isNull() && "DefaultArgumentPromotion - missing type");
Mike Stump11289f42009-09-09 15:08:12 +0000530
John Wiegley01296292011-04-08 18:41:53 +0000531 ExprResult Res = UsualUnaryConversions(E);
532 if (Res.isInvalid())
533 return Owned(E);
534 E = Res.take();
John McCall9bc26772010-12-06 18:36:11 +0000535
Chris Lattner2ce500f2008-07-25 22:25:12 +0000536 // If this is a 'float' (CVR qualified or typedef) promote to double.
Chris Lattnerbb53efb2010-05-16 04:01:30 +0000537 if (Ty->isSpecificBuiltinType(BuiltinType::Float))
John Wiegley01296292011-04-08 18:41:53 +0000538 E = ImpCastExprToType(E, Context.DoubleTy, CK_FloatingCast).take();
539
John McCall4bb057d2011-08-27 22:06:17 +0000540 // C++ performs lvalue-to-rvalue conversion as a default argument
John McCall0562caa2011-08-29 23:55:37 +0000541 // promotion, even on class types, but note:
542 // C++11 [conv.lval]p2:
543 // When an lvalue-to-rvalue conversion occurs in an unevaluated
544 // operand or a subexpression thereof the value contained in the
545 // referenced object is not accessed. Otherwise, if the glvalue
546 // has a class type, the conversion copy-initializes a temporary
547 // of type T from the glvalue and the result of the conversion
548 // is a prvalue for the temporary.
Eli Friedman05e28012012-01-17 02:13:45 +0000549 // FIXME: add some way to gate this entire thing for correctness in
550 // potentially potentially evaluated contexts.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000551 if (getLangOpts().CPlusPlus && E->isGLValue() &&
Eli Friedman05e28012012-01-17 02:13:45 +0000552 ExprEvalContexts.back().Context != Unevaluated) {
553 ExprResult Temp = PerformCopyInitialization(
554 InitializedEntity::InitializeTemporary(E->getType()),
555 E->getExprLoc(),
556 Owned(E));
557 if (Temp.isInvalid())
558 return ExprError();
559 E = Temp.get();
John McCall29ad95b2011-08-27 01:09:30 +0000560 }
561
John Wiegley01296292011-04-08 18:41:53 +0000562 return Owned(E);
Chris Lattner2ce500f2008-07-25 22:25:12 +0000563}
564
Chris Lattnera8a7d0f2009-04-12 08:11:20 +0000565/// DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but
566/// will warn if the resulting type is not a POD type, and rejects ObjC
John Wiegley01296292011-04-08 18:41:53 +0000567/// interfaces passed by value.
568ExprResult Sema::DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT,
John McCall31168b02011-06-15 23:02:42 +0000569 FunctionDecl *FDecl) {
John McCall4124c492011-10-17 18:40:02 +0000570 if (const BuiltinType *PlaceholderTy = E->getType()->getAsPlaceholderType()) {
571 // Strip the unbridged-cast placeholder expression off, if applicable.
572 if (PlaceholderTy->getKind() == BuiltinType::ARCUnbridgedCast &&
573 (CT == VariadicMethod ||
574 (FDecl && FDecl->hasAttr<CFAuditedTransferAttr>()))) {
575 E = stripARCUnbridgedCast(E);
576
577 // Otherwise, do normal placeholder checking.
578 } else {
579 ExprResult ExprRes = CheckPlaceholderExpr(E);
580 if (ExprRes.isInvalid())
581 return ExprError();
582 E = ExprRes.take();
583 }
584 }
Douglas Gregorcbd446d2011-06-17 00:15:10 +0000585
John McCall4124c492011-10-17 18:40:02 +0000586 ExprResult ExprRes = DefaultArgumentPromotion(E);
John Wiegley01296292011-04-08 18:41:53 +0000587 if (ExprRes.isInvalid())
588 return ExprError();
589 E = ExprRes.take();
Mike Stump11289f42009-09-09 15:08:12 +0000590
Douglas Gregor347e0f22011-05-21 19:26:31 +0000591 // Don't allow one to pass an Objective-C interface to a vararg.
John Wiegley01296292011-04-08 18:41:53 +0000592 if (E->getType()->isObjCObjectType() &&
Douglas Gregor347e0f22011-05-21 19:26:31 +0000593 DiagRuntimeBehavior(E->getLocStart(), 0,
594 PDiag(diag::err_cannot_pass_objc_interface_to_vararg)
595 << E->getType() << CT))
John Wiegley01296292011-04-08 18:41:53 +0000596 return ExprError();
John McCall29ad95b2011-08-27 01:09:30 +0000597
Douglas Gregor7e1aa5b2011-10-14 20:34:19 +0000598 // Complain about passing non-POD types through varargs. However, don't
599 // perform this check for incomplete types, which we can get here when we're
600 // in an unevaluated context.
Benjamin Kramer6a0a2112012-04-28 10:00:42 +0000601 if (!E->getType()->isIncompleteType() &&
602 !E->getType().isCXX98PODType(Context)) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000603 // C++0x [expr.call]p7:
604 // Passing a potentially-evaluated argument of class type (Clause 9)
605 // having a non-trivial copy constructor, a non-trivial move constructor,
606 // or a non-trivial destructor, with no corresponding parameter,
607 // is conditionally-supported with implementation-defined semantics.
608 bool TrivialEnough = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +0000609 if (getLangOpts().CPlusPlus0x && !E->getType()->isDependentType()) {
Douglas Gregor253cadf2011-05-21 16:27:21 +0000610 if (CXXRecordDecl *Record = E->getType()->getAsCXXRecordDecl()) {
611 if (Record->hasTrivialCopyConstructor() &&
612 Record->hasTrivialMoveConstructor() &&
Richard Smith0bf8a4922011-10-18 20:49:44 +0000613 Record->hasTrivialDestructor()) {
614 DiagRuntimeBehavior(E->getLocStart(), 0,
615 PDiag(diag::warn_cxx98_compat_pass_non_pod_arg_to_vararg)
616 << E->getType() << CT);
Douglas Gregor253cadf2011-05-21 16:27:21 +0000617 TrivialEnough = true;
Richard Smith0bf8a4922011-10-18 20:49:44 +0000618 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000619 }
620 }
John McCall31168b02011-06-15 23:02:42 +0000621
622 if (!TrivialEnough &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000623 getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000624 E->getType()->isObjCLifetimeType())
625 TrivialEnough = true;
Douglas Gregor253cadf2011-05-21 16:27:21 +0000626
627 if (TrivialEnough) {
628 // Nothing to diagnose. This is okay.
629 } else if (DiagRuntimeBehavior(E->getLocStart(), 0,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +0000630 PDiag(diag::warn_cannot_pass_non_pod_arg_to_vararg)
David Blaikiebbafb8a2012-03-11 07:00:24 +0000631 << getLangOpts().CPlusPlus0x << E->getType()
Douglas Gregor347e0f22011-05-21 19:26:31 +0000632 << CT)) {
633 // Turn this into a trap.
634 CXXScopeSpec SS;
Abramo Bagnara7945c982012-01-27 09:46:47 +0000635 SourceLocation TemplateKWLoc;
Douglas Gregor347e0f22011-05-21 19:26:31 +0000636 UnqualifiedId Name;
637 Name.setIdentifier(PP.getIdentifierInfo("__builtin_trap"),
638 E->getLocStart());
Abramo Bagnara7945c982012-01-27 09:46:47 +0000639 ExprResult TrapFn = ActOnIdExpression(TUScope, SS, TemplateKWLoc, Name,
640 true, false);
Douglas Gregor347e0f22011-05-21 19:26:31 +0000641 if (TrapFn.isInvalid())
642 return ExprError();
643
644 ExprResult Call = ActOnCallExpr(TUScope, TrapFn.get(), E->getLocStart(),
645 MultiExprArg(), E->getLocEnd());
646 if (Call.isInvalid())
647 return ExprError();
648
649 ExprResult Comma = ActOnBinOp(TUScope, E->getLocStart(), tok::comma,
650 Call.get(), E);
651 if (Comma.isInvalid())
John McCall1cd60a22011-08-26 18:41:18 +0000652 return ExprError();
Douglas Gregor347e0f22011-05-21 19:26:31 +0000653 E = Comma.get();
654 }
Douglas Gregor253cadf2011-05-21 16:27:21 +0000655 }
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000656 // c++ rules are enforced elsewhere.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000657 if (!getLangOpts().CPlusPlus &&
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000658 RequireCompleteType(E->getExprLoc(), E->getType(),
Fariborz Jahanianbf482812012-03-02 17:05:03 +0000659 diag::err_call_incomplete_argument))
Fariborz Jahanian3854a552012-03-01 23:42:00 +0000660 return ExprError();
Douglas Gregor253cadf2011-05-21 16:27:21 +0000661
John Wiegley01296292011-04-08 18:41:53 +0000662 return Owned(E);
Anders Carlssona7d069d2009-01-16 16:48:51 +0000663}
664
Richard Trieu7aa58f12011-09-02 20:58:51 +0000665/// \brief Converts an integer to complex float type. Helper function of
666/// UsualArithmeticConversions()
667///
668/// \return false if the integer expression is an integer type and is
669/// successfully converted to the complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000670static bool handleIntegerToComplexFloatConversion(Sema &S, ExprResult &IntExpr,
671 ExprResult &ComplexExpr,
672 QualType IntTy,
673 QualType ComplexTy,
674 bool SkipCast) {
675 if (IntTy->isComplexType() || IntTy->isRealFloatingType()) return true;
676 if (SkipCast) return false;
677 if (IntTy->isIntegerType()) {
678 QualType fpTy = cast<ComplexType>(ComplexTy)->getElementType();
679 IntExpr = S.ImpCastExprToType(IntExpr.take(), fpTy, CK_IntegralToFloating);
680 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000681 CK_FloatingRealToComplex);
682 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +0000683 assert(IntTy->isComplexIntegerType());
684 IntExpr = S.ImpCastExprToType(IntExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000685 CK_IntegralComplexToFloatingComplex);
686 }
687 return false;
688}
689
690/// \brief Takes two complex float types and converts them to the same type.
691/// Helper function of UsualArithmeticConversions()
692static QualType
Richard Trieu5065cdd2011-09-06 18:25:09 +0000693handleComplexFloatToComplexFloatConverstion(Sema &S, ExprResult &LHS,
694 ExprResult &RHS, QualType LHSType,
695 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000696 bool IsCompAssign) {
Richard Trieu5065cdd2011-09-06 18:25:09 +0000697 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000698
699 if (order < 0) {
700 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000701 if (!IsCompAssign)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000702 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingComplexCast);
703 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000704 }
705 if (order > 0)
706 // _Complex float -> _Complex double
Richard Trieu5065cdd2011-09-06 18:25:09 +0000707 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingComplexCast);
708 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000709}
710
711/// \brief Converts otherExpr to complex float and promotes complexExpr if
712/// necessary. Helper function of UsualArithmeticConversions()
713static QualType handleOtherComplexFloatConversion(Sema &S,
Richard Trieuba63ce62011-09-09 01:45:06 +0000714 ExprResult &ComplexExpr,
715 ExprResult &OtherExpr,
716 QualType ComplexTy,
717 QualType OtherTy,
718 bool ConvertComplexExpr,
719 bool ConvertOtherExpr) {
720 int order = S.Context.getFloatingTypeOrder(ComplexTy, OtherTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000721
722 // If just the complexExpr is complex, the otherExpr needs to be converted,
723 // and the complexExpr might need to be promoted.
724 if (order > 0) { // complexExpr is wider
725 // float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000726 if (ConvertOtherExpr) {
727 QualType fp = cast<ComplexType>(ComplexTy)->getElementType();
728 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), fp, CK_FloatingCast);
729 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), ComplexTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000730 CK_FloatingRealToComplex);
731 }
Richard Trieuba63ce62011-09-09 01:45:06 +0000732 return ComplexTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000733 }
734
735 // otherTy is at least as wide. Find its corresponding complex type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000736 QualType result = (order == 0 ? ComplexTy :
737 S.Context.getComplexType(OtherTy));
Richard Trieu7aa58f12011-09-02 20:58:51 +0000738
739 // double -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000740 if (ConvertOtherExpr)
741 OtherExpr = S.ImpCastExprToType(OtherExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000742 CK_FloatingRealToComplex);
743
744 // _Complex float -> _Complex double
Richard Trieuba63ce62011-09-09 01:45:06 +0000745 if (ConvertComplexExpr && order < 0)
746 ComplexExpr = S.ImpCastExprToType(ComplexExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000747 CK_FloatingComplexCast);
748
749 return result;
750}
751
752/// \brief Handle arithmetic conversion with complex types. Helper function of
753/// UsualArithmeticConversions()
Richard Trieu5065cdd2011-09-06 18:25:09 +0000754static QualType handleComplexFloatConversion(Sema &S, ExprResult &LHS,
755 ExprResult &RHS, QualType LHSType,
756 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000757 bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000758 // if we have an integer operand, the result is the complex type.
Richard Trieu5065cdd2011-09-06 18:25:09 +0000759 if (!handleIntegerToComplexFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000760 /*skipCast*/false))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000761 return LHSType;
762 if (!handleIntegerToComplexFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000763 /*skipCast*/IsCompAssign))
Richard Trieu5065cdd2011-09-06 18:25:09 +0000764 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000765
766 // This handles complex/complex, complex/float, or float/complex.
767 // When both operands are complex, the shorter operand is converted to the
768 // type of the longer, and that is the type of the result. This corresponds
769 // to what is done when combining two real floating-point operands.
770 // The fun begins when size promotion occur across type domains.
771 // From H&S 6.3.4: When one operand is complex and the other is a real
772 // floating-point type, the less precise type is converted, within it's
773 // real or complex domain, to the precision of the other type. For example,
774 // when combining a "long double" with a "double _Complex", the
775 // "double _Complex" is promoted to "long double _Complex".
776
Richard Trieu5065cdd2011-09-06 18:25:09 +0000777 bool LHSComplexFloat = LHSType->isComplexType();
778 bool RHSComplexFloat = RHSType->isComplexType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000779
780 // If both are complex, just cast to the more precise type.
781 if (LHSComplexFloat && RHSComplexFloat)
Richard Trieu5065cdd2011-09-06 18:25:09 +0000782 return handleComplexFloatToComplexFloatConverstion(S, LHS, RHS,
783 LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000784 IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000785
786 // If only one operand is complex, promote it if necessary and convert the
787 // other operand to complex.
788 if (LHSComplexFloat)
789 return handleOtherComplexFloatConversion(
Richard Trieuba63ce62011-09-09 01:45:06 +0000790 S, LHS, RHS, LHSType, RHSType, /*convertComplexExpr*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000791 /*convertOtherExpr*/ true);
792
793 assert(RHSComplexFloat);
794 return handleOtherComplexFloatConversion(
Richard Trieu5065cdd2011-09-06 18:25:09 +0000795 S, RHS, LHS, RHSType, LHSType, /*convertComplexExpr*/true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000796 /*convertOtherExpr*/ !IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000797}
798
799/// \brief Hande arithmetic conversion from integer to float. Helper function
800/// of UsualArithmeticConversions()
Richard Trieuba63ce62011-09-09 01:45:06 +0000801static QualType handleIntToFloatConversion(Sema &S, ExprResult &FloatExpr,
802 ExprResult &IntExpr,
803 QualType FloatTy, QualType IntTy,
804 bool ConvertFloat, bool ConvertInt) {
805 if (IntTy->isIntegerType()) {
806 if (ConvertInt)
Richard Trieu7aa58f12011-09-02 20:58:51 +0000807 // Convert intExpr to the lhs floating point type.
Richard Trieuba63ce62011-09-09 01:45:06 +0000808 IntExpr = S.ImpCastExprToType(IntExpr.take(), FloatTy,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000809 CK_IntegralToFloating);
Richard Trieuba63ce62011-09-09 01:45:06 +0000810 return FloatTy;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000811 }
812
813 // Convert both sides to the appropriate complex float.
Richard Trieuba63ce62011-09-09 01:45:06 +0000814 assert(IntTy->isComplexIntegerType());
815 QualType result = S.Context.getComplexType(FloatTy);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000816
817 // _Complex int -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000818 if (ConvertInt)
819 IntExpr = S.ImpCastExprToType(IntExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000820 CK_IntegralComplexToFloatingComplex);
821
822 // float -> _Complex float
Richard Trieuba63ce62011-09-09 01:45:06 +0000823 if (ConvertFloat)
824 FloatExpr = S.ImpCastExprToType(FloatExpr.take(), result,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000825 CK_FloatingRealToComplex);
826
827 return result;
828}
829
830/// \brief Handle arithmethic conversion with floating point types. Helper
831/// function of UsualArithmeticConversions()
Richard Trieucfe3f212011-09-06 18:38:41 +0000832static QualType handleFloatConversion(Sema &S, ExprResult &LHS,
833 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000834 QualType RHSType, bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000835 bool LHSFloat = LHSType->isRealFloatingType();
836 bool RHSFloat = RHSType->isRealFloatingType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000837
838 // If we have two real floating types, convert the smaller operand
839 // to the bigger result.
840 if (LHSFloat && RHSFloat) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000841 int order = S.Context.getFloatingTypeOrder(LHSType, RHSType);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000842 if (order > 0) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000843 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_FloatingCast);
844 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000845 }
846
847 assert(order < 0 && "illegal float comparison");
Richard Trieuba63ce62011-09-09 01:45:06 +0000848 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000849 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_FloatingCast);
850 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000851 }
852
853 if (LHSFloat)
Richard Trieucfe3f212011-09-06 18:38:41 +0000854 return handleIntToFloatConversion(S, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000855 /*convertFloat=*/!IsCompAssign,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000856 /*convertInt=*/ true);
857 assert(RHSFloat);
Richard Trieucfe3f212011-09-06 18:38:41 +0000858 return handleIntToFloatConversion(S, RHS, LHS, RHSType, LHSType,
Richard Trieu7aa58f12011-09-02 20:58:51 +0000859 /*convertInt=*/ true,
Richard Trieuba63ce62011-09-09 01:45:06 +0000860 /*convertFloat=*/!IsCompAssign);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000861}
862
863/// \brief Handle conversions with GCC complex int extension. Helper function
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000864/// of UsualArithmeticConversions()
Richard Trieu7aa58f12011-09-02 20:58:51 +0000865// FIXME: if the operands are (int, _Complex long), we currently
866// don't promote the complex. Also, signedness?
Benjamin Kramer499c68b2011-09-06 19:57:14 +0000867static QualType handleComplexIntConversion(Sema &S, ExprResult &LHS,
868 ExprResult &RHS, QualType LHSType,
869 QualType RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000870 bool IsCompAssign) {
Richard Trieucfe3f212011-09-06 18:38:41 +0000871 const ComplexType *LHSComplexInt = LHSType->getAsComplexIntegerType();
872 const ComplexType *RHSComplexInt = RHSType->getAsComplexIntegerType();
Richard Trieu7aa58f12011-09-02 20:58:51 +0000873
Richard Trieucfe3f212011-09-06 18:38:41 +0000874 if (LHSComplexInt && RHSComplexInt) {
875 int order = S.Context.getIntegerTypeOrder(LHSComplexInt->getElementType(),
876 RHSComplexInt->getElementType());
Richard Trieu7aa58f12011-09-02 20:58:51 +0000877 assert(order && "inequal types with equal element ordering");
878 if (order > 0) {
879 // _Complex int -> _Complex long
Richard Trieucfe3f212011-09-06 18:38:41 +0000880 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralComplexCast);
881 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000882 }
883
Richard Trieuba63ce62011-09-09 01:45:06 +0000884 if (!IsCompAssign)
Richard Trieucfe3f212011-09-06 18:38:41 +0000885 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralComplexCast);
886 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000887 }
888
Richard Trieucfe3f212011-09-06 18:38:41 +0000889 if (LHSComplexInt) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000890 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000891 // FIXME: This needs to take integer ranks into account
892 RHS = S.ImpCastExprToType(RHS.take(), LHSComplexInt->getElementType(),
893 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000894 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralRealToComplex);
895 return LHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000896 }
897
Richard Trieucfe3f212011-09-06 18:38:41 +0000898 assert(RHSComplexInt);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000899 // int -> _Complex int
Eli Friedman47133be2011-11-12 03:56:23 +0000900 // FIXME: This needs to take integer ranks into account
901 if (!IsCompAssign) {
902 LHS = S.ImpCastExprToType(LHS.take(), RHSComplexInt->getElementType(),
903 CK_IntegralCast);
Richard Trieucfe3f212011-09-06 18:38:41 +0000904 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralRealToComplex);
Eli Friedman47133be2011-11-12 03:56:23 +0000905 }
Richard Trieucfe3f212011-09-06 18:38:41 +0000906 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000907}
908
909/// \brief Handle integer arithmetic conversions. Helper function of
910/// UsualArithmeticConversions()
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000911static QualType handleIntegerConversion(Sema &S, ExprResult &LHS,
912 ExprResult &RHS, QualType LHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +0000913 QualType RHSType, bool IsCompAssign) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000914 // The rules for this case are in C99 6.3.1.8
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000915 int order = S.Context.getIntegerTypeOrder(LHSType, RHSType);
916 bool LHSSigned = LHSType->hasSignedIntegerRepresentation();
917 bool RHSSigned = RHSType->hasSignedIntegerRepresentation();
918 if (LHSSigned == RHSSigned) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000919 // Same signedness; use the higher-ranked type
920 if (order >= 0) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000921 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
922 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000923 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000924 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
925 return RHSType;
926 } else if (order != (LHSSigned ? 1 : -1)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000927 // The unsigned type has greater than or equal rank to the
928 // signed type, so use the unsigned type
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000929 if (RHSSigned) {
930 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
931 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000932 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000933 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
934 return RHSType;
935 } else if (S.Context.getIntWidth(LHSType) != S.Context.getIntWidth(RHSType)) {
Richard Trieu7aa58f12011-09-02 20:58:51 +0000936 // The two types are different widths; if we are here, that
937 // means the signed type is larger than the unsigned type, so
938 // use the signed type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000939 if (LHSSigned) {
940 RHS = S.ImpCastExprToType(RHS.take(), LHSType, CK_IntegralCast);
941 return LHSType;
Richard Trieuba63ce62011-09-09 01:45:06 +0000942 } else if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000943 LHS = S.ImpCastExprToType(LHS.take(), RHSType, CK_IntegralCast);
944 return RHSType;
Richard Trieu7aa58f12011-09-02 20:58:51 +0000945 } else {
946 // The signed type is higher-ranked than the unsigned type,
947 // but isn't actually any bigger (like unsigned int and long
948 // on most 32-bit systems). Use the unsigned type corresponding
949 // to the signed type.
950 QualType result =
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000951 S.Context.getCorrespondingUnsignedType(LHSSigned ? LHSType : RHSType);
952 RHS = S.ImpCastExprToType(RHS.take(), result, CK_IntegralCast);
Richard Trieuba63ce62011-09-09 01:45:06 +0000953 if (!IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000954 LHS = S.ImpCastExprToType(LHS.take(), result, CK_IntegralCast);
Richard Trieu7aa58f12011-09-02 20:58:51 +0000955 return result;
956 }
957}
958
Chris Lattner513165e2008-07-25 21:10:04 +0000959/// UsualArithmeticConversions - Performs various conversions that are common to
960/// binary operators (C99 6.3.1.8). If both operands aren't arithmetic, this
Mike Stump11289f42009-09-09 15:08:12 +0000961/// routine returns the first non-arithmetic type found. The client is
Chris Lattner513165e2008-07-25 21:10:04 +0000962/// responsible for emitting appropriate error diagnostics.
963/// FIXME: verify the conversion rules for "complex int" are consistent with
964/// GCC.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000965QualType Sema::UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +0000966 bool IsCompAssign) {
967 if (!IsCompAssign) {
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000968 LHS = UsualUnaryConversions(LHS.take());
969 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000970 return QualType();
971 }
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000972
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000973 RHS = UsualUnaryConversions(RHS.take());
974 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000975 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000976
Mike Stump11289f42009-09-09 15:08:12 +0000977 // For conversion purposes, we ignore any qualifiers.
Chris Lattner513165e2008-07-25 21:10:04 +0000978 // For example, "const float" and "float" are equivalent.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000979 QualType LHSType =
980 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
981 QualType RHSType =
982 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000983
Eli Friedman93ee5ca2012-06-16 02:19:17 +0000984 // For conversion purposes, we ignore any atomic qualifier on the LHS.
985 if (const AtomicType *AtomicLHS = LHSType->getAs<AtomicType>())
986 LHSType = AtomicLHS->getValueType();
987
Douglas Gregora11693b2008-11-12 17:17:38 +0000988 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000989 if (LHSType == RHSType)
990 return LHSType;
Douglas Gregora11693b2008-11-12 17:17:38 +0000991
992 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
993 // The caller can deal with this (e.g. pointer + int).
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000994 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
Eli Friedman93ee5ca2012-06-16 02:19:17 +0000995 return QualType();
Douglas Gregora11693b2008-11-12 17:17:38 +0000996
John McCalld005ac92010-11-13 08:17:45 +0000997 // Apply unary and bitfield promotions to the LHS's type.
Richard Trieu9a52fbb2011-09-06 19:52:52 +0000998 QualType LHSUnpromotedType = LHSType;
999 if (LHSType->isPromotableIntegerType())
1000 LHSType = Context.getPromotedIntegerType(LHSType);
1001 QualType LHSBitfieldPromoteTy = Context.isPromotableBitField(LHS.get());
Douglas Gregord2c2d172009-05-02 00:36:19 +00001002 if (!LHSBitfieldPromoteTy.isNull())
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001003 LHSType = LHSBitfieldPromoteTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00001004 if (LHSType != LHSUnpromotedType && !IsCompAssign)
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001005 LHS = ImpCastExprToType(LHS.take(), LHSType, CK_IntegralCast);
Douglas Gregord2c2d172009-05-02 00:36:19 +00001006
John McCalld005ac92010-11-13 08:17:45 +00001007 // If both types are identical, no conversion is needed.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001008 if (LHSType == RHSType)
1009 return LHSType;
John McCalld005ac92010-11-13 08:17:45 +00001010
1011 // At this point, we have two different arithmetic types.
1012
1013 // Handle complex types first (C99 6.3.1.8p1).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001014 if (LHSType->isComplexType() || RHSType->isComplexType())
1015 return handleComplexFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001016 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001017
1018 // Now handle "real" floating types (i.e. float, double, long double).
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001019 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType())
1020 return handleFloatConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001021 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001022
1023 // Handle GCC complex int extension.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001024 if (LHSType->isComplexIntegerType() || RHSType->isComplexIntegerType())
Benjamin Kramer499c68b2011-09-06 19:57:14 +00001025 return handleComplexIntConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001026 IsCompAssign);
John McCalld005ac92010-11-13 08:17:45 +00001027
1028 // Finally, we have two differing integer types.
Richard Trieu9a52fbb2011-09-06 19:52:52 +00001029 return handleIntegerConversion(*this, LHS, RHS, LHSType, RHSType,
Richard Trieuba63ce62011-09-09 01:45:06 +00001030 IsCompAssign);
Douglas Gregora11693b2008-11-12 17:17:38 +00001031}
1032
Chris Lattner513165e2008-07-25 21:10:04 +00001033//===----------------------------------------------------------------------===//
1034// Semantic Analysis for various Expression Types
1035//===----------------------------------------------------------------------===//
1036
1037
Peter Collingbourne91147592011-04-15 00:35:48 +00001038ExprResult
1039Sema::ActOnGenericSelectionExpr(SourceLocation KeyLoc,
1040 SourceLocation DefaultLoc,
1041 SourceLocation RParenLoc,
1042 Expr *ControllingExpr,
Richard Trieuba63ce62011-09-09 01:45:06 +00001043 MultiTypeArg ArgTypes,
1044 MultiExprArg ArgExprs) {
1045 unsigned NumAssocs = ArgTypes.size();
1046 assert(NumAssocs == ArgExprs.size());
Peter Collingbourne91147592011-04-15 00:35:48 +00001047
Richard Trieuba63ce62011-09-09 01:45:06 +00001048 ParsedType *ParsedTypes = ArgTypes.release();
1049 Expr **Exprs = ArgExprs.release();
Peter Collingbourne91147592011-04-15 00:35:48 +00001050
1051 TypeSourceInfo **Types = new TypeSourceInfo*[NumAssocs];
1052 for (unsigned i = 0; i < NumAssocs; ++i) {
1053 if (ParsedTypes[i])
1054 (void) GetTypeFromParser(ParsedTypes[i], &Types[i]);
1055 else
1056 Types[i] = 0;
1057 }
1058
1059 ExprResult ER = CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
1060 ControllingExpr, Types, Exprs,
1061 NumAssocs);
Benjamin Kramer34623762011-04-15 11:21:57 +00001062 delete [] Types;
Peter Collingbourne91147592011-04-15 00:35:48 +00001063 return ER;
1064}
1065
1066ExprResult
1067Sema::CreateGenericSelectionExpr(SourceLocation KeyLoc,
1068 SourceLocation DefaultLoc,
1069 SourceLocation RParenLoc,
1070 Expr *ControllingExpr,
1071 TypeSourceInfo **Types,
1072 Expr **Exprs,
1073 unsigned NumAssocs) {
1074 bool TypeErrorFound = false,
1075 IsResultDependent = ControllingExpr->isTypeDependent(),
1076 ContainsUnexpandedParameterPack
1077 = ControllingExpr->containsUnexpandedParameterPack();
1078
1079 for (unsigned i = 0; i < NumAssocs; ++i) {
1080 if (Exprs[i]->containsUnexpandedParameterPack())
1081 ContainsUnexpandedParameterPack = true;
1082
1083 if (Types[i]) {
1084 if (Types[i]->getType()->containsUnexpandedParameterPack())
1085 ContainsUnexpandedParameterPack = true;
1086
1087 if (Types[i]->getType()->isDependentType()) {
1088 IsResultDependent = true;
1089 } else {
Benjamin Kramere56f3932011-12-23 17:00:35 +00001090 // C11 6.5.1.1p2 "The type name in a generic association shall specify a
Peter Collingbourne91147592011-04-15 00:35:48 +00001091 // complete object type other than a variably modified type."
1092 unsigned D = 0;
1093 if (Types[i]->getType()->isIncompleteType())
1094 D = diag::err_assoc_type_incomplete;
1095 else if (!Types[i]->getType()->isObjectType())
1096 D = diag::err_assoc_type_nonobject;
1097 else if (Types[i]->getType()->isVariablyModifiedType())
1098 D = diag::err_assoc_type_variably_modified;
1099
1100 if (D != 0) {
1101 Diag(Types[i]->getTypeLoc().getBeginLoc(), D)
1102 << Types[i]->getTypeLoc().getSourceRange()
1103 << Types[i]->getType();
1104 TypeErrorFound = true;
1105 }
1106
Benjamin Kramere56f3932011-12-23 17:00:35 +00001107 // C11 6.5.1.1p2 "No two generic associations in the same generic
Peter Collingbourne91147592011-04-15 00:35:48 +00001108 // selection shall specify compatible types."
1109 for (unsigned j = i+1; j < NumAssocs; ++j)
1110 if (Types[j] && !Types[j]->getType()->isDependentType() &&
1111 Context.typesAreCompatible(Types[i]->getType(),
1112 Types[j]->getType())) {
1113 Diag(Types[j]->getTypeLoc().getBeginLoc(),
1114 diag::err_assoc_compatible_types)
1115 << Types[j]->getTypeLoc().getSourceRange()
1116 << Types[j]->getType()
1117 << Types[i]->getType();
1118 Diag(Types[i]->getTypeLoc().getBeginLoc(),
1119 diag::note_compat_assoc)
1120 << Types[i]->getTypeLoc().getSourceRange()
1121 << Types[i]->getType();
1122 TypeErrorFound = true;
1123 }
1124 }
1125 }
1126 }
1127 if (TypeErrorFound)
1128 return ExprError();
1129
1130 // If we determined that the generic selection is result-dependent, don't
1131 // try to compute the result expression.
1132 if (IsResultDependent)
1133 return Owned(new (Context) GenericSelectionExpr(
1134 Context, KeyLoc, ControllingExpr,
1135 Types, Exprs, NumAssocs, DefaultLoc,
1136 RParenLoc, ContainsUnexpandedParameterPack));
1137
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001138 SmallVector<unsigned, 1> CompatIndices;
Peter Collingbourne91147592011-04-15 00:35:48 +00001139 unsigned DefaultIndex = -1U;
1140 for (unsigned i = 0; i < NumAssocs; ++i) {
1141 if (!Types[i])
1142 DefaultIndex = i;
1143 else if (Context.typesAreCompatible(ControllingExpr->getType(),
1144 Types[i]->getType()))
1145 CompatIndices.push_back(i);
1146 }
1147
Benjamin Kramere56f3932011-12-23 17:00:35 +00001148 // C11 6.5.1.1p2 "The controlling expression of a generic selection shall have
Peter Collingbourne91147592011-04-15 00:35:48 +00001149 // type compatible with at most one of the types named in its generic
1150 // association list."
1151 if (CompatIndices.size() > 1) {
1152 // We strip parens here because the controlling expression is typically
1153 // parenthesized in macro definitions.
1154 ControllingExpr = ControllingExpr->IgnoreParens();
1155 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_multi_match)
1156 << ControllingExpr->getSourceRange() << ControllingExpr->getType()
1157 << (unsigned) CompatIndices.size();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001158 for (SmallVector<unsigned, 1>::iterator I = CompatIndices.begin(),
Peter Collingbourne91147592011-04-15 00:35:48 +00001159 E = CompatIndices.end(); I != E; ++I) {
1160 Diag(Types[*I]->getTypeLoc().getBeginLoc(),
1161 diag::note_compat_assoc)
1162 << Types[*I]->getTypeLoc().getSourceRange()
1163 << Types[*I]->getType();
1164 }
1165 return ExprError();
1166 }
1167
Benjamin Kramere56f3932011-12-23 17:00:35 +00001168 // C11 6.5.1.1p2 "If a generic selection has no default generic association,
Peter Collingbourne91147592011-04-15 00:35:48 +00001169 // its controlling expression shall have type compatible with exactly one of
1170 // the types named in its generic association list."
1171 if (DefaultIndex == -1U && CompatIndices.size() == 0) {
1172 // We strip parens here because the controlling expression is typically
1173 // parenthesized in macro definitions.
1174 ControllingExpr = ControllingExpr->IgnoreParens();
1175 Diag(ControllingExpr->getLocStart(), diag::err_generic_sel_no_match)
1176 << ControllingExpr->getSourceRange() << ControllingExpr->getType();
1177 return ExprError();
1178 }
1179
Benjamin Kramere56f3932011-12-23 17:00:35 +00001180 // C11 6.5.1.1p3 "If a generic selection has a generic association with a
Peter Collingbourne91147592011-04-15 00:35:48 +00001181 // type name that is compatible with the type of the controlling expression,
1182 // then the result expression of the generic selection is the expression
1183 // in that generic association. Otherwise, the result expression of the
1184 // generic selection is the expression in the default generic association."
1185 unsigned ResultIndex =
1186 CompatIndices.size() ? CompatIndices[0] : DefaultIndex;
1187
1188 return Owned(new (Context) GenericSelectionExpr(
1189 Context, KeyLoc, ControllingExpr,
1190 Types, Exprs, NumAssocs, DefaultLoc,
1191 RParenLoc, ContainsUnexpandedParameterPack,
1192 ResultIndex));
1193}
1194
Richard Smith75b67d62012-03-08 01:34:56 +00001195/// getUDSuffixLoc - Create a SourceLocation for a ud-suffix, given the
1196/// location of the token and the offset of the ud-suffix within it.
1197static SourceLocation getUDSuffixLoc(Sema &S, SourceLocation TokLoc,
1198 unsigned Offset) {
1199 return Lexer::AdvanceToTokenCharacter(TokLoc, Offset, S.getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001200 S.getLangOpts());
Richard Smith75b67d62012-03-08 01:34:56 +00001201}
1202
Richard Smithbcc22fc2012-03-09 08:00:36 +00001203/// BuildCookedLiteralOperatorCall - A user-defined literal was found. Look up
1204/// the corresponding cooked (non-raw) literal operator, and build a call to it.
1205static ExprResult BuildCookedLiteralOperatorCall(Sema &S, Scope *Scope,
1206 IdentifierInfo *UDSuffix,
1207 SourceLocation UDSuffixLoc,
1208 ArrayRef<Expr*> Args,
1209 SourceLocation LitEndLoc) {
1210 assert(Args.size() <= 2 && "too many arguments for literal operator");
1211
1212 QualType ArgTy[2];
1213 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
1214 ArgTy[ArgIdx] = Args[ArgIdx]->getType();
1215 if (ArgTy[ArgIdx]->isArrayType())
1216 ArgTy[ArgIdx] = S.Context.getArrayDecayedType(ArgTy[ArgIdx]);
1217 }
1218
1219 DeclarationName OpName =
1220 S.Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
1221 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
1222 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
1223
1224 LookupResult R(S, OpName, UDSuffixLoc, Sema::LookupOrdinaryName);
1225 if (S.LookupLiteralOperator(Scope, R, llvm::makeArrayRef(ArgTy, Args.size()),
1226 /*AllowRawAndTemplate*/false) == Sema::LOLR_Error)
1227 return ExprError();
1228
1229 return S.BuildLiteralOperatorCall(R, OpNameInfo, Args, LitEndLoc);
1230}
1231
Steve Naroff83895f72007-09-16 03:34:24 +00001232/// ActOnStringLiteral - The specified tokens were lexed as pasted string
Chris Lattner5b183d82006-11-10 05:03:26 +00001233/// fragments (e.g. "foo" "bar" L"baz"). The result string has to handle string
1234/// concatenation ([C99 5.1.1.2, translation phase #6]), so it may come from
1235/// multiple tokens. However, the common case is that StringToks points to one
1236/// string.
Sebastian Redlffbcf962009-01-18 18:53:16 +00001237///
John McCalldadc5752010-08-24 06:29:42 +00001238ExprResult
Richard Smithbcc22fc2012-03-09 08:00:36 +00001239Sema::ActOnStringLiteral(const Token *StringToks, unsigned NumStringToks,
1240 Scope *UDLScope) {
Chris Lattner5b183d82006-11-10 05:03:26 +00001241 assert(NumStringToks && "Must have at least one string!");
1242
Chris Lattner8a24e582009-01-16 18:51:42 +00001243 StringLiteralParser Literal(StringToks, NumStringToks, PP);
Steve Naroff4f88b312007-03-13 22:37:02 +00001244 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00001245 return ExprError();
Chris Lattner5b183d82006-11-10 05:03:26 +00001246
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001247 SmallVector<SourceLocation, 4> StringTokLocs;
Chris Lattner5b183d82006-11-10 05:03:26 +00001248 for (unsigned i = 0; i != NumStringToks; ++i)
1249 StringTokLocs.push_back(StringToks[i].getLocation());
Chris Lattner36fc8792008-02-11 00:02:17 +00001250
Chris Lattner36fc8792008-02-11 00:02:17 +00001251 QualType StrTy = Context.CharTy;
Douglas Gregorfb65e592011-07-27 05:40:30 +00001252 if (Literal.isWide())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001253 StrTy = Context.getWCharType();
Douglas Gregorfb65e592011-07-27 05:40:30 +00001254 else if (Literal.isUTF16())
1255 StrTy = Context.Char16Ty;
1256 else if (Literal.isUTF32())
1257 StrTy = Context.Char32Ty;
Eli Friedmanfcec6302011-11-01 02:23:42 +00001258 else if (Literal.isPascal())
Anders Carlsson6b06e182011-04-06 18:42:48 +00001259 StrTy = Context.UnsignedCharTy;
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001260
Douglas Gregorfb65e592011-07-27 05:40:30 +00001261 StringLiteral::StringKind Kind = StringLiteral::Ascii;
1262 if (Literal.isWide())
1263 Kind = StringLiteral::Wide;
1264 else if (Literal.isUTF8())
1265 Kind = StringLiteral::UTF8;
1266 else if (Literal.isUTF16())
1267 Kind = StringLiteral::UTF16;
1268 else if (Literal.isUTF32())
1269 Kind = StringLiteral::UTF32;
1270
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001271 // A C++ string literal has a const-qualified element type (C++ 2.13.4p1).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001272 if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings)
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00001273 StrTy.addConst();
Sebastian Redlffbcf962009-01-18 18:53:16 +00001274
Chris Lattner36fc8792008-02-11 00:02:17 +00001275 // Get an array type for the string, according to C99 6.4.5. This includes
1276 // the nul terminator character as well as the string length for pascal
1277 // strings.
1278 StrTy = Context.getConstantArrayType(StrTy,
Chris Lattnerd42c29f2009-02-26 23:01:51 +00001279 llvm::APInt(32, Literal.GetNumStringChars()+1),
Chris Lattner36fc8792008-02-11 00:02:17 +00001280 ArrayType::Normal, 0);
Mike Stump11289f42009-09-09 15:08:12 +00001281
Chris Lattner5b183d82006-11-10 05:03:26 +00001282 // Pass &StringTokLocs[0], StringTokLocs.size() to factory!
Richard Smithc67fdd42012-03-07 08:35:16 +00001283 StringLiteral *Lit = StringLiteral::Create(Context, Literal.GetString(),
1284 Kind, Literal.Pascal, StrTy,
1285 &StringTokLocs[0],
1286 StringTokLocs.size());
1287 if (Literal.getUDSuffix().empty())
1288 return Owned(Lit);
1289
1290 // We're building a user-defined literal.
1291 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
Richard Smith75b67d62012-03-08 01:34:56 +00001292 SourceLocation UDSuffixLoc =
1293 getUDSuffixLoc(*this, StringTokLocs[Literal.getUDSuffixToken()],
1294 Literal.getUDSuffixOffset());
Richard Smithc67fdd42012-03-07 08:35:16 +00001295
Richard Smithbcc22fc2012-03-09 08:00:36 +00001296 // Make sure we're allowed user-defined literals here.
1297 if (!UDLScope)
1298 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_string_udl));
1299
Richard Smithc67fdd42012-03-07 08:35:16 +00001300 // C++11 [lex.ext]p5: The literal L is treated as a call of the form
1301 // operator "" X (str, len)
1302 QualType SizeType = Context.getSizeType();
1303 llvm::APInt Len(Context.getIntWidth(SizeType), Literal.GetNumStringChars());
1304 IntegerLiteral *LenArg = IntegerLiteral::Create(Context, Len, SizeType,
1305 StringTokLocs[0]);
1306 Expr *Args[] = { Lit, LenArg };
Richard Smithbcc22fc2012-03-09 08:00:36 +00001307 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
1308 Args, StringTokLocs.back());
Chris Lattner5b183d82006-11-10 05:03:26 +00001309}
1310
John McCalldadc5752010-08-24 06:29:42 +00001311ExprResult
John McCall7decc9e2010-11-18 06:31:45 +00001312Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
John McCallf4cd4f92011-02-09 01:13:10 +00001313 SourceLocation Loc,
1314 const CXXScopeSpec *SS) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001315 DeclarationNameInfo NameInfo(D->getDeclName(), Loc);
John McCall7decc9e2010-11-18 06:31:45 +00001316 return BuildDeclRefExpr(D, Ty, VK, NameInfo, SS);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001317}
1318
John McCallf4cd4f92011-02-09 01:13:10 +00001319/// BuildDeclRefExpr - Build an expression that references a
1320/// declaration that does not require a closure capture.
John McCalldadc5752010-08-24 06:29:42 +00001321ExprResult
John McCallf4cd4f92011-02-09 01:13:10 +00001322Sema::BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001323 const DeclarationNameInfo &NameInfo,
1324 const CXXScopeSpec *SS) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001325 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00001326 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
1327 if (const FunctionDecl *Callee = dyn_cast<FunctionDecl>(D)) {
1328 CUDAFunctionTarget CallerTarget = IdentifyCUDATarget(Caller),
1329 CalleeTarget = IdentifyCUDATarget(Callee);
1330 if (CheckCUDATarget(CallerTarget, CalleeTarget)) {
1331 Diag(NameInfo.getLoc(), diag::err_ref_bad_target)
1332 << CalleeTarget << D->getIdentifier() << CallerTarget;
1333 Diag(D->getLocation(), diag::note_previous_decl)
1334 << D->getIdentifier();
1335 return ExprError();
1336 }
1337 }
1338
John McCall113bee02012-03-10 09:33:50 +00001339 bool refersToEnclosingScope =
1340 (CurContext != D->getDeclContext() &&
1341 D->getDeclContext()->isFunctionOrMethod());
1342
Eli Friedmanfa0df832012-02-02 03:46:19 +00001343 DeclRefExpr *E = DeclRefExpr::Create(Context,
1344 SS ? SS->getWithLocInContext(Context)
1345 : NestedNameSpecifierLoc(),
John McCall113bee02012-03-10 09:33:50 +00001346 SourceLocation(),
1347 D, refersToEnclosingScope,
1348 NameInfo, Ty, VK);
Mike Stump11289f42009-09-09 15:08:12 +00001349
Eli Friedmanfa0df832012-02-02 03:46:19 +00001350 MarkDeclRefReferenced(E);
John McCall086a4642010-11-24 05:12:34 +00001351
1352 // Just in case we're building an illegal pointer-to-member.
Richard Smithcaf33902011-10-10 18:28:20 +00001353 FieldDecl *FD = dyn_cast<FieldDecl>(D);
1354 if (FD && FD->isBitField())
John McCall086a4642010-11-24 05:12:34 +00001355 E->setObjectKind(OK_BitField);
1356
1357 return Owned(E);
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001358}
1359
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001360/// Decomposes the given name into a DeclarationNameInfo, its location, and
John McCall10eae182009-11-30 22:42:35 +00001361/// possibly a list of template arguments.
1362///
1363/// If this produces template arguments, it is permitted to call
1364/// DecomposeTemplateName.
1365///
1366/// This actually loses a lot of source location information for
1367/// non-standard name kinds; we should consider preserving that in
1368/// some way.
Richard Trieucfc491d2011-08-02 04:35:43 +00001369void
1370Sema::DecomposeUnqualifiedId(const UnqualifiedId &Id,
1371 TemplateArgumentListInfo &Buffer,
1372 DeclarationNameInfo &NameInfo,
1373 const TemplateArgumentListInfo *&TemplateArgs) {
John McCall10eae182009-11-30 22:42:35 +00001374 if (Id.getKind() == UnqualifiedId::IK_TemplateId) {
1375 Buffer.setLAngleLoc(Id.TemplateId->LAngleLoc);
1376 Buffer.setRAngleLoc(Id.TemplateId->RAngleLoc);
1377
Douglas Gregor5476205b2011-06-23 00:49:38 +00001378 ASTTemplateArgsPtr TemplateArgsPtr(*this,
John McCall10eae182009-11-30 22:42:35 +00001379 Id.TemplateId->getTemplateArgs(),
1380 Id.TemplateId->NumArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001381 translateTemplateArguments(TemplateArgsPtr, Buffer);
John McCall10eae182009-11-30 22:42:35 +00001382 TemplateArgsPtr.release();
1383
John McCall3e56fd42010-08-23 07:28:44 +00001384 TemplateName TName = Id.TemplateId->Template.get();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001385 SourceLocation TNameLoc = Id.TemplateId->TemplateNameLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001386 NameInfo = Context.getNameForTemplate(TName, TNameLoc);
John McCall10eae182009-11-30 22:42:35 +00001387 TemplateArgs = &Buffer;
1388 } else {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001389 NameInfo = GetNameFromUnqualifiedId(Id);
John McCall10eae182009-11-30 22:42:35 +00001390 TemplateArgs = 0;
1391 }
1392}
1393
John McCalld681c392009-12-16 08:11:27 +00001394/// Diagnose an empty lookup.
1395///
1396/// \return false if new lookup candidates were found
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001397bool Sema::DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R,
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001398 CorrectionCandidateCallback &CCC,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001399 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001400 llvm::ArrayRef<Expr *> Args) {
John McCalld681c392009-12-16 08:11:27 +00001401 DeclarationName Name = R.getLookupName();
1402
John McCalld681c392009-12-16 08:11:27 +00001403 unsigned diagnostic = diag::err_undeclared_var_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001404 unsigned diagnostic_suggest = diag::err_undeclared_var_use_suggest;
John McCalld681c392009-12-16 08:11:27 +00001405 if (Name.getNameKind() == DeclarationName::CXXOperatorName ||
1406 Name.getNameKind() == DeclarationName::CXXLiteralOperatorName ||
Douglas Gregor598b08f2009-12-31 05:20:13 +00001407 Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
John McCalld681c392009-12-16 08:11:27 +00001408 diagnostic = diag::err_undeclared_use;
Douglas Gregor598b08f2009-12-31 05:20:13 +00001409 diagnostic_suggest = diag::err_undeclared_use_suggest;
1410 }
John McCalld681c392009-12-16 08:11:27 +00001411
Douglas Gregor598b08f2009-12-31 05:20:13 +00001412 // If the original lookup was an unqualified lookup, fake an
1413 // unqualified lookup. This is useful when (for example) the
1414 // original lookup would not have found something because it was a
1415 // dependent name.
David Blaikiec4c0e8a2012-05-28 01:26:45 +00001416 DeclContext *DC = (SS.isEmpty() && !CallsUndergoingInstantiation.empty())
1417 ? CurContext : 0;
Francois Pichetde232cb2011-11-25 01:10:54 +00001418 while (DC) {
John McCalld681c392009-12-16 08:11:27 +00001419 if (isa<CXXRecordDecl>(DC)) {
1420 LookupQualifiedName(R, DC);
1421
1422 if (!R.empty()) {
1423 // Don't give errors about ambiguities in this lookup.
1424 R.suppressDiagnostics();
1425
Francois Pichet857f9d62011-11-17 03:44:24 +00001426 // During a default argument instantiation the CurContext points
1427 // to a CXXMethodDecl; but we can't apply a this-> fixit inside a
1428 // function parameter list, hence add an explicit check.
1429 bool isDefaultArgument = !ActiveTemplateInstantiations.empty() &&
1430 ActiveTemplateInstantiations.back().Kind ==
1431 ActiveTemplateInstantiation::DefaultFunctionArgumentInstantiation;
John McCalld681c392009-12-16 08:11:27 +00001432 CXXMethodDecl *CurMethod = dyn_cast<CXXMethodDecl>(CurContext);
1433 bool isInstance = CurMethod &&
1434 CurMethod->isInstance() &&
Francois Pichet857f9d62011-11-17 03:44:24 +00001435 DC == CurMethod->getParent() && !isDefaultArgument;
1436
John McCalld681c392009-12-16 08:11:27 +00001437
1438 // Give a code modification hint to insert 'this->'.
1439 // TODO: fixit for inserting 'Base<T>::' in the other cases.
1440 // Actually quite difficult!
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001441 if (isInstance) {
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001442 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(
1443 CallsUndergoingInstantiation.back()->getCallee());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001444 CXXMethodDecl *DepMethod = cast_or_null<CXXMethodDecl>(
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001445 CurMethod->getInstantiatedFromMemberFunction());
Eli Friedman04831922010-08-22 01:00:03 +00001446 if (DepMethod) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001447 if (getLangOpts().MicrosoftMode)
Francois Pichetbcf64712011-09-07 00:14:57 +00001448 diagnostic = diag::warn_found_via_dependent_bases_lookup;
Nick Lewyckyfe712382010-08-20 20:54:15 +00001449 Diag(R.getNameLoc(), diagnostic) << Name
1450 << FixItHint::CreateInsertion(R.getNameLoc(), "this->");
1451 QualType DepThisType = DepMethod->getThisType(Context);
Eli Friedman73a04092012-01-07 04:59:52 +00001452 CheckCXXThisCapture(R.getNameLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001453 CXXThisExpr *DepThis = new (Context) CXXThisExpr(
1454 R.getNameLoc(), DepThisType, false);
1455 TemplateArgumentListInfo TList;
1456 if (ULE->hasExplicitTemplateArgs())
1457 ULE->copyTemplateArgumentsInto(TList);
Douglas Gregore16af532011-02-28 18:50:33 +00001458
Douglas Gregore16af532011-02-28 18:50:33 +00001459 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00001460 SS.Adopt(ULE->getQualifierLoc());
Nick Lewyckyfe712382010-08-20 20:54:15 +00001461 CXXDependentScopeMemberExpr *DepExpr =
1462 CXXDependentScopeMemberExpr::Create(
1463 Context, DepThis, DepThisType, true, SourceLocation(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001464 SS.getWithLocInContext(Context),
1465 ULE->getTemplateKeywordLoc(), 0,
Francois Pichet4391c752011-09-04 23:00:48 +00001466 R.getLookupNameInfo(),
1467 ULE->hasExplicitTemplateArgs() ? &TList : 0);
Nick Lewyckyfe712382010-08-20 20:54:15 +00001468 CallsUndergoingInstantiation.back()->setCallee(DepExpr);
Eli Friedman04831922010-08-22 01:00:03 +00001469 } else {
Nick Lewyckyfe712382010-08-20 20:54:15 +00001470 // FIXME: we should be able to handle this case too. It is correct
1471 // to add this-> here. This is a workaround for PR7947.
1472 Diag(R.getNameLoc(), diagnostic) << Name;
Eli Friedman04831922010-08-22 01:00:03 +00001473 }
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001474 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001475 if (getLangOpts().MicrosoftMode)
Francois Pichet78286b22011-11-15 23:33:34 +00001476 diagnostic = diag::warn_found_via_dependent_bases_lookup;
John McCalld681c392009-12-16 08:11:27 +00001477 Diag(R.getNameLoc(), diagnostic) << Name;
Nick Lewyckyc96c37f2010-07-06 19:51:49 +00001478 }
John McCalld681c392009-12-16 08:11:27 +00001479
1480 // Do we really want to note all of these?
1481 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
1482 Diag((*I)->getLocation(), diag::note_dependent_var_use);
1483
Francois Pichet857f9d62011-11-17 03:44:24 +00001484 // Return true if we are inside a default argument instantiation
1485 // and the found name refers to an instance member function, otherwise
1486 // the function calling DiagnoseEmptyLookup will try to create an
1487 // implicit member call and this is wrong for default argument.
1488 if (isDefaultArgument && ((*R.begin())->isCXXInstanceMember())) {
1489 Diag(R.getNameLoc(), diag::err_member_call_without_object);
1490 return true;
1491 }
1492
John McCalld681c392009-12-16 08:11:27 +00001493 // Tell the callee to try to recover.
1494 return false;
1495 }
Douglas Gregor86b8d9f2010-08-09 22:38:14 +00001496
1497 R.clear();
John McCalld681c392009-12-16 08:11:27 +00001498 }
Francois Pichetde232cb2011-11-25 01:10:54 +00001499
1500 // In Microsoft mode, if we are performing lookup from within a friend
1501 // function definition declared at class scope then we must set
1502 // DC to the lexical parent to be able to search into the parent
1503 // class.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001504 if (getLangOpts().MicrosoftMode && isa<FunctionDecl>(DC) &&
Francois Pichetde232cb2011-11-25 01:10:54 +00001505 cast<FunctionDecl>(DC)->getFriendObjectKind() &&
1506 DC->getLexicalParent()->isRecord())
1507 DC = DC->getLexicalParent();
1508 else
1509 DC = DC->getParent();
John McCalld681c392009-12-16 08:11:27 +00001510 }
1511
Douglas Gregor598b08f2009-12-31 05:20:13 +00001512 // We didn't find anything, so try to correct for a typo.
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001513 TypoCorrection Corrected;
1514 if (S && (Corrected = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(),
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001515 S, &SS, CCC))) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001516 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
1517 std::string CorrectedQuotedStr(Corrected.getQuoted(getLangOpts()));
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001518 R.setLookupName(Corrected.getCorrection());
1519
Hans Wennborg38198de2011-07-12 08:45:31 +00001520 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001521 if (Corrected.isOverloaded()) {
1522 OverloadCandidateSet OCS(R.getNameLoc());
1523 OverloadCandidateSet::iterator Best;
1524 for (TypoCorrection::decl_iterator CD = Corrected.begin(),
1525 CDEnd = Corrected.end();
1526 CD != CDEnd; ++CD) {
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001527 if (FunctionTemplateDecl *FTD =
Kaelyn Uhrain42830922011-08-05 00:09:52 +00001528 dyn_cast<FunctionTemplateDecl>(*CD))
1529 AddTemplateOverloadCandidate(
1530 FTD, DeclAccessPair::make(FTD, AS_none), ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001531 Args, OCS);
Kaelyn Uhrain62422202011-08-08 17:35:31 +00001532 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*CD))
1533 if (!ExplicitTemplateArgs || ExplicitTemplateArgs->size() == 0)
1534 AddOverloadCandidate(FD, DeclAccessPair::make(FD, AS_none),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001535 Args, OCS);
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001536 }
1537 switch (OCS.BestViableFunction(*this, R.getNameLoc(), Best)) {
1538 case OR_Success:
1539 ND = Best->Function;
1540 break;
1541 default:
Kaelyn Uhrainea350182011-08-04 23:30:54 +00001542 break;
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00001543 }
1544 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001545 R.addDecl(ND);
1546 if (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001547 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001548 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr
1549 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001550 else
1551 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001552 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001553 << SS.getRange()
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001554 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
1555 if (ND)
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001556 Diag(ND->getLocation(), diag::note_previous_decl)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001557 << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001558
1559 // Tell the callee to try to recover.
1560 return false;
1561 }
Alexis Huntc46382e2010-04-28 23:02:27 +00001562
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001563 if (isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND)) {
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001564 // FIXME: If we ended up with a typo for a type name or
1565 // Objective-C class name, we're in trouble because the parser
1566 // is in the wrong place to recover. Suggest the typo
1567 // correction, but don't make it a fix-it since we're not going
1568 // to recover well anyway.
1569 if (SS.isEmpty())
Richard Trieucfc491d2011-08-02 04:35:43 +00001570 Diag(R.getNameLoc(), diagnostic_suggest)
1571 << Name << CorrectedQuotedStr;
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001572 else
1573 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001574 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001575 << SS.getRange();
1576
1577 // Don't try to recover; it won't work.
1578 return true;
1579 }
1580 } else {
Alexis Huntc46382e2010-04-28 23:02:27 +00001581 // FIXME: We found a keyword. Suggest it, but don't provide a fix-it
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001582 // because we aren't able to recover.
Douglas Gregor25363982010-01-01 00:15:04 +00001583 if (SS.isEmpty())
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001584 Diag(R.getNameLoc(), diagnostic_suggest) << Name << CorrectedQuotedStr;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001585 else
Douglas Gregor25363982010-01-01 00:15:04 +00001586 Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001587 << Name << computeDeclContext(SS, false) << CorrectedQuotedStr
Douglas Gregor280e1ee2010-04-14 20:04:41 +00001588 << SS.getRange();
Douglas Gregor25363982010-01-01 00:15:04 +00001589 return true;
1590 }
Douglas Gregor598b08f2009-12-31 05:20:13 +00001591 }
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001592 R.clear();
Douglas Gregor598b08f2009-12-31 05:20:13 +00001593
1594 // Emit a special diagnostic for failed member lookups.
1595 // FIXME: computing the declaration context might fail here (?)
1596 if (!SS.isEmpty()) {
1597 Diag(R.getNameLoc(), diag::err_no_member)
1598 << Name << computeDeclContext(SS, false)
1599 << SS.getRange();
1600 return true;
1601 }
1602
John McCalld681c392009-12-16 08:11:27 +00001603 // Give up, we can't recover.
1604 Diag(R.getNameLoc(), diagnostic) << Name;
1605 return true;
1606}
1607
John McCalldadc5752010-08-24 06:29:42 +00001608ExprResult Sema::ActOnIdExpression(Scope *S,
John McCall24d18942010-08-24 22:52:39 +00001609 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001610 SourceLocation TemplateKWLoc,
John McCall24d18942010-08-24 22:52:39 +00001611 UnqualifiedId &Id,
1612 bool HasTrailingLParen,
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001613 bool IsAddressOfOperand,
1614 CorrectionCandidateCallback *CCC) {
Richard Trieuba63ce62011-09-09 01:45:06 +00001615 assert(!(IsAddressOfOperand && HasTrailingLParen) &&
John McCalle66edc12009-11-24 19:00:30 +00001616 "cannot be direct & operand and have a trailing lparen");
1617
1618 if (SS.isInvalid())
Douglas Gregored8f2882009-01-30 01:04:22 +00001619 return ExprError();
Douglas Gregor90a1a652009-03-19 17:26:29 +00001620
John McCall10eae182009-11-30 22:42:35 +00001621 TemplateArgumentListInfo TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00001622
1623 // Decompose the UnqualifiedId into the following data.
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001624 DeclarationNameInfo NameInfo;
John McCalle66edc12009-11-24 19:00:30 +00001625 const TemplateArgumentListInfo *TemplateArgs;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001626 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, NameInfo, TemplateArgs);
Douglas Gregor90a1a652009-03-19 17:26:29 +00001627
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001628 DeclarationName Name = NameInfo.getName();
Douglas Gregor4ea80432008-11-18 15:03:34 +00001629 IdentifierInfo *II = Name.getAsIdentifierInfo();
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001630 SourceLocation NameLoc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00001631
John McCalle66edc12009-11-24 19:00:30 +00001632 // C++ [temp.dep.expr]p3:
1633 // An id-expression is type-dependent if it contains:
Douglas Gregorea0a0a92010-01-11 18:40:55 +00001634 // -- an identifier that was declared with a dependent type,
1635 // (note: handled after lookup)
1636 // -- a template-id that is dependent,
1637 // (note: handled in BuildTemplateIdExpr)
1638 // -- a conversion-function-id that specifies a dependent type,
John McCalle66edc12009-11-24 19:00:30 +00001639 // -- a nested-name-specifier that contains a class-name that
1640 // names a dependent type.
1641 // Determine whether this is a member of an unknown specialization;
1642 // we need to handle these differently.
Eli Friedman964dbda2010-08-06 23:41:47 +00001643 bool DependentID = false;
1644 if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName &&
1645 Name.getCXXNameType()->isDependentType()) {
1646 DependentID = true;
1647 } else if (SS.isSet()) {
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001648 if (DeclContext *DC = computeDeclContext(SS, false)) {
Eli Friedman964dbda2010-08-06 23:41:47 +00001649 if (RequireCompleteDeclContext(SS, DC))
1650 return ExprError();
Eli Friedman964dbda2010-08-06 23:41:47 +00001651 } else {
1652 DependentID = true;
1653 }
1654 }
1655
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001656 if (DependentID)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001657 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1658 IsAddressOfOperand, TemplateArgs);
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001659
John McCalle66edc12009-11-24 19:00:30 +00001660 // Perform the required lookup.
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001661 LookupResult R(*this, NameInfo,
1662 (Id.getKind() == UnqualifiedId::IK_ImplicitSelfParam)
1663 ? LookupObjCImplicitSelfParam : LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001664 if (TemplateArgs) {
Douglas Gregor3e51e172010-05-20 20:58:56 +00001665 // Lookup the template name again to correctly establish the context in
1666 // which it was found. This is really unfortunate as we already did the
1667 // lookup to determine that it was a template name in the first place. If
1668 // this becomes a performance hit, we can work harder to preserve those
1669 // results until we get here but it's likely not worth it.
Douglas Gregor786123d2010-05-21 23:18:07 +00001670 bool MemberOfUnknownSpecialization;
1671 LookupTemplateName(R, S, SS, QualType(), /*EnteringContext=*/false,
1672 MemberOfUnknownSpecialization);
Douglas Gregora5226932011-02-04 13:35:07 +00001673
1674 if (MemberOfUnknownSpecialization ||
1675 (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001676 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1677 IsAddressOfOperand, TemplateArgs);
John McCalle66edc12009-11-24 19:00:30 +00001678 } else {
Benjamin Kramer46921442012-01-20 14:57:34 +00001679 bool IvarLookupFollowUp = II && !SS.isSet() && getCurMethodDecl();
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001680 LookupParsedName(R, S, &SS, !IvarLookupFollowUp);
Mike Stump11289f42009-09-09 15:08:12 +00001681
Douglas Gregora5226932011-02-04 13:35:07 +00001682 // If the result might be in a dependent base class, this is a dependent
1683 // id-expression.
1684 if (R.getResultKind() == LookupResult::NotFoundInCurrentInstantiation)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001685 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1686 IsAddressOfOperand, TemplateArgs);
1687
John McCalle66edc12009-11-24 19:00:30 +00001688 // If this reference is in an Objective-C method, then we need to do
1689 // some special Objective-C lookup, too.
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001690 if (IvarLookupFollowUp) {
John McCalldadc5752010-08-24 06:29:42 +00001691 ExprResult E(LookupInObjCMethod(R, S, II, true));
John McCalle66edc12009-11-24 19:00:30 +00001692 if (E.isInvalid())
1693 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00001694
Chris Lattnerebb5c6c2011-02-18 01:27:55 +00001695 if (Expr *Ex = E.takeAs<Expr>())
1696 return Owned(Ex);
Steve Naroffebf4cb42008-06-02 23:03:37 +00001697 }
Chris Lattner59a25942008-03-31 00:36:02 +00001698 }
Douglas Gregorf15f5d32009-02-16 19:28:42 +00001699
John McCalle66edc12009-11-24 19:00:30 +00001700 if (R.isAmbiguous())
1701 return ExprError();
1702
Douglas Gregor171c45a2009-02-18 21:56:37 +00001703 // Determine whether this name might be a candidate for
1704 // argument-dependent lookup.
John McCalle66edc12009-11-24 19:00:30 +00001705 bool ADL = UseArgumentDependentLookup(SS, R, HasTrailingLParen);
Douglas Gregor171c45a2009-02-18 21:56:37 +00001706
John McCalle66edc12009-11-24 19:00:30 +00001707 if (R.empty() && !ADL) {
Bill Wendling4073ed52007-02-13 01:51:42 +00001708 // Otherwise, this could be an implicitly declared function reference (legal
John McCalle66edc12009-11-24 19:00:30 +00001709 // in C90, extension in C99, forbidden in C++).
David Blaikiebbafb8a2012-03-11 07:00:24 +00001710 if (HasTrailingLParen && II && !getLangOpts().CPlusPlus) {
John McCalle66edc12009-11-24 19:00:30 +00001711 NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *II, S);
1712 if (D) R.addDecl(D);
1713 }
1714
1715 // If this name wasn't predeclared and if this is not a function
1716 // call, diagnose the problem.
1717 if (R.empty()) {
Francois Pichetd8e4e412011-09-24 10:38:05 +00001718
1719 // In Microsoft mode, if we are inside a template class member function
1720 // and we can't resolve an identifier then assume the identifier is type
1721 // dependent. The goal is to postpone name lookup to instantiation time
1722 // to be able to search into type dependent base classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001723 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetd8e4e412011-09-24 10:38:05 +00001724 isa<CXXMethodDecl>(CurContext))
Abramo Bagnara7945c982012-01-27 09:46:47 +00001725 return ActOnDependentIdExpression(SS, TemplateKWLoc, NameInfo,
1726 IsAddressOfOperand, TemplateArgs);
Francois Pichetd8e4e412011-09-24 10:38:05 +00001727
Kaelyn Uhrain79d01c12012-01-18 05:58:54 +00001728 CorrectionCandidateCallback DefaultValidator;
Kaelyn Uhrain77e21fc2012-01-25 20:49:08 +00001729 if (DiagnoseEmptyLookup(S, SS, R, CCC ? *CCC : DefaultValidator))
John McCalld681c392009-12-16 08:11:27 +00001730 return ExprError();
1731
1732 assert(!R.empty() &&
1733 "DiagnoseEmptyLookup returned false but added no results");
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001734
1735 // If we found an Objective-C instance variable, let
1736 // LookupInObjCMethod build the appropriate expression to
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001737 // reference the ivar.
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001738 if (ObjCIvarDecl *Ivar = R.getAsSingle<ObjCIvarDecl>()) {
1739 R.clear();
John McCalldadc5752010-08-24 06:29:42 +00001740 ExprResult E(LookupInObjCMethod(R, S, Ivar->getIdentifier()));
Fariborz Jahanian44653702011-09-23 23:11:38 +00001741 // In a hopelessly buggy code, Objective-C instance variable
1742 // lookup fails and no expression will be built to reference it.
1743 if (!E.isInvalid() && !E.get())
1744 return ExprError();
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001745 return move(E);
1746 }
Steve Naroff92e30f82007-04-02 22:35:25 +00001747 }
Chris Lattner17ed4872006-11-20 04:58:19 +00001748 }
Mike Stump11289f42009-09-09 15:08:12 +00001749
John McCalle66edc12009-11-24 19:00:30 +00001750 // This is guaranteed from this point on.
1751 assert(!R.empty() || ADL);
1752
John McCall2d74de92009-12-01 22:10:20 +00001753 // Check whether this might be a C++ implicit instance member access.
John McCall24d18942010-08-24 22:52:39 +00001754 // C++ [class.mfct.non-static]p3:
1755 // When an id-expression that is not part of a class member access
1756 // syntax and not used to form a pointer to member is used in the
1757 // body of a non-static member function of class X, if name lookup
1758 // resolves the name in the id-expression to a non-static non-type
1759 // member of some class C, the id-expression is transformed into a
1760 // class member access expression using (*this) as the
1761 // postfix-expression to the left of the . operator.
John McCall8d08b9b2010-08-27 09:08:28 +00001762 //
1763 // But we don't actually need to do this for '&' operands if R
1764 // resolved to a function or overloaded function set, because the
1765 // expression is ill-formed if it actually works out to be a
1766 // non-static member function:
1767 //
1768 // C++ [expr.ref]p4:
1769 // Otherwise, if E1.E2 refers to a non-static member function. . .
1770 // [t]he expression can be used only as the left-hand operand of a
1771 // member function call.
1772 //
1773 // There are other safeguards against such uses, but it's important
1774 // to get this right here so that we don't end up making a
1775 // spuriously dependent expression if we're inside a dependent
1776 // instance method.
John McCall57500772009-12-16 12:17:52 +00001777 if (!R.empty() && (*R.begin())->isCXXClassMember()) {
John McCall8d08b9b2010-08-27 09:08:28 +00001778 bool MightBeImplicitMember;
Richard Trieuba63ce62011-09-09 01:45:06 +00001779 if (!IsAddressOfOperand)
John McCall8d08b9b2010-08-27 09:08:28 +00001780 MightBeImplicitMember = true;
1781 else if (!SS.isEmpty())
1782 MightBeImplicitMember = false;
1783 else if (R.isOverloadedResult())
1784 MightBeImplicitMember = false;
Douglas Gregor1262b062010-08-30 16:00:47 +00001785 else if (R.isUnresolvableResult())
1786 MightBeImplicitMember = true;
John McCall8d08b9b2010-08-27 09:08:28 +00001787 else
Francois Pichet783dd6e2010-11-21 06:08:52 +00001788 MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
1789 isa<IndirectFieldDecl>(R.getFoundDecl());
John McCall8d08b9b2010-08-27 09:08:28 +00001790
1791 if (MightBeImplicitMember)
Abramo Bagnara7945c982012-01-27 09:46:47 +00001792 return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
1793 R, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001794 }
1795
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001796 if (TemplateArgs || TemplateKWLoc.isValid())
1797 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, ADL, TemplateArgs);
John McCallb53bbd42009-11-22 01:44:31 +00001798
John McCalle66edc12009-11-24 19:00:30 +00001799 return BuildDeclarationNameExpr(SS, R, ADL);
1800}
1801
John McCall10eae182009-11-30 22:42:35 +00001802/// BuildQualifiedDeclarationNameExpr - Build a C++ qualified
1803/// declaration name, generally during template instantiation.
1804/// There's a large number of things which don't need to be done along
1805/// this path.
John McCalldadc5752010-08-24 06:29:42 +00001806ExprResult
Jeffrey Yasskinc76498d2010-04-08 16:38:48 +00001807Sema::BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001808 const DeclarationNameInfo &NameInfo) {
John McCalle66edc12009-11-24 19:00:30 +00001809 DeclContext *DC;
Douglas Gregora02bb342010-04-28 07:04:26 +00001810 if (!(DC = computeDeclContext(SS, false)) || DC->isDependentContext())
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +00001811 return BuildDependentDeclRefExpr(SS, /*TemplateKWLoc=*/SourceLocation(),
1812 NameInfo, /*TemplateArgs=*/0);
John McCalle66edc12009-11-24 19:00:30 +00001813
John McCall0b66eb32010-05-01 00:40:08 +00001814 if (RequireCompleteDeclContext(SS, DC))
Douglas Gregora02bb342010-04-28 07:04:26 +00001815 return ExprError();
1816
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001817 LookupResult R(*this, NameInfo, LookupOrdinaryName);
John McCalle66edc12009-11-24 19:00:30 +00001818 LookupQualifiedName(R, DC);
1819
1820 if (R.isAmbiguous())
1821 return ExprError();
1822
1823 if (R.empty()) {
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00001824 Diag(NameInfo.getLoc(), diag::err_no_member)
1825 << NameInfo.getName() << DC << SS.getRange();
John McCalle66edc12009-11-24 19:00:30 +00001826 return ExprError();
1827 }
1828
1829 return BuildDeclarationNameExpr(SS, R, /*ADL*/ false);
1830}
1831
1832/// LookupInObjCMethod - The parser has read a name in, and Sema has
1833/// detected that we're currently inside an ObjC method. Perform some
1834/// additional lookup.
1835///
1836/// Ideally, most of this would be done by lookup, but there's
1837/// actually quite a lot of extra work involved.
1838///
1839/// Returns a null sentinel to indicate trivial success.
John McCalldadc5752010-08-24 06:29:42 +00001840ExprResult
John McCalle66edc12009-11-24 19:00:30 +00001841Sema::LookupInObjCMethod(LookupResult &Lookup, Scope *S,
Chris Lattnera36ec422010-04-11 08:28:14 +00001842 IdentifierInfo *II, bool AllowBuiltinCreation) {
John McCalle66edc12009-11-24 19:00:30 +00001843 SourceLocation Loc = Lookup.getNameLoc();
Chris Lattner87313662010-04-12 05:10:17 +00001844 ObjCMethodDecl *CurMethod = getCurMethodDecl();
Alexis Huntc46382e2010-04-28 23:02:27 +00001845
John McCalle66edc12009-11-24 19:00:30 +00001846 // There are two cases to handle here. 1) scoped lookup could have failed,
1847 // in which case we should look for an ivar. 2) scoped lookup could have
1848 // found a decl, but that decl is outside the current instance method (i.e.
1849 // a global variable). In these two cases, we do a lookup for an ivar with
1850 // this name, if the lookup sucedes, we replace it our current decl.
1851
1852 // If we're in a class method, we don't normally want to look for
1853 // ivars. But if we don't find anything else, and there's an
1854 // ivar, that's an error.
Chris Lattner87313662010-04-12 05:10:17 +00001855 bool IsClassMethod = CurMethod->isClassMethod();
John McCalle66edc12009-11-24 19:00:30 +00001856
1857 bool LookForIvars;
1858 if (Lookup.empty())
1859 LookForIvars = true;
1860 else if (IsClassMethod)
1861 LookForIvars = false;
1862 else
1863 LookForIvars = (Lookup.isSingleResult() &&
1864 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod());
Fariborz Jahanian45878032010-02-09 19:31:38 +00001865 ObjCInterfaceDecl *IFace = 0;
John McCalle66edc12009-11-24 19:00:30 +00001866 if (LookForIvars) {
Chris Lattner87313662010-04-12 05:10:17 +00001867 IFace = CurMethod->getClassInterface();
John McCalle66edc12009-11-24 19:00:30 +00001868 ObjCInterfaceDecl *ClassDeclared;
Argyrios Kyrtzidis4e8b1362011-10-19 02:25:16 +00001869 ObjCIvarDecl *IV = 0;
1870 if (IFace && (IV = IFace->lookupInstanceVariable(II, ClassDeclared))) {
John McCalle66edc12009-11-24 19:00:30 +00001871 // Diagnose using an ivar in a class method.
1872 if (IsClassMethod)
1873 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1874 << IV->getDeclName());
1875
1876 // If we're referencing an invalid decl, just return this as a silent
1877 // error node. The error diagnostic was already emitted on the decl.
1878 if (IV->isInvalidDecl())
1879 return ExprError();
1880
1881 // Check if referencing a field with __attribute__((deprecated)).
1882 if (DiagnoseUseOfDecl(IV, Loc))
1883 return ExprError();
1884
1885 // Diagnose the use of an ivar outside of the declaring class.
1886 if (IV->getAccessControl() == ObjCIvarDecl::Private &&
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001887 !declaresSameEntity(ClassDeclared, IFace) &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00001888 !getLangOpts().DebuggerSupport)
John McCalle66edc12009-11-24 19:00:30 +00001889 Diag(Loc, diag::error_private_ivar_access) << IV->getDeclName();
1890
1891 // FIXME: This should use a new expr for a direct reference, don't
1892 // turn this into Self->ivar, just return a BareIVarExpr or something.
1893 IdentifierInfo &II = Context.Idents.get("self");
1894 UnqualifiedId SelfName;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001895 SelfName.setIdentifier(&II, SourceLocation());
Fariborz Jahanian7f4427f2011-07-12 17:16:56 +00001896 SelfName.setKind(UnqualifiedId::IK_ImplicitSelfParam);
John McCalle66edc12009-11-24 19:00:30 +00001897 CXXScopeSpec SelfScopeSpec;
Abramo Bagnara7945c982012-01-27 09:46:47 +00001898 SourceLocation TemplateKWLoc;
1899 ExprResult SelfExpr = ActOnIdExpression(S, SelfScopeSpec, TemplateKWLoc,
Douglas Gregora1ed39b2010-09-22 16:33:13 +00001900 SelfName, false, false);
1901 if (SelfExpr.isInvalid())
1902 return ExprError();
1903
John Wiegley01296292011-04-08 18:41:53 +00001904 SelfExpr = DefaultLvalueConversion(SelfExpr.take());
1905 if (SelfExpr.isInvalid())
1906 return ExprError();
John McCall27584242010-12-06 20:48:59 +00001907
Eli Friedmanfa0df832012-02-02 03:46:19 +00001908 MarkAnyDeclReferenced(Loc, IV);
John McCalle66edc12009-11-24 19:00:30 +00001909 return Owned(new (Context)
1910 ObjCIvarRefExpr(IV, IV->getType(), Loc,
John Wiegley01296292011-04-08 18:41:53 +00001911 SelfExpr.take(), true, true));
John McCalle66edc12009-11-24 19:00:30 +00001912 }
Chris Lattner87313662010-04-12 05:10:17 +00001913 } else if (CurMethod->isInstanceMethod()) {
John McCalle66edc12009-11-24 19:00:30 +00001914 // We should warn if a local variable hides an ivar.
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001915 if (ObjCInterfaceDecl *IFace = CurMethod->getClassInterface()) {
1916 ObjCInterfaceDecl *ClassDeclared;
1917 if (ObjCIvarDecl *IV = IFace->lookupInstanceVariable(II, ClassDeclared)) {
1918 if (IV->getAccessControl() != ObjCIvarDecl::Private ||
Douglas Gregor0b144e12011-12-15 00:29:59 +00001919 declaresSameEntity(IFace, ClassDeclared))
Fariborz Jahanian557fc9a2011-11-08 22:51:27 +00001920 Diag(Loc, diag::warn_ivar_use_hidden) << IV->getDeclName();
1921 }
John McCalle66edc12009-11-24 19:00:30 +00001922 }
Fariborz Jahanian028b9e12011-12-20 22:21:08 +00001923 } else if (Lookup.isSingleResult() &&
1924 Lookup.getFoundDecl()->isDefinedOutsideFunctionOrMethod()) {
1925 // If accessing a stand-alone ivar in a class method, this is an error.
1926 if (const ObjCIvarDecl *IV = dyn_cast<ObjCIvarDecl>(Lookup.getFoundDecl()))
1927 return ExprError(Diag(Loc, diag::error_ivar_use_in_class_method)
1928 << IV->getDeclName());
John McCalle66edc12009-11-24 19:00:30 +00001929 }
1930
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001931 if (Lookup.empty() && II && AllowBuiltinCreation) {
1932 // FIXME. Consolidate this with similar code in LookupName.
1933 if (unsigned BuiltinID = II->getBuiltinID()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001934 if (!(getLangOpts().CPlusPlus &&
Fariborz Jahanian6fada5b2010-01-12 23:58:59 +00001935 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))) {
1936 NamedDecl *D = LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
1937 S, Lookup.isForRedeclaration(),
1938 Lookup.getNameLoc());
1939 if (D) Lookup.addDecl(D);
1940 }
1941 }
1942 }
John McCalle66edc12009-11-24 19:00:30 +00001943 // Sentinel value saying that we didn't do anything special.
1944 return Owned((Expr*) 0);
Douglas Gregor3256d042009-06-30 15:47:41 +00001945}
John McCalld14a8642009-11-21 08:51:07 +00001946
John McCall16df1e52010-03-30 21:47:33 +00001947/// \brief Cast a base object to a member's actual type.
1948///
1949/// Logically this happens in three phases:
1950///
1951/// * First we cast from the base type to the naming class.
1952/// The naming class is the class into which we were looking
1953/// when we found the member; it's the qualifier type if a
1954/// qualifier was provided, and otherwise it's the base type.
1955///
1956/// * Next we cast from the naming class to the declaring class.
1957/// If the member we found was brought into a class's scope by
1958/// a using declaration, this is that class; otherwise it's
1959/// the class declaring the member.
1960///
1961/// * Finally we cast from the declaring class to the "true"
1962/// declaring class of the member. This conversion does not
1963/// obey access control.
John Wiegley01296292011-04-08 18:41:53 +00001964ExprResult
1965Sema::PerformObjectMemberConversion(Expr *From,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001966 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00001967 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001968 NamedDecl *Member) {
1969 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Member->getDeclContext());
1970 if (!RD)
John Wiegley01296292011-04-08 18:41:53 +00001971 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001972
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001973 QualType DestRecordType;
1974 QualType DestType;
1975 QualType FromRecordType;
1976 QualType FromType = From->getType();
1977 bool PointerConversions = false;
1978 if (isa<FieldDecl>(Member)) {
1979 DestRecordType = Context.getCanonicalType(Context.getTypeDeclType(RD));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001980
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001981 if (FromType->getAs<PointerType>()) {
1982 DestType = Context.getPointerType(DestRecordType);
1983 FromRecordType = FromType->getPointeeType();
1984 PointerConversions = true;
1985 } else {
1986 DestType = DestRecordType;
1987 FromRecordType = FromType;
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00001988 }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001989 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Member)) {
1990 if (Method->isStatic())
John Wiegley01296292011-04-08 18:41:53 +00001991 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001992
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001993 DestType = Method->getThisType(Context);
1994 DestRecordType = DestType->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00001995
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001996 if (FromType->getAs<PointerType>()) {
1997 FromRecordType = FromType->getPointeeType();
1998 PointerConversions = true;
1999 } else {
2000 FromRecordType = FromType;
2001 DestType = DestRecordType;
2002 }
2003 } else {
2004 // No conversion necessary.
John Wiegley01296292011-04-08 18:41:53 +00002005 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002006 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002007
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002008 if (DestType->isDependentType() || FromType->isDependentType())
John Wiegley01296292011-04-08 18:41:53 +00002009 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002010
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002011 // If the unqualified types are the same, no conversion is necessary.
2012 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002013 return Owned(From);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002014
John McCall16df1e52010-03-30 21:47:33 +00002015 SourceRange FromRange = From->getSourceRange();
2016 SourceLocation FromLoc = FromRange.getBegin();
2017
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002018 ExprValueKind VK = From->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002019
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002020 // C++ [class.member.lookup]p8:
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002021 // [...] Ambiguities can often be resolved by qualifying a name with its
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002022 // class name.
2023 //
2024 // If the member was a qualified name and the qualified referred to a
2025 // specific base subobject type, we'll cast to that intermediate type
2026 // first and then to the object in which the member is declared. That allows
2027 // one to resolve ambiguities in, e.g., a diamond-shaped hierarchy such as:
2028 //
2029 // class Base { public: int x; };
2030 // class Derived1 : public Base { };
2031 // class Derived2 : public Base { };
2032 // class VeryDerived : public Derived1, public Derived2 { void f(); };
2033 //
2034 // void VeryDerived::f() {
2035 // x = 17; // error: ambiguous base subobjects
2036 // Derived1::x = 17; // okay, pick the Base subobject of Derived1
2037 // }
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002038 if (Qualifier) {
John McCall16df1e52010-03-30 21:47:33 +00002039 QualType QType = QualType(Qualifier->getAsType(), 0);
2040 assert(!QType.isNull() && "lookup done with dependent qualifier?");
2041 assert(QType->isRecordType() && "lookup done with non-record type");
2042
2043 QualType QRecordType = QualType(QType->getAs<RecordType>(), 0);
2044
2045 // In C++98, the qualifier type doesn't actually have to be a base
2046 // type of the object type, in which case we just ignore it.
2047 // Otherwise build the appropriate casts.
2048 if (IsDerivedFrom(FromRecordType, QRecordType)) {
John McCallcf142162010-08-07 06:22:56 +00002049 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002050 if (CheckDerivedToBaseConversion(FromRecordType, QRecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002051 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002052 return ExprError();
John McCall16df1e52010-03-30 21:47:33 +00002053
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002054 if (PointerConversions)
John McCall16df1e52010-03-30 21:47:33 +00002055 QType = Context.getPointerType(QType);
John Wiegley01296292011-04-08 18:41:53 +00002056 From = ImpCastExprToType(From, QType, CK_UncheckedDerivedToBase,
2057 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002058
2059 FromType = QType;
2060 FromRecordType = QRecordType;
2061
2062 // If the qualifier type was the same as the destination type,
2063 // we're done.
2064 if (Context.hasSameUnqualifiedType(FromRecordType, DestRecordType))
John Wiegley01296292011-04-08 18:41:53 +00002065 return Owned(From);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002066 }
2067 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002068
John McCall16df1e52010-03-30 21:47:33 +00002069 bool IgnoreAccess = false;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002070
John McCall16df1e52010-03-30 21:47:33 +00002071 // If we actually found the member through a using declaration, cast
2072 // down to the using declaration's type.
2073 //
2074 // Pointer equality is fine here because only one declaration of a
2075 // class ever has member declarations.
2076 if (FoundDecl->getDeclContext() != Member->getDeclContext()) {
2077 assert(isa<UsingShadowDecl>(FoundDecl));
2078 QualType URecordType = Context.getTypeDeclType(
2079 cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
2080
2081 // We only need to do this if the naming-class to declaring-class
2082 // conversion is non-trivial.
2083 if (!Context.hasSameUnqualifiedType(FromRecordType, URecordType)) {
2084 assert(IsDerivedFrom(FromRecordType, URecordType));
John McCallcf142162010-08-07 06:22:56 +00002085 CXXCastPath BasePath;
John McCall16df1e52010-03-30 21:47:33 +00002086 if (CheckDerivedToBaseConversion(FromRecordType, URecordType,
Anders Carlssonb78feca2010-04-24 19:22:20 +00002087 FromLoc, FromRange, &BasePath))
John Wiegley01296292011-04-08 18:41:53 +00002088 return ExprError();
Alexis Huntc46382e2010-04-28 23:02:27 +00002089
John McCall16df1e52010-03-30 21:47:33 +00002090 QualType UType = URecordType;
2091 if (PointerConversions)
2092 UType = Context.getPointerType(UType);
John Wiegley01296292011-04-08 18:41:53 +00002093 From = ImpCastExprToType(From, UType, CK_UncheckedDerivedToBase,
2094 VK, &BasePath).take();
John McCall16df1e52010-03-30 21:47:33 +00002095 FromType = UType;
2096 FromRecordType = URecordType;
2097 }
2098
2099 // We don't do access control for the conversion from the
2100 // declaring class to the true declaring class.
2101 IgnoreAccess = true;
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002102 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002103
John McCallcf142162010-08-07 06:22:56 +00002104 CXXCastPath BasePath;
Anders Carlssonb78feca2010-04-24 19:22:20 +00002105 if (CheckDerivedToBaseConversion(FromRecordType, DestRecordType,
2106 FromLoc, FromRange, &BasePath,
John McCall16df1e52010-03-30 21:47:33 +00002107 IgnoreAccess))
John Wiegley01296292011-04-08 18:41:53 +00002108 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002109
John Wiegley01296292011-04-08 18:41:53 +00002110 return ImpCastExprToType(From, DestType, CK_UncheckedDerivedToBase,
2111 VK, &BasePath);
Fariborz Jahanianbb67b822009-07-29 18:40:24 +00002112}
Douglas Gregor3256d042009-06-30 15:47:41 +00002113
John McCalle66edc12009-11-24 19:00:30 +00002114bool Sema::UseArgumentDependentLookup(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002115 const LookupResult &R,
2116 bool HasTrailingLParen) {
John McCalld14a8642009-11-21 08:51:07 +00002117 // Only when used directly as the postfix-expression of a call.
2118 if (!HasTrailingLParen)
2119 return false;
2120
2121 // Never if a scope specifier was provided.
John McCalle66edc12009-11-24 19:00:30 +00002122 if (SS.isSet())
John McCalld14a8642009-11-21 08:51:07 +00002123 return false;
2124
2125 // Only in C++ or ObjC++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002126 if (!getLangOpts().CPlusPlus)
John McCalld14a8642009-11-21 08:51:07 +00002127 return false;
2128
2129 // Turn off ADL when we find certain kinds of declarations during
2130 // normal lookup:
2131 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
2132 NamedDecl *D = *I;
2133
2134 // C++0x [basic.lookup.argdep]p3:
2135 // -- a declaration of a class member
2136 // Since using decls preserve this property, we check this on the
2137 // original decl.
John McCall57500772009-12-16 12:17:52 +00002138 if (D->isCXXClassMember())
John McCalld14a8642009-11-21 08:51:07 +00002139 return false;
2140
2141 // C++0x [basic.lookup.argdep]p3:
2142 // -- a block-scope function declaration that is not a
2143 // using-declaration
2144 // NOTE: we also trigger this for function templates (in fact, we
2145 // don't check the decl type at all, since all other decl types
2146 // turn off ADL anyway).
2147 if (isa<UsingShadowDecl>(D))
2148 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2149 else if (D->getDeclContext()->isFunctionOrMethod())
2150 return false;
2151
2152 // C++0x [basic.lookup.argdep]p3:
2153 // -- a declaration that is neither a function or a function
2154 // template
2155 // And also for builtin functions.
2156 if (isa<FunctionDecl>(D)) {
2157 FunctionDecl *FDecl = cast<FunctionDecl>(D);
2158
2159 // But also builtin functions.
2160 if (FDecl->getBuiltinID() && FDecl->isImplicit())
2161 return false;
2162 } else if (!isa<FunctionTemplateDecl>(D))
2163 return false;
2164 }
2165
2166 return true;
2167}
2168
2169
John McCalld14a8642009-11-21 08:51:07 +00002170/// Diagnoses obvious problems with the use of the given declaration
2171/// as an expression. This is only actually called for lookups that
2172/// were not overloaded, and it doesn't promise that the declaration
2173/// will in fact be used.
2174static bool CheckDeclInExpr(Sema &S, SourceLocation Loc, NamedDecl *D) {
Richard Smithdda56e42011-04-15 14:24:37 +00002175 if (isa<TypedefNameDecl>(D)) {
John McCalld14a8642009-11-21 08:51:07 +00002176 S.Diag(Loc, diag::err_unexpected_typedef) << D->getDeclName();
2177 return true;
2178 }
2179
2180 if (isa<ObjCInterfaceDecl>(D)) {
2181 S.Diag(Loc, diag::err_unexpected_interface) << D->getDeclName();
2182 return true;
2183 }
2184
2185 if (isa<NamespaceDecl>(D)) {
2186 S.Diag(Loc, diag::err_unexpected_namespace) << D->getDeclName();
2187 return true;
2188 }
2189
2190 return false;
2191}
2192
John McCalldadc5752010-08-24 06:29:42 +00002193ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002194Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
John McCallb53bbd42009-11-22 01:44:31 +00002195 LookupResult &R,
2196 bool NeedsADL) {
John McCall3a60c872009-12-08 22:45:53 +00002197 // If this is a single, fully-resolved result and we don't need ADL,
2198 // just build an ordinary singleton decl ref.
Douglas Gregor4b4844f2010-01-29 17:15:43 +00002199 if (!NeedsADL && R.isSingleResult() && !R.getAsSingle<FunctionTemplateDecl>())
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002200 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(),
2201 R.getFoundDecl());
John McCalld14a8642009-11-21 08:51:07 +00002202
2203 // We only need to check the declaration if there's exactly one
2204 // result, because in the overloaded case the results can only be
2205 // functions and function templates.
John McCallb53bbd42009-11-22 01:44:31 +00002206 if (R.isSingleResult() &&
2207 CheckDeclInExpr(*this, R.getNameLoc(), R.getFoundDecl()))
John McCalld14a8642009-11-21 08:51:07 +00002208 return ExprError();
2209
John McCall58cc69d2010-01-27 01:50:18 +00002210 // Otherwise, just build an unresolved lookup expression. Suppress
2211 // any lookup-related diagnostics; we'll hash these out later, when
2212 // we've picked a target.
2213 R.suppressDiagnostics();
2214
John McCalld14a8642009-11-21 08:51:07 +00002215 UnresolvedLookupExpr *ULE
Douglas Gregora6e053e2010-12-15 01:34:56 +00002216 = UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
Douglas Gregor0da1d432011-02-28 20:01:57 +00002217 SS.getWithLocInContext(Context),
2218 R.getLookupNameInfo(),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00002219 NeedsADL, R.isOverloadedResult(),
2220 R.begin(), R.end());
John McCalld14a8642009-11-21 08:51:07 +00002221
2222 return Owned(ULE);
2223}
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002224
John McCalld14a8642009-11-21 08:51:07 +00002225/// \brief Complete semantic analysis for a reference to the given declaration.
John McCalldadc5752010-08-24 06:29:42 +00002226ExprResult
John McCalle66edc12009-11-24 19:00:30 +00002227Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002228 const DeclarationNameInfo &NameInfo,
2229 NamedDecl *D) {
John McCalld14a8642009-11-21 08:51:07 +00002230 assert(D && "Cannot refer to a NULL declaration");
John McCall283b9012009-11-22 00:44:51 +00002231 assert(!isa<FunctionTemplateDecl>(D) &&
2232 "Cannot refer unambiguously to a function template");
John McCalld14a8642009-11-21 08:51:07 +00002233
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00002234 SourceLocation Loc = NameInfo.getLoc();
John McCalld14a8642009-11-21 08:51:07 +00002235 if (CheckDeclInExpr(*this, Loc, D))
2236 return ExprError();
Steve Narofff1e53692007-03-23 22:27:02 +00002237
Douglas Gregore7488b92009-12-01 16:58:18 +00002238 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) {
2239 // Specifically diagnose references to class templates that are missing
2240 // a template argument list.
2241 Diag(Loc, diag::err_template_decl_ref)
2242 << Template << SS.getRange();
2243 Diag(Template->getLocation(), diag::note_template_decl_here);
2244 return ExprError();
2245 }
2246
2247 // Make sure that we're referring to a value.
2248 ValueDecl *VD = dyn_cast<ValueDecl>(D);
2249 if (!VD) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00002250 Diag(Loc, diag::err_ref_non_value)
Douglas Gregore7488b92009-12-01 16:58:18 +00002251 << D << SS.getRange();
John McCallb48971d2009-12-18 18:35:10 +00002252 Diag(D->getLocation(), diag::note_declared_at);
Douglas Gregore7488b92009-12-01 16:58:18 +00002253 return ExprError();
2254 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002255
Douglas Gregor171c45a2009-02-18 21:56:37 +00002256 // Check whether this declaration can be used. Note that we suppress
2257 // this check when we're going to perform argument-dependent lookup
2258 // on this function name, because this might not be the function
2259 // that overload resolution actually selects.
John McCalld14a8642009-11-21 08:51:07 +00002260 if (DiagnoseUseOfDecl(VD, Loc))
Douglas Gregor171c45a2009-02-18 21:56:37 +00002261 return ExprError();
2262
Steve Naroff8de9c3a2008-09-05 22:11:13 +00002263 // Only create DeclRefExpr's for valid Decl's.
2264 if (VD->isInvalidDecl())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002265 return ExprError();
2266
John McCallf3a88602011-02-03 08:15:49 +00002267 // Handle members of anonymous structs and unions. If we got here,
2268 // and the reference is to a class member indirect field, then this
2269 // must be the subject of a pointer-to-member expression.
2270 if (IndirectFieldDecl *indirectField = dyn_cast<IndirectFieldDecl>(VD))
2271 if (!indirectField->isCXXClassMember())
2272 return BuildAnonymousStructUnionMemberReference(SS, NameInfo.getLoc(),
2273 indirectField);
Francois Pichet783dd6e2010-11-21 06:08:52 +00002274
Eli Friedman9bb33f52012-02-03 02:04:35 +00002275 {
John McCallf4cd4f92011-02-09 01:13:10 +00002276 QualType type = VD->getType();
Daniel Dunbar7c2dc362011-02-10 18:29:28 +00002277 ExprValueKind valueKind = VK_RValue;
John McCallf4cd4f92011-02-09 01:13:10 +00002278
2279 switch (D->getKind()) {
2280 // Ignore all the non-ValueDecl kinds.
2281#define ABSTRACT_DECL(kind)
2282#define VALUE(type, base)
2283#define DECL(type, base) \
2284 case Decl::type:
2285#include "clang/AST/DeclNodes.inc"
2286 llvm_unreachable("invalid value decl kind");
John McCallf4cd4f92011-02-09 01:13:10 +00002287
2288 // These shouldn't make it here.
2289 case Decl::ObjCAtDefsField:
2290 case Decl::ObjCIvar:
2291 llvm_unreachable("forming non-member reference to ivar?");
John McCallf4cd4f92011-02-09 01:13:10 +00002292
2293 // Enum constants are always r-values and never references.
2294 // Unresolved using declarations are dependent.
2295 case Decl::EnumConstant:
2296 case Decl::UnresolvedUsingValue:
2297 valueKind = VK_RValue;
2298 break;
2299
2300 // Fields and indirect fields that got here must be for
2301 // pointer-to-member expressions; we just call them l-values for
2302 // internal consistency, because this subexpression doesn't really
2303 // exist in the high-level semantics.
2304 case Decl::Field:
2305 case Decl::IndirectField:
David Blaikiebbafb8a2012-03-11 07:00:24 +00002306 assert(getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002307 "building reference to field in C?");
2308
2309 // These can't have reference type in well-formed programs, but
2310 // for internal consistency we do this anyway.
2311 type = type.getNonReferenceType();
2312 valueKind = VK_LValue;
2313 break;
2314
2315 // Non-type template parameters are either l-values or r-values
2316 // depending on the type.
2317 case Decl::NonTypeTemplateParm: {
2318 if (const ReferenceType *reftype = type->getAs<ReferenceType>()) {
2319 type = reftype->getPointeeType();
2320 valueKind = VK_LValue; // even if the parameter is an r-value reference
2321 break;
2322 }
2323
2324 // For non-references, we need to strip qualifiers just in case
2325 // the template parameter was declared as 'const int' or whatever.
2326 valueKind = VK_RValue;
2327 type = type.getUnqualifiedType();
2328 break;
2329 }
2330
2331 case Decl::Var:
2332 // In C, "extern void blah;" is valid and is an r-value.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002333 if (!getLangOpts().CPlusPlus &&
John McCallf4cd4f92011-02-09 01:13:10 +00002334 !type.hasQualifiers() &&
2335 type->isVoidType()) {
2336 valueKind = VK_RValue;
2337 break;
2338 }
2339 // fallthrough
2340
2341 case Decl::ImplicitParam:
Douglas Gregor812d8f62012-02-18 05:51:20 +00002342 case Decl::ParmVar: {
John McCallf4cd4f92011-02-09 01:13:10 +00002343 // These are always l-values.
2344 valueKind = VK_LValue;
2345 type = type.getNonReferenceType();
Eli Friedman9bb33f52012-02-03 02:04:35 +00002346
Douglas Gregor812d8f62012-02-18 05:51:20 +00002347 // FIXME: Does the addition of const really only apply in
2348 // potentially-evaluated contexts? Since the variable isn't actually
2349 // captured in an unevaluated context, it seems that the answer is no.
2350 if (ExprEvalContexts.back().Context != Sema::Unevaluated) {
2351 QualType CapturedType = getCapturedDeclRefType(cast<VarDecl>(VD), Loc);
2352 if (!CapturedType.isNull())
2353 type = CapturedType;
2354 }
2355
John McCallf4cd4f92011-02-09 01:13:10 +00002356 break;
Douglas Gregor812d8f62012-02-18 05:51:20 +00002357 }
2358
John McCallf4cd4f92011-02-09 01:13:10 +00002359 case Decl::Function: {
John McCall2979fe02011-04-12 00:42:48 +00002360 const FunctionType *fty = type->castAs<FunctionType>();
2361
2362 // If we're referring to a function with an __unknown_anytype
2363 // result type, make the entire expression __unknown_anytype.
2364 if (fty->getResultType() == Context.UnknownAnyTy) {
2365 type = Context.UnknownAnyTy;
2366 valueKind = VK_RValue;
2367 break;
2368 }
2369
John McCallf4cd4f92011-02-09 01:13:10 +00002370 // Functions are l-values in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002371 if (getLangOpts().CPlusPlus) {
John McCallf4cd4f92011-02-09 01:13:10 +00002372 valueKind = VK_LValue;
2373 break;
2374 }
2375
2376 // C99 DR 316 says that, if a function type comes from a
2377 // function definition (without a prototype), that type is only
2378 // used for checking compatibility. Therefore, when referencing
2379 // the function, we pretend that we don't have the full function
2380 // type.
John McCall2979fe02011-04-12 00:42:48 +00002381 if (!cast<FunctionDecl>(VD)->hasPrototype() &&
2382 isa<FunctionProtoType>(fty))
2383 type = Context.getFunctionNoProtoType(fty->getResultType(),
2384 fty->getExtInfo());
John McCallf4cd4f92011-02-09 01:13:10 +00002385
2386 // Functions are r-values in C.
2387 valueKind = VK_RValue;
2388 break;
2389 }
2390
2391 case Decl::CXXMethod:
John McCall2979fe02011-04-12 00:42:48 +00002392 // If we're referring to a method with an __unknown_anytype
2393 // result type, make the entire expression __unknown_anytype.
2394 // This should only be possible with a type written directly.
Richard Trieucfc491d2011-08-02 04:35:43 +00002395 if (const FunctionProtoType *proto
2396 = dyn_cast<FunctionProtoType>(VD->getType()))
John McCall2979fe02011-04-12 00:42:48 +00002397 if (proto->getResultType() == Context.UnknownAnyTy) {
2398 type = Context.UnknownAnyTy;
2399 valueKind = VK_RValue;
2400 break;
2401 }
2402
John McCallf4cd4f92011-02-09 01:13:10 +00002403 // C++ methods are l-values if static, r-values if non-static.
2404 if (cast<CXXMethodDecl>(VD)->isStatic()) {
2405 valueKind = VK_LValue;
2406 break;
2407 }
2408 // fallthrough
2409
2410 case Decl::CXXConversion:
2411 case Decl::CXXDestructor:
2412 case Decl::CXXConstructor:
2413 valueKind = VK_RValue;
2414 break;
2415 }
2416
2417 return BuildDeclRefExpr(VD, type, valueKind, NameInfo, &SS);
2418 }
Chris Lattner17ed4872006-11-20 04:58:19 +00002419}
Chris Lattnere168f762006-11-10 05:29:30 +00002420
John McCall2979fe02011-04-12 00:42:48 +00002421ExprResult Sema::ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind) {
Chris Lattner6307f192008-08-10 01:53:14 +00002422 PredefinedExpr::IdentType IT;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002423
Chris Lattnere168f762006-11-10 05:29:30 +00002424 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002425 default: llvm_unreachable("Unknown simple primary expr!");
Chris Lattner6307f192008-08-10 01:53:14 +00002426 case tok::kw___func__: IT = PredefinedExpr::Func; break; // [C99 6.4.2.2]
2427 case tok::kw___FUNCTION__: IT = PredefinedExpr::Function; break;
2428 case tok::kw___PRETTY_FUNCTION__: IT = PredefinedExpr::PrettyFunction; break;
Chris Lattnere168f762006-11-10 05:29:30 +00002429 }
Chris Lattner317e6ba2008-01-12 18:39:25 +00002430
Chris Lattnera81a0272008-01-12 08:14:25 +00002431 // Pre-defined identifiers are of type char[x], where x is the length of the
2432 // string.
Mike Stump11289f42009-09-09 15:08:12 +00002433
Anders Carlsson2fb08242009-09-08 18:24:21 +00002434 Decl *currentDecl = getCurFunctionOrMethodDecl();
Fariborz Jahanian94627442010-07-23 21:53:24 +00002435 if (!currentDecl && getCurBlock())
2436 currentDecl = getCurBlock()->TheDecl;
Anders Carlsson2fb08242009-09-08 18:24:21 +00002437 if (!currentDecl) {
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002438 Diag(Loc, diag::ext_predef_outside_function);
Anders Carlsson2fb08242009-09-08 18:24:21 +00002439 currentDecl = Context.getTranslationUnitDecl();
Chris Lattnerf45c5ec2008-12-12 05:05:20 +00002440 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002441
Anders Carlsson0b209a82009-09-11 01:22:35 +00002442 QualType ResTy;
2443 if (cast<DeclContext>(currentDecl)->isDependentContext()) {
2444 ResTy = Context.DependentTy;
2445 } else {
Anders Carlsson5bd8d192010-02-11 18:20:28 +00002446 unsigned Length = PredefinedExpr::ComputeName(IT, currentDecl).length();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002447
Anders Carlsson0b209a82009-09-11 01:22:35 +00002448 llvm::APInt LengthI(32, Length + 1);
John McCall8ccfcb52009-09-24 19:53:00 +00002449 ResTy = Context.CharTy.withConst();
Anders Carlsson0b209a82009-09-11 01:22:35 +00002450 ResTy = Context.getConstantArrayType(ResTy, LengthI, ArrayType::Normal, 0);
2451 }
Steve Narofff6009ed2009-01-21 00:14:39 +00002452 return Owned(new (Context) PredefinedExpr(Loc, ResTy, IT));
Chris Lattnere168f762006-11-10 05:29:30 +00002453}
2454
Richard Smithbcc22fc2012-03-09 08:00:36 +00002455ExprResult Sema::ActOnCharacterConstant(const Token &Tok, Scope *UDLScope) {
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002456 SmallString<16> CharBuffer;
Douglas Gregordc970f02010-03-16 22:30:13 +00002457 bool Invalid = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002458 StringRef ThisTok = PP.getSpelling(Tok, CharBuffer, &Invalid);
Douglas Gregordc970f02010-03-16 22:30:13 +00002459 if (Invalid)
2460 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002461
Benjamin Kramer0a1abd42010-02-27 13:44:12 +00002462 CharLiteralParser Literal(ThisTok.begin(), ThisTok.end(), Tok.getLocation(),
Douglas Gregorfb65e592011-07-27 05:40:30 +00002463 PP, Tok.getKind());
Steve Naroffae4143e2007-04-26 20:39:23 +00002464 if (Literal.hadError())
Sebastian Redlffbcf962009-01-18 18:53:16 +00002465 return ExprError();
Chris Lattneref24b382008-03-01 08:32:21 +00002466
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002467 QualType Ty;
Seth Cantrell02f86052012-01-18 12:27:06 +00002468 if (Literal.isWide())
2469 Ty = Context.WCharTy; // L'x' -> wchar_t in C and C++.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002470 else if (Literal.isUTF16())
Seth Cantrell02f86052012-01-18 12:27:06 +00002471 Ty = Context.Char16Ty; // u'x' -> char16_t in C11 and C++11.
Douglas Gregorfb65e592011-07-27 05:40:30 +00002472 else if (Literal.isUTF32())
Seth Cantrell02f86052012-01-18 12:27:06 +00002473 Ty = Context.Char32Ty; // U'x' -> char32_t in C11 and C++11.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002474 else if (!getLangOpts().CPlusPlus || Literal.isMultiChar())
Seth Cantrell02f86052012-01-18 12:27:06 +00002475 Ty = Context.IntTy; // 'x' -> int in C, 'wxyz' -> int in C++.
Chris Lattnerc3847ba2009-12-30 21:19:39 +00002476 else
2477 Ty = Context.CharTy; // 'x' -> char in C++
Chris Lattneref24b382008-03-01 08:32:21 +00002478
Douglas Gregorfb65e592011-07-27 05:40:30 +00002479 CharacterLiteral::CharacterKind Kind = CharacterLiteral::Ascii;
2480 if (Literal.isWide())
2481 Kind = CharacterLiteral::Wide;
2482 else if (Literal.isUTF16())
2483 Kind = CharacterLiteral::UTF16;
2484 else if (Literal.isUTF32())
2485 Kind = CharacterLiteral::UTF32;
2486
Richard Smith75b67d62012-03-08 01:34:56 +00002487 Expr *Lit = new (Context) CharacterLiteral(Literal.getValue(), Kind, Ty,
2488 Tok.getLocation());
2489
2490 if (Literal.getUDSuffix().empty())
2491 return Owned(Lit);
2492
2493 // We're building a user-defined literal.
2494 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2495 SourceLocation UDSuffixLoc =
2496 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2497
Richard Smithbcc22fc2012-03-09 08:00:36 +00002498 // Make sure we're allowed user-defined literals here.
2499 if (!UDLScope)
2500 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_character_udl));
2501
Richard Smith75b67d62012-03-08 01:34:56 +00002502 // C++11 [lex.ext]p6: The literal L is treated as a call of the form
2503 // operator "" X (ch)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002504 return BuildCookedLiteralOperatorCall(*this, UDLScope, UDSuffix, UDSuffixLoc,
2505 llvm::makeArrayRef(&Lit, 1),
2506 Tok.getLocation());
Steve Naroffae4143e2007-04-26 20:39:23 +00002507}
2508
Ted Kremeneke65b0862012-03-06 20:05:56 +00002509ExprResult Sema::ActOnIntegerConstant(SourceLocation Loc, uint64_t Val) {
2510 unsigned IntSize = Context.getTargetInfo().getIntWidth();
2511 return Owned(IntegerLiteral::Create(Context, llvm::APInt(IntSize, Val),
2512 Context.IntTy, Loc));
2513}
2514
Richard Smith39570d002012-03-08 08:45:32 +00002515static Expr *BuildFloatingLiteral(Sema &S, NumericLiteralParser &Literal,
2516 QualType Ty, SourceLocation Loc) {
2517 const llvm::fltSemantics &Format = S.Context.getFloatTypeSemantics(Ty);
2518
2519 using llvm::APFloat;
2520 APFloat Val(Format);
2521
2522 APFloat::opStatus result = Literal.GetFloatValue(Val);
2523
2524 // Overflow is always an error, but underflow is only an error if
2525 // we underflowed to zero (APFloat reports denormals as underflow).
2526 if ((result & APFloat::opOverflow) ||
2527 ((result & APFloat::opUnderflow) && Val.isZero())) {
2528 unsigned diagnostic;
2529 SmallString<20> buffer;
2530 if (result & APFloat::opOverflow) {
2531 diagnostic = diag::warn_float_overflow;
2532 APFloat::getLargest(Format).toString(buffer);
2533 } else {
2534 diagnostic = diag::warn_float_underflow;
2535 APFloat::getSmallest(Format).toString(buffer);
2536 }
2537
2538 S.Diag(Loc, diagnostic)
2539 << Ty
2540 << StringRef(buffer.data(), buffer.size());
2541 }
2542
2543 bool isExact = (result == APFloat::opOK);
2544 return FloatingLiteral::Create(S.Context, Val, isExact, Ty, Loc);
2545}
2546
Richard Smithbcc22fc2012-03-09 08:00:36 +00002547ExprResult Sema::ActOnNumericConstant(const Token &Tok, Scope *UDLScope) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002548 // Fast path for a single digit (which is quite common). A single digit
Richard Smithbcc22fc2012-03-09 08:00:36 +00002549 // cannot have a trigraph, escaped newline, radix prefix, or suffix.
Steve Narofff2fb89e2007-03-13 20:29:44 +00002550 if (Tok.getLength() == 1) {
Chris Lattner9240b3e2009-01-26 22:36:52 +00002551 const char Val = PP.getSpellingOfSingleCharacterNumericConstant(Tok);
Ted Kremeneke65b0862012-03-06 20:05:56 +00002552 return ActOnIntegerConstant(Tok.getLocation(), Val-'0');
Steve Narofff2fb89e2007-03-13 20:29:44 +00002553 }
Ted Kremeneke9814182009-01-13 23:19:12 +00002554
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00002555 SmallString<512> IntegerBuffer;
Chris Lattnera1cf5f92008-09-30 20:53:45 +00002556 // Add padding so that NumericLiteralParser can overread by one character.
2557 IntegerBuffer.resize(Tok.getLength()+1);
Steve Naroff8160ea22007-03-06 01:09:46 +00002558 const char *ThisTokBegin = &IntegerBuffer[0];
Sebastian Redlffbcf962009-01-18 18:53:16 +00002559
Chris Lattner67ca9252007-05-21 01:08:44 +00002560 // Get the spelling of the token, which eliminates trigraphs, etc.
Douglas Gregordc970f02010-03-16 22:30:13 +00002561 bool Invalid = false;
2562 unsigned ActualLength = PP.getSpelling(Tok, ThisTokBegin, &Invalid);
2563 if (Invalid)
2564 return ExprError();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002565
Mike Stump11289f42009-09-09 15:08:12 +00002566 NumericLiteralParser Literal(ThisTokBegin, ThisTokBegin+ActualLength,
Steve Naroff451d8f162007-03-12 23:22:38 +00002567 Tok.getLocation(), PP);
Steve Narofff2fb89e2007-03-13 20:29:44 +00002568 if (Literal.hadError)
Sebastian Redlffbcf962009-01-18 18:53:16 +00002569 return ExprError();
2570
Richard Smith39570d002012-03-08 08:45:32 +00002571 if (Literal.hasUDSuffix()) {
2572 // We're building a user-defined literal.
2573 IdentifierInfo *UDSuffix = &Context.Idents.get(Literal.getUDSuffix());
2574 SourceLocation UDSuffixLoc =
2575 getUDSuffixLoc(*this, Tok.getLocation(), Literal.getUDSuffixOffset());
2576
Richard Smithbcc22fc2012-03-09 08:00:36 +00002577 // Make sure we're allowed user-defined literals here.
2578 if (!UDLScope)
2579 return ExprError(Diag(UDSuffixLoc, diag::err_invalid_numeric_udl));
Richard Smith39570d002012-03-08 08:45:32 +00002580
Richard Smithbcc22fc2012-03-09 08:00:36 +00002581 QualType CookedTy;
Richard Smith39570d002012-03-08 08:45:32 +00002582 if (Literal.isFloatingLiteral()) {
2583 // C++11 [lex.ext]p4: If S contains a literal operator with parameter type
2584 // long double, the literal is treated as a call of the form
2585 // operator "" X (f L)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002586 CookedTy = Context.LongDoubleTy;
Richard Smith39570d002012-03-08 08:45:32 +00002587 } else {
2588 // C++11 [lex.ext]p3: If S contains a literal operator with parameter type
2589 // unsigned long long, the literal is treated as a call of the form
2590 // operator "" X (n ULL)
Richard Smithbcc22fc2012-03-09 08:00:36 +00002591 CookedTy = Context.UnsignedLongLongTy;
Richard Smith39570d002012-03-08 08:45:32 +00002592 }
2593
Richard Smithbcc22fc2012-03-09 08:00:36 +00002594 DeclarationName OpName =
2595 Context.DeclarationNames.getCXXLiteralOperatorName(UDSuffix);
2596 DeclarationNameInfo OpNameInfo(OpName, UDSuffixLoc);
2597 OpNameInfo.setCXXLiteralOperatorNameLoc(UDSuffixLoc);
2598
2599 // Perform literal operator lookup to determine if we're building a raw
2600 // literal or a cooked one.
2601 LookupResult R(*this, OpName, UDSuffixLoc, LookupOrdinaryName);
2602 switch (LookupLiteralOperator(UDLScope, R, llvm::makeArrayRef(&CookedTy, 1),
2603 /*AllowRawAndTemplate*/true)) {
2604 case LOLR_Error:
2605 return ExprError();
2606
2607 case LOLR_Cooked: {
2608 Expr *Lit;
2609 if (Literal.isFloatingLiteral()) {
2610 Lit = BuildFloatingLiteral(*this, Literal, CookedTy, Tok.getLocation());
2611 } else {
2612 llvm::APInt ResultVal(Context.getTargetInfo().getLongLongWidth(), 0);
2613 if (Literal.GetIntegerValue(ResultVal))
2614 Diag(Tok.getLocation(), diag::warn_integer_too_large);
2615 Lit = IntegerLiteral::Create(Context, ResultVal, CookedTy,
2616 Tok.getLocation());
2617 }
2618 return BuildLiteralOperatorCall(R, OpNameInfo,
2619 llvm::makeArrayRef(&Lit, 1),
2620 Tok.getLocation());
2621 }
2622
2623 case LOLR_Raw: {
2624 // C++11 [lit.ext]p3, p4: If S contains a raw literal operator, the
2625 // literal is treated as a call of the form
2626 // operator "" X ("n")
2627 SourceLocation TokLoc = Tok.getLocation();
2628 unsigned Length = Literal.getUDSuffixOffset();
2629 QualType StrTy = Context.getConstantArrayType(
2630 Context.CharTy, llvm::APInt(32, Length + 1),
2631 ArrayType::Normal, 0);
2632 Expr *Lit = StringLiteral::Create(
2633 Context, StringRef(ThisTokBegin, Length), StringLiteral::Ascii,
2634 /*Pascal*/false, StrTy, &TokLoc, 1);
2635 return BuildLiteralOperatorCall(R, OpNameInfo,
2636 llvm::makeArrayRef(&Lit, 1), TokLoc);
2637 }
2638
2639 case LOLR_Template:
2640 // C++11 [lit.ext]p3, p4: Otherwise (S contains a literal operator
2641 // template), L is treated as a call fo the form
2642 // operator "" X <'c1', 'c2', ... 'ck'>()
2643 // where n is the source character sequence c1 c2 ... ck.
2644 TemplateArgumentListInfo ExplicitArgs;
2645 unsigned CharBits = Context.getIntWidth(Context.CharTy);
2646 bool CharIsUnsigned = Context.CharTy->isUnsignedIntegerType();
2647 llvm::APSInt Value(CharBits, CharIsUnsigned);
2648 for (unsigned I = 0, N = Literal.getUDSuffixOffset(); I != N; ++I) {
2649 Value = ThisTokBegin[I];
Benjamin Kramer6003ad52012-06-07 15:09:51 +00002650 TemplateArgument Arg(Context, Value, Context.CharTy);
Richard Smithbcc22fc2012-03-09 08:00:36 +00002651 TemplateArgumentLocInfo ArgInfo;
2652 ExplicitArgs.addArgument(TemplateArgumentLoc(Arg, ArgInfo));
2653 }
2654 return BuildLiteralOperatorCall(R, OpNameInfo, ArrayRef<Expr*>(),
2655 Tok.getLocation(), &ExplicitArgs);
2656 }
2657
2658 llvm_unreachable("unexpected literal operator lookup result");
Richard Smith39570d002012-03-08 08:45:32 +00002659 }
2660
Chris Lattner1c20a172007-08-26 03:42:43 +00002661 Expr *Res;
Sebastian Redlffbcf962009-01-18 18:53:16 +00002662
Chris Lattner1c20a172007-08-26 03:42:43 +00002663 if (Literal.isFloatingLiteral()) {
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002664 QualType Ty;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002665 if (Literal.isFloat)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002666 Ty = Context.FloatTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002667 else if (!Literal.isLong)
Chris Lattnerec0a6d92007-09-22 18:29:59 +00002668 Ty = Context.DoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002669 else
Chris Lattner7570e9c2008-03-08 08:52:55 +00002670 Ty = Context.LongDoubleTy;
Chris Lattner9a8d1d92008-06-30 18:32:54 +00002671
Richard Smith39570d002012-03-08 08:45:32 +00002672 Res = BuildFloatingLiteral(*this, Literal, Ty, Tok.getLocation());
Sebastian Redlffbcf962009-01-18 18:53:16 +00002673
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002674 if (Ty == Context.DoubleTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002675 if (getLangOpts().SinglePrecisionConstants) {
John Wiegley01296292011-04-08 18:41:53 +00002676 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002677 } else if (getLangOpts().OpenCL && !getOpenCLOptions().cl_khr_fp64) {
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002678 Diag(Tok.getLocation(), diag::warn_double_const_requires_fp64);
John Wiegley01296292011-04-08 18:41:53 +00002679 Res = ImpCastExprToType(Res, Context.FloatTy, CK_FloatingCast).take();
Peter Collingbournec77f85b2011-03-11 19:24:59 +00002680 }
2681 }
Chris Lattner1c20a172007-08-26 03:42:43 +00002682 } else if (!Literal.isIntegerLiteral()) {
Sebastian Redlffbcf962009-01-18 18:53:16 +00002683 return ExprError();
Chris Lattner1c20a172007-08-26 03:42:43 +00002684 } else {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002685 QualType Ty;
Chris Lattner67ca9252007-05-21 01:08:44 +00002686
Neil Boothac582c52007-08-29 22:00:19 +00002687 // long long is a C99 feature.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002688 if (!getLangOpts().C99 && Literal.isLongLong)
Richard Smith0bf8a4922011-10-18 20:49:44 +00002689 Diag(Tok.getLocation(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00002690 getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00002691 diag::warn_cxx98_compat_longlong : diag::ext_longlong);
Neil Boothac582c52007-08-29 22:00:19 +00002692
Chris Lattner67ca9252007-05-21 01:08:44 +00002693 // Get the value in the widest-possible width.
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002694 unsigned MaxWidth = Context.getTargetInfo().getIntMaxTWidth();
2695 // The microsoft literal suffix extensions support 128-bit literals, which
2696 // may be wider than [u]intmax_t.
2697 if (Literal.isMicrosoftInteger && MaxWidth < 128)
2698 MaxWidth = 128;
2699 llvm::APInt ResultVal(MaxWidth, 0);
Sebastian Redlffbcf962009-01-18 18:53:16 +00002700
Chris Lattner67ca9252007-05-21 01:08:44 +00002701 if (Literal.GetIntegerValue(ResultVal)) {
2702 // If this value didn't fit into uintmax_t, warn and force to ull.
2703 Diag(Tok.getLocation(), diag::warn_integer_too_large);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002704 Ty = Context.UnsignedLongLongTy;
2705 assert(Context.getTypeSize(Ty) == ResultVal.getBitWidth() &&
Chris Lattner37e05872008-03-05 18:54:05 +00002706 "long long is not intmax_t?");
Steve Naroff09ef4742007-03-09 23:16:33 +00002707 } else {
Chris Lattner67ca9252007-05-21 01:08:44 +00002708 // If this value fits into a ULL, try to figure out what else it fits into
2709 // according to the rules of C99 6.4.4.1p5.
Sebastian Redlffbcf962009-01-18 18:53:16 +00002710
Chris Lattner67ca9252007-05-21 01:08:44 +00002711 // Octal, Hexadecimal, and integers with a U suffix are allowed to
2712 // be an unsigned int.
2713 bool AllowUnsigned = Literal.isUnsigned || Literal.getRadix() != 10;
2714
2715 // Check from smallest to largest, picking the smallest type we can.
Chris Lattner55258cf2008-05-09 05:59:00 +00002716 unsigned Width = 0;
Chris Lattner7b939cf2007-08-23 21:58:08 +00002717 if (!Literal.isLong && !Literal.isLongLong) {
2718 // Are int/unsigned possibilities?
Douglas Gregore8bbc122011-09-02 00:18:52 +00002719 unsigned IntSize = Context.getTargetInfo().getIntWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002720
Chris Lattner67ca9252007-05-21 01:08:44 +00002721 // Does it fit in a unsigned int?
2722 if (ResultVal.isIntN(IntSize)) {
2723 // Does it fit in a signed int?
2724 if (!Literal.isUnsigned && ResultVal[IntSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002725 Ty = Context.IntTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002726 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002727 Ty = Context.UnsignedIntTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002728 Width = IntSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002729 }
Chris Lattner67ca9252007-05-21 01:08:44 +00002730 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002731
Chris Lattner67ca9252007-05-21 01:08:44 +00002732 // Are long/unsigned long possibilities?
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002733 if (Ty.isNull() && !Literal.isLongLong) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002734 unsigned LongSize = Context.getTargetInfo().getLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002735
Chris Lattner67ca9252007-05-21 01:08:44 +00002736 // Does it fit in a unsigned long?
2737 if (ResultVal.isIntN(LongSize)) {
2738 // Does it fit in a signed long?
2739 if (!Literal.isUnsigned && ResultVal[LongSize-1] == 0)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002740 Ty = Context.LongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002741 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002742 Ty = Context.UnsignedLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002743 Width = LongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002744 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002745 }
2746
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002747 // Check long long if needed.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002748 if (Ty.isNull()) {
Douglas Gregore8bbc122011-09-02 00:18:52 +00002749 unsigned LongLongSize = Context.getTargetInfo().getLongLongWidth();
Sebastian Redlffbcf962009-01-18 18:53:16 +00002750
Chris Lattner67ca9252007-05-21 01:08:44 +00002751 // Does it fit in a unsigned long long?
2752 if (ResultVal.isIntN(LongLongSize)) {
2753 // Does it fit in a signed long long?
Francois Pichetc3e73b32011-01-11 23:38:13 +00002754 // To be compatible with MSVC, hex integer literals ending with the
2755 // LL or i64 suffix are always signed in Microsoft mode.
Francois Pichetbf711d92011-01-11 12:23:00 +00002756 if (!Literal.isUnsigned && (ResultVal[LongLongSize-1] == 0 ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00002757 (getLangOpts().MicrosoftExt && Literal.isLongLong)))
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002758 Ty = Context.LongLongTy;
Chris Lattner67ca9252007-05-21 01:08:44 +00002759 else if (AllowUnsigned)
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002760 Ty = Context.UnsignedLongLongTy;
Chris Lattner55258cf2008-05-09 05:59:00 +00002761 Width = LongLongSize;
Chris Lattner67ca9252007-05-21 01:08:44 +00002762 }
2763 }
Stephen Canonfdc6c1a2012-05-03 22:49:43 +00002764
2765 // If it doesn't fit in unsigned long long, and we're using Microsoft
2766 // extensions, then its a 128-bit integer literal.
2767 if (Ty.isNull() && Literal.isMicrosoftInteger) {
2768 if (Literal.isUnsigned)
2769 Ty = Context.UnsignedInt128Ty;
2770 else
2771 Ty = Context.Int128Ty;
2772 Width = 128;
2773 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002774
Chris Lattner67ca9252007-05-21 01:08:44 +00002775 // If we still couldn't decide a type, we probably have something that
2776 // does not fit in a signed long long, but has no U suffix.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002777 if (Ty.isNull()) {
Chris Lattner67ca9252007-05-21 01:08:44 +00002778 Diag(Tok.getLocation(), diag::warn_integer_too_large_for_signed);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002779 Ty = Context.UnsignedLongLongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00002780 Width = Context.getTargetInfo().getLongLongWidth();
Chris Lattner67ca9252007-05-21 01:08:44 +00002781 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002782
Chris Lattner55258cf2008-05-09 05:59:00 +00002783 if (ResultVal.getBitWidth() != Width)
Jay Foad6d4db0c2010-12-07 08:25:34 +00002784 ResultVal = ResultVal.trunc(Width);
Steve Naroff09ef4742007-03-09 23:16:33 +00002785 }
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00002786 Res = IntegerLiteral::Create(Context, ResultVal, Ty, Tok.getLocation());
Steve Naroff09ef4742007-03-09 23:16:33 +00002787 }
Sebastian Redlffbcf962009-01-18 18:53:16 +00002788
Chris Lattner1c20a172007-08-26 03:42:43 +00002789 // If this is an imaginary literal, create the ImaginaryLiteral wrapper.
2790 if (Literal.isImaginary)
Mike Stump11289f42009-09-09 15:08:12 +00002791 Res = new (Context) ImaginaryLiteral(Res,
Steve Narofff6009ed2009-01-21 00:14:39 +00002792 Context.getComplexType(Res->getType()));
Sebastian Redlffbcf962009-01-18 18:53:16 +00002793
2794 return Owned(Res);
Chris Lattnere168f762006-11-10 05:29:30 +00002795}
2796
Richard Trieuba63ce62011-09-09 01:45:06 +00002797ExprResult Sema::ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00002798 assert((E != 0) && "ActOnParenExpr() missing expr");
Steve Narofff6009ed2009-01-21 00:14:39 +00002799 return Owned(new (Context) ParenExpr(L, R, E));
Chris Lattnere168f762006-11-10 05:29:30 +00002800}
2801
Chandler Carruth62da79c2011-05-26 08:53:12 +00002802static bool CheckVecStepTraitOperandType(Sema &S, QualType T,
2803 SourceLocation Loc,
2804 SourceRange ArgRange) {
2805 // [OpenCL 1.1 6.11.12] "The vec_step built-in function takes a built-in
2806 // scalar or vector data type argument..."
2807 // Every built-in scalar type (OpenCL 1.1 6.1.1) is either an arithmetic
2808 // type (C99 6.2.5p18) or void.
2809 if (!(T->isArithmeticType() || T->isVoidType() || T->isVectorType())) {
2810 S.Diag(Loc, diag::err_vecstep_non_scalar_vector_type)
2811 << T << ArgRange;
2812 return true;
2813 }
2814
2815 assert((T->isVoidType() || !T->isIncompleteType()) &&
2816 "Scalar types should always be complete");
2817 return false;
2818}
2819
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002820static bool CheckExtensionTraitOperandType(Sema &S, QualType T,
2821 SourceLocation Loc,
2822 SourceRange ArgRange,
2823 UnaryExprOrTypeTrait TraitKind) {
2824 // C99 6.5.3.4p1:
2825 if (T->isFunctionType()) {
2826 // alignof(function) is allowed as an extension.
2827 if (TraitKind == UETT_SizeOf)
2828 S.Diag(Loc, diag::ext_sizeof_function_type) << ArgRange;
2829 return false;
2830 }
2831
2832 // Allow sizeof(void)/alignof(void) as an extension.
2833 if (T->isVoidType()) {
2834 S.Diag(Loc, diag::ext_sizeof_void_type) << TraitKind << ArgRange;
2835 return false;
2836 }
2837
2838 return true;
2839}
2840
2841static bool CheckObjCTraitOperandConstraints(Sema &S, QualType T,
2842 SourceLocation Loc,
2843 SourceRange ArgRange,
2844 UnaryExprOrTypeTrait TraitKind) {
2845 // Reject sizeof(interface) and sizeof(interface<proto>) in 64-bit mode.
2846 if (S.LangOpts.ObjCNonFragileABI && T->isObjCObjectType()) {
2847 S.Diag(Loc, diag::err_sizeof_nonfragile_interface)
2848 << T << (TraitKind == UETT_SizeOf)
2849 << ArgRange;
2850 return true;
2851 }
2852
2853 return false;
2854}
2855
Chandler Carruth14502c22011-05-26 08:53:10 +00002856/// \brief Check the constrains on expression operands to unary type expression
2857/// and type traits.
2858///
Chandler Carruth7c430c02011-05-27 01:33:31 +00002859/// Completes any types necessary and validates the constraints on the operand
2860/// expression. The logic mostly mirrors the type-based overload, but may modify
2861/// the expression as it completes the type for that expression through template
2862/// instantiation, etc.
Richard Trieuba63ce62011-09-09 01:45:06 +00002863bool Sema::CheckUnaryExprOrTypeTraitOperand(Expr *E,
Chandler Carruth14502c22011-05-26 08:53:10 +00002864 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002865 QualType ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002866
2867 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2868 // the result is the size of the referenced type."
2869 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2870 // result shall be the alignment of the referenced type."
2871 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2872 ExprTy = Ref->getPointeeType();
2873
2874 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002875 return CheckVecStepTraitOperandType(*this, ExprTy, E->getExprLoc(),
2876 E->getSourceRange());
Chandler Carruth7c430c02011-05-27 01:33:31 +00002877
2878 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002879 if (!CheckExtensionTraitOperandType(*this, ExprTy, E->getExprLoc(),
2880 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002881 return false;
2882
Richard Trieuba63ce62011-09-09 01:45:06 +00002883 if (RequireCompleteExprType(E,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002884 diag::err_sizeof_alignof_incomplete_type,
2885 ExprKind, E->getSourceRange()))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002886 return true;
2887
2888 // Completeing the expression's type may have changed it.
Richard Trieuba63ce62011-09-09 01:45:06 +00002889 ExprTy = E->getType();
Chandler Carruth7c430c02011-05-27 01:33:31 +00002890 if (const ReferenceType *Ref = ExprTy->getAs<ReferenceType>())
2891 ExprTy = Ref->getPointeeType();
2892
Richard Trieuba63ce62011-09-09 01:45:06 +00002893 if (CheckObjCTraitOperandConstraints(*this, ExprTy, E->getExprLoc(),
2894 E->getSourceRange(), ExprKind))
Chandler Carruth7c430c02011-05-27 01:33:31 +00002895 return true;
2896
Nico Weber0870deb2011-06-15 02:47:03 +00002897 if (ExprKind == UETT_SizeOf) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002898 if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
Nico Weber0870deb2011-06-15 02:47:03 +00002899 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(DeclRef->getFoundDecl())) {
2900 QualType OType = PVD->getOriginalType();
2901 QualType Type = PVD->getType();
2902 if (Type->isPointerType() && OType->isArrayType()) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002903 Diag(E->getExprLoc(), diag::warn_sizeof_array_param)
Nico Weber0870deb2011-06-15 02:47:03 +00002904 << Type << OType;
2905 Diag(PVD->getLocation(), diag::note_declared_at);
2906 }
2907 }
2908 }
2909 }
2910
Chandler Carruth7c430c02011-05-27 01:33:31 +00002911 return false;
Chandler Carruth14502c22011-05-26 08:53:10 +00002912}
2913
2914/// \brief Check the constraints on operands to unary expression and type
2915/// traits.
2916///
2917/// This will complete any types necessary, and validate the various constraints
2918/// on those operands.
2919///
Steve Naroff71b59a92007-06-04 22:22:31 +00002920/// The UsualUnaryConversions() function is *not* called by this routine.
Chandler Carruth14502c22011-05-26 08:53:10 +00002921/// C99 6.3.2.1p[2-4] all state:
2922/// Except when it is the operand of the sizeof operator ...
2923///
2924/// C++ [expr.sizeof]p4
2925/// The lvalue-to-rvalue, array-to-pointer, and function-to-pointer
2926/// standard conversions are not applied to the operand of sizeof.
2927///
2928/// This policy is followed for all of the unary trait expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +00002929bool Sema::CheckUnaryExprOrTypeTraitOperand(QualType ExprType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00002930 SourceLocation OpLoc,
2931 SourceRange ExprRange,
2932 UnaryExprOrTypeTrait ExprKind) {
Richard Trieuba63ce62011-09-09 01:45:06 +00002933 if (ExprType->isDependentType())
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002934 return false;
2935
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002936 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2937 // the result is the size of the referenced type."
2938 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2939 // result shall be the alignment of the referenced type."
Richard Trieuba63ce62011-09-09 01:45:06 +00002940 if (const ReferenceType *Ref = ExprType->getAs<ReferenceType>())
2941 ExprType = Ref->getPointeeType();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00002942
Chandler Carruth62da79c2011-05-26 08:53:12 +00002943 if (ExprKind == UETT_VecStep)
Richard Trieuba63ce62011-09-09 01:45:06 +00002944 return CheckVecStepTraitOperandType(*this, ExprType, OpLoc, ExprRange);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002945
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002946 // Whitelist some types as extensions
Richard Trieuba63ce62011-09-09 01:45:06 +00002947 if (!CheckExtensionTraitOperandType(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002948 ExprKind))
Chris Lattnerb1355b12009-01-24 19:46:37 +00002949 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002950
Richard Trieuba63ce62011-09-09 01:45:06 +00002951 if (RequireCompleteType(OpLoc, ExprType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002952 diag::err_sizeof_alignof_incomplete_type,
2953 ExprKind, ExprRange))
Chris Lattner62975a72009-04-24 00:30:45 +00002954 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002955
Richard Trieuba63ce62011-09-09 01:45:06 +00002956 if (CheckObjCTraitOperandConstraints(*this, ExprType, OpLoc, ExprRange,
Chandler Carruthcea1aac2011-05-26 08:53:16 +00002957 ExprKind))
Chris Lattnercd2a8c52009-04-24 22:30:50 +00002958 return true;
Mike Stump11289f42009-09-09 15:08:12 +00002959
Chris Lattner62975a72009-04-24 00:30:45 +00002960 return false;
Steve Naroff043d45d2007-05-15 02:32:35 +00002961}
2962
Chandler Carruth14502c22011-05-26 08:53:10 +00002963static bool CheckAlignOfExpr(Sema &S, Expr *E) {
Chris Lattner8dff0172009-01-24 20:17:12 +00002964 E = E->IgnoreParens();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002965
Mike Stump11289f42009-09-09 15:08:12 +00002966 // alignof decl is always ok.
Chris Lattner8dff0172009-01-24 20:17:12 +00002967 if (isa<DeclRefExpr>(E))
2968 return false;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002969
2970 // Cannot know anything else if the expression is dependent.
2971 if (E->isTypeDependent())
2972 return false;
2973
Douglas Gregor71235ec2009-05-02 02:18:30 +00002974 if (E->getBitField()) {
Chandler Carruth14502c22011-05-26 08:53:10 +00002975 S.Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield)
2976 << 1 << E->getSourceRange();
Douglas Gregor71235ec2009-05-02 02:18:30 +00002977 return true;
Chris Lattner8dff0172009-01-24 20:17:12 +00002978 }
Douglas Gregor71235ec2009-05-02 02:18:30 +00002979
2980 // Alignment of a field access is always okay, so long as it isn't a
2981 // bit-field.
2982 if (MemberExpr *ME = dyn_cast<MemberExpr>(E))
Mike Stump212005c2009-07-22 18:58:19 +00002983 if (isa<FieldDecl>(ME->getMemberDecl()))
Douglas Gregor71235ec2009-05-02 02:18:30 +00002984 return false;
2985
Chandler Carruth14502c22011-05-26 08:53:10 +00002986 return S.CheckUnaryExprOrTypeTraitOperand(E, UETT_AlignOf);
Peter Collingbournee190dee2011-03-11 19:24:49 +00002987}
2988
Chandler Carruth14502c22011-05-26 08:53:10 +00002989bool Sema::CheckVecStepExpr(Expr *E) {
Peter Collingbournee190dee2011-03-11 19:24:49 +00002990 E = E->IgnoreParens();
2991
2992 // Cannot know anything else if the expression is dependent.
2993 if (E->isTypeDependent())
2994 return false;
2995
Chandler Carruth14502c22011-05-26 08:53:10 +00002996 return CheckUnaryExprOrTypeTraitOperand(E, UETT_VecStep);
Chris Lattner8dff0172009-01-24 20:17:12 +00002997}
2998
Douglas Gregor0950e412009-03-13 21:01:28 +00002999/// \brief Build a sizeof or alignof expression given a type operand.
John McCalldadc5752010-08-24 06:29:42 +00003000ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003001Sema::CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo,
3002 SourceLocation OpLoc,
3003 UnaryExprOrTypeTrait ExprKind,
3004 SourceRange R) {
John McCallbcd03502009-12-07 02:54:59 +00003005 if (!TInfo)
Douglas Gregor0950e412009-03-13 21:01:28 +00003006 return ExprError();
3007
John McCallbcd03502009-12-07 02:54:59 +00003008 QualType T = TInfo->getType();
John McCall4c98fd82009-11-04 07:28:41 +00003009
Douglas Gregor0950e412009-03-13 21:01:28 +00003010 if (!T->isDependentType() &&
Peter Collingbournee190dee2011-03-11 19:24:49 +00003011 CheckUnaryExprOrTypeTraitOperand(T, OpLoc, R, ExprKind))
Douglas Gregor0950e412009-03-13 21:01:28 +00003012 return ExprError();
3013
3014 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003015 return Owned(new (Context) UnaryExprOrTypeTraitExpr(ExprKind, TInfo,
3016 Context.getSizeType(),
3017 OpLoc, R.getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003018}
3019
3020/// \brief Build a sizeof or alignof expression given an expression
3021/// operand.
John McCalldadc5752010-08-24 06:29:42 +00003022ExprResult
Chandler Carrutha923fb22011-05-29 07:32:14 +00003023Sema::CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc,
3024 UnaryExprOrTypeTrait ExprKind) {
Douglas Gregor835af982011-06-22 23:21:00 +00003025 ExprResult PE = CheckPlaceholderExpr(E);
3026 if (PE.isInvalid())
3027 return ExprError();
3028
3029 E = PE.get();
3030
Douglas Gregor0950e412009-03-13 21:01:28 +00003031 // Verify that the operand is valid.
3032 bool isInvalid = false;
3033 if (E->isTypeDependent()) {
3034 // Delay type-checking for type-dependent expressions.
Peter Collingbournee190dee2011-03-11 19:24:49 +00003035 } else if (ExprKind == UETT_AlignOf) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003036 isInvalid = CheckAlignOfExpr(*this, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003037 } else if (ExprKind == UETT_VecStep) {
Chandler Carruth14502c22011-05-26 08:53:10 +00003038 isInvalid = CheckVecStepExpr(E);
Douglas Gregor71235ec2009-05-02 02:18:30 +00003039 } else if (E->getBitField()) { // C99 6.5.3.4p1.
Chandler Carruth14502c22011-05-26 08:53:10 +00003040 Diag(E->getExprLoc(), diag::err_sizeof_alignof_bitfield) << 0;
Douglas Gregor0950e412009-03-13 21:01:28 +00003041 isInvalid = true;
3042 } else {
Chandler Carruth14502c22011-05-26 08:53:10 +00003043 isInvalid = CheckUnaryExprOrTypeTraitOperand(E, UETT_SizeOf);
Douglas Gregor0950e412009-03-13 21:01:28 +00003044 }
3045
3046 if (isInvalid)
3047 return ExprError();
3048
Eli Friedmane0afc982012-01-21 01:01:51 +00003049 if (ExprKind == UETT_SizeOf && E->getType()->isVariableArrayType()) {
3050 PE = TranformToPotentiallyEvaluated(E);
3051 if (PE.isInvalid()) return ExprError();
3052 E = PE.take();
3053 }
3054
Douglas Gregor0950e412009-03-13 21:01:28 +00003055 // C99 6.5.3.4p4: the type (an unsigned integer type) is size_t.
Chandler Carruth14502c22011-05-26 08:53:10 +00003056 return Owned(new (Context) UnaryExprOrTypeTraitExpr(
Chandler Carrutha923fb22011-05-29 07:32:14 +00003057 ExprKind, E, Context.getSizeType(), OpLoc,
Chandler Carruth14502c22011-05-26 08:53:10 +00003058 E->getSourceRange().getEnd()));
Douglas Gregor0950e412009-03-13 21:01:28 +00003059}
3060
Peter Collingbournee190dee2011-03-11 19:24:49 +00003061/// ActOnUnaryExprOrTypeTraitExpr - Handle @c sizeof(type) and @c sizeof @c
3062/// expr and the same for @c alignof and @c __alignof
Sebastian Redl6f282892008-11-11 17:56:53 +00003063/// Note that the ArgRange is invalid if isType is false.
John McCalldadc5752010-08-24 06:29:42 +00003064ExprResult
Peter Collingbournee190dee2011-03-11 19:24:49 +00003065Sema::ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003066 UnaryExprOrTypeTrait ExprKind, bool IsType,
Peter Collingbournee190dee2011-03-11 19:24:49 +00003067 void *TyOrEx, const SourceRange &ArgRange) {
Chris Lattner0d8b1a12006-11-20 04:34:45 +00003068 // If error parsing type, ignore.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003069 if (TyOrEx == 0) return ExprError();
Steve Naroff043d45d2007-05-15 02:32:35 +00003070
Richard Trieuba63ce62011-09-09 01:45:06 +00003071 if (IsType) {
John McCallbcd03502009-12-07 02:54:59 +00003072 TypeSourceInfo *TInfo;
John McCallba7bf592010-08-24 05:47:05 +00003073 (void) GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrEx), &TInfo);
Peter Collingbournee190dee2011-03-11 19:24:49 +00003074 return CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, ArgRange);
Mike Stump11289f42009-09-09 15:08:12 +00003075 }
Sebastian Redl6f282892008-11-11 17:56:53 +00003076
Douglas Gregor0950e412009-03-13 21:01:28 +00003077 Expr *ArgEx = (Expr *)TyOrEx;
Chandler Carrutha923fb22011-05-29 07:32:14 +00003078 ExprResult Result = CreateUnaryExprOrTypeTraitExpr(ArgEx, OpLoc, ExprKind);
Douglas Gregor0950e412009-03-13 21:01:28 +00003079 return move(Result);
Chris Lattnere168f762006-11-10 05:29:30 +00003080}
3081
John Wiegley01296292011-04-08 18:41:53 +00003082static QualType CheckRealImagOperand(Sema &S, ExprResult &V, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003083 bool IsReal) {
John Wiegley01296292011-04-08 18:41:53 +00003084 if (V.get()->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00003085 return S.Context.DependentTy;
Mike Stump11289f42009-09-09 15:08:12 +00003086
John McCall34376a62010-12-04 03:47:34 +00003087 // _Real and _Imag are only l-values for normal l-values.
John Wiegley01296292011-04-08 18:41:53 +00003088 if (V.get()->getObjectKind() != OK_Ordinary) {
3089 V = S.DefaultLvalueConversion(V.take());
3090 if (V.isInvalid())
3091 return QualType();
3092 }
John McCall34376a62010-12-04 03:47:34 +00003093
Chris Lattnere267f5d2007-08-26 05:39:26 +00003094 // These operators return the element type of a complex type.
John Wiegley01296292011-04-08 18:41:53 +00003095 if (const ComplexType *CT = V.get()->getType()->getAs<ComplexType>())
Chris Lattner30b5dd02007-08-24 21:16:53 +00003096 return CT->getElementType();
Mike Stump11289f42009-09-09 15:08:12 +00003097
Chris Lattnere267f5d2007-08-26 05:39:26 +00003098 // Otherwise they pass through real integer and floating point types here.
John Wiegley01296292011-04-08 18:41:53 +00003099 if (V.get()->getType()->isArithmeticType())
3100 return V.get()->getType();
Mike Stump11289f42009-09-09 15:08:12 +00003101
John McCall36226622010-10-12 02:09:17 +00003102 // Test for placeholders.
John McCall3aef3d82011-04-10 19:13:55 +00003103 ExprResult PR = S.CheckPlaceholderExpr(V.get());
John McCall36226622010-10-12 02:09:17 +00003104 if (PR.isInvalid()) return QualType();
John Wiegley01296292011-04-08 18:41:53 +00003105 if (PR.get() != V.get()) {
3106 V = move(PR);
Richard Trieuba63ce62011-09-09 01:45:06 +00003107 return CheckRealImagOperand(S, V, Loc, IsReal);
John McCall36226622010-10-12 02:09:17 +00003108 }
3109
Chris Lattnere267f5d2007-08-26 05:39:26 +00003110 // Reject anything else.
John Wiegley01296292011-04-08 18:41:53 +00003111 S.Diag(Loc, diag::err_realimag_invalid_type) << V.get()->getType()
Richard Trieuba63ce62011-09-09 01:45:06 +00003112 << (IsReal ? "__real" : "__imag");
Chris Lattnere267f5d2007-08-26 05:39:26 +00003113 return QualType();
Chris Lattner30b5dd02007-08-24 21:16:53 +00003114}
3115
3116
Chris Lattnere168f762006-11-10 05:29:30 +00003117
John McCalldadc5752010-08-24 06:29:42 +00003118ExprResult
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003119Sema::ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc,
John McCallb268a282010-08-23 23:25:46 +00003120 tok::TokenKind Kind, Expr *Input) {
John McCalle3027922010-08-25 11:45:40 +00003121 UnaryOperatorKind Opc;
Chris Lattnere168f762006-11-10 05:29:30 +00003122 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003123 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00003124 case tok::plusplus: Opc = UO_PostInc; break;
3125 case tok::minusminus: Opc = UO_PostDec; break;
Chris Lattnere168f762006-11-10 05:29:30 +00003126 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003127
Sebastian Redla9351792012-02-11 23:51:47 +00003128 // Since this might is a postfix expression, get rid of ParenListExprs.
3129 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Input);
3130 if (Result.isInvalid()) return ExprError();
3131 Input = Result.take();
3132
John McCallb268a282010-08-23 23:25:46 +00003133 return BuildUnaryOp(S, OpLoc, Opc, Input);
Chris Lattnere168f762006-11-10 05:29:30 +00003134}
3135
John McCalldadc5752010-08-24 06:29:42 +00003136ExprResult
John McCallb268a282010-08-23 23:25:46 +00003137Sema::ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc,
3138 Expr *Idx, SourceLocation RLoc) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00003139 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003140 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00003141 if (Result.isInvalid()) return ExprError();
3142 Base = Result.take();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003143
John McCallb268a282010-08-23 23:25:46 +00003144 Expr *LHSExp = Base, *RHSExp = Idx;
Mike Stump11289f42009-09-09 15:08:12 +00003145
David Blaikiebbafb8a2012-03-11 07:00:24 +00003146 if (getLangOpts().CPlusPlus &&
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003147 (LHSExp->isTypeDependent() || RHSExp->isTypeDependent())) {
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003148 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003149 Context.DependentTy,
3150 VK_LValue, OK_Ordinary,
3151 RLoc));
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00003152 }
3153
David Blaikiebbafb8a2012-03-11 07:00:24 +00003154 if (getLangOpts().CPlusPlus &&
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003155 (LHSExp->getType()->isRecordType() ||
Eli Friedman254a1a22008-12-15 22:34:21 +00003156 LHSExp->getType()->isEnumeralType() ||
3157 RHSExp->getType()->isRecordType() ||
Ted Kremeneke65b0862012-03-06 20:05:56 +00003158 RHSExp->getType()->isEnumeralType()) &&
3159 !LHSExp->getType()->isObjCObjectPointerType()) {
John McCallb268a282010-08-23 23:25:46 +00003160 return CreateOverloadedArraySubscriptExpr(LLoc, RLoc, Base, Idx);
Douglas Gregor40412ac2008-11-19 17:17:41 +00003161 }
3162
John McCallb268a282010-08-23 23:25:46 +00003163 return CreateBuiltinArraySubscriptExpr(Base, LLoc, Idx, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00003164}
3165
3166
John McCalldadc5752010-08-24 06:29:42 +00003167ExprResult
John McCallb268a282010-08-23 23:25:46 +00003168Sema::CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003169 Expr *Idx, SourceLocation RLoc) {
John McCallb268a282010-08-23 23:25:46 +00003170 Expr *LHSExp = Base;
3171 Expr *RHSExp = Idx;
Sebastian Redladba46e2009-10-29 20:17:01 +00003172
Chris Lattner36d572b2007-07-16 00:14:47 +00003173 // Perform default conversions.
John Wiegley01296292011-04-08 18:41:53 +00003174 if (!LHSExp->getType()->getAs<VectorType>()) {
3175 ExprResult Result = DefaultFunctionArrayLvalueConversion(LHSExp);
3176 if (Result.isInvalid())
3177 return ExprError();
3178 LHSExp = Result.take();
3179 }
3180 ExprResult Result = DefaultFunctionArrayLvalueConversion(RHSExp);
3181 if (Result.isInvalid())
3182 return ExprError();
3183 RHSExp = Result.take();
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003184
Chris Lattner36d572b2007-07-16 00:14:47 +00003185 QualType LHSTy = LHSExp->getType(), RHSTy = RHSExp->getType();
John McCall7decc9e2010-11-18 06:31:45 +00003186 ExprValueKind VK = VK_LValue;
3187 ExprObjectKind OK = OK_Ordinary;
Steve Narofff1e53692007-03-23 22:27:02 +00003188
Steve Naroffc1aadb12007-03-28 21:49:40 +00003189 // C99 6.5.2.1p2: the expression e1[e2] is by definition precisely equivalent
Chris Lattnerf17bd422007-08-30 17:45:32 +00003190 // to the expression *((e1)+(e2)). This means the array "Base" may actually be
Mike Stump4e1f26a2009-02-19 03:04:26 +00003191 // in the subscript position. As a result, we need to derive the array base
Steve Narofff1e53692007-03-23 22:27:02 +00003192 // and index from the expression types.
Chris Lattner36d572b2007-07-16 00:14:47 +00003193 Expr *BaseExpr, *IndexExpr;
3194 QualType ResultType;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00003195 if (LHSTy->isDependentType() || RHSTy->isDependentType()) {
3196 BaseExpr = LHSExp;
3197 IndexExpr = RHSExp;
3198 ResultType = Context.DependentTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003199 } else if (const PointerType *PTy = LHSTy->getAs<PointerType>()) {
Chris Lattner36d572b2007-07-16 00:14:47 +00003200 BaseExpr = LHSExp;
3201 IndexExpr = RHSExp;
Chris Lattner36d572b2007-07-16 00:14:47 +00003202 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003203 } else if (const ObjCObjectPointerType *PTy =
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003204 LHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003205 BaseExpr = LHSExp;
3206 IndexExpr = RHSExp;
Ted Kremeneke65b0862012-03-06 20:05:56 +00003207 Result = BuildObjCSubscriptExpression(RLoc, BaseExpr, IndexExpr, 0, 0);
3208 if (!Result.isInvalid())
3209 return Owned(Result.take());
Steve Naroff7cae42b2009-07-10 23:34:53 +00003210 ResultType = PTy->getPointeeType();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00003211 } else if (const PointerType *PTy = RHSTy->getAs<PointerType>()) {
3212 // Handle the uncommon case of "123[Ptr]".
3213 BaseExpr = RHSExp;
3214 IndexExpr = LHSExp;
3215 ResultType = PTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003216 } else if (const ObjCObjectPointerType *PTy =
John McCall9dd450b2009-09-21 23:43:11 +00003217 RHSTy->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00003218 // Handle the uncommon case of "123[Ptr]".
3219 BaseExpr = RHSExp;
3220 IndexExpr = LHSExp;
3221 ResultType = PTy->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +00003222 } else if (const VectorType *VTy = LHSTy->getAs<VectorType>()) {
Chris Lattner41977962007-07-31 19:29:30 +00003223 BaseExpr = LHSExp; // vectors: V[123]
Chris Lattner36d572b2007-07-16 00:14:47 +00003224 IndexExpr = RHSExp;
John McCall7decc9e2010-11-18 06:31:45 +00003225 VK = LHSExp->getValueKind();
3226 if (VK != VK_RValue)
3227 OK = OK_VectorComponent;
Nate Begemanc1bf0612009-01-18 00:45:31 +00003228
Chris Lattner36d572b2007-07-16 00:14:47 +00003229 // FIXME: need to deal with const...
3230 ResultType = VTy->getElementType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003231 } else if (LHSTy->isArrayType()) {
3232 // If we see an array that wasn't promoted by
Douglas Gregorb92a1562010-02-03 00:27:59 +00003233 // DefaultFunctionArrayLvalueConversion, it must be an array that
Eli Friedmanab2784f2009-04-25 23:46:54 +00003234 // wasn't promoted because of the C90 rule that doesn't
3235 // allow promoting non-lvalue arrays. Warn, then
3236 // force the promotion here.
3237 Diag(LHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3238 LHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003239 LHSExp = ImpCastExprToType(LHSExp, Context.getArrayDecayedType(LHSTy),
3240 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003241 LHSTy = LHSExp->getType();
3242
3243 BaseExpr = LHSExp;
3244 IndexExpr = RHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003245 ResultType = LHSTy->getAs<PointerType>()->getPointeeType();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003246 } else if (RHSTy->isArrayType()) {
3247 // Same as previous, except for 123[f().a] case
3248 Diag(RHSExp->getLocStart(), diag::ext_subscript_non_lvalue) <<
3249 RHSExp->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003250 RHSExp = ImpCastExprToType(RHSExp, Context.getArrayDecayedType(RHSTy),
3251 CK_ArrayToPointerDecay).take();
Eli Friedmanab2784f2009-04-25 23:46:54 +00003252 RHSTy = RHSExp->getType();
3253
3254 BaseExpr = RHSExp;
3255 IndexExpr = LHSExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003256 ResultType = RHSTy->getAs<PointerType>()->getPointeeType();
Steve Naroffb3096442007-06-09 03:47:53 +00003257 } else {
Chris Lattner003af242009-04-25 22:50:55 +00003258 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_value)
3259 << LHSExp->getSourceRange() << RHSExp->getSourceRange());
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003260 }
Steve Naroffc1aadb12007-03-28 21:49:40 +00003261 // C99 6.5.2.1p1
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003262 if (!IndexExpr->getType()->isIntegerType() && !IndexExpr->isTypeDependent())
Chris Lattner003af242009-04-25 22:50:55 +00003263 return ExprError(Diag(LLoc, diag::err_typecheck_subscript_not_integer)
3264 << IndexExpr->getSourceRange());
Steve Naroffb29cdd52007-07-10 18:23:31 +00003265
Daniel Dunbar4782a6e2009-09-17 06:31:17 +00003266 if ((IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_S) ||
Sam Weinigb7608d72009-09-14 20:14:57 +00003267 IndexExpr->getType()->isSpecificBuiltinType(BuiltinType::Char_U))
3268 && !IndexExpr->isTypeDependent())
Sam Weinig914244e2009-09-14 01:58:58 +00003269 Diag(LLoc, diag::warn_subscript_is_char) << IndexExpr->getSourceRange();
3270
Douglas Gregorac1fb652009-03-24 19:52:54 +00003271 // C99 6.5.2.1p1: "shall have type "pointer to *object* type". Similarly,
Mike Stump11289f42009-09-09 15:08:12 +00003272 // C++ [expr.sub]p1: The type "T" shall be a completely-defined object
3273 // type. Note that Functions are not objects, and that (in C99 parlance)
Douglas Gregorac1fb652009-03-24 19:52:54 +00003274 // incomplete types are not object types.
3275 if (ResultType->isFunctionType()) {
3276 Diag(BaseExpr->getLocStart(), diag::err_subscript_function_type)
3277 << ResultType << BaseExpr->getSourceRange();
3278 return ExprError();
3279 }
Mike Stump11289f42009-09-09 15:08:12 +00003280
David Blaikiebbafb8a2012-03-11 07:00:24 +00003281 if (ResultType->isVoidType() && !getLangOpts().CPlusPlus) {
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003282 // GNU extension: subscripting on pointer to void
Chandler Carruth4cc3f292011-06-27 16:32:27 +00003283 Diag(LLoc, diag::ext_gnu_subscript_void_type)
3284 << BaseExpr->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00003285
3286 // C forbids expressions of unqualified void type from being l-values.
3287 // See IsCForbiddenLValueType.
3288 if (!ResultType.hasQualifiers()) VK = VK_RValue;
Abramo Bagnara3aabb4b2010-09-13 06:50:07 +00003289 } else if (!ResultType->isDependentType() &&
Mike Stump11289f42009-09-09 15:08:12 +00003290 RequireCompleteType(LLoc, ResultType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003291 diag::err_subscript_incomplete_type, BaseExpr))
Douglas Gregorac1fb652009-03-24 19:52:54 +00003292 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003293
Chris Lattner62975a72009-04-24 00:30:45 +00003294 // Diagnose bad cases where we step over interface counts.
John McCall8b07ec22010-05-15 11:32:37 +00003295 if (ResultType->isObjCObjectType() && LangOpts.ObjCNonFragileABI) {
Chris Lattner62975a72009-04-24 00:30:45 +00003296 Diag(LLoc, diag::err_subscript_nonfragile_interface)
3297 << ResultType << BaseExpr->getSourceRange();
3298 return ExprError();
3299 }
Mike Stump11289f42009-09-09 15:08:12 +00003300
John McCall4bc41ae2010-11-18 19:01:18 +00003301 assert(VK == VK_RValue || LangOpts.CPlusPlus ||
Douglas Gregor5476205b2011-06-23 00:49:38 +00003302 !ResultType.isCForbiddenLValueType());
John McCall4bc41ae2010-11-18 19:01:18 +00003303
Mike Stump4e1f26a2009-02-19 03:04:26 +00003304 return Owned(new (Context) ArraySubscriptExpr(LHSExp, RHSExp,
John McCall7decc9e2010-11-18 06:31:45 +00003305 ResultType, VK, OK, RLoc));
Chris Lattnere168f762006-11-10 05:29:30 +00003306}
3307
John McCalldadc5752010-08-24 06:29:42 +00003308ExprResult Sema::BuildCXXDefaultArgExpr(SourceLocation CallLoc,
Nico Weber44887f62010-11-29 18:19:25 +00003309 FunctionDecl *FD,
3310 ParmVarDecl *Param) {
Anders Carlsson355933d2009-08-25 03:49:14 +00003311 if (Param->hasUnparsedDefaultArg()) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003312 Diag(CallLoc,
Nico Weberebd45a02010-11-30 04:44:33 +00003313 diag::err_use_of_default_argument_to_function_declared_later) <<
Anders Carlsson355933d2009-08-25 03:49:14 +00003314 FD << cast<CXXRecordDecl>(FD->getDeclContext())->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00003315 Diag(UnparsedDefaultArgLocs[Param],
Nico Weberebd45a02010-11-30 04:44:33 +00003316 diag::note_default_argument_declared_here);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003317 return ExprError();
3318 }
3319
3320 if (Param->hasUninstantiatedDefaultArg()) {
3321 Expr *UninstExpr = Param->getUninstantiatedDefaultArg();
Anders Carlsson355933d2009-08-25 03:49:14 +00003322
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003323 // Instantiate the expression.
3324 MultiLevelTemplateArgumentList ArgList
3325 = getTemplateInstantiationArgs(FD, 0, /*RelativeToPrimary=*/true);
Anders Carlsson657bad42009-09-05 05:14:19 +00003326
Nico Weber44887f62010-11-29 18:19:25 +00003327 std::pair<const TemplateArgument *, unsigned> Innermost
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003328 = ArgList.getInnermost();
3329 InstantiatingTemplate Inst(*this, CallLoc, Param, Innermost.first,
3330 Innermost.second);
Anders Carlsson355933d2009-08-25 03:49:14 +00003331
Nico Weber44887f62010-11-29 18:19:25 +00003332 ExprResult Result;
3333 {
3334 // C++ [dcl.fct.default]p5:
3335 // The names in the [default argument] expression are bound, and
3336 // the semantic constraints are checked, at the point where the
3337 // default argument expression appears.
Nico Weberebd45a02010-11-30 04:44:33 +00003338 ContextRAII SavedContext(*this, FD);
Douglas Gregora86bc002012-02-16 21:36:18 +00003339 LocalInstantiationScope Local(*this);
Nico Weber44887f62010-11-29 18:19:25 +00003340 Result = SubstExpr(UninstExpr, ArgList);
3341 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003342 if (Result.isInvalid())
3343 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003344
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003345 // Check the expression as an initializer for the parameter.
3346 InitializedEntity Entity
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003347 = InitializedEntity::InitializeParameter(Context, Param);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003348 InitializationKind Kind
3349 = InitializationKind::CreateCopy(Param->getLocation(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003350 /*FIXME:EqualLoc*/UninstExpr->getLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003351 Expr *ResultE = Result.takeAs<Expr>();
Douglas Gregor25ab25f2009-12-23 18:19:08 +00003352
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003353 InitializationSequence InitSeq(*this, Entity, Kind, &ResultE, 1);
3354 Result = InitSeq.Perform(*this, Entity, Kind,
3355 MultiExprArg(*this, &ResultE, 1));
3356 if (Result.isInvalid())
3357 return ExprError();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003358
David Blaikief68e8092012-04-30 18:21:31 +00003359 Expr *Arg = Result.takeAs<Expr>();
David Blaikie18e9ac72012-05-15 21:57:38 +00003360 CheckImplicitConversions(Arg, Param->getOuterLocStart());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003361 // Build the default argument expression.
David Blaikief68e8092012-04-30 18:21:31 +00003362 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param, Arg));
Anders Carlsson355933d2009-08-25 03:49:14 +00003363 }
3364
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003365 // If the default expression creates temporaries, we need to
3366 // push them to the current stack of expression temporaries so they'll
3367 // be properly destroyed.
3368 // FIXME: We should really be rebuilding the default argument with new
3369 // bound temporaries; see the comment in PR5810.
John McCall28fc7092011-11-10 05:35:25 +00003370 // We don't need to do that with block decls, though, because
3371 // blocks in default argument expression can never capture anything.
3372 if (isa<ExprWithCleanups>(Param->getInit())) {
3373 // Set the "needs cleanups" bit regardless of whether there are
3374 // any explicit objects.
John McCall31168b02011-06-15 23:02:42 +00003375 ExprNeedsCleanups = true;
John McCall28fc7092011-11-10 05:35:25 +00003376
3377 // Append all the objects to the cleanup list. Right now, this
3378 // should always be a no-op, because blocks in default argument
3379 // expressions should never be able to capture anything.
3380 assert(!cast<ExprWithCleanups>(Param->getInit())->getNumObjects() &&
3381 "default argument expression has capturing blocks?");
Douglas Gregor6ed2fee2010-09-14 22:55:20 +00003382 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +00003383
3384 // We already type-checked the argument, so we know it works.
Douglas Gregor32b3de52010-09-11 23:32:50 +00003385 // Just mark all of the declarations in this potentially-evaluated expression
3386 // as being "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +00003387 MarkDeclarationsReferencedInExpr(Param->getDefaultArg(),
3388 /*SkipLocalVariables=*/true);
Douglas Gregor033f6752009-12-23 23:03:06 +00003389 return Owned(CXXDefaultArgExpr::Create(Context, CallLoc, Param));
Anders Carlsson355933d2009-08-25 03:49:14 +00003390}
3391
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003392/// ConvertArgumentsForCall - Converts the arguments specified in
3393/// Args/NumArgs to the parameter types of the function FDecl with
3394/// function prototype Proto. Call is the call expression itself, and
3395/// Fn is the function expression. For a C++ member function, this
3396/// routine does not attempt to convert the object argument. Returns
3397/// true if the call is ill-formed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00003398bool
3399Sema::ConvertArgumentsForCall(CallExpr *Call, Expr *Fn,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003400 FunctionDecl *FDecl,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003401 const FunctionProtoType *Proto,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003402 Expr **Args, unsigned NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003403 SourceLocation RParenLoc,
3404 bool IsExecConfig) {
John McCallbebede42011-02-26 05:39:39 +00003405 // Bail out early if calling a builtin with custom typechecking.
3406 // We don't need to do this in the
3407 if (FDecl)
3408 if (unsigned ID = FDecl->getBuiltinID())
3409 if (Context.BuiltinInfo.hasCustomTypechecking(ID))
3410 return false;
3411
Mike Stump4e1f26a2009-02-19 03:04:26 +00003412 // C99 6.5.2.2p7 - the arguments are implicitly converted, as if by
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003413 // assignment, to the types of the corresponding parameter, ...
3414 unsigned NumArgsInProto = Proto->getNumArgs();
Douglas Gregorb6b99612009-01-23 21:30:56 +00003415 bool Invalid = false;
Peter Collingbourne740afe22011-10-02 23:49:20 +00003416 unsigned MinArgs = FDecl ? FDecl->getMinRequiredArguments() : NumArgsInProto;
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003417 unsigned FnKind = Fn->getType()->isBlockPointerType()
3418 ? 1 /* block */
3419 : (IsExecConfig ? 3 /* kernel function (exec config) */
3420 : 0 /* function */);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003421
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003422 // If too few arguments are available (and we don't have default
3423 // arguments for the remaining parameters), don't make the call.
3424 if (NumArgs < NumArgsInProto) {
Peter Collingbourne740afe22011-10-02 23:49:20 +00003425 if (NumArgs < MinArgs) {
Richard Smith10ff50d2012-05-11 05:16:41 +00003426 if (MinArgs == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3427 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3428 ? diag::err_typecheck_call_too_few_args_one
3429 : diag::err_typecheck_call_too_few_args_at_least_one)
3430 << FnKind
3431 << FDecl->getParamDecl(0) << Fn->getSourceRange();
3432 else
3433 Diag(RParenLoc, MinArgs == NumArgsInProto && !Proto->isVariadic()
3434 ? diag::err_typecheck_call_too_few_args
3435 : diag::err_typecheck_call_too_few_args_at_least)
3436 << FnKind
3437 << MinArgs << NumArgs << Fn->getSourceRange();
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003438
3439 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003440 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003441 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3442 << FDecl;
3443
3444 return true;
3445 }
Ted Kremenek5a201952009-02-07 01:47:29 +00003446 Call->setNumArgs(Context, NumArgsInProto);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003447 }
3448
3449 // If too many are passed and not variadic, error on the extras and drop
3450 // them.
3451 if (NumArgs > NumArgsInProto) {
3452 if (!Proto->isVariadic()) {
Richard Smithd72da152012-05-15 06:21:54 +00003453 if (NumArgsInProto == 1 && FDecl && FDecl->getParamDecl(0)->getDeclName())
3454 Diag(Args[NumArgsInProto]->getLocStart(),
3455 MinArgs == NumArgsInProto
3456 ? diag::err_typecheck_call_too_many_args_one
3457 : diag::err_typecheck_call_too_many_args_at_most_one)
3458 << FnKind
3459 << FDecl->getParamDecl(0) << NumArgs << Fn->getSourceRange()
3460 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3461 Args[NumArgs-1]->getLocEnd());
3462 else
3463 Diag(Args[NumArgsInProto]->getLocStart(),
3464 MinArgs == NumArgsInProto
3465 ? diag::err_typecheck_call_too_many_args
3466 : diag::err_typecheck_call_too_many_args_at_most)
3467 << FnKind
3468 << NumArgsInProto << NumArgs << Fn->getSourceRange()
3469 << SourceRange(Args[NumArgsInProto]->getLocStart(),
3470 Args[NumArgs-1]->getLocEnd());
Ted Kremenek99a337e2011-04-04 17:22:27 +00003471
3472 // Emit the location of the prototype.
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003473 if (FDecl && !FDecl->getBuiltinID() && !IsExecConfig)
Peter Collingbourne3bc84ca2011-07-29 00:24:42 +00003474 Diag(FDecl->getLocStart(), diag::note_callee_decl)
3475 << FDecl;
Ted Kremenek99a337e2011-04-04 17:22:27 +00003476
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003477 // This deletes the extra arguments.
Ted Kremenek5a201952009-02-07 01:47:29 +00003478 Call->setNumArgs(Context, NumArgsInProto);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003479 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003480 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003481 }
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003482 SmallVector<Expr *, 8> AllArgs;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003483 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003484 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
3485 if (Fn->getType()->isBlockPointerType())
3486 CallType = VariadicBlock; // Block
3487 else if (isa<MemberExpr>(Fn))
3488 CallType = VariadicMethod;
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003489 Invalid = GatherArgumentsForCall(Call->getLocStart(), FDecl,
Fariborz Jahanian4fa66ce2009-11-24 21:37:28 +00003490 Proto, 0, Args, NumArgs, AllArgs, CallType);
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003491 if (Invalid)
3492 return true;
3493 unsigned TotalNumArgs = AllArgs.size();
3494 for (unsigned i = 0; i < TotalNumArgs; ++i)
3495 Call->setArg(i, AllArgs[i]);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003496
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003497 return false;
3498}
Mike Stump4e1f26a2009-02-19 03:04:26 +00003499
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003500bool Sema::GatherArgumentsForCall(SourceLocation CallLoc,
3501 FunctionDecl *FDecl,
3502 const FunctionProtoType *Proto,
3503 unsigned FirstProtoArg,
3504 Expr **Args, unsigned NumArgs,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003505 SmallVector<Expr *, 8> &AllArgs,
Douglas Gregor6073dca2012-02-24 23:56:31 +00003506 VariadicCallType CallType,
3507 bool AllowExplicit) {
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003508 unsigned NumArgsInProto = Proto->getNumArgs();
3509 unsigned NumArgsToCheck = NumArgs;
3510 bool Invalid = false;
3511 if (NumArgs != NumArgsInProto)
3512 // Use default arguments for missing arguments
3513 NumArgsToCheck = NumArgsInProto;
3514 unsigned ArgIx = 0;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003515 // Continue to check argument types (even if we have too few/many args).
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003516 for (unsigned i = FirstProtoArg; i != NumArgsToCheck; i++) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003517 QualType ProtoArgType = Proto->getArgType(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003518
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003519 Expr *Arg;
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003520 ParmVarDecl *Param;
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003521 if (ArgIx < NumArgs) {
3522 Arg = Args[ArgIx++];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003523
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003524 if (RequireCompleteType(Arg->getLocStart(),
Eli Friedman3164fb12009-03-22 22:00:50 +00003525 ProtoArgType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003526 diag::err_call_incomplete_argument, Arg))
Eli Friedman3164fb12009-03-22 22:00:50 +00003527 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003528
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003529 // Pass the argument
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003530 Param = 0;
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003531 if (FDecl && i < FDecl->getNumParams())
3532 Param = FDecl->getParamDecl(i);
Douglas Gregor96596c92009-12-22 07:24:36 +00003533
John McCall4124c492011-10-17 18:40:02 +00003534 // Strip the unbridged-cast placeholder expression off, if applicable.
3535 if (Arg->getType() == Context.ARCUnbridgedCastTy &&
3536 FDecl && FDecl->hasAttr<CFAuditedTransferAttr>() &&
3537 (!Param || !Param->hasAttr<CFConsumedAttr>()))
3538 Arg = stripARCUnbridgedCast(Arg);
3539
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003540 InitializedEntity Entity =
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00003541 Param? InitializedEntity::InitializeParameter(Context, Param)
John McCall31168b02011-06-15 23:02:42 +00003542 : InitializedEntity::InitializeParameter(Context, ProtoArgType,
3543 Proto->isArgConsumed(i));
John McCalldadc5752010-08-24 06:29:42 +00003544 ExprResult ArgE = PerformCopyInitialization(Entity,
John McCall34376a62010-12-04 03:47:34 +00003545 SourceLocation(),
Douglas Gregor6073dca2012-02-24 23:56:31 +00003546 Owned(Arg),
3547 /*TopLevelOfInitList=*/false,
3548 AllowExplicit);
Douglas Gregorbbeb5c32009-12-22 16:09:06 +00003549 if (ArgE.isInvalid())
3550 return true;
3551
3552 Arg = ArgE.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003553 } else {
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003554 Param = FDecl->getParamDecl(i);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003555
John McCalldadc5752010-08-24 06:29:42 +00003556 ExprResult ArgExpr =
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003557 BuildCXXDefaultArgExpr(CallLoc, FDecl, Param);
Anders Carlsson355933d2009-08-25 03:49:14 +00003558 if (ArgExpr.isInvalid())
3559 return true;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003560
Anders Carlsson355933d2009-08-25 03:49:14 +00003561 Arg = ArgExpr.takeAs<Expr>();
Anders Carlsson84613c42009-06-12 16:51:40 +00003562 }
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00003563
3564 // Check for array bounds violations for each argument to the call. This
3565 // check only triggers warnings when the argument isn't a more complex Expr
3566 // with its own checking, such as a BinaryOperator.
3567 CheckArrayAccess(Arg);
3568
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003569 // Check for violations of C99 static array rules (C99 6.7.5.3p7).
3570 CheckStaticArrayArgument(CallLoc, Param, Arg);
3571
Fariborz Jahanian835026e2009-11-24 18:29:37 +00003572 AllArgs.push_back(Arg);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003573 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003574
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003575 // If this is a variadic call, handle args passed through "...".
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00003576 if (CallType != VariadicDoesNotApply) {
John McCall2979fe02011-04-12 00:42:48 +00003577
3578 // Assume that extern "C" functions with variadic arguments that
3579 // return __unknown_anytype aren't *really* variadic.
3580 if (Proto->getResultType() == Context.UnknownAnyTy &&
3581 FDecl && FDecl->isExternC()) {
3582 for (unsigned i = ArgIx; i != NumArgs; ++i) {
3583 ExprResult arg;
3584 if (isa<ExplicitCastExpr>(Args[i]->IgnoreParens()))
3585 arg = DefaultFunctionArrayLvalueConversion(Args[i]);
3586 else
3587 arg = DefaultVariadicArgumentPromotion(Args[i], CallType, FDecl);
3588 Invalid |= arg.isInvalid();
3589 AllArgs.push_back(arg.take());
3590 }
3591
3592 // Otherwise do argument promotion, (C99 6.5.2.2p7).
3593 } else {
3594 for (unsigned i = ArgIx; i != NumArgs; ++i) {
Richard Trieucfc491d2011-08-02 04:35:43 +00003595 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], CallType,
3596 FDecl);
John McCall2979fe02011-04-12 00:42:48 +00003597 Invalid |= Arg.isInvalid();
3598 AllArgs.push_back(Arg.take());
3599 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003600 }
Ted Kremenekd41f3462011-09-26 23:36:13 +00003601
3602 // Check for array bounds violations.
3603 for (unsigned i = ArgIx; i != NumArgs; ++i)
3604 CheckArrayAccess(Args[i]);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003605 }
Douglas Gregorb6b99612009-01-23 21:30:56 +00003606 return Invalid;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003607}
3608
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003609static void DiagnoseCalleeStaticArrayParam(Sema &S, ParmVarDecl *PVD) {
3610 TypeLoc TL = PVD->getTypeSourceInfo()->getTypeLoc();
3611 if (ArrayTypeLoc *ATL = dyn_cast<ArrayTypeLoc>(&TL))
3612 S.Diag(PVD->getLocation(), diag::note_callee_static_array)
3613 << ATL->getLocalSourceRange();
3614}
3615
3616/// CheckStaticArrayArgument - If the given argument corresponds to a static
3617/// array parameter, check that it is non-null, and that if it is formed by
3618/// array-to-pointer decay, the underlying array is sufficiently large.
3619///
3620/// C99 6.7.5.3p7: If the keyword static also appears within the [ and ] of the
3621/// array type derivation, then for each call to the function, the value of the
3622/// corresponding actual argument shall provide access to the first element of
3623/// an array with at least as many elements as specified by the size expression.
3624void
3625Sema::CheckStaticArrayArgument(SourceLocation CallLoc,
3626 ParmVarDecl *Param,
3627 const Expr *ArgExpr) {
3628 // Static array parameters are not supported in C++.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003629 if (!Param || getLangOpts().CPlusPlus)
Peter Collingbournea48f33f2011-10-19 00:16:45 +00003630 return;
3631
3632 QualType OrigTy = Param->getOriginalType();
3633
3634 const ArrayType *AT = Context.getAsArrayType(OrigTy);
3635 if (!AT || AT->getSizeModifier() != ArrayType::Static)
3636 return;
3637
3638 if (ArgExpr->isNullPointerConstant(Context,
3639 Expr::NPC_NeverValueDependent)) {
3640 Diag(CallLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
3641 DiagnoseCalleeStaticArrayParam(*this, Param);
3642 return;
3643 }
3644
3645 const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT);
3646 if (!CAT)
3647 return;
3648
3649 const ConstantArrayType *ArgCAT =
3650 Context.getAsConstantArrayType(ArgExpr->IgnoreParenImpCasts()->getType());
3651 if (!ArgCAT)
3652 return;
3653
3654 if (ArgCAT->getSize().ult(CAT->getSize())) {
3655 Diag(CallLoc, diag::warn_static_array_too_small)
3656 << ArgExpr->getSourceRange()
3657 << (unsigned) ArgCAT->getSize().getZExtValue()
3658 << (unsigned) CAT->getSize().getZExtValue();
3659 DiagnoseCalleeStaticArrayParam(*this, Param);
3660 }
3661}
3662
John McCall2979fe02011-04-12 00:42:48 +00003663/// Given a function expression of unknown-any type, try to rebuild it
3664/// to have a function type.
3665static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *fn);
3666
Steve Naroff83895f72007-09-16 03:34:24 +00003667/// ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
Chris Lattnere168f762006-11-10 05:29:30 +00003668/// This provides the location of the left/right parens and a list of comma
3669/// locations.
John McCalldadc5752010-08-24 06:29:42 +00003670ExprResult
John McCallb268a282010-08-23 23:25:46 +00003671Sema::ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003672 MultiExprArg ArgExprs, SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003673 Expr *ExecConfig, bool IsExecConfig) {
Richard Trieuba63ce62011-09-09 01:45:06 +00003674 unsigned NumArgs = ArgExprs.size();
Nate Begeman5ec4b312009-08-10 23:49:36 +00003675
3676 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00003677 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Fn);
John McCallb268a282010-08-23 23:25:46 +00003678 if (Result.isInvalid()) return ExprError();
3679 Fn = Result.take();
Mike Stump11289f42009-09-09 15:08:12 +00003680
Richard Trieuba63ce62011-09-09 01:45:06 +00003681 Expr **Args = ArgExprs.release();
Mike Stump11289f42009-09-09 15:08:12 +00003682
David Blaikiebbafb8a2012-03-11 07:00:24 +00003683 if (getLangOpts().CPlusPlus) {
Douglas Gregorad8a3362009-09-04 17:36:40 +00003684 // If this is a pseudo-destructor expression, build the call immediately.
3685 if (isa<CXXPseudoDestructorExpr>(Fn)) {
3686 if (NumArgs > 0) {
3687 // Pseudo-destructor calls should not have any arguments.
3688 Diag(Fn->getLocStart(), diag::err_pseudo_dtor_call_with_args)
Douglas Gregora771f462010-03-31 17:46:05 +00003689 << FixItHint::CreateRemoval(
Douglas Gregorad8a3362009-09-04 17:36:40 +00003690 SourceRange(Args[0]->getLocStart(),
3691 Args[NumArgs-1]->getLocEnd()));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003692 }
Mike Stump11289f42009-09-09 15:08:12 +00003693
Douglas Gregorad8a3362009-09-04 17:36:40 +00003694 return Owned(new (Context) CallExpr(Context, Fn, 0, 0, Context.VoidTy,
John McCall7decc9e2010-11-18 06:31:45 +00003695 VK_RValue, RParenLoc));
Douglas Gregorad8a3362009-09-04 17:36:40 +00003696 }
Mike Stump11289f42009-09-09 15:08:12 +00003697
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003698 // Determine whether this is a dependent call inside a C++ template,
Mike Stump4e1f26a2009-02-19 03:04:26 +00003699 // in which case we won't do any semantic analysis now.
Mike Stump87c57ac2009-05-16 07:39:55 +00003700 // FIXME: Will need to cache the results of name lookup (including ADL) in
3701 // Fn.
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003702 bool Dependent = false;
3703 if (Fn->isTypeDependent())
3704 Dependent = true;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003705 else if (Expr::hasAnyTypeDependentArguments(
3706 llvm::makeArrayRef(Args, NumArgs)))
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003707 Dependent = true;
3708
Peter Collingbourne41f85462011-02-09 21:07:24 +00003709 if (Dependent) {
3710 if (ExecConfig) {
3711 return Owned(new (Context) CUDAKernelCallExpr(
3712 Context, Fn, cast<CallExpr>(ExecConfig), Args, NumArgs,
3713 Context.DependentTy, VK_RValue, RParenLoc));
3714 } else {
3715 return Owned(new (Context) CallExpr(Context, Fn, Args, NumArgs,
3716 Context.DependentTy, VK_RValue,
3717 RParenLoc));
3718 }
3719 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003720
3721 // Determine whether this is a call to an object (C++ [over.call.object]).
3722 if (Fn->getType()->isRecordType())
3723 return Owned(BuildCallToObjectOfClassType(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003724 RParenLoc));
Douglas Gregorb8a9a412009-02-04 15:01:18 +00003725
John McCall2979fe02011-04-12 00:42:48 +00003726 if (Fn->getType() == Context.UnknownAnyTy) {
3727 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3728 if (result.isInvalid()) return ExprError();
3729 Fn = result.take();
3730 }
3731
John McCall0009fcc2011-04-26 20:42:42 +00003732 if (Fn->getType() == Context.BoundMemberTy) {
John McCall2d74de92009-12-01 22:10:20 +00003733 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003734 RParenLoc);
John McCall10eae182009-11-30 22:42:35 +00003735 }
John McCall0009fcc2011-04-26 20:42:42 +00003736 }
John McCall10eae182009-11-30 22:42:35 +00003737
John McCall0009fcc2011-04-26 20:42:42 +00003738 // Check for overloaded calls. This can happen even in C due to extensions.
3739 if (Fn->getType() == Context.OverloadTy) {
3740 OverloadExpr::FindResult find = OverloadExpr::find(Fn);
3741
Douglas Gregorcda22702011-10-13 18:10:35 +00003742 // We aren't supposed to apply this logic for if there's an '&' involved.
Douglas Gregorf4a06c22011-10-13 18:26:27 +00003743 if (!find.HasFormOfMemberPointer) {
John McCall0009fcc2011-04-26 20:42:42 +00003744 OverloadExpr *ovl = find.Expression;
3745 if (isa<UnresolvedLookupExpr>(ovl)) {
3746 UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(ovl);
3747 return BuildOverloadedCallExpr(S, Fn, ULE, LParenLoc, Args, NumArgs,
3748 RParenLoc, ExecConfig);
3749 } else {
John McCall2d74de92009-12-01 22:10:20 +00003750 return BuildCallToMemberFunction(S, Fn, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00003751 RParenLoc);
Anders Carlsson61914b52009-10-03 17:40:22 +00003752 }
3753 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003754 }
3755
Douglas Gregore254f902009-02-04 00:32:51 +00003756 // If we're directly calling a function, get the appropriate declaration.
Douglas Gregord8fb1e32011-12-01 01:37:36 +00003757 if (Fn->getType() == Context.UnknownAnyTy) {
3758 ExprResult result = rebuildUnknownAnyFunction(*this, Fn);
3759 if (result.isInvalid()) return ExprError();
3760 Fn = result.take();
3761 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00003762
Eli Friedmane14b1992009-12-26 03:35:45 +00003763 Expr *NakedFn = Fn->IgnoreParens();
Douglas Gregor928479e2010-11-09 20:03:54 +00003764
John McCall57500772009-12-16 12:17:52 +00003765 NamedDecl *NDecl = 0;
Douglas Gregor59f16ed2010-10-25 20:48:33 +00003766 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(NakedFn))
3767 if (UnOp->getOpcode() == UO_AddrOf)
3768 NakedFn = UnOp->getSubExpr()->IgnoreParens();
3769
John McCall57500772009-12-16 12:17:52 +00003770 if (isa<DeclRefExpr>(NakedFn))
3771 NDecl = cast<DeclRefExpr>(NakedFn)->getDecl();
John McCall0009fcc2011-04-26 20:42:42 +00003772 else if (isa<MemberExpr>(NakedFn))
3773 NDecl = cast<MemberExpr>(NakedFn)->getMemberDecl();
John McCall57500772009-12-16 12:17:52 +00003774
Peter Collingbourne41f85462011-02-09 21:07:24 +00003775 return BuildResolvedCallExpr(Fn, NDecl, LParenLoc, Args, NumArgs, RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003776 ExecConfig, IsExecConfig);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003777}
3778
3779ExprResult
3780Sema::ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00003781 MultiExprArg ExecConfig, SourceLocation GGGLoc) {
Peter Collingbourne41f85462011-02-09 21:07:24 +00003782 FunctionDecl *ConfigDecl = Context.getcudaConfigureCallDecl();
3783 if (!ConfigDecl)
3784 return ExprError(Diag(LLLLoc, diag::err_undeclared_var_use)
3785 << "cudaConfigureCall");
3786 QualType ConfigQTy = ConfigDecl->getType();
3787
3788 DeclRefExpr *ConfigDR = new (Context) DeclRefExpr(
John McCall113bee02012-03-10 09:33:50 +00003789 ConfigDecl, false, ConfigQTy, VK_LValue, LLLLoc);
Eli Friedmanfa0df832012-02-02 03:46:19 +00003790 MarkFunctionReferenced(LLLLoc, ConfigDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00003791
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003792 return ActOnCallExpr(S, ConfigDR, LLLLoc, ExecConfig, GGGLoc, 0,
3793 /*IsExecConfig=*/true);
John McCall2d74de92009-12-01 22:10:20 +00003794}
3795
Tanya Lattner55808c12011-06-04 00:47:47 +00003796/// ActOnAsTypeExpr - create a new asType (bitcast) from the arguments.
3797///
3798/// __builtin_astype( value, dst type )
3799///
Richard Trieuba63ce62011-09-09 01:45:06 +00003800ExprResult Sema::ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003801 SourceLocation BuiltinLoc,
3802 SourceLocation RParenLoc) {
3803 ExprValueKind VK = VK_RValue;
3804 ExprObjectKind OK = OK_Ordinary;
Richard Trieuba63ce62011-09-09 01:45:06 +00003805 QualType DstTy = GetTypeFromParser(ParsedDestTy);
3806 QualType SrcTy = E->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003807 if (Context.getTypeSize(DstTy) != Context.getTypeSize(SrcTy))
3808 return ExprError(Diag(BuiltinLoc,
3809 diag::err_invalid_astype_of_different_size)
Peter Collingbourne23f1bee2011-06-08 15:15:17 +00003810 << DstTy
3811 << SrcTy
Richard Trieuba63ce62011-09-09 01:45:06 +00003812 << E->getSourceRange());
3813 return Owned(new (Context) AsTypeExpr(E, DstTy, VK, OK, BuiltinLoc,
Richard Trieucfc491d2011-08-02 04:35:43 +00003814 RParenLoc));
Tanya Lattner55808c12011-06-04 00:47:47 +00003815}
3816
John McCall57500772009-12-16 12:17:52 +00003817/// BuildResolvedCallExpr - Build a call to a resolved expression,
3818/// i.e. an expression not of \p OverloadTy. The expression should
John McCall2d74de92009-12-01 22:10:20 +00003819/// unary-convert to an expression of function-pointer or
3820/// block-pointer type.
3821///
3822/// \param NDecl the declaration being called, if available
John McCalldadc5752010-08-24 06:29:42 +00003823ExprResult
John McCall2d74de92009-12-01 22:10:20 +00003824Sema::BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl,
3825 SourceLocation LParenLoc,
3826 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00003827 SourceLocation RParenLoc,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003828 Expr *Config, bool IsExecConfig) {
John McCall2d74de92009-12-01 22:10:20 +00003829 FunctionDecl *FDecl = dyn_cast_or_null<FunctionDecl>(NDecl);
3830
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003831 // Promote the function operand.
John Wiegley01296292011-04-08 18:41:53 +00003832 ExprResult Result = UsualUnaryConversions(Fn);
3833 if (Result.isInvalid())
3834 return ExprError();
3835 Fn = Result.take();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00003836
Chris Lattner08464942007-12-28 05:29:59 +00003837 // Make the call expr early, before semantic checks. This guarantees cleanup
3838 // of arguments and function on error.
Peter Collingbourne41f85462011-02-09 21:07:24 +00003839 CallExpr *TheCall;
Eric Christopher13586ab2012-05-30 01:14:28 +00003840 if (Config)
Peter Collingbourne41f85462011-02-09 21:07:24 +00003841 TheCall = new (Context) CUDAKernelCallExpr(Context, Fn,
3842 cast<CallExpr>(Config),
3843 Args, NumArgs,
3844 Context.BoolTy,
3845 VK_RValue,
3846 RParenLoc);
Eric Christopher13586ab2012-05-30 01:14:28 +00003847 else
Peter Collingbourne41f85462011-02-09 21:07:24 +00003848 TheCall = new (Context) CallExpr(Context, Fn,
3849 Args, NumArgs,
3850 Context.BoolTy,
3851 VK_RValue,
3852 RParenLoc);
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003853
John McCallbebede42011-02-26 05:39:39 +00003854 unsigned BuiltinID = (FDecl ? FDecl->getBuiltinID() : 0);
3855
3856 // Bail out early if calling a builtin with custom typechecking.
3857 if (BuiltinID && Context.BuiltinInfo.hasCustomTypechecking(BuiltinID))
3858 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
3859
John McCall31996342011-04-07 08:22:57 +00003860 retry:
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003861 const FunctionType *FuncT;
John McCallbebede42011-02-26 05:39:39 +00003862 if (const PointerType *PT = Fn->getType()->getAs<PointerType>()) {
Steve Naroff8de9c3a2008-09-05 22:11:13 +00003863 // C99 6.5.2.2p1 - "The expression that denotes the called function shall
3864 // have type pointer to function".
John McCall9dd450b2009-09-21 23:43:11 +00003865 FuncT = PT->getPointeeType()->getAs<FunctionType>();
John McCallbebede42011-02-26 05:39:39 +00003866 if (FuncT == 0)
3867 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3868 << Fn->getType() << Fn->getSourceRange());
3869 } else if (const BlockPointerType *BPT =
3870 Fn->getType()->getAs<BlockPointerType>()) {
3871 FuncT = BPT->getPointeeType()->castAs<FunctionType>();
3872 } else {
John McCall31996342011-04-07 08:22:57 +00003873 // Handle calls to expressions of unknown-any type.
3874 if (Fn->getType() == Context.UnknownAnyTy) {
John McCall2979fe02011-04-12 00:42:48 +00003875 ExprResult rewrite = rebuildUnknownAnyFunction(*this, Fn);
John McCall31996342011-04-07 08:22:57 +00003876 if (rewrite.isInvalid()) return ExprError();
3877 Fn = rewrite.take();
John McCall39439732011-04-09 22:50:59 +00003878 TheCall->setCallee(Fn);
John McCall31996342011-04-07 08:22:57 +00003879 goto retry;
3880 }
3881
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003882 return ExprError(Diag(LParenLoc, diag::err_typecheck_call_not_function)
3883 << Fn->getType() << Fn->getSourceRange());
John McCallbebede42011-02-26 05:39:39 +00003884 }
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003885
David Blaikiebbafb8a2012-03-11 07:00:24 +00003886 if (getLangOpts().CUDA) {
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003887 if (Config) {
3888 // CUDA: Kernel calls must be to global functions
3889 if (FDecl && !FDecl->hasAttr<CUDAGlobalAttr>())
3890 return ExprError(Diag(LParenLoc,diag::err_kern_call_not_global_function)
3891 << FDecl->getName() << Fn->getSourceRange());
3892
3893 // CUDA: Kernel function must have 'void' return type
3894 if (!FuncT->getResultType()->isVoidType())
3895 return ExprError(Diag(LParenLoc, diag::err_kern_type_not_void_return)
3896 << Fn->getType() << Fn->getSourceRange());
Peter Collingbourne34a20b02011-10-02 23:49:15 +00003897 } else {
3898 // CUDA: Calls to global functions must be configured
3899 if (FDecl && FDecl->hasAttr<CUDAGlobalAttr>())
3900 return ExprError(Diag(LParenLoc, diag::err_global_call_not_config)
3901 << FDecl->getName() << Fn->getSourceRange());
Peter Collingbourne4b66c472011-02-23 01:53:29 +00003902 }
3903 }
3904
Eli Friedman3164fb12009-03-22 22:00:50 +00003905 // Check for a valid return type
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00003906 if (CheckCallReturnType(FuncT->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003907 Fn->getLocStart(), TheCall,
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003908 FDecl))
Eli Friedman3164fb12009-03-22 22:00:50 +00003909 return ExprError();
3910
Chris Lattner08464942007-12-28 05:29:59 +00003911 // We know the result type of the call, set it.
Douglas Gregor603d81b2010-07-13 08:18:22 +00003912 TheCall->setType(FuncT->getCallResultType(Context));
John McCall7decc9e2010-11-18 06:31:45 +00003913 TheCall->setValueKind(Expr::getValueKindForType(FuncT->getResultType()));
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003914
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003915 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FuncT)) {
John McCallb268a282010-08-23 23:25:46 +00003916 if (ConvertArgumentsForCall(TheCall, Fn, FDecl, Proto, Args, NumArgs,
Peter Collingbourne619a8c72011-10-02 23:49:29 +00003917 RParenLoc, IsExecConfig))
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003918 return ExprError();
Chris Lattner08464942007-12-28 05:29:59 +00003919 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003920 assert(isa<FunctionNoProtoType>(FuncT) && "Unknown FunctionType!");
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003921
Douglas Gregord8e97de2009-04-02 15:37:10 +00003922 if (FDecl) {
3923 // Check if we have too few/too many template arguments, based
3924 // on our knowledge of the function definition.
3925 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis36ea3222010-07-07 11:31:19 +00003926 if (FDecl->hasBody(Def) && NumArgs != Def->param_size()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003927 const FunctionProtoType *Proto
3928 = Def->getType()->getAs<FunctionProtoType>();
3929 if (!Proto || !(Proto->isVariadic() && NumArgs >= Def->param_size()))
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003930 Diag(RParenLoc, diag::warn_call_wrong_number_of_arguments)
3931 << (NumArgs > Def->param_size()) << FDecl << Fn->getSourceRange();
Eli Friedmanfcbf7d22009-06-01 09:24:59 +00003932 }
Douglas Gregor8e09a722010-10-25 20:39:23 +00003933
3934 // If the function we're calling isn't a function prototype, but we have
3935 // a function prototype from a prior declaratiom, use that prototype.
3936 if (!FDecl->hasPrototype())
3937 Proto = FDecl->getType()->getAs<FunctionProtoType>();
Douglas Gregord8e97de2009-04-02 15:37:10 +00003938 }
3939
Steve Naroff0b661582007-08-28 23:30:39 +00003940 // Promote the arguments (C99 6.5.2.2p6).
Chris Lattner08464942007-12-28 05:29:59 +00003941 for (unsigned i = 0; i != NumArgs; i++) {
3942 Expr *Arg = Args[i];
Douglas Gregor8e09a722010-10-25 20:39:23 +00003943
3944 if (Proto && i < Proto->getNumArgs()) {
Douglas Gregor8e09a722010-10-25 20:39:23 +00003945 InitializedEntity Entity
3946 = InitializedEntity::InitializeParameter(Context,
John McCall31168b02011-06-15 23:02:42 +00003947 Proto->getArgType(i),
3948 Proto->isArgConsumed(i));
Douglas Gregor8e09a722010-10-25 20:39:23 +00003949 ExprResult ArgE = PerformCopyInitialization(Entity,
3950 SourceLocation(),
3951 Owned(Arg));
3952 if (ArgE.isInvalid())
3953 return true;
3954
3955 Arg = ArgE.takeAs<Expr>();
3956
3957 } else {
John Wiegley01296292011-04-08 18:41:53 +00003958 ExprResult ArgE = DefaultArgumentPromotion(Arg);
3959
3960 if (ArgE.isInvalid())
3961 return true;
3962
3963 Arg = ArgE.takeAs<Expr>();
Douglas Gregor8e09a722010-10-25 20:39:23 +00003964 }
3965
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003966 if (RequireCompleteType(Arg->getLocStart(),
Douglas Gregor83025412010-10-26 05:45:40 +00003967 Arg->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003968 diag::err_call_incomplete_argument, Arg))
Douglas Gregor83025412010-10-26 05:45:40 +00003969 return ExprError();
3970
Chris Lattner08464942007-12-28 05:29:59 +00003971 TheCall->setArg(i, Arg);
Steve Naroff0b661582007-08-28 23:30:39 +00003972 }
Steve Naroffae4143e2007-04-26 20:39:23 +00003973 }
Chris Lattner08464942007-12-28 05:29:59 +00003974
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003975 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(FDecl))
3976 if (!Method->isStatic())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00003977 return ExprError(Diag(LParenLoc, diag::err_member_call_without_object)
3978 << Fn->getSourceRange());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003979
Fariborz Jahanian0aa5c452009-05-15 20:33:25 +00003980 // Check for sentinels
3981 if (NDecl)
3982 DiagnoseSentinelCalls(NDecl, LParenLoc, Args, NumArgs);
Mike Stump11289f42009-09-09 15:08:12 +00003983
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003984 // Do special checking on direct calls to functions.
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003985 if (FDecl) {
John McCallb268a282010-08-23 23:25:46 +00003986 if (CheckFunctionCall(FDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003987 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00003988
John McCallbebede42011-02-26 05:39:39 +00003989 if (BuiltinID)
Fariborz Jahaniane8473c22010-11-30 17:35:24 +00003990 return CheckBuiltinFunctionCall(BuiltinID, TheCall);
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003991 } else if (NDecl) {
John McCallb268a282010-08-23 23:25:46 +00003992 if (CheckBlockCall(NDecl, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00003993 return ExprError();
3994 }
Chris Lattnerb87b1b32007-08-10 20:18:51 +00003995
John McCallb268a282010-08-23 23:25:46 +00003996 return MaybeBindToTemporary(TheCall);
Chris Lattnere168f762006-11-10 05:29:30 +00003997}
3998
John McCalldadc5752010-08-24 06:29:42 +00003999ExprResult
John McCallba7bf592010-08-24 05:47:05 +00004000Sema::ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty,
John McCallb268a282010-08-23 23:25:46 +00004001 SourceLocation RParenLoc, Expr *InitExpr) {
Steve Naroff83895f72007-09-16 03:34:24 +00004002 assert((Ty != 0) && "ActOnCompoundLiteral(): missing type");
Steve Naroff57eb2c52007-07-19 21:32:11 +00004003 // FIXME: put back this assert when initializers are worked out.
Steve Naroff83895f72007-09-16 03:34:24 +00004004 //assert((InitExpr != 0) && "ActOnCompoundLiteral(): missing expression");
John McCalle15bbff2010-01-18 19:35:47 +00004005
4006 TypeSourceInfo *TInfo;
4007 QualType literalType = GetTypeFromParser(Ty, &TInfo);
4008 if (!TInfo)
4009 TInfo = Context.getTrivialTypeSourceInfo(literalType);
4010
John McCallb268a282010-08-23 23:25:46 +00004011 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, InitExpr);
John McCalle15bbff2010-01-18 19:35:47 +00004012}
4013
John McCalldadc5752010-08-24 06:29:42 +00004014ExprResult
John McCalle15bbff2010-01-18 19:35:47 +00004015Sema::BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo,
Richard Trieuba63ce62011-09-09 01:45:06 +00004016 SourceLocation RParenLoc, Expr *LiteralExpr) {
John McCalle15bbff2010-01-18 19:35:47 +00004017 QualType literalType = TInfo->getType();
Anders Carlsson2c1ec6d2007-12-05 07:24:19 +00004018
Eli Friedman37a186d2008-05-20 05:22:08 +00004019 if (literalType->isArrayType()) {
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004020 if (RequireCompleteType(LParenLoc, Context.getBaseElementType(literalType),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004021 diag::err_illegal_decl_array_incomplete_type,
4022 SourceRange(LParenLoc,
4023 LiteralExpr->getSourceRange().getEnd())))
Argyrios Kyrtzidis85663562010-11-08 19:14:19 +00004024 return ExprError();
Chris Lattner7adf0762008-08-04 07:31:14 +00004025 if (literalType->isVariableArrayType())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004026 return ExprError(Diag(LParenLoc, diag::err_variable_object_no_init)
Richard Trieuba63ce62011-09-09 01:45:06 +00004027 << SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd()));
Douglas Gregor1c37d9e2009-05-21 23:48:18 +00004028 } else if (!literalType->isDependentType() &&
4029 RequireCompleteType(LParenLoc, literalType,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004030 diag::err_typecheck_decl_incomplete_type,
4031 SourceRange(LParenLoc, LiteralExpr->getSourceRange().getEnd())))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004032 return ExprError();
Eli Friedman37a186d2008-05-20 05:22:08 +00004033
Douglas Gregor85dabae2009-12-16 01:38:02 +00004034 InitializedEntity Entity
Douglas Gregor1b303932009-12-22 15:35:07 +00004035 = InitializedEntity::InitializeTemporary(literalType);
Douglas Gregor85dabae2009-12-16 01:38:02 +00004036 InitializationKind Kind
John McCall31168b02011-06-15 23:02:42 +00004037 = InitializationKind::CreateCStyleCast(LParenLoc,
Sebastian Redl0501c632012-02-12 16:37:36 +00004038 SourceRange(LParenLoc, RParenLoc),
4039 /*InitList=*/true);
Richard Trieuba63ce62011-09-09 01:45:06 +00004040 InitializationSequence InitSeq(*this, Entity, Kind, &LiteralExpr, 1);
John McCalldadc5752010-08-24 06:29:42 +00004041 ExprResult Result = InitSeq.Perform(*this, Entity, Kind,
Richard Trieuba63ce62011-09-09 01:45:06 +00004042 MultiExprArg(*this, &LiteralExpr, 1),
Eli Friedmana553d4a2009-12-22 02:35:53 +00004043 &literalType);
4044 if (Result.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00004045 return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004046 LiteralExpr = Result.get();
Steve Naroffd32419d2008-01-14 18:19:28 +00004047
Chris Lattner79413952008-12-04 23:50:19 +00004048 bool isFileScope = getCurFunctionOrMethodDecl() == 0;
Steve Naroffd32419d2008-01-14 18:19:28 +00004049 if (isFileScope) { // 6.5.2.5p3
Richard Trieuba63ce62011-09-09 01:45:06 +00004050 if (CheckForConstantInitializer(LiteralExpr, literalType))
Sebastian Redlb5d49352009-01-19 22:31:54 +00004051 return ExprError();
Steve Naroff98f72032008-01-10 22:15:12 +00004052 }
Eli Friedmana553d4a2009-12-22 02:35:53 +00004053
John McCall7decc9e2010-11-18 06:31:45 +00004054 // In C, compound literals are l-values for some reason.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004055 ExprValueKind VK = getLangOpts().CPlusPlus ? VK_RValue : VK_LValue;
John McCall7decc9e2010-11-18 06:31:45 +00004056
Douglas Gregor9b71f0c2011-06-17 04:59:12 +00004057 return MaybeBindToTemporary(
4058 new (Context) CompoundLiteralExpr(LParenLoc, TInfo, literalType,
Richard Trieuba63ce62011-09-09 01:45:06 +00004059 VK, LiteralExpr, isFileScope));
Steve Narofffbd09832007-07-19 01:06:55 +00004060}
4061
John McCalldadc5752010-08-24 06:29:42 +00004062ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004063Sema::ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList,
Sebastian Redlb5d49352009-01-19 22:31:54 +00004064 SourceLocation RBraceLoc) {
Richard Trieuba63ce62011-09-09 01:45:06 +00004065 unsigned NumInit = InitArgList.size();
4066 Expr **InitList = InitArgList.release();
Anders Carlsson4692db02007-08-31 04:56:16 +00004067
John McCall526ab472011-10-25 17:37:35 +00004068 // Immediately handle non-overload placeholders. Overloads can be
4069 // resolved contextually, but everything else here can't.
4070 for (unsigned I = 0; I != NumInit; ++I) {
John McCalld5c98ae2011-11-15 01:35:18 +00004071 if (InitList[I]->getType()->isNonOverloadPlaceholderType()) {
John McCall526ab472011-10-25 17:37:35 +00004072 ExprResult result = CheckPlaceholderExpr(InitList[I]);
4073
4074 // Ignore failures; dropping the entire initializer list because
4075 // of one failure would be terrible for indexing/etc.
4076 if (result.isInvalid()) continue;
4077
4078 InitList[I] = result.take();
4079 }
4080 }
4081
Steve Naroff30d242c2007-09-15 18:49:24 +00004082 // Semantic analysis for initializers is done by ActOnDeclarator() and
Mike Stump4e1f26a2009-02-19 03:04:26 +00004083 // CheckInitializer() - it requires knowledge of the object being intialized.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004084
Ted Kremenekac034612010-04-13 23:39:13 +00004085 InitListExpr *E = new (Context) InitListExpr(Context, LBraceLoc, InitList,
4086 NumInit, RBraceLoc);
Chris Lattner24d5bfe2008-04-02 04:24:33 +00004087 E->setType(Context.VoidTy); // FIXME: just a place holder for now.
Sebastian Redlb5d49352009-01-19 22:31:54 +00004088 return Owned(E);
Steve Narofffbd09832007-07-19 01:06:55 +00004089}
4090
John McCallcd78e802011-09-10 01:16:55 +00004091/// Do an explicit extend of the given block pointer if we're in ARC.
4092static void maybeExtendBlockObject(Sema &S, ExprResult &E) {
4093 assert(E.get()->getType()->isBlockPointerType());
4094 assert(E.get()->isRValue());
4095
4096 // Only do this in an r-value context.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004097 if (!S.getLangOpts().ObjCAutoRefCount) return;
John McCallcd78e802011-09-10 01:16:55 +00004098
4099 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(),
John McCall2d637d22011-09-10 06:18:15 +00004100 CK_ARCExtendBlockObject, E.get(),
John McCallcd78e802011-09-10 01:16:55 +00004101 /*base path*/ 0, VK_RValue);
4102 S.ExprNeedsCleanups = true;
4103}
4104
4105/// Prepare a conversion of the given expression to an ObjC object
4106/// pointer type.
4107CastKind Sema::PrepareCastToObjCObjectPointer(ExprResult &E) {
4108 QualType type = E.get()->getType();
4109 if (type->isObjCObjectPointerType()) {
4110 return CK_BitCast;
4111 } else if (type->isBlockPointerType()) {
4112 maybeExtendBlockObject(*this, E);
4113 return CK_BlockPointerToObjCPointerCast;
4114 } else {
4115 assert(type->isPointerType());
4116 return CK_CPointerToObjCPointerCast;
4117 }
4118}
4119
John McCalld7646252010-11-14 08:17:51 +00004120/// Prepares for a scalar cast, performing all the necessary stages
4121/// except the final cast and returning the kind required.
John McCall9776e432011-10-06 23:25:11 +00004122CastKind Sema::PrepareScalarCast(ExprResult &Src, QualType DestTy) {
John McCalld7646252010-11-14 08:17:51 +00004123 // Both Src and Dest are scalar types, i.e. arithmetic or pointer.
4124 // Also, callers should have filtered out the invalid cases with
4125 // pointers. Everything else should be possible.
4126
John Wiegley01296292011-04-08 18:41:53 +00004127 QualType SrcTy = Src.get()->getType();
John McCall9776e432011-10-06 23:25:11 +00004128 if (Context.hasSameUnqualifiedType(SrcTy, DestTy))
John McCalle3027922010-08-25 11:45:40 +00004129 return CK_NoOp;
Anders Carlsson094c4592009-10-18 18:12:03 +00004130
John McCall9320b872011-09-09 05:25:32 +00004131 switch (Type::ScalarTypeKind SrcKind = SrcTy->getScalarTypeKind()) {
John McCall8cb679e2010-11-15 09:13:47 +00004132 case Type::STK_MemberPointer:
4133 llvm_unreachable("member pointer type in C");
Abramo Bagnaraba854972011-01-04 09:50:03 +00004134
John McCall9320b872011-09-09 05:25:32 +00004135 case Type::STK_CPointer:
4136 case Type::STK_BlockPointer:
4137 case Type::STK_ObjCObjectPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004138 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004139 case Type::STK_CPointer:
4140 return CK_BitCast;
4141 case Type::STK_BlockPointer:
4142 return (SrcKind == Type::STK_BlockPointer
4143 ? CK_BitCast : CK_AnyPointerToBlockPointerCast);
4144 case Type::STK_ObjCObjectPointer:
4145 if (SrcKind == Type::STK_ObjCObjectPointer)
4146 return CK_BitCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004147 if (SrcKind == Type::STK_CPointer)
John McCall9320b872011-09-09 05:25:32 +00004148 return CK_CPointerToObjCPointerCast;
David Blaikie8a40f702012-01-17 06:56:22 +00004149 maybeExtendBlockObject(*this, Src);
4150 return CK_BlockPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00004151 case Type::STK_Bool:
4152 return CK_PointerToBoolean;
4153 case Type::STK_Integral:
4154 return CK_PointerToIntegral;
4155 case Type::STK_Floating:
4156 case Type::STK_FloatingComplex:
4157 case Type::STK_IntegralComplex:
4158 case Type::STK_MemberPointer:
4159 llvm_unreachable("illegal cast from pointer");
4160 }
David Blaikie8a40f702012-01-17 06:56:22 +00004161 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004162
John McCall8cb679e2010-11-15 09:13:47 +00004163 case Type::STK_Bool: // casting from bool is like casting from an integer
4164 case Type::STK_Integral:
4165 switch (DestTy->getScalarTypeKind()) {
John McCall9320b872011-09-09 05:25:32 +00004166 case Type::STK_CPointer:
4167 case Type::STK_ObjCObjectPointer:
4168 case Type::STK_BlockPointer:
John McCall9776e432011-10-06 23:25:11 +00004169 if (Src.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00004170 Expr::NPC_ValueDependentIsNull))
John McCalle84af4e2010-11-13 01:35:44 +00004171 return CK_NullToPointer;
John McCalle3027922010-08-25 11:45:40 +00004172 return CK_IntegralToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00004173 case Type::STK_Bool:
4174 return CK_IntegralToBoolean;
4175 case Type::STK_Integral:
John McCalld7646252010-11-14 08:17:51 +00004176 return CK_IntegralCast;
John McCall8cb679e2010-11-15 09:13:47 +00004177 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004178 return CK_IntegralToFloating;
John McCall8cb679e2010-11-15 09:13:47 +00004179 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004180 Src = ImpCastExprToType(Src.take(),
4181 DestTy->castAs<ComplexType>()->getElementType(),
4182 CK_IntegralCast);
John McCalld7646252010-11-14 08:17:51 +00004183 return CK_IntegralRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004184 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004185 Src = ImpCastExprToType(Src.take(),
4186 DestTy->castAs<ComplexType>()->getElementType(),
4187 CK_IntegralToFloating);
John McCalld7646252010-11-14 08:17:51 +00004188 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004189 case Type::STK_MemberPointer:
4190 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004191 }
David Blaikie8a40f702012-01-17 06:56:22 +00004192 llvm_unreachable("Should have returned before this");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004193
John McCall8cb679e2010-11-15 09:13:47 +00004194 case Type::STK_Floating:
4195 switch (DestTy->getScalarTypeKind()) {
4196 case Type::STK_Floating:
John McCalle3027922010-08-25 11:45:40 +00004197 return CK_FloatingCast;
John McCall8cb679e2010-11-15 09:13:47 +00004198 case Type::STK_Bool:
4199 return CK_FloatingToBoolean;
4200 case Type::STK_Integral:
John McCalle3027922010-08-25 11:45:40 +00004201 return CK_FloatingToIntegral;
John McCall8cb679e2010-11-15 09:13:47 +00004202 case Type::STK_FloatingComplex:
John McCall9776e432011-10-06 23:25:11 +00004203 Src = ImpCastExprToType(Src.take(),
4204 DestTy->castAs<ComplexType>()->getElementType(),
4205 CK_FloatingCast);
John McCalld7646252010-11-14 08:17:51 +00004206 return CK_FloatingRealToComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004207 case Type::STK_IntegralComplex:
John McCall9776e432011-10-06 23:25:11 +00004208 Src = ImpCastExprToType(Src.take(),
4209 DestTy->castAs<ComplexType>()->getElementType(),
4210 CK_FloatingToIntegral);
John McCalld7646252010-11-14 08:17:51 +00004211 return CK_IntegralRealToComplex;
John McCall9320b872011-09-09 05:25:32 +00004212 case Type::STK_CPointer:
4213 case Type::STK_ObjCObjectPointer:
4214 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004215 llvm_unreachable("valid float->pointer cast?");
4216 case Type::STK_MemberPointer:
4217 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004218 }
David Blaikie8a40f702012-01-17 06:56:22 +00004219 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004220
John McCall8cb679e2010-11-15 09:13:47 +00004221 case Type::STK_FloatingComplex:
4222 switch (DestTy->getScalarTypeKind()) {
4223 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004224 return CK_FloatingComplexCast;
John McCall8cb679e2010-11-15 09:13:47 +00004225 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004226 return CK_FloatingComplexToIntegralComplex;
John McCallfcef3cf2010-12-14 17:51:41 +00004227 case Type::STK_Floating: {
John McCall9776e432011-10-06 23:25:11 +00004228 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4229 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004230 return CK_FloatingComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004231 Src = ImpCastExprToType(Src.take(), ET, CK_FloatingComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004232 return CK_FloatingCast;
4233 }
John McCall8cb679e2010-11-15 09:13:47 +00004234 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004235 return CK_FloatingComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004236 case Type::STK_Integral:
John McCall9776e432011-10-06 23:25:11 +00004237 Src = ImpCastExprToType(Src.take(),
4238 SrcTy->castAs<ComplexType>()->getElementType(),
4239 CK_FloatingComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004240 return CK_FloatingToIntegral;
John McCall9320b872011-09-09 05:25:32 +00004241 case Type::STK_CPointer:
4242 case Type::STK_ObjCObjectPointer:
4243 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004244 llvm_unreachable("valid complex float->pointer cast?");
4245 case Type::STK_MemberPointer:
4246 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004247 }
David Blaikie8a40f702012-01-17 06:56:22 +00004248 llvm_unreachable("Should have returned before this");
John McCalld7646252010-11-14 08:17:51 +00004249
John McCall8cb679e2010-11-15 09:13:47 +00004250 case Type::STK_IntegralComplex:
4251 switch (DestTy->getScalarTypeKind()) {
4252 case Type::STK_FloatingComplex:
John McCalld7646252010-11-14 08:17:51 +00004253 return CK_IntegralComplexToFloatingComplex;
John McCall8cb679e2010-11-15 09:13:47 +00004254 case Type::STK_IntegralComplex:
John McCalld7646252010-11-14 08:17:51 +00004255 return CK_IntegralComplexCast;
John McCallfcef3cf2010-12-14 17:51:41 +00004256 case Type::STK_Integral: {
John McCall9776e432011-10-06 23:25:11 +00004257 QualType ET = SrcTy->castAs<ComplexType>()->getElementType();
4258 if (Context.hasSameType(ET, DestTy))
John McCallfcef3cf2010-12-14 17:51:41 +00004259 return CK_IntegralComplexToReal;
John McCall9776e432011-10-06 23:25:11 +00004260 Src = ImpCastExprToType(Src.take(), ET, CK_IntegralComplexToReal);
John McCallfcef3cf2010-12-14 17:51:41 +00004261 return CK_IntegralCast;
4262 }
John McCall8cb679e2010-11-15 09:13:47 +00004263 case Type::STK_Bool:
John McCalld7646252010-11-14 08:17:51 +00004264 return CK_IntegralComplexToBoolean;
John McCall8cb679e2010-11-15 09:13:47 +00004265 case Type::STK_Floating:
John McCall9776e432011-10-06 23:25:11 +00004266 Src = ImpCastExprToType(Src.take(),
4267 SrcTy->castAs<ComplexType>()->getElementType(),
4268 CK_IntegralComplexToReal);
John McCalld7646252010-11-14 08:17:51 +00004269 return CK_IntegralToFloating;
John McCall9320b872011-09-09 05:25:32 +00004270 case Type::STK_CPointer:
4271 case Type::STK_ObjCObjectPointer:
4272 case Type::STK_BlockPointer:
John McCall8cb679e2010-11-15 09:13:47 +00004273 llvm_unreachable("valid complex int->pointer cast?");
4274 case Type::STK_MemberPointer:
4275 llvm_unreachable("member pointer type in C");
John McCalld7646252010-11-14 08:17:51 +00004276 }
David Blaikie8a40f702012-01-17 06:56:22 +00004277 llvm_unreachable("Should have returned before this");
Anders Carlsson094c4592009-10-18 18:12:03 +00004278 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004279
John McCalld7646252010-11-14 08:17:51 +00004280 llvm_unreachable("Unhandled scalar cast");
Anders Carlsson094c4592009-10-18 18:12:03 +00004281}
4282
Anders Carlsson525b76b2009-10-16 02:48:28 +00004283bool Sema::CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty,
John McCalle3027922010-08-25 11:45:40 +00004284 CastKind &Kind) {
Anders Carlssonde71adf2007-11-27 05:51:55 +00004285 assert(VectorTy->isVectorType() && "Not a vector type!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00004286
Anders Carlssonde71adf2007-11-27 05:51:55 +00004287 if (Ty->isVectorType() || Ty->isIntegerType()) {
Chris Lattner37e05872008-03-05 18:54:05 +00004288 if (Context.getTypeSize(VectorTy) != Context.getTypeSize(Ty))
Anders Carlssonde71adf2007-11-27 05:51:55 +00004289 return Diag(R.getBegin(),
Mike Stump4e1f26a2009-02-19 03:04:26 +00004290 Ty->isVectorType() ?
Anders Carlssonde71adf2007-11-27 05:51:55 +00004291 diag::err_invalid_conversion_between_vectors :
Chris Lattner3b054132008-11-19 05:08:23 +00004292 diag::err_invalid_conversion_between_vector_and_integer)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004293 << VectorTy << Ty << R;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004294 } else
4295 return Diag(R.getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004296 diag::err_invalid_conversion_between_vector_and_scalar)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004297 << VectorTy << Ty << R;
Mike Stump4e1f26a2009-02-19 03:04:26 +00004298
John McCalle3027922010-08-25 11:45:40 +00004299 Kind = CK_BitCast;
Anders Carlssonde71adf2007-11-27 05:51:55 +00004300 return false;
4301}
4302
John Wiegley01296292011-04-08 18:41:53 +00004303ExprResult Sema::CheckExtVectorCast(SourceRange R, QualType DestTy,
4304 Expr *CastExpr, CastKind &Kind) {
Nate Begemanc69b7402009-06-26 00:50:28 +00004305 assert(DestTy->isExtVectorType() && "Not an extended vector type!");
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004306
Anders Carlsson43d70f82009-10-16 05:23:41 +00004307 QualType SrcTy = CastExpr->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004308
Nate Begemanc8961a42009-06-27 22:05:55 +00004309 // If SrcTy is a VectorType, the total size must match to explicitly cast to
4310 // an ExtVectorType.
Tobias Grosser766bcc22011-09-22 13:03:14 +00004311 // In OpenCL, casts between vectors of different types are not allowed.
4312 // (See OpenCL 6.2).
Nate Begemanc69b7402009-06-26 00:50:28 +00004313 if (SrcTy->isVectorType()) {
Tobias Grosser766bcc22011-09-22 13:03:14 +00004314 if (Context.getTypeSize(DestTy) != Context.getTypeSize(SrcTy)
David Blaikiebbafb8a2012-03-11 07:00:24 +00004315 || (getLangOpts().OpenCL &&
Tobias Grosser766bcc22011-09-22 13:03:14 +00004316 (DestTy.getCanonicalType() != SrcTy.getCanonicalType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004317 Diag(R.getBegin(),diag::err_invalid_conversion_between_ext_vectors)
Nate Begemanc69b7402009-06-26 00:50:28 +00004318 << DestTy << SrcTy << R;
John Wiegley01296292011-04-08 18:41:53 +00004319 return ExprError();
4320 }
John McCalle3027922010-08-25 11:45:40 +00004321 Kind = CK_BitCast;
John Wiegley01296292011-04-08 18:41:53 +00004322 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004323 }
4324
Nate Begemanbd956c42009-06-28 02:36:38 +00004325 // All non-pointer scalars can be cast to ExtVector type. The appropriate
Nate Begemanc69b7402009-06-26 00:50:28 +00004326 // conversion will take place first from scalar to elt type, and then
4327 // splat from elt type to vector.
Nate Begemanbd956c42009-06-28 02:36:38 +00004328 if (SrcTy->isPointerType())
4329 return Diag(R.getBegin(),
4330 diag::err_invalid_conversion_between_vector_and_scalar)
4331 << DestTy << SrcTy << R;
Eli Friedman06ed2a52009-10-20 08:27:19 +00004332
4333 QualType DestElemTy = DestTy->getAs<ExtVectorType>()->getElementType();
John Wiegley01296292011-04-08 18:41:53 +00004334 ExprResult CastExprRes = Owned(CastExpr);
John McCall9776e432011-10-06 23:25:11 +00004335 CastKind CK = PrepareScalarCast(CastExprRes, DestElemTy);
John Wiegley01296292011-04-08 18:41:53 +00004336 if (CastExprRes.isInvalid())
4337 return ExprError();
4338 CastExpr = ImpCastExprToType(CastExprRes.take(), DestElemTy, CK).take();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004339
John McCalle3027922010-08-25 11:45:40 +00004340 Kind = CK_VectorSplat;
John Wiegley01296292011-04-08 18:41:53 +00004341 return Owned(CastExpr);
Nate Begemanc69b7402009-06-26 00:50:28 +00004342}
4343
John McCalldadc5752010-08-24 06:29:42 +00004344ExprResult
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004345Sema::ActOnCastExpr(Scope *S, SourceLocation LParenLoc,
4346 Declarator &D, ParsedType &Ty,
Richard Trieuba63ce62011-09-09 01:45:06 +00004347 SourceLocation RParenLoc, Expr *CastExpr) {
4348 assert(!D.isInvalidType() && (CastExpr != 0) &&
Sebastian Redlb5d49352009-01-19 22:31:54 +00004349 "ActOnCastExpr(): missing type or expr");
Steve Naroff1a2cf6b2007-07-16 23:25:18 +00004350
Richard Trieuba63ce62011-09-09 01:45:06 +00004351 TypeSourceInfo *castTInfo = GetTypeForDeclaratorCast(D, CastExpr->getType());
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004352 if (D.isInvalidType())
4353 return ExprError();
4354
David Blaikiebbafb8a2012-03-11 07:00:24 +00004355 if (getLangOpts().CPlusPlus) {
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004356 // Check that there are no default arguments (C++ only).
4357 CheckExtraCXXDefaultArguments(D);
4358 }
4359
John McCall42856de2011-10-01 05:17:03 +00004360 checkUnusedDeclAttributes(D);
4361
Argyrios Kyrtzidis7192a3b2011-07-01 22:22:59 +00004362 QualType castType = castTInfo->getType();
4363 Ty = CreateParsedType(castType, castTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004364
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004365 bool isVectorLiteral = false;
4366
4367 // Check for an altivec or OpenCL literal,
4368 // i.e. all the elements are integer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00004369 ParenExpr *PE = dyn_cast<ParenExpr>(CastExpr);
4370 ParenListExpr *PLE = dyn_cast<ParenListExpr>(CastExpr);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004371 if ((getLangOpts().AltiVec || getLangOpts().OpenCL)
Tobias Grosser0a3a22f2011-09-21 18:28:29 +00004372 && castType->isVectorType() && (PE || PLE)) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004373 if (PLE && PLE->getNumExprs() == 0) {
4374 Diag(PLE->getExprLoc(), diag::err_altivec_empty_initializer);
4375 return ExprError();
4376 }
4377 if (PE || PLE->getNumExprs() == 1) {
4378 Expr *E = (PE ? PE->getSubExpr() : PLE->getExpr(0));
4379 if (!E->getType()->isVectorType())
4380 isVectorLiteral = true;
4381 }
4382 else
4383 isVectorLiteral = true;
4384 }
4385
4386 // If this is a vector initializer, '(' type ')' '(' init, ..., init ')'
4387 // then handle it as such.
4388 if (isVectorLiteral)
Richard Trieuba63ce62011-09-09 01:45:06 +00004389 return BuildVectorLiteral(LParenLoc, RParenLoc, CastExpr, castTInfo);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004390
Nate Begeman5ec4b312009-08-10 23:49:36 +00004391 // If the Expr being casted is a ParenListExpr, handle it specially.
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004392 // This is not an AltiVec-style cast, so turn the ParenListExpr into a
4393 // sequence of BinOp comma operators.
Richard Trieuba63ce62011-09-09 01:45:06 +00004394 if (isa<ParenListExpr>(CastExpr)) {
4395 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, CastExpr);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004396 if (Result.isInvalid()) return ExprError();
Richard Trieuba63ce62011-09-09 01:45:06 +00004397 CastExpr = Result.take();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004398 }
John McCallebe54742010-01-15 18:56:44 +00004399
Richard Trieuba63ce62011-09-09 01:45:06 +00004400 return BuildCStyleCastExpr(LParenLoc, castTInfo, RParenLoc, CastExpr);
John McCallebe54742010-01-15 18:56:44 +00004401}
4402
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004403ExprResult Sema::BuildVectorLiteral(SourceLocation LParenLoc,
4404 SourceLocation RParenLoc, Expr *E,
4405 TypeSourceInfo *TInfo) {
4406 assert((isa<ParenListExpr>(E) || isa<ParenExpr>(E)) &&
4407 "Expected paren or paren list expression");
4408
4409 Expr **exprs;
4410 unsigned numExprs;
4411 Expr *subExpr;
4412 if (ParenListExpr *PE = dyn_cast<ParenListExpr>(E)) {
4413 exprs = PE->getExprs();
4414 numExprs = PE->getNumExprs();
4415 } else {
4416 subExpr = cast<ParenExpr>(E)->getSubExpr();
4417 exprs = &subExpr;
4418 numExprs = 1;
4419 }
4420
4421 QualType Ty = TInfo->getType();
4422 assert(Ty->isVectorType() && "Expected vector type");
4423
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004424 SmallVector<Expr *, 8> initExprs;
Tanya Lattner83559382011-07-15 23:07:01 +00004425 const VectorType *VTy = Ty->getAs<VectorType>();
4426 unsigned numElems = Ty->getAs<VectorType>()->getNumElements();
4427
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004428 // '(...)' form of vector initialization in AltiVec: the number of
4429 // initializers must be one or must match the size of the vector.
4430 // If a single value is specified in the initializer then it will be
4431 // replicated to all the components of the vector
Tanya Lattner83559382011-07-15 23:07:01 +00004432 if (VTy->getVectorKind() == VectorType::AltiVecVector) {
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004433 // The number of initializers must be one or must match the size of the
4434 // vector. If a single value is specified in the initializer then it will
4435 // be replicated to all the components of the vector
4436 if (numExprs == 1) {
4437 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004438 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4439 if (Literal.isInvalid())
4440 return ExprError();
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004441 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004442 PrepareScalarCast(Literal, ElemTy));
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004443 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4444 }
4445 else if (numExprs < numElems) {
4446 Diag(E->getExprLoc(),
4447 diag::err_incorrect_number_of_vector_initializers);
4448 return ExprError();
4449 }
4450 else
Benjamin Kramer8001f742012-02-14 12:06:21 +00004451 initExprs.append(exprs, exprs + numExprs);
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004452 }
Tanya Lattner83559382011-07-15 23:07:01 +00004453 else {
4454 // For OpenCL, when the number of initializers is a single value,
4455 // it will be replicated to all components of the vector.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004456 if (getLangOpts().OpenCL &&
Tanya Lattner83559382011-07-15 23:07:01 +00004457 VTy->getVectorKind() == VectorType::GenericVector &&
4458 numExprs == 1) {
4459 QualType ElemTy = Ty->getAs<VectorType>()->getElementType();
Richard Smith01ebacd2011-10-27 23:31:58 +00004460 ExprResult Literal = DefaultLvalueConversion(exprs[0]);
4461 if (Literal.isInvalid())
4462 return ExprError();
Tanya Lattner83559382011-07-15 23:07:01 +00004463 Literal = ImpCastExprToType(Literal.take(), ElemTy,
John McCall9776e432011-10-06 23:25:11 +00004464 PrepareScalarCast(Literal, ElemTy));
Tanya Lattner83559382011-07-15 23:07:01 +00004465 return BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc, Literal.take());
4466 }
4467
Benjamin Kramer8001f742012-02-14 12:06:21 +00004468 initExprs.append(exprs, exprs + numExprs);
Tanya Lattner83559382011-07-15 23:07:01 +00004469 }
Argyrios Kyrtzidisd8701b62011-07-01 22:22:54 +00004470 // FIXME: This means that pretty-printing the final AST will produce curly
4471 // braces instead of the original commas.
4472 InitListExpr *initE = new (Context) InitListExpr(Context, LParenLoc,
4473 &initExprs[0],
4474 initExprs.size(), RParenLoc);
4475 initE->setType(Ty);
4476 return BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc, initE);
4477}
4478
Sebastian Redla9351792012-02-11 23:51:47 +00004479/// This is not an AltiVec-style cast or or C++ direct-initialization, so turn
4480/// the ParenListExpr into a sequence of comma binary operators.
John McCalldadc5752010-08-24 06:29:42 +00004481ExprResult
Richard Trieuba63ce62011-09-09 01:45:06 +00004482Sema::MaybeConvertParenListExprToParenExpr(Scope *S, Expr *OrigExpr) {
4483 ParenListExpr *E = dyn_cast<ParenListExpr>(OrigExpr);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004484 if (!E)
Richard Trieuba63ce62011-09-09 01:45:06 +00004485 return Owned(OrigExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004486
John McCalldadc5752010-08-24 06:29:42 +00004487 ExprResult Result(E->getExpr(0));
Mike Stump11289f42009-09-09 15:08:12 +00004488
Nate Begeman5ec4b312009-08-10 23:49:36 +00004489 for (unsigned i = 1, e = E->getNumExprs(); i != e && !Result.isInvalid(); ++i)
John McCallb268a282010-08-23 23:25:46 +00004490 Result = ActOnBinOp(S, E->getExprLoc(), tok::comma, Result.get(),
4491 E->getExpr(i));
Mike Stump11289f42009-09-09 15:08:12 +00004492
John McCallb268a282010-08-23 23:25:46 +00004493 if (Result.isInvalid()) return ExprError();
4494
4495 return ActOnParenExpr(E->getLParenLoc(), E->getRParenLoc(), Result.get());
Nate Begeman5ec4b312009-08-10 23:49:36 +00004496}
4497
Sebastian Redla9351792012-02-11 23:51:47 +00004498ExprResult Sema::ActOnParenListExpr(SourceLocation L,
4499 SourceLocation R,
4500 MultiExprArg Val) {
Nate Begeman5ec4b312009-08-10 23:49:36 +00004501 unsigned nexprs = Val.size();
4502 Expr **exprs = reinterpret_cast<Expr**>(Val.release());
Fariborz Jahanian906d8712009-11-25 01:26:41 +00004503 assert((exprs != 0) && "ActOnParenOrParenListExpr() missing expr list");
Sebastian Redla9351792012-02-11 23:51:47 +00004504 Expr *expr = new (Context) ParenListExpr(Context, L, exprs, nexprs, R);
Nate Begeman5ec4b312009-08-10 23:49:36 +00004505 return Owned(expr);
4506}
4507
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004508/// \brief Emit a specialized diagnostic when one expression is a null pointer
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004509/// constant and the other is not a pointer. Returns true if a diagnostic is
4510/// emitted.
Richard Trieud33e46e2011-09-06 20:06:39 +00004511bool Sema::DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004512 SourceLocation QuestionLoc) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004513 Expr *NullExpr = LHSExpr;
4514 Expr *NonPointerExpr = RHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004515 Expr::NullPointerConstantKind NullKind =
4516 NullExpr->isNullPointerConstant(Context,
4517 Expr::NPC_ValueDependentIsNotNull);
4518
4519 if (NullKind == Expr::NPCK_NotNull) {
Richard Trieud33e46e2011-09-06 20:06:39 +00004520 NullExpr = RHSExpr;
4521 NonPointerExpr = LHSExpr;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004522 NullKind =
4523 NullExpr->isNullPointerConstant(Context,
4524 Expr::NPC_ValueDependentIsNotNull);
4525 }
4526
4527 if (NullKind == Expr::NPCK_NotNull)
4528 return false;
4529
4530 if (NullKind == Expr::NPCK_ZeroInteger) {
4531 // In this case, check to make sure that we got here from a "NULL"
4532 // string in the source code.
4533 NullExpr = NullExpr->IgnoreParenImpCasts();
John McCall462c0552011-03-08 07:59:04 +00004534 SourceLocation loc = NullExpr->getExprLoc();
4535 if (!findMacroSpelling(loc, "NULL"))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004536 return false;
4537 }
4538
4539 int DiagType = (NullKind == Expr::NPCK_CXX0X_nullptr);
4540 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands_null)
4541 << NonPointerExpr->getType() << DiagType
4542 << NonPointerExpr->getSourceRange();
4543 return true;
4544}
4545
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004546/// \brief Return false if the condition expression is valid, true otherwise.
4547static bool checkCondition(Sema &S, Expr *Cond) {
4548 QualType CondTy = Cond->getType();
4549
4550 // C99 6.5.15p2
4551 if (CondTy->isScalarType()) return false;
4552
4553 // OpenCL: Sec 6.3.i says the condition is allowed to be a vector or scalar.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004554 if (S.getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004555 return false;
4556
4557 // Emit the proper error message.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004558 S.Diag(Cond->getLocStart(), S.getLangOpts().OpenCL ?
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004559 diag::err_typecheck_cond_expect_scalar :
4560 diag::err_typecheck_cond_expect_scalar_or_vector)
4561 << CondTy;
4562 return true;
4563}
4564
4565/// \brief Return false if the two expressions can be converted to a vector,
4566/// true otherwise
4567static bool checkConditionalConvertScalarsToVectors(Sema &S, ExprResult &LHS,
4568 ExprResult &RHS,
4569 QualType CondTy) {
4570 // Both operands should be of scalar type.
4571 if (!LHS.get()->getType()->isScalarType()) {
4572 S.Diag(LHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4573 << CondTy;
4574 return true;
4575 }
4576 if (!RHS.get()->getType()->isScalarType()) {
4577 S.Diag(RHS.get()->getLocStart(), diag::err_typecheck_cond_expect_scalar)
4578 << CondTy;
4579 return true;
4580 }
4581
4582 // Implicity convert these scalars to the type of the condition.
4583 LHS = S.ImpCastExprToType(LHS.take(), CondTy, CK_IntegralCast);
4584 RHS = S.ImpCastExprToType(RHS.take(), CondTy, CK_IntegralCast);
4585 return false;
4586}
4587
4588/// \brief Handle when one or both operands are void type.
4589static QualType checkConditionalVoidType(Sema &S, ExprResult &LHS,
4590 ExprResult &RHS) {
4591 Expr *LHSExpr = LHS.get();
4592 Expr *RHSExpr = RHS.get();
4593
4594 if (!LHSExpr->getType()->isVoidType())
4595 S.Diag(RHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4596 << RHSExpr->getSourceRange();
4597 if (!RHSExpr->getType()->isVoidType())
4598 S.Diag(LHSExpr->getLocStart(), diag::ext_typecheck_cond_one_void)
4599 << LHSExpr->getSourceRange();
4600 LHS = S.ImpCastExprToType(LHS.take(), S.Context.VoidTy, CK_ToVoid);
4601 RHS = S.ImpCastExprToType(RHS.take(), S.Context.VoidTy, CK_ToVoid);
4602 return S.Context.VoidTy;
4603}
4604
4605/// \brief Return false if the NullExpr can be promoted to PointerTy,
4606/// true otherwise.
4607static bool checkConditionalNullPointer(Sema &S, ExprResult &NullExpr,
4608 QualType PointerTy) {
4609 if ((!PointerTy->isAnyPointerType() && !PointerTy->isBlockPointerType()) ||
4610 !NullExpr.get()->isNullPointerConstant(S.Context,
4611 Expr::NPC_ValueDependentIsNull))
4612 return true;
4613
4614 NullExpr = S.ImpCastExprToType(NullExpr.take(), PointerTy, CK_NullToPointer);
4615 return false;
4616}
4617
4618/// \brief Checks compatibility between two pointers and return the resulting
4619/// type.
4620static QualType checkConditionalPointerCompatibility(Sema &S, ExprResult &LHS,
4621 ExprResult &RHS,
4622 SourceLocation Loc) {
4623 QualType LHSTy = LHS.get()->getType();
4624 QualType RHSTy = RHS.get()->getType();
4625
4626 if (S.Context.hasSameType(LHSTy, RHSTy)) {
4627 // Two identical pointers types are always compatible.
4628 return LHSTy;
4629 }
4630
4631 QualType lhptee, rhptee;
4632
4633 // Get the pointee types.
John McCall9320b872011-09-09 05:25:32 +00004634 if (const BlockPointerType *LHSBTy = LHSTy->getAs<BlockPointerType>()) {
4635 lhptee = LHSBTy->getPointeeType();
4636 rhptee = RHSTy->castAs<BlockPointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004637 } else {
John McCall9320b872011-09-09 05:25:32 +00004638 lhptee = LHSTy->castAs<PointerType>()->getPointeeType();
4639 rhptee = RHSTy->castAs<PointerType>()->getPointeeType();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004640 }
4641
Eli Friedman57a75392012-04-05 22:30:04 +00004642 // C99 6.5.15p6: If both operands are pointers to compatible types or to
4643 // differently qualified versions of compatible types, the result type is
4644 // a pointer to an appropriately qualified version of the composite
4645 // type.
4646
4647 // Only CVR-qualifiers exist in the standard, and the differently-qualified
4648 // clause doesn't make sense for our extensions. E.g. address space 2 should
4649 // be incompatible with address space 3: they may live on different devices or
4650 // anything.
4651 Qualifiers lhQual = lhptee.getQualifiers();
4652 Qualifiers rhQual = rhptee.getQualifiers();
4653
4654 unsigned MergedCVRQual = lhQual.getCVRQualifiers() | rhQual.getCVRQualifiers();
4655 lhQual.removeCVRQualifiers();
4656 rhQual.removeCVRQualifiers();
4657
4658 lhptee = S.Context.getQualifiedType(lhptee.getUnqualifiedType(), lhQual);
4659 rhptee = S.Context.getQualifiedType(rhptee.getUnqualifiedType(), rhQual);
4660
4661 QualType CompositeTy = S.Context.mergeTypes(lhptee, rhptee);
4662
4663 if (CompositeTy.isNull()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004664 S.Diag(Loc, diag::warn_typecheck_cond_incompatible_pointers)
4665 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4666 << RHS.get()->getSourceRange();
4667 // In this situation, we assume void* type. No especially good
4668 // reason, but this is what gcc does, and we do have to pick
4669 // to get a consistent AST.
4670 QualType incompatTy = S.Context.getPointerType(S.Context.VoidTy);
4671 LHS = S.ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4672 RHS = S.ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
4673 return incompatTy;
4674 }
4675
4676 // The pointer types are compatible.
Eli Friedman57a75392012-04-05 22:30:04 +00004677 QualType ResultTy = CompositeTy.withCVRQualifiers(MergedCVRQual);
4678 ResultTy = S.Context.getPointerType(ResultTy);
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004679
Eli Friedman57a75392012-04-05 22:30:04 +00004680 LHS = S.ImpCastExprToType(LHS.take(), ResultTy, CK_BitCast);
4681 RHS = S.ImpCastExprToType(RHS.take(), ResultTy, CK_BitCast);
4682 return ResultTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004683}
4684
4685/// \brief Return the resulting type when the operands are both block pointers.
4686static QualType checkConditionalBlockPointerCompatibility(Sema &S,
4687 ExprResult &LHS,
4688 ExprResult &RHS,
4689 SourceLocation Loc) {
4690 QualType LHSTy = LHS.get()->getType();
4691 QualType RHSTy = RHS.get()->getType();
4692
4693 if (!LHSTy->isBlockPointerType() || !RHSTy->isBlockPointerType()) {
4694 if (LHSTy->isVoidPointerType() || RHSTy->isVoidPointerType()) {
4695 QualType destType = S.Context.getPointerType(S.Context.VoidTy);
4696 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4697 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4698 return destType;
4699 }
4700 S.Diag(Loc, diag::err_typecheck_cond_incompatible_operands)
4701 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4702 << RHS.get()->getSourceRange();
4703 return QualType();
4704 }
4705
4706 // We have 2 block pointer types.
4707 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4708}
4709
4710/// \brief Return the resulting type when the operands are both pointers.
4711static QualType
4712checkConditionalObjectPointersCompatibility(Sema &S, ExprResult &LHS,
4713 ExprResult &RHS,
4714 SourceLocation Loc) {
4715 // get the pointer types
4716 QualType LHSTy = LHS.get()->getType();
4717 QualType RHSTy = RHS.get()->getType();
4718
4719 // get the "pointed to" types
4720 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
4721 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
4722
4723 // ignore qualifiers on void (C99 6.5.15p3, clause 6)
4724 if (lhptee->isVoidType() && rhptee->isIncompleteOrObjectType()) {
4725 // Figure out necessary qualifiers (C99 6.5.15p6)
4726 QualType destPointee
4727 = S.Context.getQualifiedType(lhptee, rhptee.getQualifiers());
4728 QualType destType = S.Context.getPointerType(destPointee);
4729 // Add qualifiers if necessary.
4730 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_NoOp);
4731 // Promote to void*.
4732 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_BitCast);
4733 return destType;
4734 }
4735 if (rhptee->isVoidType() && lhptee->isIncompleteOrObjectType()) {
4736 QualType destPointee
4737 = S.Context.getQualifiedType(rhptee, lhptee.getQualifiers());
4738 QualType destType = S.Context.getPointerType(destPointee);
4739 // Add qualifiers if necessary.
4740 RHS = S.ImpCastExprToType(RHS.take(), destType, CK_NoOp);
4741 // Promote to void*.
4742 LHS = S.ImpCastExprToType(LHS.take(), destType, CK_BitCast);
4743 return destType;
4744 }
4745
4746 return checkConditionalPointerCompatibility(S, LHS, RHS, Loc);
4747}
4748
4749/// \brief Return false if the first expression is not an integer and the second
4750/// expression is not a pointer, true otherwise.
4751static bool checkPointerIntegerMismatch(Sema &S, ExprResult &Int,
4752 Expr* PointerExpr, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00004753 bool IsIntFirstExpr) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004754 if (!PointerExpr->getType()->isPointerType() ||
4755 !Int.get()->getType()->isIntegerType())
4756 return false;
4757
Richard Trieuba63ce62011-09-09 01:45:06 +00004758 Expr *Expr1 = IsIntFirstExpr ? Int.get() : PointerExpr;
4759 Expr *Expr2 = IsIntFirstExpr ? PointerExpr : Int.get();
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004760
4761 S.Diag(Loc, diag::warn_typecheck_cond_pointer_integer_mismatch)
4762 << Expr1->getType() << Expr2->getType()
4763 << Expr1->getSourceRange() << Expr2->getSourceRange();
4764 Int = S.ImpCastExprToType(Int.take(), PointerExpr->getType(),
4765 CK_IntegralToPointer);
4766 return true;
4767}
4768
Richard Trieud33e46e2011-09-06 20:06:39 +00004769/// Note that LHS is not null here, even if this is the gnu "x ?: y" extension.
4770/// In that case, LHS = cond.
Chris Lattner2c486602009-02-18 04:38:20 +00004771/// C99 6.5.15
Richard Trieucfc491d2011-08-02 04:35:43 +00004772QualType Sema::CheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4773 ExprResult &RHS, ExprValueKind &VK,
4774 ExprObjectKind &OK,
Chris Lattner2c486602009-02-18 04:38:20 +00004775 SourceLocation QuestionLoc) {
Douglas Gregor1beec452011-03-12 01:48:56 +00004776
Richard Trieud33e46e2011-09-06 20:06:39 +00004777 ExprResult LHSResult = CheckPlaceholderExpr(LHS.get());
4778 if (!LHSResult.isUsable()) return QualType();
4779 LHS = move(LHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004780
Richard Trieud33e46e2011-09-06 20:06:39 +00004781 ExprResult RHSResult = CheckPlaceholderExpr(RHS.get());
4782 if (!RHSResult.isUsable()) return QualType();
4783 RHS = move(RHSResult);
Douglas Gregor0124e9b2010-11-09 21:07:58 +00004784
Sebastian Redl1a99f442009-04-16 17:51:27 +00004785 // C++ is sufficiently different to merit its own checker.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004786 if (getLangOpts().CPlusPlus)
John McCallc07a0c72011-02-17 10:25:35 +00004787 return CXXCheckConditionalOperands(Cond, LHS, RHS, VK, OK, QuestionLoc);
John McCall7decc9e2010-11-18 06:31:45 +00004788
4789 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004790 OK = OK_Ordinary;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004791
John Wiegley01296292011-04-08 18:41:53 +00004792 Cond = UsualUnaryConversions(Cond.take());
4793 if (Cond.isInvalid())
4794 return QualType();
4795 LHS = UsualUnaryConversions(LHS.take());
4796 if (LHS.isInvalid())
4797 return QualType();
4798 RHS = UsualUnaryConversions(RHS.take());
4799 if (RHS.isInvalid())
4800 return QualType();
4801
4802 QualType CondTy = Cond.get()->getType();
4803 QualType LHSTy = LHS.get()->getType();
4804 QualType RHSTy = RHS.get()->getType();
Steve Naroff31090012007-07-16 21:54:35 +00004805
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004806 // first, check the condition.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004807 if (checkCondition(*this, Cond.get()))
4808 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00004809
Chris Lattnere2949f42008-01-06 22:42:25 +00004810 // Now check the two expressions.
Nate Begeman5ec4b312009-08-10 23:49:36 +00004811 if (LHSTy->isVectorType() || RHSTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004812 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor4619e432008-12-05 23:32:09 +00004813
Nate Begemanabb5a732010-09-20 22:41:17 +00004814 // OpenCL: If the condition is a vector, and both operands are scalar,
4815 // attempt to implicity convert them to the vector type to act like the
4816 // built in select.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004817 if (getLangOpts().OpenCL && CondTy->isVectorType())
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004818 if (checkConditionalConvertScalarsToVectors(*this, LHS, RHS, CondTy))
Nate Begemanabb5a732010-09-20 22:41:17 +00004819 return QualType();
Nate Begemanabb5a732010-09-20 22:41:17 +00004820
Chris Lattnere2949f42008-01-06 22:42:25 +00004821 // If both operands have arithmetic type, do the usual arithmetic conversions
4822 // to find a common type: C99 6.5.15p3,5.
Chris Lattner432cff52009-02-18 04:28:32 +00004823 if (LHSTy->isArithmeticType() && RHSTy->isArithmeticType()) {
4824 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004825 if (LHS.isInvalid() || RHS.isInvalid())
4826 return QualType();
4827 return LHS.get()->getType();
Steve Naroffdbd9e892007-07-17 00:58:39 +00004828 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004829
Chris Lattnere2949f42008-01-06 22:42:25 +00004830 // If both operands are the same structure or union type, the result is that
4831 // type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004832 if (const RecordType *LHSRT = LHSTy->getAs<RecordType>()) { // C99 6.5.15p3
4833 if (const RecordType *RHSRT = RHSTy->getAs<RecordType>())
Chris Lattner2ab40a62007-11-26 01:40:58 +00004834 if (LHSRT->getDecl() == RHSRT->getDecl())
Mike Stump4e1f26a2009-02-19 03:04:26 +00004835 // "If both the operands have structure or union type, the result has
Chris Lattnere2949f42008-01-06 22:42:25 +00004836 // that type." This implies that CV qualifiers are dropped.
Chris Lattner432cff52009-02-18 04:28:32 +00004837 return LHSTy.getUnqualifiedType();
Eli Friedmanba961a92009-03-23 00:24:07 +00004838 // FIXME: Type of conditional expression must be complete in C mode.
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004839 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00004840
Chris Lattnere2949f42008-01-06 22:42:25 +00004841 // C99 6.5.15p5: "If both operands have void type, the result has void type."
Steve Naroffbf1516c2008-05-12 21:44:38 +00004842 // The following || allows only one side to be void (a GCC-ism).
Chris Lattner432cff52009-02-18 04:28:32 +00004843 if (LHSTy->isVoidType() || RHSTy->isVoidType()) {
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004844 return checkConditionalVoidType(*this, LHS, RHS);
Steve Naroffbf1516c2008-05-12 21:44:38 +00004845 }
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004846
Steve Naroff039ad3c2008-01-08 01:11:38 +00004847 // C99 6.5.15p6 - "if one operand is a null pointer constant, the result has
4848 // the type of the other operand."
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004849 if (!checkConditionalNullPointer(*this, RHS, LHSTy)) return LHSTy;
4850 if (!checkConditionalNullPointer(*this, LHS, RHSTy)) return RHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004851
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004852 // All objective-c pointer type analysis is done here.
4853 QualType compositeType = FindCompositeObjCPointerType(LHS, RHS,
4854 QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00004855 if (LHS.isInvalid() || RHS.isInvalid())
4856 return QualType();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004857 if (!compositeType.isNull())
4858 return compositeType;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004859
4860
Steve Naroff05efa972009-07-01 14:36:47 +00004861 // Handle block pointer types.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004862 if (LHSTy->isBlockPointerType() || RHSTy->isBlockPointerType())
4863 return checkConditionalBlockPointerCompatibility(*this, LHS, RHS,
4864 QuestionLoc);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004865
Steve Naroff05efa972009-07-01 14:36:47 +00004866 // Check constraints for C object pointers types (C99 6.5.15p3,6).
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004867 if (LHSTy->isPointerType() && RHSTy->isPointerType())
4868 return checkConditionalObjectPointersCompatibility(*this, LHS, RHS,
4869 QuestionLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004870
John McCalle84af4e2010-11-13 01:35:44 +00004871 // GCC compatibility: soften pointer/integer mismatch. Note that
4872 // null pointers have been filtered out by this point.
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004873 if (checkPointerIntegerMismatch(*this, LHS, RHS.get(), QuestionLoc,
4874 /*isIntFirstExpr=*/true))
Steve Naroff05efa972009-07-01 14:36:47 +00004875 return RHSTy;
Richard Trieu27ae4cb2011-09-02 01:51:02 +00004876 if (checkPointerIntegerMismatch(*this, RHS, LHS.get(), QuestionLoc,
4877 /*isIntFirstExpr=*/false))
Steve Naroff05efa972009-07-01 14:36:47 +00004878 return LHSTy;
Daniel Dunbar484603b2008-09-11 23:12:46 +00004879
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004880 // Emit a better diagnostic if one of the expressions is a null pointer
4881 // constant and the other is not a pointer type. In this case, the user most
4882 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004883 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004884 return QualType();
4885
Chris Lattnere2949f42008-01-06 22:42:25 +00004886 // Otherwise, the operands are not compatible.
Chris Lattner432cff52009-02-18 04:28:32 +00004887 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
Richard Trieucfc491d2011-08-02 04:35:43 +00004888 << LHSTy << RHSTy << LHS.get()->getSourceRange()
4889 << RHS.get()->getSourceRange();
Steve Naroffa78fe7e2007-05-16 19:47:19 +00004890 return QualType();
Steve Narofff8a28c52007-05-15 20:29:32 +00004891}
4892
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004893/// FindCompositeObjCPointerType - Helper method to find composite type of
4894/// two objective-c pointer types of the two input expressions.
John Wiegley01296292011-04-08 18:41:53 +00004895QualType Sema::FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00004896 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004897 QualType LHSTy = LHS.get()->getType();
4898 QualType RHSTy = RHS.get()->getType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004899
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004900 // Handle things like Class and struct objc_class*. Here we case the result
4901 // to the pseudo-builtin, because that will be implicitly cast back to the
4902 // redefinition type if an attempt is made to access its fields.
4903 if (LHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004904 (Context.hasSameType(RHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004905 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004906 return LHSTy;
4907 }
4908 if (RHSTy->isObjCClassType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004909 (Context.hasSameType(LHSTy, Context.getObjCClassRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004910 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004911 return RHSTy;
4912 }
4913 // And the same for struct objc_object* / id
4914 if (LHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004915 (Context.hasSameType(RHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004916 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004917 return LHSTy;
4918 }
4919 if (RHSTy->isObjCIdType() &&
Douglas Gregor97673472011-08-11 20:58:55 +00004920 (Context.hasSameType(LHSTy, Context.getObjCIdRedefinitionType()))) {
John McCall9320b872011-09-09 05:25:32 +00004921 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_CPointerToObjCPointerCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004922 return RHSTy;
4923 }
4924 // And the same for struct objc_selector* / SEL
4925 if (Context.isObjCSelType(LHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004926 (Context.hasSameType(RHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004927 RHS = ImpCastExprToType(RHS.take(), LHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004928 return LHSTy;
4929 }
4930 if (Context.isObjCSelType(RHSTy) &&
Douglas Gregor97673472011-08-11 20:58:55 +00004931 (Context.hasSameType(LHSTy, Context.getObjCSelRedefinitionType()))) {
John Wiegley01296292011-04-08 18:41:53 +00004932 LHS = ImpCastExprToType(LHS.take(), RHSTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004933 return RHSTy;
4934 }
4935 // Check constraints for Objective-C object pointers types.
4936 if (LHSTy->isObjCObjectPointerType() && RHSTy->isObjCObjectPointerType()) {
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004937
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004938 if (Context.getCanonicalType(LHSTy) == Context.getCanonicalType(RHSTy)) {
4939 // Two identical object pointer types are always compatible.
4940 return LHSTy;
4941 }
John McCall9320b872011-09-09 05:25:32 +00004942 const ObjCObjectPointerType *LHSOPT = LHSTy->castAs<ObjCObjectPointerType>();
4943 const ObjCObjectPointerType *RHSOPT = RHSTy->castAs<ObjCObjectPointerType>();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004944 QualType compositeType = LHSTy;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004945
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004946 // If both operands are interfaces and either operand can be
4947 // assigned to the other, use that type as the composite
4948 // type. This allows
4949 // xxx ? (A*) a : (B*) b
4950 // where B is a subclass of A.
4951 //
4952 // Additionally, as for assignment, if either type is 'id'
4953 // allow silent coercion. Finally, if the types are
4954 // incompatible then make sure to use 'id' as the composite
4955 // type so the result is acceptable for sending messages to.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004956
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004957 // FIXME: Consider unifying with 'areComparableObjCPointerTypes'.
4958 // It could return the composite type.
4959 if (Context.canAssignObjCInterfaces(LHSOPT, RHSOPT)) {
4960 compositeType = RHSOPT->isObjCBuiltinType() ? RHSTy : LHSTy;
4961 } else if (Context.canAssignObjCInterfaces(RHSOPT, LHSOPT)) {
4962 compositeType = LHSOPT->isObjCBuiltinType() ? LHSTy : RHSTy;
4963 } else if ((LHSTy->isObjCQualifiedIdType() ||
4964 RHSTy->isObjCQualifiedIdType()) &&
4965 Context.ObjCQualifiedIdTypesAreCompatible(LHSTy, RHSTy, true)) {
4966 // Need to handle "id<xx>" explicitly.
4967 // GCC allows qualified id and any Objective-C type to devolve to
4968 // id. Currently localizing to here until clear this should be
4969 // part of ObjCQualifiedIdTypesAreCompatible.
4970 compositeType = Context.getObjCIdType();
4971 } else if (LHSTy->isObjCIdType() || RHSTy->isObjCIdType()) {
4972 compositeType = Context.getObjCIdType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00004973 } else if (!(compositeType =
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004974 Context.areCommonBaseCompatible(LHSOPT, RHSOPT)).isNull())
4975 ;
4976 else {
4977 Diag(QuestionLoc, diag::ext_typecheck_cond_incompatible_operands)
4978 << LHSTy << RHSTy
John Wiegley01296292011-04-08 18:41:53 +00004979 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004980 QualType incompatTy = Context.getObjCIdType();
John Wiegley01296292011-04-08 18:41:53 +00004981 LHS = ImpCastExprToType(LHS.take(), incompatTy, CK_BitCast);
4982 RHS = ImpCastExprToType(RHS.take(), incompatTy, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004983 return incompatTy;
4984 }
4985 // The object pointer types are compatible.
John Wiegley01296292011-04-08 18:41:53 +00004986 LHS = ImpCastExprToType(LHS.take(), compositeType, CK_BitCast);
4987 RHS = ImpCastExprToType(RHS.take(), compositeType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00004988 return compositeType;
4989 }
4990 // Check Objective-C object pointer types and 'void *'
4991 if (LHSTy->isVoidPointerType() && RHSTy->isObjCObjectPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004992 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00004993 // ARC forbids the implicit conversion of object pointers to 'void *',
4994 // so these types are not compatible.
4995 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
4996 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
4997 LHS = RHS = true;
4998 return QualType();
4999 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005000 QualType lhptee = LHSTy->getAs<PointerType>()->getPointeeType();
5001 QualType rhptee = RHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5002 QualType destPointee
5003 = Context.getQualifiedType(lhptee, rhptee.getQualifiers());
5004 QualType destType = Context.getPointerType(destPointee);
5005 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005006 LHS = ImpCastExprToType(LHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005007 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005008 RHS = ImpCastExprToType(RHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005009 return destType;
5010 }
5011 if (LHSTy->isObjCObjectPointerType() && RHSTy->isVoidPointerType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005012 if (getLangOpts().ObjCAutoRefCount) {
Eli Friedman8a78a582012-02-25 00:23:44 +00005013 // ARC forbids the implicit conversion of object pointers to 'void *',
5014 // so these types are not compatible.
5015 Diag(QuestionLoc, diag::err_cond_voidptr_arc) << LHSTy << RHSTy
5016 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5017 LHS = RHS = true;
5018 return QualType();
5019 }
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005020 QualType lhptee = LHSTy->getAs<ObjCObjectPointerType>()->getPointeeType();
5021 QualType rhptee = RHSTy->getAs<PointerType>()->getPointeeType();
5022 QualType destPointee
5023 = Context.getQualifiedType(rhptee, lhptee.getQualifiers());
5024 QualType destType = Context.getPointerType(destPointee);
5025 // Add qualifiers if necessary.
John Wiegley01296292011-04-08 18:41:53 +00005026 RHS = ImpCastExprToType(RHS.take(), destType, CK_NoOp);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005027 // Promote to void*.
John Wiegley01296292011-04-08 18:41:53 +00005028 LHS = ImpCastExprToType(LHS.take(), destType, CK_BitCast);
Fariborz Jahaniana430f712009-12-10 19:47:41 +00005029 return destType;
5030 }
5031 return QualType();
5032}
5033
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005034/// SuggestParentheses - Emit a note with a fixit hint that wraps
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005035/// ParenRange in parentheses.
5036static void SuggestParentheses(Sema &Self, SourceLocation Loc,
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005037 const PartialDiagnostic &Note,
5038 SourceRange ParenRange) {
5039 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(ParenRange.getEnd());
5040 if (ParenRange.getBegin().isFileID() && ParenRange.getEnd().isFileID() &&
5041 EndLoc.isValid()) {
5042 Self.Diag(Loc, Note)
5043 << FixItHint::CreateInsertion(ParenRange.getBegin(), "(")
5044 << FixItHint::CreateInsertion(EndLoc, ")");
5045 } else {
5046 // We can't display the parentheses, so just show the bare note.
5047 Self.Diag(Loc, Note) << ParenRange;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005048 }
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005049}
5050
5051static bool IsArithmeticOp(BinaryOperatorKind Opc) {
5052 return Opc >= BO_Mul && Opc <= BO_Shr;
5053}
5054
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005055/// IsArithmeticBinaryExpr - Returns true if E is an arithmetic binary
5056/// expression, either using a built-in or overloaded operator,
Richard Trieud33e46e2011-09-06 20:06:39 +00005057/// and sets *OpCode to the opcode and *RHSExprs to the right-hand side
5058/// expression.
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005059static bool IsArithmeticBinaryExpr(Expr *E, BinaryOperatorKind *Opcode,
Richard Trieud33e46e2011-09-06 20:06:39 +00005060 Expr **RHSExprs) {
Hans Wennborgbe207b32011-09-12 12:07:30 +00005061 // Don't strip parenthesis: we should not warn if E is in parenthesis.
5062 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005063 E = E->IgnoreConversionOperator();
Hans Wennborgbe207b32011-09-12 12:07:30 +00005064 E = E->IgnoreImpCasts();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005065
5066 // Built-in binary operator.
5067 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E)) {
5068 if (IsArithmeticOp(OP->getOpcode())) {
5069 *Opcode = OP->getOpcode();
Richard Trieud33e46e2011-09-06 20:06:39 +00005070 *RHSExprs = OP->getRHS();
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005071 return true;
5072 }
5073 }
5074
5075 // Overloaded operator.
5076 if (CXXOperatorCallExpr *Call = dyn_cast<CXXOperatorCallExpr>(E)) {
5077 if (Call->getNumArgs() != 2)
5078 return false;
5079
5080 // Make sure this is really a binary operator that is safe to pass into
5081 // BinaryOperator::getOverloadedOpcode(), e.g. it's not a subscript op.
5082 OverloadedOperatorKind OO = Call->getOperator();
5083 if (OO < OO_Plus || OO > OO_Arrow)
5084 return false;
5085
5086 BinaryOperatorKind OpKind = BinaryOperator::getOverloadedOpcode(OO);
5087 if (IsArithmeticOp(OpKind)) {
5088 *Opcode = OpKind;
Richard Trieud33e46e2011-09-06 20:06:39 +00005089 *RHSExprs = Call->getArg(1);
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005090 return true;
5091 }
5092 }
5093
5094 return false;
5095}
5096
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005097static bool IsLogicOp(BinaryOperatorKind Opc) {
5098 return (Opc >= BO_LT && Opc <= BO_NE) || (Opc >= BO_LAnd && Opc <= BO_LOr);
5099}
5100
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005101/// ExprLooksBoolean - Returns true if E looks boolean, i.e. it has boolean type
5102/// or is a logical expression such as (x==y) which has int type, but is
5103/// commonly interpreted as boolean.
5104static bool ExprLooksBoolean(Expr *E) {
5105 E = E->IgnoreParenImpCasts();
5106
5107 if (E->getType()->isBooleanType())
5108 return true;
5109 if (BinaryOperator *OP = dyn_cast<BinaryOperator>(E))
5110 return IsLogicOp(OP->getOpcode());
5111 if (UnaryOperator *OP = dyn_cast<UnaryOperator>(E))
5112 return OP->getOpcode() == UO_LNot;
5113
5114 return false;
5115}
5116
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005117/// DiagnoseConditionalPrecedence - Emit a warning when a conditional operator
5118/// and binary operator are mixed in a way that suggests the programmer assumed
5119/// the conditional operator has higher precedence, for example:
5120/// "int x = a + someBinaryCondition ? 1 : 2".
5121static void DiagnoseConditionalPrecedence(Sema &Self,
5122 SourceLocation OpLoc,
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005123 Expr *Condition,
Richard Trieud33e46e2011-09-06 20:06:39 +00005124 Expr *LHSExpr,
5125 Expr *RHSExpr) {
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005126 BinaryOperatorKind CondOpcode;
5127 Expr *CondRHS;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005128
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005129 if (!IsArithmeticBinaryExpr(Condition, &CondOpcode, &CondRHS))
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005130 return;
5131 if (!ExprLooksBoolean(CondRHS))
5132 return;
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005133
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005134 // The condition is an arithmetic binary expression, with a right-
5135 // hand side that looks boolean, so warn.
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005136
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005137 Self.Diag(OpLoc, diag::warn_precedence_conditional)
Chandler Carruth08dc2ba2011-06-16 01:05:08 +00005138 << Condition->getSourceRange()
Hans Wennborgde2e67e2011-06-09 17:06:51 +00005139 << BinaryOperator::getOpcodeStr(CondOpcode);
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005140
Chandler Carruthb00e8c02011-06-16 01:05:14 +00005141 SuggestParentheses(Self, OpLoc,
5142 Self.PDiag(diag::note_precedence_conditional_silence)
5143 << BinaryOperator::getOpcodeStr(CondOpcode),
5144 SourceRange(Condition->getLocStart(), Condition->getLocEnd()));
Chandler Carruthf51c5a52011-06-21 23:04:18 +00005145
5146 SuggestParentheses(Self, OpLoc,
5147 Self.PDiag(diag::note_precedence_conditional_first),
Richard Trieud33e46e2011-09-06 20:06:39 +00005148 SourceRange(CondRHS->getLocStart(), RHSExpr->getLocEnd()));
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005149}
5150
Steve Naroff83895f72007-09-16 03:34:24 +00005151/// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null
Chris Lattnere168f762006-11-10 05:29:30 +00005152/// in the case of a the GNU conditional expr extension.
John McCalldadc5752010-08-24 06:29:42 +00005153ExprResult Sema::ActOnConditionalOp(SourceLocation QuestionLoc,
John McCallc07a0c72011-02-17 10:25:35 +00005154 SourceLocation ColonLoc,
5155 Expr *CondExpr, Expr *LHSExpr,
5156 Expr *RHSExpr) {
Chris Lattner2ab40a62007-11-26 01:40:58 +00005157 // If this is the gnu "x ?: y" extension, analyze the types as though the LHS
5158 // was the condition.
John McCallc07a0c72011-02-17 10:25:35 +00005159 OpaqueValueExpr *opaqueValue = 0;
5160 Expr *commonExpr = 0;
5161 if (LHSExpr == 0) {
5162 commonExpr = CondExpr;
5163
5164 // We usually want to apply unary conversions *before* saving, except
5165 // in the special case of a C++ l-value conditional.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005166 if (!(getLangOpts().CPlusPlus
John McCallc07a0c72011-02-17 10:25:35 +00005167 && !commonExpr->isTypeDependent()
5168 && commonExpr->getValueKind() == RHSExpr->getValueKind()
5169 && commonExpr->isGLValue()
5170 && commonExpr->isOrdinaryOrBitFieldObject()
5171 && RHSExpr->isOrdinaryOrBitFieldObject()
5172 && Context.hasSameType(commonExpr->getType(), RHSExpr->getType()))) {
John Wiegley01296292011-04-08 18:41:53 +00005173 ExprResult commonRes = UsualUnaryConversions(commonExpr);
5174 if (commonRes.isInvalid())
5175 return ExprError();
5176 commonExpr = commonRes.take();
John McCallc07a0c72011-02-17 10:25:35 +00005177 }
5178
5179 opaqueValue = new (Context) OpaqueValueExpr(commonExpr->getExprLoc(),
5180 commonExpr->getType(),
5181 commonExpr->getValueKind(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +00005182 commonExpr->getObjectKind(),
5183 commonExpr);
John McCallc07a0c72011-02-17 10:25:35 +00005184 LHSExpr = CondExpr = opaqueValue;
Fariborz Jahanianc6bf0bd2010-08-31 18:02:20 +00005185 }
Sebastian Redlb5d49352009-01-19 22:31:54 +00005186
John McCall7decc9e2010-11-18 06:31:45 +00005187 ExprValueKind VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00005188 ExprObjectKind OK = OK_Ordinary;
John Wiegley01296292011-04-08 18:41:53 +00005189 ExprResult Cond = Owned(CondExpr), LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
5190 QualType result = CheckConditionalOperands(Cond, LHS, RHS,
John McCallc07a0c72011-02-17 10:25:35 +00005191 VK, OK, QuestionLoc);
John Wiegley01296292011-04-08 18:41:53 +00005192 if (result.isNull() || Cond.isInvalid() || LHS.isInvalid() ||
5193 RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00005194 return ExprError();
5195
Hans Wennborgcf9bac42011-06-03 18:00:36 +00005196 DiagnoseConditionalPrecedence(*this, QuestionLoc, Cond.get(), LHS.get(),
5197 RHS.get());
5198
John McCallc07a0c72011-02-17 10:25:35 +00005199 if (!commonExpr)
John Wiegley01296292011-04-08 18:41:53 +00005200 return Owned(new (Context) ConditionalOperator(Cond.take(), QuestionLoc,
5201 LHS.take(), ColonLoc,
5202 RHS.take(), result, VK, OK));
John McCallc07a0c72011-02-17 10:25:35 +00005203
5204 return Owned(new (Context)
John Wiegley01296292011-04-08 18:41:53 +00005205 BinaryConditionalOperator(commonExpr, opaqueValue, Cond.take(), LHS.take(),
Richard Trieucfc491d2011-08-02 04:35:43 +00005206 RHS.take(), QuestionLoc, ColonLoc, result, VK,
5207 OK));
Chris Lattnere168f762006-11-10 05:29:30 +00005208}
5209
John McCallaba90822011-01-31 23:13:11 +00005210// checkPointerTypesForAssignment - This is a very tricky routine (despite
Mike Stump4e1f26a2009-02-19 03:04:26 +00005211// being closely modeled after the C99 spec:-). The odd characteristic of this
Steve Naroff3f597292007-05-11 22:18:03 +00005212// routine is it effectively iqnores the qualifiers on the top level pointee.
5213// This circumvents the usual type rules specified in 6.2.7p1 & 6.7.5.[1-3].
5214// FIXME: add a couple examples in this comment.
John McCallaba90822011-01-31 23:13:11 +00005215static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005216checkPointerTypesForAssignment(Sema &S, QualType LHSType, QualType RHSType) {
5217 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5218 assert(RHSType.isCanonical() && "RHS not canonicalized!");
Mike Stump4e1f26a2009-02-19 03:04:26 +00005219
Steve Naroff1f4d7272007-05-11 04:00:31 +00005220 // get the "pointed to" type (ignoring qualifiers at the top level)
John McCall4fff8f62011-02-01 00:10:29 +00005221 const Type *lhptee, *rhptee;
5222 Qualifiers lhq, rhq;
Richard Trieua871b972011-09-06 20:21:22 +00005223 llvm::tie(lhptee, lhq) = cast<PointerType>(LHSType)->getPointeeType().split();
5224 llvm::tie(rhptee, rhq) = cast<PointerType>(RHSType)->getPointeeType().split();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005225
John McCallaba90822011-01-31 23:13:11 +00005226 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005227
5228 // C99 6.5.16.1p1: This following citation is common to constraints
5229 // 3 & 4 (below). ...and the type *pointed to* by the left has all the
5230 // qualifiers of the type *pointed to* by the right;
John McCall4fff8f62011-02-01 00:10:29 +00005231 Qualifiers lq;
5232
John McCall31168b02011-06-15 23:02:42 +00005233 // As a special case, 'non-__weak A *' -> 'non-__weak const *' is okay.
5234 if (lhq.getObjCLifetime() != rhq.getObjCLifetime() &&
5235 lhq.compatiblyIncludesObjCLifetime(rhq)) {
5236 // Ignore lifetime for further calculation.
5237 lhq.removeObjCLifetime();
5238 rhq.removeObjCLifetime();
5239 }
5240
John McCall4fff8f62011-02-01 00:10:29 +00005241 if (!lhq.compatiblyIncludes(rhq)) {
5242 // Treat address-space mismatches as fatal. TODO: address subspaces
5243 if (lhq.getAddressSpace() != rhq.getAddressSpace())
5244 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5245
John McCall31168b02011-06-15 23:02:42 +00005246 // It's okay to add or remove GC or lifetime qualifiers when converting to
John McCall78535952011-03-26 02:56:45 +00005247 // and from void*.
John McCall18ce25e2012-02-08 00:46:36 +00005248 else if (lhq.withoutObjCGCAttr().withoutObjCLifetime()
John McCall31168b02011-06-15 23:02:42 +00005249 .compatiblyIncludes(
John McCall18ce25e2012-02-08 00:46:36 +00005250 rhq.withoutObjCGCAttr().withoutObjCLifetime())
John McCall78535952011-03-26 02:56:45 +00005251 && (lhptee->isVoidType() || rhptee->isVoidType()))
5252 ; // keep old
5253
John McCall31168b02011-06-15 23:02:42 +00005254 // Treat lifetime mismatches as fatal.
5255 else if (lhq.getObjCLifetime() != rhq.getObjCLifetime())
5256 ConvTy = Sema::IncompatiblePointerDiscardsQualifiers;
5257
John McCall4fff8f62011-02-01 00:10:29 +00005258 // For GCC compatibility, other qualifier mismatches are treated
5259 // as still compatible in C.
5260 else ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
5261 }
Steve Naroff3f597292007-05-11 22:18:03 +00005262
Mike Stump4e1f26a2009-02-19 03:04:26 +00005263 // C99 6.5.16.1p1 (constraint 4): If one operand is a pointer to an object or
5264 // incomplete type and the other is a pointer to a qualified or unqualified
Steve Naroff3f597292007-05-11 22:18:03 +00005265 // version of void...
Chris Lattner0a788432008-01-03 22:56:36 +00005266 if (lhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005267 if (rhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005268 return ConvTy;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005269
Chris Lattner0a788432008-01-03 22:56:36 +00005270 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005271 assert(rhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005272 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005273 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005274
Chris Lattner0a788432008-01-03 22:56:36 +00005275 if (rhptee->isVoidType()) {
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005276 if (lhptee->isIncompleteOrObjectType())
Chris Lattner9bad62c2008-01-04 18:04:52 +00005277 return ConvTy;
Chris Lattner0a788432008-01-03 22:56:36 +00005278
5279 // As an extension, we allow cast to/from void* to function pointer.
Chris Lattnerb3a176d2008-04-02 06:59:01 +00005280 assert(lhptee->isFunctionType());
John McCallaba90822011-01-31 23:13:11 +00005281 return Sema::FunctionVoidPointer;
Chris Lattner0a788432008-01-03 22:56:36 +00005282 }
John McCall4fff8f62011-02-01 00:10:29 +00005283
Mike Stump4e1f26a2009-02-19 03:04:26 +00005284 // C99 6.5.16.1p1 (constraint 3): both operands are pointers to qualified or
Steve Naroff3f597292007-05-11 22:18:03 +00005285 // unqualified versions of compatible types, ...
John McCall4fff8f62011-02-01 00:10:29 +00005286 QualType ltrans = QualType(lhptee, 0), rtrans = QualType(rhptee, 0);
5287 if (!S.Context.typesAreCompatible(ltrans, rtrans)) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005288 // Check if the pointee types are compatible ignoring the sign.
5289 // We explicitly check for char so that we catch "char" vs
5290 // "unsigned char" on systems where "char" is unsigned.
Chris Lattnerec3a1562009-10-17 20:33:28 +00005291 if (lhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005292 ltrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005293 else if (lhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005294 ltrans = S.Context.getCorrespondingUnsignedType(ltrans);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005295
Chris Lattnerec3a1562009-10-17 20:33:28 +00005296 if (rhptee->isCharType())
John McCall4fff8f62011-02-01 00:10:29 +00005297 rtrans = S.Context.UnsignedCharTy;
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00005298 else if (rhptee->hasSignedIntegerRepresentation())
John McCall4fff8f62011-02-01 00:10:29 +00005299 rtrans = S.Context.getCorrespondingUnsignedType(rtrans);
Chris Lattnerec3a1562009-10-17 20:33:28 +00005300
John McCall4fff8f62011-02-01 00:10:29 +00005301 if (ltrans == rtrans) {
Eli Friedman80160bd2009-03-22 23:59:44 +00005302 // Types are compatible ignoring the sign. Qualifier incompatibility
5303 // takes priority over sign incompatibility because the sign
5304 // warning can be disabled.
John McCallaba90822011-01-31 23:13:11 +00005305 if (ConvTy != Sema::Compatible)
Eli Friedman80160bd2009-03-22 23:59:44 +00005306 return ConvTy;
John McCall4fff8f62011-02-01 00:10:29 +00005307
John McCallaba90822011-01-31 23:13:11 +00005308 return Sema::IncompatiblePointerSign;
Eli Friedman80160bd2009-03-22 23:59:44 +00005309 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005310
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005311 // If we are a multi-level pointer, it's possible that our issue is simply
5312 // one of qualification - e.g. char ** -> const char ** is not allowed. If
5313 // the eventual target type is the same and the pointers have the same
5314 // level of indirection, this must be the issue.
John McCallaba90822011-01-31 23:13:11 +00005315 if (isa<PointerType>(lhptee) && isa<PointerType>(rhptee)) {
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005316 do {
John McCall4fff8f62011-02-01 00:10:29 +00005317 lhptee = cast<PointerType>(lhptee)->getPointeeType().getTypePtr();
5318 rhptee = cast<PointerType>(rhptee)->getPointeeType().getTypePtr();
John McCallaba90822011-01-31 23:13:11 +00005319 } while (isa<PointerType>(lhptee) && isa<PointerType>(rhptee));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005320
John McCall4fff8f62011-02-01 00:10:29 +00005321 if (lhptee == rhptee)
John McCallaba90822011-01-31 23:13:11 +00005322 return Sema::IncompatibleNestedPointerQualifiers;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00005323 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005324
Eli Friedman80160bd2009-03-22 23:59:44 +00005325 // General pointer incompatibility takes priority over qualifiers.
John McCallaba90822011-01-31 23:13:11 +00005326 return Sema::IncompatiblePointer;
Eli Friedman80160bd2009-03-22 23:59:44 +00005327 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00005328 if (!S.getLangOpts().CPlusPlus &&
Fariborz Jahanian48c69102011-10-05 00:05:34 +00005329 S.IsNoReturnConversion(ltrans, rtrans, ltrans))
5330 return Sema::IncompatiblePointer;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005331 return ConvTy;
Steve Naroff1f4d7272007-05-11 04:00:31 +00005332}
5333
John McCallaba90822011-01-31 23:13:11 +00005334/// checkBlockPointerTypesForAssignment - This routine determines whether two
Steve Naroff081c7422008-09-04 15:10:53 +00005335/// block pointer types are compatible or whether a block and normal pointer
5336/// are compatible. It is more restrict than comparing two function pointer
5337// types.
John McCallaba90822011-01-31 23:13:11 +00005338static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005339checkBlockPointerTypesForAssignment(Sema &S, QualType LHSType,
5340 QualType RHSType) {
5341 assert(LHSType.isCanonical() && "LHS not canonicalized!");
5342 assert(RHSType.isCanonical() && "RHS not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005343
Steve Naroff081c7422008-09-04 15:10:53 +00005344 QualType lhptee, rhptee;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005345
Steve Naroff081c7422008-09-04 15:10:53 +00005346 // get the "pointed to" type (ignoring qualifiers at the top level)
Richard Trieua871b972011-09-06 20:21:22 +00005347 lhptee = cast<BlockPointerType>(LHSType)->getPointeeType();
5348 rhptee = cast<BlockPointerType>(RHSType)->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005349
John McCallaba90822011-01-31 23:13:11 +00005350 // In C++, the types have to match exactly.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005351 if (S.getLangOpts().CPlusPlus)
John McCallaba90822011-01-31 23:13:11 +00005352 return Sema::IncompatibleBlockPointer;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005353
John McCallaba90822011-01-31 23:13:11 +00005354 Sema::AssignConvertType ConvTy = Sema::Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005355
Steve Naroff081c7422008-09-04 15:10:53 +00005356 // For blocks we enforce that qualifiers are identical.
John McCallaba90822011-01-31 23:13:11 +00005357 if (lhptee.getLocalQualifiers() != rhptee.getLocalQualifiers())
5358 ConvTy = Sema::CompatiblePointerDiscardsQualifiers;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005359
Richard Trieua871b972011-09-06 20:21:22 +00005360 if (!S.Context.typesAreBlockPointerCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005361 return Sema::IncompatibleBlockPointer;
5362
Steve Naroff081c7422008-09-04 15:10:53 +00005363 return ConvTy;
5364}
5365
John McCallaba90822011-01-31 23:13:11 +00005366/// checkObjCPointerTypesForAssignment - Compares two objective-c pointer types
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005367/// for assignment compatibility.
John McCallaba90822011-01-31 23:13:11 +00005368static Sema::AssignConvertType
Richard Trieua871b972011-09-06 20:21:22 +00005369checkObjCPointerTypesForAssignment(Sema &S, QualType LHSType,
5370 QualType RHSType) {
5371 assert(LHSType.isCanonical() && "LHS was not canonicalized!");
5372 assert(RHSType.isCanonical() && "RHS was not canonicalized!");
John McCallaba90822011-01-31 23:13:11 +00005373
Richard Trieua871b972011-09-06 20:21:22 +00005374 if (LHSType->isObjCBuiltinType()) {
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005375 // Class is not compatible with ObjC object pointers.
Richard Trieua871b972011-09-06 20:21:22 +00005376 if (LHSType->isObjCClassType() && !RHSType->isObjCBuiltinType() &&
5377 !RHSType->isObjCQualifiedClassType())
John McCallaba90822011-01-31 23:13:11 +00005378 return Sema::IncompatiblePointer;
5379 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005380 }
Richard Trieua871b972011-09-06 20:21:22 +00005381 if (RHSType->isObjCBuiltinType()) {
Richard Trieua871b972011-09-06 20:21:22 +00005382 if (RHSType->isObjCClassType() && !LHSType->isObjCBuiltinType() &&
5383 !LHSType->isObjCQualifiedClassType())
Fariborz Jahaniand923eb02011-09-15 20:40:18 +00005384 return Sema::IncompatiblePointer;
John McCallaba90822011-01-31 23:13:11 +00005385 return Sema::Compatible;
Fariborz Jahaniand5bb8cb2010-03-19 18:06:10 +00005386 }
Richard Trieua871b972011-09-06 20:21:22 +00005387 QualType lhptee = LHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
5388 QualType rhptee = RHSType->getAs<ObjCObjectPointerType>()->getPointeeType();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00005389
Fariborz Jahaniane74d47e2012-01-12 22:12:08 +00005390 if (!lhptee.isAtLeastAsQualifiedAs(rhptee) &&
5391 // make an exception for id<P>
5392 !LHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005393 return Sema::CompatiblePointerDiscardsQualifiers;
5394
Richard Trieua871b972011-09-06 20:21:22 +00005395 if (S.Context.typesAreCompatible(LHSType, RHSType))
John McCallaba90822011-01-31 23:13:11 +00005396 return Sema::Compatible;
Richard Trieua871b972011-09-06 20:21:22 +00005397 if (LHSType->isObjCQualifiedIdType() || RHSType->isObjCQualifiedIdType())
John McCallaba90822011-01-31 23:13:11 +00005398 return Sema::IncompatibleObjCQualifiedId;
5399 return Sema::IncompatiblePointer;
Fariborz Jahanian410f2eb2009-12-08 18:24:49 +00005400}
5401
John McCall29600e12010-11-16 02:32:08 +00005402Sema::AssignConvertType
Douglas Gregorc03a1082011-01-28 02:26:04 +00005403Sema::CheckAssignmentConstraints(SourceLocation Loc,
Richard Trieua871b972011-09-06 20:21:22 +00005404 QualType LHSType, QualType RHSType) {
John McCall29600e12010-11-16 02:32:08 +00005405 // Fake up an opaque expression. We don't actually care about what
5406 // cast operations are required, so if CheckAssignmentConstraints
5407 // adds casts to this they'll be wasted, but fortunately that doesn't
5408 // usually happen on valid code.
Richard Trieua871b972011-09-06 20:21:22 +00005409 OpaqueValueExpr RHSExpr(Loc, RHSType, VK_RValue);
5410 ExprResult RHSPtr = &RHSExpr;
John McCall29600e12010-11-16 02:32:08 +00005411 CastKind K = CK_Invalid;
5412
Richard Trieua871b972011-09-06 20:21:22 +00005413 return CheckAssignmentConstraints(LHSType, RHSPtr, K);
John McCall29600e12010-11-16 02:32:08 +00005414}
5415
Mike Stump4e1f26a2009-02-19 03:04:26 +00005416/// CheckAssignmentConstraints (C99 6.5.16) - This routine currently
5417/// has code to accommodate several GCC extensions when type checking
Steve Naroff17f76e02007-05-03 21:03:48 +00005418/// pointers. Here are some objectionable examples that GCC considers warnings:
5419///
5420/// int a, *pint;
5421/// short *pshort;
5422/// struct foo *pfoo;
5423///
5424/// pint = pshort; // warning: assignment from incompatible pointer type
5425/// a = pint; // warning: assignment makes integer from pointer without a cast
5426/// pint = a; // warning: assignment makes pointer from integer without a cast
5427/// pint = pfoo; // warning: assignment from incompatible pointer type
5428///
5429/// As a result, the code for dealing with pointers is more complex than the
Mike Stump4e1f26a2009-02-19 03:04:26 +00005430/// C99 spec dictates.
Steve Naroff17f76e02007-05-03 21:03:48 +00005431///
John McCall8cb679e2010-11-15 09:13:47 +00005432/// Sets 'Kind' for any result kind except Incompatible.
Chris Lattner9bad62c2008-01-04 18:04:52 +00005433Sema::AssignConvertType
Richard Trieude4958f2011-09-06 20:30:53 +00005434Sema::CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS,
John McCall8cb679e2010-11-15 09:13:47 +00005435 CastKind &Kind) {
Richard Trieude4958f2011-09-06 20:30:53 +00005436 QualType RHSType = RHS.get()->getType();
5437 QualType OrigLHSType = LHSType;
John McCall29600e12010-11-16 02:32:08 +00005438
Chris Lattnera52c2f22008-01-04 23:18:45 +00005439 // Get canonical types. We're not formatting these types, just comparing
5440 // them.
Richard Trieude4958f2011-09-06 20:30:53 +00005441 LHSType = Context.getCanonicalType(LHSType).getUnqualifiedType();
5442 RHSType = Context.getCanonicalType(RHSType).getUnqualifiedType();
Eli Friedman3360d892008-05-30 18:07:22 +00005443
Eli Friedman0dfb8892011-10-06 23:00:33 +00005444
John McCalle5255932011-01-31 22:28:28 +00005445 // Common case: no conversion required.
Richard Trieude4958f2011-09-06 20:30:53 +00005446 if (LHSType == RHSType) {
John McCall8cb679e2010-11-15 09:13:47 +00005447 Kind = CK_NoOp;
John McCall8cb679e2010-11-15 09:13:47 +00005448 return Compatible;
David Chisnall9f57c292009-08-17 16:35:33 +00005449 }
5450
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005451 // If we have an atomic type, try a non-atomic assignment, then just add an
5452 // atomic qualification step.
David Chisnallfa35df62012-01-16 17:27:18 +00005453 if (const AtomicType *AtomicTy = dyn_cast<AtomicType>(LHSType)) {
Eli Friedman93ee5ca2012-06-16 02:19:17 +00005454 Sema::AssignConvertType result =
5455 CheckAssignmentConstraints(AtomicTy->getValueType(), RHS, Kind);
5456 if (result != Compatible)
5457 return result;
5458 if (Kind != CK_NoOp)
5459 RHS = ImpCastExprToType(RHS.take(), AtomicTy->getValueType(), Kind);
5460 Kind = CK_NonAtomicToAtomic;
5461 return Compatible;
David Chisnallfa35df62012-01-16 17:27:18 +00005462 }
5463
Douglas Gregor6b754842008-10-28 00:22:11 +00005464 // If the left-hand side is a reference type, then we are in a
5465 // (rare!) case where we've allowed the use of references in C,
5466 // e.g., as a parameter type in a built-in function. In this case,
5467 // just make sure that the type referenced is compatible with the
5468 // right-hand side type. The caller is responsible for adjusting
Richard Trieude4958f2011-09-06 20:30:53 +00005469 // LHSType so that the resulting expression does not have reference
Douglas Gregor6b754842008-10-28 00:22:11 +00005470 // type.
Richard Trieude4958f2011-09-06 20:30:53 +00005471 if (const ReferenceType *LHSTypeRef = LHSType->getAs<ReferenceType>()) {
5472 if (Context.typesAreCompatible(LHSTypeRef->getPointeeType(), RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005473 Kind = CK_LValueBitCast;
Anders Carlsson24ebce62007-10-12 23:56:29 +00005474 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005475 }
Chris Lattnera52c2f22008-01-04 23:18:45 +00005476 return Incompatible;
Fariborz Jahaniana1e34202007-12-19 17:45:58 +00005477 }
John McCalle5255932011-01-31 22:28:28 +00005478
Nate Begemanbd956c42009-06-28 02:36:38 +00005479 // Allow scalar to ExtVector assignments, and assignments of an ExtVector type
5480 // to the same ExtVector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005481 if (LHSType->isExtVectorType()) {
5482 if (RHSType->isExtVectorType())
John McCall8cb679e2010-11-15 09:13:47 +00005483 return Incompatible;
Richard Trieude4958f2011-09-06 20:30:53 +00005484 if (RHSType->isArithmeticType()) {
John McCall29600e12010-11-16 02:32:08 +00005485 // CK_VectorSplat does T -> vector T, so first cast to the
5486 // element type.
Richard Trieude4958f2011-09-06 20:30:53 +00005487 QualType elType = cast<ExtVectorType>(LHSType)->getElementType();
5488 if (elType != RHSType) {
John McCall9776e432011-10-06 23:25:11 +00005489 Kind = PrepareScalarCast(RHS, elType);
Richard Trieude4958f2011-09-06 20:30:53 +00005490 RHS = ImpCastExprToType(RHS.take(), elType, Kind);
John McCall29600e12010-11-16 02:32:08 +00005491 }
5492 Kind = CK_VectorSplat;
Nate Begemanbd956c42009-06-28 02:36:38 +00005493 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005494 }
Nate Begemanbd956c42009-06-28 02:36:38 +00005495 }
Mike Stump11289f42009-09-09 15:08:12 +00005496
John McCalle5255932011-01-31 22:28:28 +00005497 // Conversions to or from vector type.
Richard Trieude4958f2011-09-06 20:30:53 +00005498 if (LHSType->isVectorType() || RHSType->isVectorType()) {
5499 if (LHSType->isVectorType() && RHSType->isVectorType()) {
Bob Wilson01856f32010-12-02 00:25:15 +00005500 // Allow assignments of an AltiVec vector type to an equivalent GCC
5501 // vector type and vice versa
Richard Trieude4958f2011-09-06 20:30:53 +00005502 if (Context.areCompatibleVectorTypes(LHSType, RHSType)) {
Bob Wilson01856f32010-12-02 00:25:15 +00005503 Kind = CK_BitCast;
5504 return Compatible;
5505 }
5506
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005507 // If we are allowing lax vector conversions, and LHS and RHS are both
5508 // vectors, the total size only needs to be the same. This is a bitcast;
5509 // no bits are changed but the result type is different.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005510 if (getLangOpts().LaxVectorConversions &&
Richard Trieude4958f2011-09-06 20:30:53 +00005511 (Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType))) {
John McCall3065d042010-11-15 10:08:00 +00005512 Kind = CK_BitCast;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00005513 return IncompatibleVectors;
John McCall8cb679e2010-11-15 09:13:47 +00005514 }
Chris Lattner881a2122008-01-04 23:32:24 +00005515 }
5516 return Incompatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00005517 }
Eli Friedman3360d892008-05-30 18:07:22 +00005518
John McCalle5255932011-01-31 22:28:28 +00005519 // Arithmetic conversions.
Richard Trieude4958f2011-09-06 20:30:53 +00005520 if (LHSType->isArithmeticType() && RHSType->isArithmeticType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00005521 !(getLangOpts().CPlusPlus && LHSType->isEnumeralType())) {
John McCall9776e432011-10-06 23:25:11 +00005522 Kind = PrepareScalarCast(RHS, LHSType);
Steve Naroff98cf3e92007-06-06 18:38:38 +00005523 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005524 }
Eli Friedman3360d892008-05-30 18:07:22 +00005525
John McCalle5255932011-01-31 22:28:28 +00005526 // Conversions to normal pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005527 if (const PointerType *LHSPointer = dyn_cast<PointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005528 // U* -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005529 if (isa<PointerType>(RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005530 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005531 return checkPointerTypesForAssignment(*this, LHSType, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005532 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005533
John McCalle5255932011-01-31 22:28:28 +00005534 // int -> T*
Richard Trieude4958f2011-09-06 20:30:53 +00005535 if (RHSType->isIntegerType()) {
John McCalle5255932011-01-31 22:28:28 +00005536 Kind = CK_IntegralToPointer; // FIXME: null?
5537 return IntToPointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005538 }
John McCalle5255932011-01-31 22:28:28 +00005539
5540 // C pointers are not compatible with ObjC object pointers,
5541 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005542 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005543 // - conversions to void*
Richard Trieude4958f2011-09-06 20:30:53 +00005544 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCall9320b872011-09-09 05:25:32 +00005545 Kind = CK_BitCast;
John McCalle5255932011-01-31 22:28:28 +00005546 return Compatible;
5547 }
5548
5549 // - conversions from 'Class' to the redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005550 if (RHSType->isObjCClassType() &&
5551 Context.hasSameType(LHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005552 Context.getObjCClassRedefinitionType())) {
John McCall8cb679e2010-11-15 09:13:47 +00005553 Kind = CK_BitCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005554 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005555 }
Douglas Gregor486b74e2011-09-27 16:10:05 +00005556
John McCalle5255932011-01-31 22:28:28 +00005557 Kind = CK_BitCast;
5558 return IncompatiblePointer;
5559 }
5560
5561 // U^ -> void*
Richard Trieude4958f2011-09-06 20:30:53 +00005562 if (RHSType->getAs<BlockPointerType>()) {
5563 if (LHSPointer->getPointeeType()->isVoidType()) {
John McCalle5255932011-01-31 22:28:28 +00005564 Kind = CK_BitCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005565 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005566 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005567 }
John McCalle5255932011-01-31 22:28:28 +00005568
Steve Naroff081c7422008-09-04 15:10:53 +00005569 return Incompatible;
5570 }
5571
John McCalle5255932011-01-31 22:28:28 +00005572 // Conversions to block pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005573 if (isa<BlockPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005574 // U^ -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005575 if (RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00005576 Kind = CK_BitCast;
Richard Trieude4958f2011-09-06 20:30:53 +00005577 return checkBlockPointerTypesForAssignment(*this, LHSType, RHSType);
John McCalle5255932011-01-31 22:28:28 +00005578 }
5579
5580 // int or null -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005581 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005582 Kind = CK_IntegralToPointer; // FIXME: null
Eli Friedman8163b7a2009-02-25 04:20:42 +00005583 return IntToBlockPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005584 }
5585
John McCalle5255932011-01-31 22:28:28 +00005586 // id -> T^
David Blaikiebbafb8a2012-03-11 07:00:24 +00005587 if (getLangOpts().ObjC1 && RHSType->isObjCIdType()) {
John McCalle5255932011-01-31 22:28:28 +00005588 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff32d072c2008-09-29 18:10:17 +00005589 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005590 }
Steve Naroff32d072c2008-09-29 18:10:17 +00005591
John McCalle5255932011-01-31 22:28:28 +00005592 // void* -> T^
Richard Trieude4958f2011-09-06 20:30:53 +00005593 if (const PointerType *RHSPT = RHSType->getAs<PointerType>())
John McCalle5255932011-01-31 22:28:28 +00005594 if (RHSPT->getPointeeType()->isVoidType()) {
5595 Kind = CK_AnyPointerToBlockPointerCast;
Douglas Gregore7dd1452008-11-27 00:44:28 +00005596 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005597 }
John McCall8cb679e2010-11-15 09:13:47 +00005598
Chris Lattnera52c2f22008-01-04 23:18:45 +00005599 return Incompatible;
5600 }
5601
John McCalle5255932011-01-31 22:28:28 +00005602 // Conversions to Objective-C pointers.
Richard Trieude4958f2011-09-06 20:30:53 +00005603 if (isa<ObjCObjectPointerType>(LHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005604 // A* -> B*
Richard Trieude4958f2011-09-06 20:30:53 +00005605 if (RHSType->isObjCObjectPointerType()) {
John McCalle5255932011-01-31 22:28:28 +00005606 Kind = CK_BitCast;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005607 Sema::AssignConvertType result =
Richard Trieude4958f2011-09-06 20:30:53 +00005608 checkObjCPointerTypesForAssignment(*this, LHSType, RHSType);
David Blaikiebbafb8a2012-03-11 07:00:24 +00005609 if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005610 result == Compatible &&
Richard Trieude4958f2011-09-06 20:30:53 +00005611 !CheckObjCARCUnavailableWeakConversion(OrigLHSType, RHSType))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005612 result = IncompatibleObjCWeakRef;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00005613 return result;
John McCalle5255932011-01-31 22:28:28 +00005614 }
5615
5616 // int or null -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005617 if (RHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005618 Kind = CK_IntegralToPointer; // FIXME: null
Steve Naroff7cae42b2009-07-10 23:34:53 +00005619 return IntToPointer;
John McCall8cb679e2010-11-15 09:13:47 +00005620 }
5621
John McCalle5255932011-01-31 22:28:28 +00005622 // In general, C pointers are not compatible with ObjC object pointers,
5623 // with two exceptions:
Richard Trieude4958f2011-09-06 20:30:53 +00005624 if (isa<PointerType>(RHSType)) {
John McCall9320b872011-09-09 05:25:32 +00005625 Kind = CK_CPointerToObjCPointerCast;
5626
John McCalle5255932011-01-31 22:28:28 +00005627 // - conversions from 'void*'
Richard Trieude4958f2011-09-06 20:30:53 +00005628 if (RHSType->isVoidPointerType()) {
Steve Naroffaccc4882009-07-20 17:56:53 +00005629 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005630 }
5631
5632 // - conversions to 'Class' from its redefinition type
Richard Trieude4958f2011-09-06 20:30:53 +00005633 if (LHSType->isObjCClassType() &&
5634 Context.hasSameType(RHSType,
Douglas Gregor97673472011-08-11 20:58:55 +00005635 Context.getObjCClassRedefinitionType())) {
John McCalle5255932011-01-31 22:28:28 +00005636 return Compatible;
5637 }
5638
Steve Naroffaccc4882009-07-20 17:56:53 +00005639 return IncompatiblePointer;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005640 }
John McCalle5255932011-01-31 22:28:28 +00005641
5642 // T^ -> A*
Richard Trieude4958f2011-09-06 20:30:53 +00005643 if (RHSType->isBlockPointerType()) {
John McCallcd78e802011-09-10 01:16:55 +00005644 maybeExtendBlockObject(*this, RHS);
John McCall9320b872011-09-09 05:25:32 +00005645 Kind = CK_BlockPointerToObjCPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005646 return Compatible;
John McCalle5255932011-01-31 22:28:28 +00005647 }
5648
Steve Naroff7cae42b2009-07-10 23:34:53 +00005649 return Incompatible;
5650 }
John McCalle5255932011-01-31 22:28:28 +00005651
5652 // Conversions from pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005653 if (isa<PointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005654 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005655 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005656 Kind = CK_PointerToBoolean;
Eli Friedman3360d892008-05-30 18:07:22 +00005657 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005658 }
Eli Friedman3360d892008-05-30 18:07:22 +00005659
John McCalle5255932011-01-31 22:28:28 +00005660 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005661 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005662 Kind = CK_PointerToIntegral;
Chris Lattner940cfeb2008-01-04 18:22:42 +00005663 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005664 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005665
Chris Lattnera52c2f22008-01-04 23:18:45 +00005666 return Incompatible;
Chris Lattnera52c2f22008-01-04 23:18:45 +00005667 }
John McCalle5255932011-01-31 22:28:28 +00005668
5669 // Conversions from Objective-C pointers that are not covered by the above.
Richard Trieude4958f2011-09-06 20:30:53 +00005670 if (isa<ObjCObjectPointerType>(RHSType)) {
John McCalle5255932011-01-31 22:28:28 +00005671 // T* -> _Bool
Richard Trieude4958f2011-09-06 20:30:53 +00005672 if (LHSType == Context.BoolTy) {
John McCall8cb679e2010-11-15 09:13:47 +00005673 Kind = CK_PointerToBoolean;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005674 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005675 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00005676
John McCalle5255932011-01-31 22:28:28 +00005677 // T* -> int
Richard Trieude4958f2011-09-06 20:30:53 +00005678 if (LHSType->isIntegerType()) {
John McCall8cb679e2010-11-15 09:13:47 +00005679 Kind = CK_PointerToIntegral;
Steve Naroff7cae42b2009-07-10 23:34:53 +00005680 return PointerToInt;
John McCall8cb679e2010-11-15 09:13:47 +00005681 }
5682
Steve Naroff7cae42b2009-07-10 23:34:53 +00005683 return Incompatible;
5684 }
Eli Friedman3360d892008-05-30 18:07:22 +00005685
John McCalle5255932011-01-31 22:28:28 +00005686 // struct A -> struct B
Richard Trieude4958f2011-09-06 20:30:53 +00005687 if (isa<TagType>(LHSType) && isa<TagType>(RHSType)) {
5688 if (Context.typesAreCompatible(LHSType, RHSType)) {
John McCall8cb679e2010-11-15 09:13:47 +00005689 Kind = CK_NoOp;
Steve Naroff98cf3e92007-06-06 18:38:38 +00005690 return Compatible;
John McCall8cb679e2010-11-15 09:13:47 +00005691 }
Bill Wendling216423b2007-05-30 06:30:29 +00005692 }
John McCalle5255932011-01-31 22:28:28 +00005693
Steve Naroff98cf3e92007-06-06 18:38:38 +00005694 return Incompatible;
Steve Naroff9eb24652007-05-02 21:58:15 +00005695}
5696
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005697/// \brief Constructs a transparent union from an expression that is
5698/// used to initialize the transparent union.
Richard Trieucfc491d2011-08-02 04:35:43 +00005699static void ConstructTransparentUnion(Sema &S, ASTContext &C,
5700 ExprResult &EResult, QualType UnionType,
5701 FieldDecl *Field) {
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005702 // Build an initializer list that designates the appropriate member
5703 // of the transparent union.
John Wiegley01296292011-04-08 18:41:53 +00005704 Expr *E = EResult.take();
Ted Kremenekac034612010-04-13 23:39:13 +00005705 InitListExpr *Initializer = new (C) InitListExpr(C, SourceLocation(),
Ted Kremenek013041e2010-02-19 01:50:18 +00005706 &E, 1,
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005707 SourceLocation());
5708 Initializer->setType(UnionType);
5709 Initializer->setInitializedFieldInUnion(Field);
5710
5711 // Build a compound literal constructing a value of the transparent
5712 // union type from this initializer list.
John McCalle15bbff2010-01-18 19:35:47 +00005713 TypeSourceInfo *unionTInfo = C.getTrivialTypeSourceInfo(UnionType);
John Wiegley01296292011-04-08 18:41:53 +00005714 EResult = S.Owned(
5715 new (C) CompoundLiteralExpr(SourceLocation(), unionTInfo, UnionType,
5716 VK_RValue, Initializer, false));
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005717}
5718
5719Sema::AssignConvertType
Richard Trieucfc491d2011-08-02 04:35:43 +00005720Sema::CheckTransparentUnionArgumentConstraints(QualType ArgType,
Richard Trieueb299142011-09-06 20:40:12 +00005721 ExprResult &RHS) {
5722 QualType RHSType = RHS.get()->getType();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005723
Mike Stump11289f42009-09-09 15:08:12 +00005724 // If the ArgType is a Union type, we want to handle a potential
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005725 // transparent_union GCC extension.
5726 const RecordType *UT = ArgType->getAsUnionType();
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005727 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005728 return Incompatible;
5729
5730 // The field to initialize within the transparent union.
5731 RecordDecl *UD = UT->getDecl();
5732 FieldDecl *InitField = 0;
5733 // It's compatible if the expression matches any of the fields.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005734 for (RecordDecl::field_iterator it = UD->field_begin(),
5735 itend = UD->field_end();
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005736 it != itend; ++it) {
5737 if (it->getType()->isPointerType()) {
5738 // If the transparent union contains a pointer type, we allow:
5739 // 1) void pointer
5740 // 2) null pointer constant
Richard Trieueb299142011-09-06 20:40:12 +00005741 if (RHSType->isPointerType())
John McCall9320b872011-09-09 05:25:32 +00005742 if (RHSType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
Richard Trieueb299142011-09-06 20:40:12 +00005743 RHS = ImpCastExprToType(RHS.take(), it->getType(), CK_BitCast);
David Blaikie40ed2972012-06-06 20:45:41 +00005744 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005745 break;
5746 }
Mike Stump11289f42009-09-09 15:08:12 +00005747
Richard Trieueb299142011-09-06 20:40:12 +00005748 if (RHS.get()->isNullPointerConstant(Context,
5749 Expr::NPC_ValueDependentIsNull)) {
5750 RHS = ImpCastExprToType(RHS.take(), it->getType(),
5751 CK_NullToPointer);
David Blaikie40ed2972012-06-06 20:45:41 +00005752 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005753 break;
5754 }
5755 }
5756
John McCall8cb679e2010-11-15 09:13:47 +00005757 CastKind Kind = CK_Invalid;
Richard Trieueb299142011-09-06 20:40:12 +00005758 if (CheckAssignmentConstraints(it->getType(), RHS, Kind)
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005759 == Compatible) {
Richard Trieueb299142011-09-06 20:40:12 +00005760 RHS = ImpCastExprToType(RHS.take(), it->getType(), Kind);
David Blaikie40ed2972012-06-06 20:45:41 +00005761 InitField = *it;
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005762 break;
5763 }
5764 }
5765
5766 if (!InitField)
5767 return Incompatible;
5768
Richard Trieueb299142011-09-06 20:40:12 +00005769 ConstructTransparentUnion(*this, Context, RHS, ArgType, InitField);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00005770 return Compatible;
5771}
5772
Chris Lattner9bad62c2008-01-04 18:04:52 +00005773Sema::AssignConvertType
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005774Sema::CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS,
5775 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00005776 if (getLangOpts().CPlusPlus) {
Eli Friedman0dfb8892011-10-06 23:00:33 +00005777 if (!LHSType->isRecordType() && !LHSType->isAtomicType()) {
Douglas Gregor9a657932008-10-21 23:43:52 +00005778 // C++ 5.17p3: If the left operand is not of class type, the
5779 // expression is implicitly converted (C++ 4) to the
5780 // cv-unqualified type of the left operand.
Sebastian Redlcc152642011-10-16 18:19:06 +00005781 ExprResult Res;
5782 if (Diagnose) {
5783 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5784 AA_Assigning);
5785 } else {
5786 ImplicitConversionSequence ICS =
5787 TryImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5788 /*SuppressUserConversions=*/false,
5789 /*AllowExplicit=*/false,
5790 /*InOverloadResolution=*/false,
5791 /*CStyle=*/false,
5792 /*AllowObjCWritebackConversion=*/false);
5793 if (ICS.isFailure())
5794 return Incompatible;
5795 Res = PerformImplicitConversion(RHS.get(), LHSType.getUnqualifiedType(),
5796 ICS, AA_Assigning);
5797 }
John Wiegley01296292011-04-08 18:41:53 +00005798 if (Res.isInvalid())
Douglas Gregor9a657932008-10-21 23:43:52 +00005799 return Incompatible;
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005800 Sema::AssignConvertType result = Compatible;
David Blaikiebbafb8a2012-03-11 07:00:24 +00005801 if (getLangOpts().ObjCAutoRefCount &&
Richard Trieueb299142011-09-06 20:40:12 +00005802 !CheckObjCARCUnavailableWeakConversion(LHSType,
5803 RHS.get()->getType()))
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005804 result = IncompatibleObjCWeakRef;
Richard Trieueb299142011-09-06 20:40:12 +00005805 RHS = move(Res);
Fariborz Jahanian7fcce682011-07-07 23:04:17 +00005806 return result;
Douglas Gregor9a657932008-10-21 23:43:52 +00005807 }
5808
5809 // FIXME: Currently, we fall through and treat C++ classes like C
5810 // structures.
Eli Friedman0dfb8892011-10-06 23:00:33 +00005811 // FIXME: We also fall through for atomics; not sure what should
5812 // happen there, though.
Sebastian Redlb49c46c2011-09-24 17:48:00 +00005813 }
Douglas Gregor9a657932008-10-21 23:43:52 +00005814
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005815 // C99 6.5.16.1p1: the left operand is a pointer and the right is
5816 // a null pointer constant.
Richard Trieueb299142011-09-06 20:40:12 +00005817 if ((LHSType->isPointerType() ||
5818 LHSType->isObjCObjectPointerType() ||
5819 LHSType->isBlockPointerType())
5820 && RHS.get()->isNullPointerConstant(Context,
5821 Expr::NPC_ValueDependentIsNull)) {
5822 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Steve Naroff0ee0b0a2007-11-27 17:58:44 +00005823 return Compatible;
5824 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00005825
Chris Lattnere6dcd502007-10-16 02:55:40 +00005826 // This check seems unnatural, however it is necessary to ensure the proper
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005827 // conversion of functions/arrays. If the conversion were done for all
Douglas Gregora121b752009-11-03 16:56:39 +00005828 // DeclExpr's (created by ActOnIdExpression), it would mess up the unary
Nick Lewyckyef7c0ff2010-08-05 06:27:49 +00005829 // expressions that suppress this implicit conversion (&, sizeof).
Chris Lattnere6dcd502007-10-16 02:55:40 +00005830 //
Mike Stump4e1f26a2009-02-19 03:04:26 +00005831 // Suppress this for references: C++ 8.5.3p5.
Richard Trieueb299142011-09-06 20:40:12 +00005832 if (!LHSType->isReferenceType()) {
5833 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5834 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00005835 return Incompatible;
5836 }
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005837
John McCall8cb679e2010-11-15 09:13:47 +00005838 CastKind Kind = CK_Invalid;
Chris Lattner9bad62c2008-01-04 18:04:52 +00005839 Sema::AssignConvertType result =
Richard Trieueb299142011-09-06 20:40:12 +00005840 CheckAssignmentConstraints(LHSType, RHS, Kind);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005841
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005842 // C99 6.5.16.1p2: The value of the right operand is converted to the
5843 // type of the assignment expression.
Douglas Gregor6b754842008-10-28 00:22:11 +00005844 // CheckAssignmentConstraints allows the left-hand side to be a reference,
5845 // so that we can use references in built-in functions even in C.
5846 // The getNonReferenceType() call makes sure that the resulting expression
5847 // does not have reference type.
Richard Trieueb299142011-09-06 20:40:12 +00005848 if (result != Incompatible && RHS.get()->getType() != LHSType)
5849 RHS = ImpCastExprToType(RHS.take(),
5850 LHSType.getNonLValueExprType(Context), Kind);
Steve Naroff0c1c7ed2007-08-24 22:33:52 +00005851 return result;
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00005852}
5853
Richard Trieueb299142011-09-06 20:40:12 +00005854QualType Sema::InvalidOperands(SourceLocation Loc, ExprResult &LHS,
5855 ExprResult &RHS) {
Chris Lattner377d1f82008-11-18 22:52:51 +00005856 Diag(Loc, diag::err_typecheck_invalid_operands)
Richard Trieueb299142011-09-06 20:40:12 +00005857 << LHS.get()->getType() << RHS.get()->getType()
5858 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chris Lattner5c11c412007-12-12 05:47:28 +00005859 return QualType();
Steve Naroff6f49f5d2007-05-29 14:23:36 +00005860}
5861
Richard Trieu859d23f2011-09-06 21:01:04 +00005862QualType Sema::CheckVectorOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00005863 SourceLocation Loc, bool IsCompAssign) {
Richard Smith508ebf32011-10-28 03:31:48 +00005864 if (!IsCompAssign) {
5865 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
5866 if (LHS.isInvalid())
5867 return QualType();
5868 }
5869 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
5870 if (RHS.isInvalid())
5871 return QualType();
5872
Mike Stump4e1f26a2009-02-19 03:04:26 +00005873 // For conversion purposes, we ignore any qualifiers.
Nate Begeman002e4bd2008-04-04 01:30:25 +00005874 // For example, "const float" and "float" are equivalent.
Richard Trieu859d23f2011-09-06 21:01:04 +00005875 QualType LHSType =
5876 Context.getCanonicalType(LHS.get()->getType()).getUnqualifiedType();
5877 QualType RHSType =
5878 Context.getCanonicalType(RHS.get()->getType()).getUnqualifiedType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00005879
Nate Begeman191a6b12008-07-14 18:02:46 +00005880 // If the vector types are identical, return.
Richard Trieu859d23f2011-09-06 21:01:04 +00005881 if (LHSType == RHSType)
5882 return LHSType;
Nate Begeman330aaa72007-12-30 02:59:45 +00005883
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005884 // Handle the case of equivalent AltiVec and GCC vector types
Richard Trieu859d23f2011-09-06 21:01:04 +00005885 if (LHSType->isVectorType() && RHSType->isVectorType() &&
5886 Context.areCompatibleVectorTypes(LHSType, RHSType)) {
5887 if (LHSType->isExtVectorType()) {
5888 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5889 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005890 }
5891
Richard Trieuba63ce62011-09-09 01:45:06 +00005892 if (!IsCompAssign)
Richard Trieu859d23f2011-09-06 21:01:04 +00005893 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
5894 return RHSType;
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00005895 }
5896
David Blaikiebbafb8a2012-03-11 07:00:24 +00005897 if (getLangOpts().LaxVectorConversions &&
Richard Trieu859d23f2011-09-06 21:01:04 +00005898 Context.getTypeSize(LHSType) == Context.getTypeSize(RHSType)) {
Eli Friedman1408bc92011-06-23 18:10:35 +00005899 // If we are allowing lax vector conversions, and LHS and RHS are both
5900 // vectors, the total size only needs to be the same. This is a
5901 // bitcast; no bits are changed but the result type is different.
5902 // FIXME: Should we really be allowing this?
Richard Trieu859d23f2011-09-06 21:01:04 +00005903 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
5904 return LHSType;
Eli Friedman1408bc92011-06-23 18:10:35 +00005905 }
5906
Nate Begemanbd956c42009-06-28 02:36:38 +00005907 // Canonicalize the ExtVector to the LHS, remember if we swapped so we can
5908 // swap back (so that we don't reverse the inputs to a subtract, for instance.
5909 bool swapped = false;
Richard Trieuba63ce62011-09-09 01:45:06 +00005910 if (RHSType->isExtVectorType() && !IsCompAssign) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005911 swapped = true;
Richard Trieu859d23f2011-09-06 21:01:04 +00005912 std::swap(RHS, LHS);
5913 std::swap(RHSType, LHSType);
Nate Begemanbd956c42009-06-28 02:36:38 +00005914 }
Mike Stump11289f42009-09-09 15:08:12 +00005915
Nate Begeman886448d2009-06-28 19:12:57 +00005916 // Handle the case of an ext vector and scalar.
Richard Trieu859d23f2011-09-06 21:01:04 +00005917 if (const ExtVectorType *LV = LHSType->getAs<ExtVectorType>()) {
Nate Begemanbd956c42009-06-28 02:36:38 +00005918 QualType EltTy = LV->getElementType();
Richard Trieu859d23f2011-09-06 21:01:04 +00005919 if (EltTy->isIntegralType(Context) && RHSType->isIntegralType(Context)) {
5920 int order = Context.getIntegerTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005921 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005922 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_IntegralCast);
John McCall8cb679e2010-11-15 09:13:47 +00005923 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005924 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5925 if (swapped) std::swap(RHS, LHS);
5926 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005927 }
5928 }
Richard Trieu859d23f2011-09-06 21:01:04 +00005929 if (EltTy->isRealFloatingType() && RHSType->isScalarType() &&
5930 RHSType->isRealFloatingType()) {
5931 int order = Context.getFloatingTypeOrder(EltTy, RHSType);
John McCall8cb679e2010-11-15 09:13:47 +00005932 if (order > 0)
Richard Trieu859d23f2011-09-06 21:01:04 +00005933 RHS = ImpCastExprToType(RHS.take(), EltTy, CK_FloatingCast);
John McCall8cb679e2010-11-15 09:13:47 +00005934 if (order >= 0) {
Richard Trieu859d23f2011-09-06 21:01:04 +00005935 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_VectorSplat);
5936 if (swapped) std::swap(RHS, LHS);
5937 return LHSType;
Nate Begemanbd956c42009-06-28 02:36:38 +00005938 }
Nate Begeman330aaa72007-12-30 02:59:45 +00005939 }
5940 }
Mike Stump11289f42009-09-09 15:08:12 +00005941
Nate Begeman886448d2009-06-28 19:12:57 +00005942 // Vectors of different size or scalar and non-ext-vector are errors.
Richard Trieu859d23f2011-09-06 21:01:04 +00005943 if (swapped) std::swap(RHS, LHS);
Chris Lattner377d1f82008-11-18 22:52:51 +00005944 Diag(Loc, diag::err_typecheck_vector_not_convertable)
Richard Trieu859d23f2011-09-06 21:01:04 +00005945 << LHS.get()->getType() << RHS.get()->getType()
5946 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Steve Naroff84ff4b42007-07-09 21:31:10 +00005947 return QualType();
Sebastian Redl112a97662009-02-07 00:15:38 +00005948}
5949
Richard Trieuf8916e12011-09-16 00:53:10 +00005950// checkArithmeticNull - Detect when a NULL constant is used improperly in an
5951// expression. These are mainly cases where the null pointer is used as an
5952// integer instead of a pointer.
5953static void checkArithmeticNull(Sema &S, ExprResult &LHS, ExprResult &RHS,
5954 SourceLocation Loc, bool IsCompare) {
5955 // The canonical way to check for a GNU null is with isNullPointerConstant,
5956 // but we use a bit of a hack here for speed; this is a relatively
5957 // hot path, and isNullPointerConstant is slow.
5958 bool LHSNull = isa<GNUNullExpr>(LHS.get()->IgnoreParenImpCasts());
5959 bool RHSNull = isa<GNUNullExpr>(RHS.get()->IgnoreParenImpCasts());
5960
5961 QualType NonNullType = LHSNull ? RHS.get()->getType() : LHS.get()->getType();
5962
5963 // Avoid analyzing cases where the result will either be invalid (and
5964 // diagnosed as such) or entirely valid and not something to warn about.
5965 if ((!LHSNull && !RHSNull) || NonNullType->isBlockPointerType() ||
5966 NonNullType->isMemberPointerType() || NonNullType->isFunctionType())
5967 return;
5968
5969 // Comparison operations would not make sense with a null pointer no matter
5970 // what the other expression is.
5971 if (!IsCompare) {
5972 S.Diag(Loc, diag::warn_null_in_arithmetic_operation)
5973 << (LHSNull ? LHS.get()->getSourceRange() : SourceRange())
5974 << (RHSNull ? RHS.get()->getSourceRange() : SourceRange());
5975 return;
5976 }
5977
5978 // The rest of the operations only make sense with a null pointer
5979 // if the other expression is a pointer.
5980 if (LHSNull == RHSNull || NonNullType->isAnyPointerType() ||
5981 NonNullType->canDecayToPointerType())
5982 return;
5983
5984 S.Diag(Loc, diag::warn_null_in_comparison_operation)
5985 << LHSNull /* LHS is NULL */ << NonNullType
5986 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5987}
5988
Richard Trieu859d23f2011-09-06 21:01:04 +00005989QualType Sema::CheckMultiplyDivideOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00005990 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00005991 bool IsCompAssign, bool IsDiv) {
Richard Trieuf8916e12011-09-16 00:53:10 +00005992 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
5993
Richard Trieu859d23f2011-09-06 21:01:04 +00005994 if (LHS.get()->getType()->isVectorType() ||
5995 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00005996 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Mike Stump4e1f26a2009-02-19 03:04:26 +00005997
Richard Trieuba63ce62011-09-09 01:45:06 +00005998 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00005999 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006000 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006001
David Chisnallfa35df62012-01-16 17:27:18 +00006002
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006003 if (compType.isNull() || !compType->isArithmeticType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006004 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006005
Chris Lattnerfaa54172010-01-12 21:23:57 +00006006 // Check for division by zero.
Richard Trieuba63ce62011-09-09 01:45:06 +00006007 if (IsDiv &&
Richard Trieu859d23f2011-09-06 21:01:04 +00006008 RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006009 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006010 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_division_by_zero)
6011 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006012
Chris Lattnerfaa54172010-01-12 21:23:57 +00006013 return compType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006014}
6015
Chris Lattnerfaa54172010-01-12 21:23:57 +00006016QualType Sema::CheckRemainderOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00006017 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006018 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6019
Richard Trieu859d23f2011-09-06 21:01:04 +00006020 if (LHS.get()->getType()->isVectorType() ||
6021 RHS.get()->getType()->isVectorType()) {
6022 if (LHS.get()->getType()->hasIntegerRepresentation() &&
6023 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00006024 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006025 return InvalidOperands(Loc, LHS, RHS);
Daniel Dunbar0d2bfec2009-01-05 22:55:36 +00006026 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00006027
Richard Trieuba63ce62011-09-09 01:45:06 +00006028 QualType compType = UsualArithmeticConversions(LHS, RHS, IsCompAssign);
Richard Trieu859d23f2011-09-06 21:01:04 +00006029 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006030 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006031
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006032 if (compType.isNull() || !compType->isIntegerType())
Richard Trieu859d23f2011-09-06 21:01:04 +00006033 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006034
Chris Lattnerfaa54172010-01-12 21:23:57 +00006035 // Check for remainder by zero.
Richard Trieu859d23f2011-09-06 21:01:04 +00006036 if (RHS.get()->isNullPointerConstant(Context,
Richard Trieucfc491d2011-08-02 04:35:43 +00006037 Expr::NPC_ValueDependentIsNotNull))
Richard Trieu859d23f2011-09-06 21:01:04 +00006038 DiagRuntimeBehavior(Loc, RHS.get(), PDiag(diag::warn_remainder_by_zero)
6039 << RHS.get()->getSourceRange());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006040
Chris Lattnerfaa54172010-01-12 21:23:57 +00006041 return compType;
Steve Naroff218bc2b2007-05-04 21:54:46 +00006042}
6043
Chandler Carruthc9332212011-06-27 08:02:19 +00006044/// \brief Diagnose invalid arithmetic on two void pointers.
6045static void diagnoseArithmeticOnTwoVoidPointers(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006046 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006047 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006048 ? diag::err_typecheck_pointer_arith_void_type
6049 : diag::ext_gnu_void_ptr)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006050 << 1 /* two pointers */ << LHSExpr->getSourceRange()
6051 << RHSExpr->getSourceRange();
Chandler Carruthc9332212011-06-27 08:02:19 +00006052}
6053
6054/// \brief Diagnose invalid arithmetic on a void pointer.
6055static void diagnoseArithmeticOnVoidPointer(Sema &S, SourceLocation Loc,
6056 Expr *Pointer) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006057 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006058 ? diag::err_typecheck_pointer_arith_void_type
6059 : diag::ext_gnu_void_ptr)
6060 << 0 /* one pointer */ << Pointer->getSourceRange();
6061}
6062
6063/// \brief Diagnose invalid arithmetic on two function pointers.
6064static void diagnoseArithmeticOnTwoFunctionPointers(Sema &S, SourceLocation Loc,
6065 Expr *LHS, Expr *RHS) {
6066 assert(LHS->getType()->isAnyPointerType());
6067 assert(RHS->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006068 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006069 ? diag::err_typecheck_pointer_arith_function_type
6070 : diag::ext_gnu_ptr_func_arith)
6071 << 1 /* two pointers */ << LHS->getType()->getPointeeType()
6072 // We only show the second type if it differs from the first.
6073 << (unsigned)!S.Context.hasSameUnqualifiedType(LHS->getType(),
6074 RHS->getType())
6075 << RHS->getType()->getPointeeType()
6076 << LHS->getSourceRange() << RHS->getSourceRange();
6077}
6078
6079/// \brief Diagnose invalid arithmetic on a function pointer.
6080static void diagnoseArithmeticOnFunctionPointer(Sema &S, SourceLocation Loc,
6081 Expr *Pointer) {
6082 assert(Pointer->getType()->isAnyPointerType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006083 S.Diag(Loc, S.getLangOpts().CPlusPlus
Chandler Carruthc9332212011-06-27 08:02:19 +00006084 ? diag::err_typecheck_pointer_arith_function_type
6085 : diag::ext_gnu_ptr_func_arith)
6086 << 0 /* one pointer */ << Pointer->getType()->getPointeeType()
6087 << 0 /* one pointer, so only one type */
6088 << Pointer->getSourceRange();
6089}
6090
Richard Trieu993f3ab2011-09-12 18:08:02 +00006091/// \brief Emit error if Operand is incomplete pointer type
Richard Trieuaba22802011-09-02 02:15:37 +00006092///
6093/// \returns True if pointer has incomplete type
6094static bool checkArithmeticIncompletePointerType(Sema &S, SourceLocation Loc,
6095 Expr *Operand) {
6096 if ((Operand->getType()->isPointerType() &&
6097 !Operand->getType()->isDependentType()) ||
6098 Operand->getType()->isObjCObjectPointerType()) {
6099 QualType PointeeTy = Operand->getType()->getPointeeType();
6100 if (S.RequireCompleteType(
6101 Loc, PointeeTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00006102 diag::err_typecheck_arithmetic_incomplete_type,
6103 PointeeTy, Operand->getSourceRange()))
Richard Trieuaba22802011-09-02 02:15:37 +00006104 return true;
6105 }
6106 return false;
6107}
6108
Chandler Carruthc9332212011-06-27 08:02:19 +00006109/// \brief Check the validity of an arithmetic pointer operand.
6110///
6111/// If the operand has pointer type, this code will check for pointer types
6112/// which are invalid in arithmetic operations. These will be diagnosed
6113/// appropriately, including whether or not the use is supported as an
6114/// extension.
6115///
6116/// \returns True when the operand is valid to use (even if as an extension).
6117static bool checkArithmeticOpPointerOperand(Sema &S, SourceLocation Loc,
6118 Expr *Operand) {
6119 if (!Operand->getType()->isAnyPointerType()) return true;
6120
6121 QualType PointeeTy = Operand->getType()->getPointeeType();
6122 if (PointeeTy->isVoidType()) {
6123 diagnoseArithmeticOnVoidPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006124 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006125 }
6126 if (PointeeTy->isFunctionType()) {
6127 diagnoseArithmeticOnFunctionPointer(S, Loc, Operand);
David Blaikiebbafb8a2012-03-11 07:00:24 +00006128 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006129 }
6130
Richard Trieuaba22802011-09-02 02:15:37 +00006131 if (checkArithmeticIncompletePointerType(S, Loc, Operand)) return false;
Chandler Carruthc9332212011-06-27 08:02:19 +00006132
6133 return true;
6134}
6135
6136/// \brief Check the validity of a binary arithmetic operation w.r.t. pointer
6137/// operands.
6138///
6139/// This routine will diagnose any invalid arithmetic on pointer operands much
6140/// like \see checkArithmeticOpPointerOperand. However, it has special logic
6141/// for emitting a single diagnostic even for operations where both LHS and RHS
6142/// are (potentially problematic) pointers.
6143///
6144/// \returns True when the operand is valid to use (even if as an extension).
6145static bool checkArithmeticBinOpPointerOperands(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006146 Expr *LHSExpr, Expr *RHSExpr) {
6147 bool isLHSPointer = LHSExpr->getType()->isAnyPointerType();
6148 bool isRHSPointer = RHSExpr->getType()->isAnyPointerType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006149 if (!isLHSPointer && !isRHSPointer) return true;
6150
6151 QualType LHSPointeeTy, RHSPointeeTy;
Richard Trieu4ae7e972011-09-06 21:13:51 +00006152 if (isLHSPointer) LHSPointeeTy = LHSExpr->getType()->getPointeeType();
6153 if (isRHSPointer) RHSPointeeTy = RHSExpr->getType()->getPointeeType();
Chandler Carruthc9332212011-06-27 08:02:19 +00006154
6155 // Check for arithmetic on pointers to incomplete types.
6156 bool isLHSVoidPtr = isLHSPointer && LHSPointeeTy->isVoidType();
6157 bool isRHSVoidPtr = isRHSPointer && RHSPointeeTy->isVoidType();
6158 if (isLHSVoidPtr || isRHSVoidPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006159 if (!isRHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, LHSExpr);
6160 else if (!isLHSVoidPtr) diagnoseArithmeticOnVoidPointer(S, Loc, RHSExpr);
6161 else diagnoseArithmeticOnTwoVoidPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006162
David Blaikiebbafb8a2012-03-11 07:00:24 +00006163 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006164 }
6165
6166 bool isLHSFuncPtr = isLHSPointer && LHSPointeeTy->isFunctionType();
6167 bool isRHSFuncPtr = isRHSPointer && RHSPointeeTy->isFunctionType();
6168 if (isLHSFuncPtr || isRHSFuncPtr) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006169 if (!isRHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc, LHSExpr);
6170 else if (!isLHSFuncPtr) diagnoseArithmeticOnFunctionPointer(S, Loc,
6171 RHSExpr);
6172 else diagnoseArithmeticOnTwoFunctionPointers(S, Loc, LHSExpr, RHSExpr);
Chandler Carruthc9332212011-06-27 08:02:19 +00006173
David Blaikiebbafb8a2012-03-11 07:00:24 +00006174 return !S.getLangOpts().CPlusPlus;
Chandler Carruthc9332212011-06-27 08:02:19 +00006175 }
6176
Richard Trieu4ae7e972011-09-06 21:13:51 +00006177 if (checkArithmeticIncompletePointerType(S, Loc, LHSExpr)) return false;
6178 if (checkArithmeticIncompletePointerType(S, Loc, RHSExpr)) return false;
Richard Trieuaba22802011-09-02 02:15:37 +00006179
Chandler Carruthc9332212011-06-27 08:02:19 +00006180 return true;
6181}
6182
Richard Trieub10c6312011-09-01 22:53:23 +00006183/// \brief Check bad cases where we step over interface counts.
6184static bool checkArithmethicPointerOnNonFragileABI(Sema &S,
6185 SourceLocation OpLoc,
6186 Expr *Op) {
6187 assert(Op->getType()->isAnyPointerType());
6188 QualType PointeeTy = Op->getType()->getPointeeType();
6189 if (!PointeeTy->isObjCObjectType() || !S.LangOpts.ObjCNonFragileABI)
6190 return true;
6191
6192 S.Diag(OpLoc, diag::err_arithmetic_nonfragile_interface)
6193 << PointeeTy << Op->getSourceRange();
6194 return false;
6195}
6196
Nico Weberccec40d2012-03-02 22:01:22 +00006197/// diagnoseStringPlusInt - Emit a warning when adding an integer to a string
6198/// literal.
6199static void diagnoseStringPlusInt(Sema &Self, SourceLocation OpLoc,
6200 Expr *LHSExpr, Expr *RHSExpr) {
6201 StringLiteral* StrExpr = dyn_cast<StringLiteral>(LHSExpr->IgnoreImpCasts());
6202 Expr* IndexExpr = RHSExpr;
6203 if (!StrExpr) {
6204 StrExpr = dyn_cast<StringLiteral>(RHSExpr->IgnoreImpCasts());
6205 IndexExpr = LHSExpr;
6206 }
6207
6208 bool IsStringPlusInt = StrExpr &&
6209 IndexExpr->getType()->isIntegralOrUnscopedEnumerationType();
6210 if (!IsStringPlusInt)
6211 return;
6212
6213 llvm::APSInt index;
6214 if (IndexExpr->EvaluateAsInt(index, Self.getASTContext())) {
6215 unsigned StrLenWithNull = StrExpr->getLength() + 1;
6216 if (index.isNonNegative() &&
6217 index <= llvm::APSInt(llvm::APInt(index.getBitWidth(), StrLenWithNull),
6218 index.isUnsigned()))
6219 return;
6220 }
6221
6222 SourceRange DiagRange(LHSExpr->getLocStart(), RHSExpr->getLocEnd());
6223 Self.Diag(OpLoc, diag::warn_string_plus_int)
6224 << DiagRange << IndexExpr->IgnoreImpCasts()->getType();
6225
6226 // Only print a fixit for "str" + int, not for int + "str".
6227 if (IndexExpr == RHSExpr) {
6228 SourceLocation EndLoc = Self.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6229 Self.Diag(OpLoc, diag::note_string_plus_int_silence)
6230 << FixItHint::CreateInsertion(LHSExpr->getLocStart(), "&")
6231 << FixItHint::CreateReplacement(SourceRange(OpLoc), "[")
6232 << FixItHint::CreateInsertion(EndLoc, "]");
6233 } else
6234 Self.Diag(OpLoc, diag::note_string_plus_int_silence);
6235}
6236
Richard Trieu993f3ab2011-09-12 18:08:02 +00006237/// \brief Emit error when two pointers are incompatible.
Richard Trieub10c6312011-09-01 22:53:23 +00006238static void diagnosePointerIncompatibility(Sema &S, SourceLocation Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006239 Expr *LHSExpr, Expr *RHSExpr) {
6240 assert(LHSExpr->getType()->isAnyPointerType());
6241 assert(RHSExpr->getType()->isAnyPointerType());
Richard Trieub10c6312011-09-01 22:53:23 +00006242 S.Diag(Loc, diag::err_typecheck_sub_ptr_compatible)
Richard Trieu4ae7e972011-09-06 21:13:51 +00006243 << LHSExpr->getType() << RHSExpr->getType() << LHSExpr->getSourceRange()
6244 << RHSExpr->getSourceRange();
Richard Trieub10c6312011-09-01 22:53:23 +00006245}
6246
Chris Lattnerfaa54172010-01-12 21:23:57 +00006247QualType Sema::CheckAdditionOperands( // C99 6.5.6
Nico Weberccec40d2012-03-02 22:01:22 +00006248 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc,
6249 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006250 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6251
Richard Trieu4ae7e972011-09-06 21:13:51 +00006252 if (LHS.get()->getType()->isVectorType() ||
6253 RHS.get()->getType()->isVectorType()) {
6254 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006255 if (CompLHSTy) *CompLHSTy = compType;
6256 return compType;
6257 }
Steve Naroff7a5af782007-07-13 16:58:59 +00006258
Richard Trieu4ae7e972011-09-06 21:13:51 +00006259 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6260 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006261 return QualType();
Eli Friedman8e122982008-05-18 18:08:51 +00006262
Nico Weberccec40d2012-03-02 22:01:22 +00006263 // Diagnose "string literal" '+' int.
6264 if (Opc == BO_Add)
6265 diagnoseStringPlusInt(*this, Loc, LHS.get(), RHS.get());
6266
Steve Naroffe4718892007-04-27 18:30:00 +00006267 // handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006268 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006269 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006270 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006271 }
Steve Naroff218bc2b2007-05-04 21:54:46 +00006272
Eli Friedman8e122982008-05-18 18:08:51 +00006273 // Put any potential pointer into PExp
Richard Trieu4ae7e972011-09-06 21:13:51 +00006274 Expr* PExp = LHS.get(), *IExp = RHS.get();
Steve Naroff6b712a72009-07-14 18:25:06 +00006275 if (IExp->getType()->isAnyPointerType())
Eli Friedman8e122982008-05-18 18:08:51 +00006276 std::swap(PExp, IExp);
6277
Richard Trieub420bca2011-09-12 18:37:54 +00006278 if (!PExp->getType()->isAnyPointerType())
6279 return InvalidOperands(Loc, LHS, RHS);
Chandler Carruthc9332212011-06-27 08:02:19 +00006280
Richard Trieub420bca2011-09-12 18:37:54 +00006281 if (!IExp->getType()->isIntegerType())
6282 return InvalidOperands(Loc, LHS, RHS);
Mike Stump11289f42009-09-09 15:08:12 +00006283
Richard Trieub420bca2011-09-12 18:37:54 +00006284 if (!checkArithmeticOpPointerOperand(*this, Loc, PExp))
6285 return QualType();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006286
Richard Trieub420bca2011-09-12 18:37:54 +00006287 // Diagnose bad cases where we step over interface counts.
6288 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, PExp))
6289 return QualType();
6290
6291 // Check array bounds for pointer arithemtic
6292 CheckArrayAccess(PExp, IExp);
6293
6294 if (CompLHSTy) {
6295 QualType LHSTy = Context.isPromotableBitField(LHS.get());
6296 if (LHSTy.isNull()) {
6297 LHSTy = LHS.get()->getType();
6298 if (LHSTy->isPromotableIntegerType())
6299 LHSTy = Context.getPromotedIntegerType(LHSTy);
Eli Friedman8e122982008-05-18 18:08:51 +00006300 }
Richard Trieub420bca2011-09-12 18:37:54 +00006301 *CompLHSTy = LHSTy;
Eli Friedman8e122982008-05-18 18:08:51 +00006302 }
6303
Richard Trieub420bca2011-09-12 18:37:54 +00006304 return PExp->getType();
Steve Naroff26c8ea52007-03-21 21:08:52 +00006305}
6306
Chris Lattner2a3569b2008-04-07 05:30:13 +00006307// C99 6.5.6
Richard Trieu4ae7e972011-09-06 21:13:51 +00006308QualType Sema::CheckSubtractionOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006309 SourceLocation Loc,
6310 QualType* CompLHSTy) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006311 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6312
Richard Trieu4ae7e972011-09-06 21:13:51 +00006313 if (LHS.get()->getType()->isVectorType() ||
6314 RHS.get()->getType()->isVectorType()) {
6315 QualType compType = CheckVectorOperands(LHS, RHS, Loc, CompLHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006316 if (CompLHSTy) *CompLHSTy = compType;
6317 return compType;
6318 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006319
Richard Trieu4ae7e972011-09-06 21:13:51 +00006320 QualType compType = UsualArithmeticConversions(LHS, RHS, CompLHSTy);
6321 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006322 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006323
Chris Lattner4d62f422007-12-09 21:53:25 +00006324 // Enforce type constraints: C99 6.5.6p3.
Mike Stump4e1f26a2009-02-19 03:04:26 +00006325
Chris Lattner4d62f422007-12-09 21:53:25 +00006326 // Handle the common case first (both operands are arithmetic).
Eli Friedman93ee5ca2012-06-16 02:19:17 +00006327 if (!compType.isNull() && compType->isArithmeticType()) {
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006328 if (CompLHSTy) *CompLHSTy = compType;
Steve Naroffbe4c4d12007-08-24 19:07:16 +00006329 return compType;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006330 }
Mike Stump11289f42009-09-09 15:08:12 +00006331
Chris Lattner4d62f422007-12-09 21:53:25 +00006332 // Either ptr - int or ptr - ptr.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006333 if (LHS.get()->getType()->isAnyPointerType()) {
6334 QualType lpointee = LHS.get()->getType()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006335
Chris Lattner12bdebb2009-04-24 23:50:08 +00006336 // Diagnose bad cases where we step over interface counts.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006337 if (!checkArithmethicPointerOnNonFragileABI(*this, Loc, LHS.get()))
Chris Lattner12bdebb2009-04-24 23:50:08 +00006338 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00006339
Chris Lattner4d62f422007-12-09 21:53:25 +00006340 // The result type of a pointer-int computation is the pointer type.
Richard Trieu4ae7e972011-09-06 21:13:51 +00006341 if (RHS.get()->getType()->isIntegerType()) {
6342 if (!checkArithmeticOpPointerOperand(*this, Loc, LHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006343 return QualType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006344
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006345 // Check array bounds for pointer arithemtic
Richard Smith13f67182011-12-16 19:31:14 +00006346 CheckArrayAccess(LHS.get(), RHS.get(), /*ArraySubscriptExpr*/0,
6347 /*AllowOnePastEnd*/true, /*IndexNegated*/true);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00006348
Richard Trieu4ae7e972011-09-06 21:13:51 +00006349 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
6350 return LHS.get()->getType();
Douglas Gregorac1fb652009-03-24 19:52:54 +00006351 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006352
Chris Lattner4d62f422007-12-09 21:53:25 +00006353 // Handle pointer-pointer subtractions.
Richard Trieucfc491d2011-08-02 04:35:43 +00006354 if (const PointerType *RHSPTy
Richard Trieu4ae7e972011-09-06 21:13:51 +00006355 = RHS.get()->getType()->getAs<PointerType>()) {
Eli Friedman1974e532008-02-08 01:19:44 +00006356 QualType rpointee = RHSPTy->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006357
David Blaikiebbafb8a2012-03-11 07:00:24 +00006358 if (getLangOpts().CPlusPlus) {
Eli Friedman168fe152009-05-16 13:54:38 +00006359 // Pointee types must be the same: C++ [expr.add]
6360 if (!Context.hasSameUnqualifiedType(lpointee, rpointee)) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006361 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006362 }
6363 } else {
6364 // Pointee types must be compatible C99 6.5.6p3
6365 if (!Context.typesAreCompatible(
6366 Context.getCanonicalType(lpointee).getUnqualifiedType(),
6367 Context.getCanonicalType(rpointee).getUnqualifiedType())) {
Richard Trieu4ae7e972011-09-06 21:13:51 +00006368 diagnosePointerIncompatibility(*this, Loc, LHS.get(), RHS.get());
Eli Friedman168fe152009-05-16 13:54:38 +00006369 return QualType();
6370 }
Chris Lattner4d62f422007-12-09 21:53:25 +00006371 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006372
Chandler Carruthc9332212011-06-27 08:02:19 +00006373 if (!checkArithmeticBinOpPointerOperands(*this, Loc,
Richard Trieu4ae7e972011-09-06 21:13:51 +00006374 LHS.get(), RHS.get()))
Chandler Carruthc9332212011-06-27 08:02:19 +00006375 return QualType();
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006376
Richard Trieu4ae7e972011-09-06 21:13:51 +00006377 if (CompLHSTy) *CompLHSTy = LHS.get()->getType();
Chris Lattner4d62f422007-12-09 21:53:25 +00006378 return Context.getPointerDiffType();
6379 }
6380 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006381
Richard Trieu4ae7e972011-09-06 21:13:51 +00006382 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff218bc2b2007-05-04 21:54:46 +00006383}
6384
Douglas Gregor0bf31402010-10-08 23:50:27 +00006385static bool isScopedEnumerationType(QualType T) {
6386 if (const EnumType *ET = dyn_cast<EnumType>(T))
6387 return ET->getDecl()->isScoped();
6388 return false;
6389}
6390
Richard Trieue4a19fb2011-09-06 21:21:28 +00006391static void DiagnoseBadShiftValues(Sema& S, ExprResult &LHS, ExprResult &RHS,
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006392 SourceLocation Loc, unsigned Opc,
Richard Trieue4a19fb2011-09-06 21:21:28 +00006393 QualType LHSType) {
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006394 llvm::APSInt Right;
6395 // Check right/shifter operand
Richard Trieue4a19fb2011-09-06 21:21:28 +00006396 if (RHS.get()->isValueDependent() ||
6397 !RHS.get()->isIntegerConstantExpr(Right, S.Context))
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006398 return;
6399
6400 if (Right.isNegative()) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006401 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek63657fe2011-03-01 18:09:31 +00006402 S.PDiag(diag::warn_shift_negative)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006403 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006404 return;
6405 }
6406 llvm::APInt LeftBits(Right.getBitWidth(),
Richard Trieue4a19fb2011-09-06 21:21:28 +00006407 S.Context.getTypeSize(LHS.get()->getType()));
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006408 if (Right.uge(LeftBits)) {
Richard Trieue4a19fb2011-09-06 21:21:28 +00006409 S.DiagRuntimeBehavior(Loc, RHS.get(),
Ted Kremenek26bbc3d2011-03-01 19:13:22 +00006410 S.PDiag(diag::warn_shift_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006411 << RHS.get()->getSourceRange());
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006412 return;
6413 }
6414 if (Opc != BO_Shl)
6415 return;
6416
6417 // When left shifting an ICE which is signed, we can check for overflow which
6418 // according to C++ has undefined behavior ([expr.shift] 5.8/2). Unsigned
6419 // integers have defined behavior modulo one more than the maximum value
6420 // representable in the result type, so never warn for those.
6421 llvm::APSInt Left;
Richard Trieue4a19fb2011-09-06 21:21:28 +00006422 if (LHS.get()->isValueDependent() ||
6423 !LHS.get()->isIntegerConstantExpr(Left, S.Context) ||
6424 LHSType->hasUnsignedIntegerRepresentation())
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006425 return;
6426 llvm::APInt ResultBits =
6427 static_cast<llvm::APInt&>(Right) + Left.getMinSignedBits();
6428 if (LeftBits.uge(ResultBits))
6429 return;
6430 llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
6431 Result = Result.shl(Right);
6432
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006433 // Print the bit representation of the signed integer as an unsigned
6434 // hexadecimal number.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00006435 SmallString<40> HexResult;
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006436 Result.toString(HexResult, 16, /*Signed =*/false, /*Literal =*/true);
6437
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006438 // If we are only missing a sign bit, this is less likely to result in actual
6439 // bugs -- if the result is cast back to an unsigned type, it will have the
6440 // expected value. Thus we place this behind a different warning that can be
6441 // turned off separately if needed.
6442 if (LeftBits == ResultBits - 1) {
Ted Kremenek70f05fd2011-06-15 00:54:52 +00006443 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006444 << HexResult.str() << LHSType
6445 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006446 return;
6447 }
6448
6449 S.Diag(Loc, diag::warn_shift_result_gt_typewidth)
Richard Trieue4a19fb2011-09-06 21:21:28 +00006450 << HexResult.str() << Result.getMinSignedBits() << LHSType
6451 << Left.getBitWidth() << LHS.get()->getSourceRange()
6452 << RHS.get()->getSourceRange();
Chandler Carruth4c6fdca2011-02-23 23:34:11 +00006453}
6454
Chris Lattner2a3569b2008-04-07 05:30:13 +00006455// C99 6.5.7
Richard Trieue4a19fb2011-09-06 21:21:28 +00006456QualType Sema::CheckShiftOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006457 SourceLocation Loc, unsigned Opc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006458 bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006459 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
6460
Chris Lattner5c11c412007-12-12 05:47:28 +00006461 // C99 6.5.7p2: Each of the operands shall have integer type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006462 if (!LHS.get()->getType()->hasIntegerRepresentation() ||
6463 !RHS.get()->getType()->hasIntegerRepresentation())
6464 return InvalidOperands(Loc, LHS, RHS);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006465
Douglas Gregor0bf31402010-10-08 23:50:27 +00006466 // C++0x: Don't allow scoped enums. FIXME: Use something better than
6467 // hasIntegerRepresentation() above instead of this.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006468 if (isScopedEnumerationType(LHS.get()->getType()) ||
6469 isScopedEnumerationType(RHS.get()->getType())) {
6470 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor0bf31402010-10-08 23:50:27 +00006471 }
6472
Nate Begemane46ee9a2009-10-25 02:26:48 +00006473 // Vector shifts promote their scalar inputs to vector type.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006474 if (LHS.get()->getType()->isVectorType() ||
6475 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006476 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Nate Begemane46ee9a2009-10-25 02:26:48 +00006477
Chris Lattner5c11c412007-12-12 05:47:28 +00006478 // Shifts don't perform usual arithmetic conversions, they just do integer
6479 // promotions on each operand. C99 6.5.7p3
Eli Friedman8b7b1b12009-03-28 01:22:36 +00006480
John McCall57cdd882010-12-16 19:28:59 +00006481 // For the LHS, do usual unary conversions, but then reset them away
6482 // if this is a compound assignment.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006483 ExprResult OldLHS = LHS;
6484 LHS = UsualUnaryConversions(LHS.take());
6485 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006486 return QualType();
Richard Trieue4a19fb2011-09-06 21:21:28 +00006487 QualType LHSType = LHS.get()->getType();
Richard Trieuba63ce62011-09-09 01:45:06 +00006488 if (IsCompAssign) LHS = OldLHS;
John McCall57cdd882010-12-16 19:28:59 +00006489
6490 // The RHS is simpler.
Richard Trieue4a19fb2011-09-06 21:21:28 +00006491 RHS = UsualUnaryConversions(RHS.take());
6492 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006493 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006494
Ryan Flynnf53fab82009-08-07 16:20:20 +00006495 // Sanity-check shift operands
Richard Trieue4a19fb2011-09-06 21:21:28 +00006496 DiagnoseBadShiftValues(*this, LHS, RHS, Loc, Opc, LHSType);
Ryan Flynnf53fab82009-08-07 16:20:20 +00006497
Chris Lattner5c11c412007-12-12 05:47:28 +00006498 // "The type of the result is that of the promoted left operand."
Richard Trieue4a19fb2011-09-06 21:21:28 +00006499 return LHSType;
Steve Naroff26c8ea52007-03-21 21:08:52 +00006500}
6501
Chandler Carruth17773fc2010-07-10 12:30:03 +00006502static bool IsWithinTemplateSpecialization(Decl *D) {
6503 if (DeclContext *DC = D->getDeclContext()) {
6504 if (isa<ClassTemplateSpecializationDecl>(DC))
6505 return true;
6506 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
6507 return FD->isFunctionTemplateSpecialization();
6508 }
6509 return false;
6510}
6511
Richard Trieueea56f72011-09-02 03:48:46 +00006512/// If two different enums are compared, raise a warning.
Richard Trieu1762d7c2011-09-06 21:27:33 +00006513static void checkEnumComparison(Sema &S, SourceLocation Loc, ExprResult &LHS,
6514 ExprResult &RHS) {
6515 QualType LHSStrippedType = LHS.get()->IgnoreParenImpCasts()->getType();
6516 QualType RHSStrippedType = RHS.get()->IgnoreParenImpCasts()->getType();
Richard Trieueea56f72011-09-02 03:48:46 +00006517
6518 const EnumType *LHSEnumType = LHSStrippedType->getAs<EnumType>();
6519 if (!LHSEnumType)
6520 return;
6521 const EnumType *RHSEnumType = RHSStrippedType->getAs<EnumType>();
6522 if (!RHSEnumType)
6523 return;
6524
6525 // Ignore anonymous enums.
6526 if (!LHSEnumType->getDecl()->getIdentifier())
6527 return;
6528 if (!RHSEnumType->getDecl()->getIdentifier())
6529 return;
6530
6531 if (S.Context.hasSameUnqualifiedType(LHSStrippedType, RHSStrippedType))
6532 return;
6533
6534 S.Diag(Loc, diag::warn_comparison_of_mixed_enum_types)
6535 << LHSStrippedType << RHSStrippedType
Richard Trieu1762d7c2011-09-06 21:27:33 +00006536 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieueea56f72011-09-02 03:48:46 +00006537}
6538
Richard Trieudd82a5c2011-09-02 02:55:45 +00006539/// \brief Diagnose bad pointer comparisons.
6540static void diagnoseDistinctPointerComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006541 ExprResult &LHS, ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006542 bool IsError) {
6543 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_distinct_pointers
Richard Trieudd82a5c2011-09-02 02:55:45 +00006544 : diag::ext_typecheck_comparison_of_distinct_pointers)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006545 << LHS.get()->getType() << RHS.get()->getType()
6546 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006547}
6548
6549/// \brief Returns false if the pointers are converted to a composite type,
6550/// true otherwise.
6551static bool convertPointersToCompositeType(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006552 ExprResult &LHS, ExprResult &RHS) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006553 // C++ [expr.rel]p2:
6554 // [...] Pointer conversions (4.10) and qualification
6555 // conversions (4.4) are performed on pointer operands (or on
6556 // a pointer operand and a null pointer constant) to bring
6557 // them to their composite pointer type. [...]
6558 //
6559 // C++ [expr.eq]p1 uses the same notion for (in)equality
6560 // comparisons of pointers.
6561
6562 // C++ [expr.eq]p2:
6563 // In addition, pointers to members can be compared, or a pointer to
6564 // member and a null pointer constant. Pointer to member conversions
6565 // (4.11) and qualification conversions (4.4) are performed to bring
6566 // them to a common type. If one operand is a null pointer constant,
6567 // the common type is the type of the other operand. Otherwise, the
6568 // common type is a pointer to member type similar (4.4) to the type
6569 // of one of the operands, with a cv-qualification signature (4.4)
6570 // that is the union of the cv-qualification signatures of the operand
6571 // types.
6572
Richard Trieu1762d7c2011-09-06 21:27:33 +00006573 QualType LHSType = LHS.get()->getType();
6574 QualType RHSType = RHS.get()->getType();
6575 assert((LHSType->isPointerType() && RHSType->isPointerType()) ||
6576 (LHSType->isMemberPointerType() && RHSType->isMemberPointerType()));
Richard Trieudd82a5c2011-09-02 02:55:45 +00006577
6578 bool NonStandardCompositeType = false;
Richard Trieu48277e52011-09-02 21:44:27 +00006579 bool *BoolPtr = S.isSFINAEContext() ? 0 : &NonStandardCompositeType;
Richard Trieu1762d7c2011-09-06 21:27:33 +00006580 QualType T = S.FindCompositePointerType(Loc, LHS, RHS, BoolPtr);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006581 if (T.isNull()) {
Richard Trieu1762d7c2011-09-06 21:27:33 +00006582 diagnoseDistinctPointerComparison(S, Loc, LHS, RHS, /*isError*/true);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006583 return true;
6584 }
6585
6586 if (NonStandardCompositeType)
6587 S.Diag(Loc, diag::ext_typecheck_comparison_of_distinct_pointers_nonstandard)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006588 << LHSType << RHSType << T << LHS.get()->getSourceRange()
6589 << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006590
Richard Trieu1762d7c2011-09-06 21:27:33 +00006591 LHS = S.ImpCastExprToType(LHS.take(), T, CK_BitCast);
6592 RHS = S.ImpCastExprToType(RHS.take(), T, CK_BitCast);
Richard Trieudd82a5c2011-09-02 02:55:45 +00006593 return false;
6594}
6595
6596static void diagnoseFunctionPointerToVoidComparison(Sema &S, SourceLocation Loc,
Richard Trieu1762d7c2011-09-06 21:27:33 +00006597 ExprResult &LHS,
6598 ExprResult &RHS,
Richard Trieuba63ce62011-09-09 01:45:06 +00006599 bool IsError) {
6600 S.Diag(Loc, IsError ? diag::err_typecheck_comparison_of_fptr_to_void
6601 : diag::ext_typecheck_comparison_of_fptr_to_void)
Richard Trieu1762d7c2011-09-06 21:27:33 +00006602 << LHS.get()->getType() << RHS.get()->getType()
6603 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006604}
6605
Jordan Rosed49a33e2012-06-08 21:14:25 +00006606static bool isObjCObjectLiteral(ExprResult &E) {
6607 switch (E.get()->getStmtClass()) {
6608 case Stmt::ObjCArrayLiteralClass:
6609 case Stmt::ObjCDictionaryLiteralClass:
6610 case Stmt::ObjCStringLiteralClass:
6611 case Stmt::ObjCBoxedExprClass:
6612 return true;
6613 default:
6614 // Note that ObjCBoolLiteral is NOT an object literal!
6615 return false;
6616 }
6617}
6618
6619static DiagnosticBuilder diagnoseObjCLiteralComparison(Sema &S,
6620 SourceLocation Loc,
6621 ExprResult &LHS,
6622 ExprResult &RHS,
6623 bool CanFix = false) {
6624 Expr *Literal = (isObjCObjectLiteral(LHS) ? LHS : RHS).get();
6625
6626 unsigned LiteralKind;
6627 switch (Literal->getStmtClass()) {
6628 case Stmt::ObjCStringLiteralClass:
6629 // "string literal"
6630 LiteralKind = 0;
6631 break;
6632 case Stmt::ObjCArrayLiteralClass:
6633 // "array literal"
6634 LiteralKind = 1;
6635 break;
6636 case Stmt::ObjCDictionaryLiteralClass:
6637 // "dictionary literal"
6638 LiteralKind = 2;
6639 break;
6640 case Stmt::ObjCBoxedExprClass: {
6641 Expr *Inner = cast<ObjCBoxedExpr>(Literal)->getSubExpr();
6642 switch (Inner->getStmtClass()) {
6643 case Stmt::IntegerLiteralClass:
6644 case Stmt::FloatingLiteralClass:
6645 case Stmt::CharacterLiteralClass:
6646 case Stmt::ObjCBoolLiteralExprClass:
6647 case Stmt::CXXBoolLiteralExprClass:
6648 // "numeric literal"
6649 LiteralKind = 3;
6650 break;
6651 case Stmt::ImplicitCastExprClass: {
6652 CastKind CK = cast<CastExpr>(Inner)->getCastKind();
6653 // Boolean literals can be represented by implicit casts.
6654 if (CK == CK_IntegralToBoolean || CK == CK_IntegralCast) {
6655 LiteralKind = 3;
6656 break;
6657 }
6658 // FALLTHROUGH
6659 }
6660 default:
6661 // "boxed expression"
6662 LiteralKind = 4;
6663 break;
6664 }
6665 break;
6666 }
6667 default:
6668 llvm_unreachable("Unknown Objective-C object literal kind");
6669 }
6670
6671 return S.Diag(Loc, diag::err_objc_literal_comparison)
6672 << LiteralKind << CanFix << Literal->getSourceRange();
6673}
6674
6675static ExprResult fixObjCLiteralComparison(Sema &S, SourceLocation OpLoc,
6676 ExprResult &LHS,
6677 ExprResult &RHS,
6678 BinaryOperatorKind Op) {
6679 assert((Op == BO_EQ || Op == BO_NE) && "Cannot fix other operations.");
6680
6681 // Get the LHS object's interface type.
6682 QualType Type = LHS.get()->getType();
6683 QualType InterfaceType;
6684 if (const ObjCObjectPointerType *PTy = Type->getAs<ObjCObjectPointerType>()) {
6685 InterfaceType = PTy->getPointeeType();
6686 if (const ObjCObjectType *iQFaceTy =
6687 InterfaceType->getAsObjCQualifiedInterfaceType())
6688 InterfaceType = iQFaceTy->getBaseType();
6689 } else {
6690 // If this is not actually an Objective-C object, bail out.
6691 return ExprEmpty();
6692 }
6693
6694 // If the RHS isn't an Objective-C object, bail out.
6695 if (!RHS.get()->getType()->isObjCObjectPointerType())
6696 return ExprEmpty();
6697
6698 // Try to find the -isEqual: method.
6699 Selector IsEqualSel = S.NSAPIObj->getIsEqualSelector();
6700 ObjCMethodDecl *Method = S.LookupMethodInObjectType(IsEqualSel,
6701 InterfaceType,
6702 /*instance=*/true);
6703 bool ReceiverIsId = (Type->isObjCIdType() || Type->isObjCQualifiedIdType());
6704
6705 if (!Method && ReceiverIsId) {
6706 Method = S.LookupInstanceMethodInGlobalPool(IsEqualSel, SourceRange(),
6707 /*receiverId=*/true,
6708 /*warn=*/false);
6709 }
6710
6711 if (!Method)
6712 return ExprEmpty();
6713
6714 QualType T = Method->param_begin()[0]->getType();
6715 if (!T->isObjCObjectPointerType())
6716 return ExprEmpty();
6717
6718 QualType R = Method->getResultType();
6719 if (!R->isScalarType())
6720 return ExprEmpty();
6721
6722 // At this point we know we have a good -isEqual: method.
6723 // Emit the diagnostic and fixit.
6724 DiagnosticBuilder Diag = diagnoseObjCLiteralComparison(S, OpLoc,
6725 LHS, RHS, true);
6726
6727 Expr *LHSExpr = LHS.take();
6728 Expr *RHSExpr = RHS.take();
6729
6730 SourceLocation Start = LHSExpr->getLocStart();
6731 SourceLocation End = S.PP.getLocForEndOfToken(RHSExpr->getLocEnd());
6732 SourceRange OpRange(OpLoc, S.PP.getLocForEndOfToken(OpLoc));
6733
6734 Diag << FixItHint::CreateInsertion(Start, Op == BO_EQ ? "[" : "![")
6735 << FixItHint::CreateReplacement(OpRange, "isEqual:")
6736 << FixItHint::CreateInsertion(End, "]");
6737
6738 // Finally, build the call to -isEqual: (and possible logical not).
6739 ExprResult Call = S.BuildInstanceMessage(LHSExpr, LHSExpr->getType(),
6740 /*SuperLoc=*/SourceLocation(),
6741 IsEqualSel, Method,
6742 OpLoc, OpLoc, OpLoc,
6743 MultiExprArg(S, &RHSExpr, 1),
6744 /*isImplicit=*/false);
6745
6746 ExprResult CallCond = S.CheckBooleanCondition(Call.get(), OpLoc);
6747
6748 if (Op == BO_NE)
6749 return S.CreateBuiltinUnaryOp(OpLoc, UO_LNot, CallCond.get());
6750 return CallCond;
6751}
6752
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006753// C99 6.5.8, C++ [expr.rel]
Richard Trieub80728f2011-09-06 21:43:51 +00006754QualType Sema::CheckCompareOperands(ExprResult &LHS, ExprResult &RHS,
Richard Trieucfc491d2011-08-02 04:35:43 +00006755 SourceLocation Loc, unsigned OpaqueOpc,
Richard Trieuba63ce62011-09-09 01:45:06 +00006756 bool IsRelational) {
Richard Trieuf8916e12011-09-16 00:53:10 +00006757 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/true);
6758
John McCalle3027922010-08-25 11:45:40 +00006759 BinaryOperatorKind Opc = (BinaryOperatorKind) OpaqueOpc;
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006760
Chris Lattner9a152e22009-12-05 05:40:13 +00006761 // Handle vector comparisons separately.
Richard Trieub80728f2011-09-06 21:43:51 +00006762 if (LHS.get()->getType()->isVectorType() ||
6763 RHS.get()->getType()->isVectorType())
Richard Trieuba63ce62011-09-09 01:45:06 +00006764 return CheckVectorCompareOperands(LHS, RHS, Loc, IsRelational);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006765
Richard Trieub80728f2011-09-06 21:43:51 +00006766 QualType LHSType = LHS.get()->getType();
6767 QualType RHSType = RHS.get()->getType();
Benjamin Kramera66aaa92011-09-03 08:46:20 +00006768
Richard Trieub80728f2011-09-06 21:43:51 +00006769 Expr *LHSStripped = LHS.get()->IgnoreParenImpCasts();
6770 Expr *RHSStripped = RHS.get()->IgnoreParenImpCasts();
Chandler Carruth712563b2011-02-17 08:37:06 +00006771
Richard Trieub80728f2011-09-06 21:43:51 +00006772 checkEnumComparison(*this, Loc, LHS, RHS);
Chandler Carruth712563b2011-02-17 08:37:06 +00006773
Richard Trieub80728f2011-09-06 21:43:51 +00006774 if (!LHSType->hasFloatingRepresentation() &&
Richard Trieuba63ce62011-09-09 01:45:06 +00006775 !(LHSType->isBlockPointerType() && IsRelational) &&
Richard Trieub80728f2011-09-06 21:43:51 +00006776 !LHS.get()->getLocStart().isMacroID() &&
6777 !RHS.get()->getLocStart().isMacroID()) {
Chris Lattner222b8bd2009-03-08 19:39:53 +00006778 // For non-floating point types, check for self-comparisons of the form
6779 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
6780 // often indicate logic errors in the program.
Chandler Carruth65a38182010-07-12 06:23:38 +00006781 //
6782 // NOTE: Don't warn about comparison expressions resulting from macro
6783 // expansion. Also don't warn about comparisons which are only self
6784 // comparisons within a template specialization. The warnings should catch
6785 // obvious cases in the definition of the template anyways. The idea is to
6786 // warn when the typed comparison operator will always evaluate to the same
6787 // result.
Chandler Carruth17773fc2010-07-10 12:30:03 +00006788 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LHSStripped)) {
Douglas Gregorec170db2010-06-08 19:50:34 +00006789 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RHSStripped)) {
Ted Kremenek853734e2010-09-16 00:03:01 +00006790 if (DRL->getDecl() == DRR->getDecl() &&
Chandler Carruth17773fc2010-07-10 12:30:03 +00006791 !IsWithinTemplateSpecialization(DRL->getDecl())) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00006792 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006793 << 0 // self-
John McCalle3027922010-08-25 11:45:40 +00006794 << (Opc == BO_EQ
6795 || Opc == BO_LE
6796 || Opc == BO_GE));
Richard Trieub80728f2011-09-06 21:43:51 +00006797 } else if (LHSType->isArrayType() && RHSType->isArrayType() &&
Douglas Gregorec170db2010-06-08 19:50:34 +00006798 !DRL->getDecl()->getType()->isReferenceType() &&
6799 !DRR->getDecl()->getType()->isReferenceType()) {
6800 // what is it always going to eval to?
6801 char always_evals_to;
6802 switch(Opc) {
John McCalle3027922010-08-25 11:45:40 +00006803 case BO_EQ: // e.g. array1 == array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006804 always_evals_to = 0; // false
6805 break;
John McCalle3027922010-08-25 11:45:40 +00006806 case BO_NE: // e.g. array1 != array2
Douglas Gregorec170db2010-06-08 19:50:34 +00006807 always_evals_to = 1; // true
6808 break;
6809 default:
6810 // best we can say is 'a constant'
6811 always_evals_to = 2; // e.g. array1 <= array2
6812 break;
6813 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00006814 DiagRuntimeBehavior(Loc, 0, PDiag(diag::warn_comparison_always)
Douglas Gregorec170db2010-06-08 19:50:34 +00006815 << 1 // array
6816 << always_evals_to);
6817 }
6818 }
Chandler Carruth17773fc2010-07-10 12:30:03 +00006819 }
Mike Stump11289f42009-09-09 15:08:12 +00006820
Chris Lattner222b8bd2009-03-08 19:39:53 +00006821 if (isa<CastExpr>(LHSStripped))
6822 LHSStripped = LHSStripped->IgnoreParenCasts();
6823 if (isa<CastExpr>(RHSStripped))
6824 RHSStripped = RHSStripped->IgnoreParenCasts();
Mike Stump11289f42009-09-09 15:08:12 +00006825
Chris Lattner222b8bd2009-03-08 19:39:53 +00006826 // Warn about comparisons against a string constant (unless the other
6827 // operand is null), the user probably wants strcmp.
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006828 Expr *literalString = 0;
6829 Expr *literalStringStripped = 0;
Chris Lattner222b8bd2009-03-08 19:39:53 +00006830 if ((isa<StringLiteral>(LHSStripped) || isa<ObjCEncodeExpr>(LHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006831 !RHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006832 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006833 literalString = LHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006834 literalStringStripped = LHSStripped;
Mike Stump12b8ce12009-08-04 21:02:39 +00006835 } else if ((isa<StringLiteral>(RHSStripped) ||
6836 isa<ObjCEncodeExpr>(RHSStripped)) &&
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006837 !LHSStripped->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006838 Expr::NPC_ValueDependentIsNull)) {
Richard Trieub80728f2011-09-06 21:43:51 +00006839 literalString = RHS.get();
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006840 literalStringStripped = RHSStripped;
6841 }
6842
6843 if (literalString) {
6844 std::string resultComparison;
6845 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00006846 case BO_LT: resultComparison = ") < 0"; break;
6847 case BO_GT: resultComparison = ") > 0"; break;
6848 case BO_LE: resultComparison = ") <= 0"; break;
6849 case BO_GE: resultComparison = ") >= 0"; break;
6850 case BO_EQ: resultComparison = ") == 0"; break;
6851 case BO_NE: resultComparison = ") != 0"; break;
David Blaikie83d382b2011-09-23 05:06:16 +00006852 default: llvm_unreachable("Invalid comparison operator");
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006853 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00006854
Ted Kremenek3427fac2011-02-23 01:52:04 +00006855 DiagRuntimeBehavior(Loc, 0,
Douglas Gregor49862b82010-01-12 23:18:54 +00006856 PDiag(diag::warn_stringcompare)
6857 << isa<ObjCEncodeExpr>(literalStringStripped)
Ted Kremenek800b66b2010-04-09 20:26:53 +00006858 << literalString->getSourceRange());
Douglas Gregor7a5bc762009-04-06 18:45:53 +00006859 }
Ted Kremeneke451eae2007-10-29 16:58:49 +00006860 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006861
Douglas Gregorec170db2010-06-08 19:50:34 +00006862 // C99 6.5.8p3 / C99 6.5.9p4
Richard Trieub80728f2011-09-06 21:43:51 +00006863 if (LHS.get()->getType()->isArithmeticType() &&
6864 RHS.get()->getType()->isArithmeticType()) {
6865 UsualArithmeticConversions(LHS, RHS);
6866 if (LHS.isInvalid() || RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006867 return QualType();
6868 }
Douglas Gregorec170db2010-06-08 19:50:34 +00006869 else {
Richard Trieub80728f2011-09-06 21:43:51 +00006870 LHS = UsualUnaryConversions(LHS.take());
6871 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006872 return QualType();
6873
Richard Trieub80728f2011-09-06 21:43:51 +00006874 RHS = UsualUnaryConversions(RHS.take());
6875 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00006876 return QualType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006877 }
6878
Richard Trieub80728f2011-09-06 21:43:51 +00006879 LHSType = LHS.get()->getType();
6880 RHSType = RHS.get()->getType();
Douglas Gregorec170db2010-06-08 19:50:34 +00006881
Douglas Gregorca63811b2008-11-19 03:25:36 +00006882 // The result of comparisons is 'bool' in C++, 'int' in C.
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00006883 QualType ResultTy = Context.getLogicalOperationType();
Douglas Gregorca63811b2008-11-19 03:25:36 +00006884
Richard Trieuba63ce62011-09-09 01:45:06 +00006885 if (IsRelational) {
Richard Trieub80728f2011-09-06 21:43:51 +00006886 if (LHSType->isRealType() && RHSType->isRealType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006887 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006888 } else {
Ted Kremeneke2763b02007-10-29 17:13:39 +00006889 // Check for comparisons of floating point operands using != and ==.
Richard Trieub80728f2011-09-06 21:43:51 +00006890 if (LHSType->hasFloatingRepresentation())
6891 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Mike Stump4e1f26a2009-02-19 03:04:26 +00006892
Richard Trieub80728f2011-09-06 21:43:51 +00006893 if (LHSType->isArithmeticType() && RHSType->isArithmeticType())
Douglas Gregorca63811b2008-11-19 03:25:36 +00006894 return ResultTy;
Chris Lattnerb620c342007-08-26 01:18:55 +00006895 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00006896
Richard Trieub80728f2011-09-06 21:43:51 +00006897 bool LHSIsNull = LHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006898 Expr::NPC_ValueDependentIsNull);
Richard Trieub80728f2011-09-06 21:43:51 +00006899 bool RHSIsNull = RHS.get()->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00006900 Expr::NPC_ValueDependentIsNull);
Mike Stump4e1f26a2009-02-19 03:04:26 +00006901
Douglas Gregorf267edd2010-06-15 21:38:40 +00006902 // All of the following pointer-related warnings are GCC extensions, except
6903 // when handling null pointer constants.
Richard Trieub80728f2011-09-06 21:43:51 +00006904 if (LHSType->isPointerType() && RHSType->isPointerType()) { // C99 6.5.8p2
Chris Lattner3a0702e2008-04-03 05:07:25 +00006905 QualType LCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006906 LHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Chris Lattner3a0702e2008-04-03 05:07:25 +00006907 QualType RCanPointeeTy =
John McCall9320b872011-09-09 05:25:32 +00006908 RHSType->castAs<PointerType>()->getPointeeType().getCanonicalType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00006909
David Blaikiebbafb8a2012-03-11 07:00:24 +00006910 if (getLangOpts().CPlusPlus) {
Eli Friedman16c209612009-08-23 00:27:47 +00006911 if (LCanPointeeTy == RCanPointeeTy)
6912 return ResultTy;
Richard Trieuba63ce62011-09-09 01:45:06 +00006913 if (!IsRelational &&
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006914 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6915 // Valid unless comparison between non-null pointer and function pointer
6916 // This is a gcc extension compatibility comparison.
Douglas Gregorf267edd2010-06-15 21:38:40 +00006917 // In a SFINAE context, we treat this as a hard error to maintain
6918 // conformance with the C++ standard.
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006919 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
6920 && !LHSIsNull && !RHSIsNull) {
Richard Trieudd82a5c2011-09-02 02:55:45 +00006921 diagnoseFunctionPointerToVoidComparison(
Richard Trieub80728f2011-09-06 21:43:51 +00006922 *this, Loc, LHS, RHS, /*isError*/ isSFINAEContext());
Douglas Gregorf267edd2010-06-15 21:38:40 +00006923
6924 if (isSFINAEContext())
6925 return QualType();
6926
Richard Trieub80728f2011-09-06 21:43:51 +00006927 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Fariborz Jahanianffc420c2009-12-21 18:19:17 +00006928 return ResultTy;
6929 }
6930 }
Anders Carlssona95069c2010-11-04 03:17:43 +00006931
Richard Trieub80728f2011-09-06 21:43:51 +00006932 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006933 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006934 else
6935 return ResultTy;
Douglas Gregor5b07c7e2009-05-04 06:07:12 +00006936 }
Eli Friedman16c209612009-08-23 00:27:47 +00006937 // C99 6.5.9p2 and C99 6.5.8p2
6938 if (Context.typesAreCompatible(LCanPointeeTy.getUnqualifiedType(),
6939 RCanPointeeTy.getUnqualifiedType())) {
6940 // Valid unless a relational comparison of function pointers
Richard Trieuba63ce62011-09-09 01:45:06 +00006941 if (IsRelational && LCanPointeeTy->isFunctionType()) {
Eli Friedman16c209612009-08-23 00:27:47 +00006942 Diag(Loc, diag::ext_typecheck_ordered_comparison_of_function_pointers)
Richard Trieub80728f2011-09-06 21:43:51 +00006943 << LHSType << RHSType << LHS.get()->getSourceRange()
6944 << RHS.get()->getSourceRange();
Eli Friedman16c209612009-08-23 00:27:47 +00006945 }
Richard Trieuba63ce62011-09-09 01:45:06 +00006946 } else if (!IsRelational &&
Eli Friedman16c209612009-08-23 00:27:47 +00006947 (LCanPointeeTy->isVoidType() || RCanPointeeTy->isVoidType())) {
6948 // Valid unless comparison between non-null pointer and function pointer
6949 if ((LCanPointeeTy->isFunctionType() || RCanPointeeTy->isFunctionType())
Richard Trieudd82a5c2011-09-02 02:55:45 +00006950 && !LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006951 diagnoseFunctionPointerToVoidComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00006952 /*isError*/false);
Eli Friedman16c209612009-08-23 00:27:47 +00006953 } else {
6954 // Invalid
Richard Trieub80728f2011-09-06 21:43:51 +00006955 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS, /*isError*/false);
Steve Naroff75c17232007-06-13 21:41:08 +00006956 }
John McCall7684dde2011-03-11 04:25:25 +00006957 if (LCanPointeeTy != RCanPointeeTy) {
6958 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00006959 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006960 else
Richard Trieub80728f2011-09-06 21:43:51 +00006961 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00006962 }
Douglas Gregorca63811b2008-11-19 03:25:36 +00006963 return ResultTy;
Steve Naroffcdee44c2007-08-16 21:48:38 +00006964 }
Mike Stump11289f42009-09-09 15:08:12 +00006965
David Blaikiebbafb8a2012-03-11 07:00:24 +00006966 if (getLangOpts().CPlusPlus) {
Anders Carlssona95069c2010-11-04 03:17:43 +00006967 // Comparison of nullptr_t with itself.
Richard Trieub80728f2011-09-06 21:43:51 +00006968 if (LHSType->isNullPtrType() && RHSType->isNullPtrType())
Anders Carlssona95069c2010-11-04 03:17:43 +00006969 return ResultTy;
6970
Mike Stump11289f42009-09-09 15:08:12 +00006971 // Comparison of pointers with null pointer constants and equality
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006972 // comparisons of member pointers to null pointer constants.
Mike Stump11289f42009-09-09 15:08:12 +00006973 if (RHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006974 ((LHSType->isAnyPointerType() || LHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006975 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006976 (LHSType->isMemberPointerType() || LHSType->isBlockPointerType())))) {
6977 RHS = ImpCastExprToType(RHS.take(), LHSType,
6978 LHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006979 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006980 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006981 return ResultTy;
6982 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006983 if (LHSIsNull &&
Richard Trieub80728f2011-09-06 21:43:51 +00006984 ((RHSType->isAnyPointerType() || RHSType->isNullPtrType()) ||
Richard Trieuba63ce62011-09-09 01:45:06 +00006985 (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006986 (RHSType->isMemberPointerType() || RHSType->isBlockPointerType())))) {
6987 LHS = ImpCastExprToType(LHS.take(), RHSType,
6988 RHSType->isMemberPointerType()
John McCalle3027922010-08-25 11:45:40 +00006989 ? CK_NullToMemberPointer
John McCalle84af4e2010-11-13 01:35:44 +00006990 : CK_NullToPointer);
Sebastian Redl576fd422009-05-10 18:38:11 +00006991 return ResultTy;
6992 }
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006993
6994 // Comparison of member pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00006995 if (!IsRelational &&
Richard Trieub80728f2011-09-06 21:43:51 +00006996 LHSType->isMemberPointerType() && RHSType->isMemberPointerType()) {
6997 if (convertPointersToCompositeType(*this, Loc, LHS, RHS))
Douglas Gregorb00b10e2009-08-24 17:42:35 +00006998 return QualType();
Richard Trieudd82a5c2011-09-02 02:55:45 +00006999 else
7000 return ResultTy;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00007001 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007002
7003 // Handle scoped enumeration types specifically, since they don't promote
7004 // to integers.
Richard Trieub80728f2011-09-06 21:43:51 +00007005 if (LHS.get()->getType()->isEnumeralType() &&
7006 Context.hasSameUnqualifiedType(LHS.get()->getType(),
7007 RHS.get()->getType()))
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007008 return ResultTy;
Sebastian Redl576fd422009-05-10 18:38:11 +00007009 }
Mike Stump11289f42009-09-09 15:08:12 +00007010
Steve Naroff081c7422008-09-04 15:10:53 +00007011 // Handle block pointer types.
Richard Trieuba63ce62011-09-09 01:45:06 +00007012 if (!IsRelational && LHSType->isBlockPointerType() &&
Richard Trieub80728f2011-09-06 21:43:51 +00007013 RHSType->isBlockPointerType()) {
John McCall9320b872011-09-09 05:25:32 +00007014 QualType lpointee = LHSType->castAs<BlockPointerType>()->getPointeeType();
7015 QualType rpointee = RHSType->castAs<BlockPointerType>()->getPointeeType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007016
Steve Naroff081c7422008-09-04 15:10:53 +00007017 if (!LHSIsNull && !RHSIsNull &&
Eli Friedmana6638ca2009-06-08 05:08:54 +00007018 !Context.typesAreCompatible(lpointee, rpointee)) {
Chris Lattner377d1f82008-11-18 22:52:51 +00007019 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007020 << LHSType << RHSType << LHS.get()->getSourceRange()
7021 << RHS.get()->getSourceRange();
Steve Naroff081c7422008-09-04 15:10:53 +00007022 }
Richard Trieub80728f2011-09-06 21:43:51 +00007023 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007024 return ResultTy;
Steve Naroff081c7422008-09-04 15:10:53 +00007025 }
John Wiegley01296292011-04-08 18:41:53 +00007026
Steve Naroffe18f94c2008-09-28 01:11:11 +00007027 // Allow block pointers to be compared with null pointer constants.
Richard Trieuba63ce62011-09-09 01:45:06 +00007028 if (!IsRelational
Richard Trieub80728f2011-09-06 21:43:51 +00007029 && ((LHSType->isBlockPointerType() && RHSType->isPointerType())
7030 || (LHSType->isPointerType() && RHSType->isBlockPointerType()))) {
Steve Naroffe18f94c2008-09-28 01:11:11 +00007031 if (!LHSIsNull && !RHSIsNull) {
Richard Trieub80728f2011-09-06 21:43:51 +00007032 if (!((RHSType->isPointerType() && RHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007033 ->getPointeeType()->isVoidType())
Richard Trieub80728f2011-09-06 21:43:51 +00007034 || (LHSType->isPointerType() && LHSType->castAs<PointerType>()
Mike Stump1b821b42009-05-07 03:14:14 +00007035 ->getPointeeType()->isVoidType())))
7036 Diag(Loc, diag::err_typecheck_comparison_of_distinct_blocks)
Richard Trieub80728f2011-09-06 21:43:51 +00007037 << LHSType << RHSType << LHS.get()->getSourceRange()
7038 << RHS.get()->getSourceRange();
Steve Naroffe18f94c2008-09-28 01:11:11 +00007039 }
John McCall7684dde2011-03-11 04:25:25 +00007040 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007041 LHS = ImpCastExprToType(LHS.take(), RHSType,
7042 RHSType->isPointerType() ? CK_BitCast
7043 : CK_AnyPointerToBlockPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007044 else
John McCall9320b872011-09-09 05:25:32 +00007045 RHS = ImpCastExprToType(RHS.take(), LHSType,
7046 LHSType->isPointerType() ? CK_BitCast
7047 : CK_AnyPointerToBlockPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007048 return ResultTy;
Steve Naroffe18f94c2008-09-28 01:11:11 +00007049 }
Steve Naroff081c7422008-09-04 15:10:53 +00007050
Richard Trieub80728f2011-09-06 21:43:51 +00007051 if (LHSType->isObjCObjectPointerType() ||
7052 RHSType->isObjCObjectPointerType()) {
7053 const PointerType *LPT = LHSType->getAs<PointerType>();
7054 const PointerType *RPT = RHSType->getAs<PointerType>();
John McCall7684dde2011-03-11 04:25:25 +00007055 if (LPT || RPT) {
7056 bool LPtrToVoid = LPT ? LPT->getPointeeType()->isVoidType() : false;
7057 bool RPtrToVoid = RPT ? RPT->getPointeeType()->isVoidType() : false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007058
Steve Naroff753567f2008-11-17 19:49:16 +00007059 if (!LPtrToVoid && !RPtrToVoid &&
Richard Trieub80728f2011-09-06 21:43:51 +00007060 !Context.typesAreCompatible(LHSType, RHSType)) {
7061 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007062 /*isError*/false);
Steve Naroff1d4a9a32008-10-27 10:33:19 +00007063 }
John McCall7684dde2011-03-11 04:25:25 +00007064 if (LHSIsNull && !RHSIsNull)
John McCall9320b872011-09-09 05:25:32 +00007065 LHS = ImpCastExprToType(LHS.take(), RHSType,
7066 RPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
John McCall7684dde2011-03-11 04:25:25 +00007067 else
John McCall9320b872011-09-09 05:25:32 +00007068 RHS = ImpCastExprToType(RHS.take(), LHSType,
7069 LPT ? CK_BitCast :CK_CPointerToObjCPointerCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007070 return ResultTy;
Steve Naroffea54d9e2008-10-20 18:19:10 +00007071 }
Richard Trieub80728f2011-09-06 21:43:51 +00007072 if (LHSType->isObjCObjectPointerType() &&
7073 RHSType->isObjCObjectPointerType()) {
7074 if (!Context.areComparableObjCPointerTypes(LHSType, RHSType))
7075 diagnoseDistinctPointerComparison(*this, Loc, LHS, RHS,
Richard Trieudd82a5c2011-09-02 02:55:45 +00007076 /*isError*/false);
Jordan Rosed49a33e2012-06-08 21:14:25 +00007077 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS))
7078 diagnoseObjCLiteralComparison(*this, Loc, LHS, RHS);
7079
John McCall7684dde2011-03-11 04:25:25 +00007080 if (LHSIsNull && !RHSIsNull)
Richard Trieub80728f2011-09-06 21:43:51 +00007081 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_BitCast);
John McCall7684dde2011-03-11 04:25:25 +00007082 else
Richard Trieub80728f2011-09-06 21:43:51 +00007083 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_BitCast);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007084 return ResultTy;
Steve Naroffb788d9b2008-06-03 14:04:54 +00007085 }
Fariborz Jahanian134cbef2007-12-20 01:06:58 +00007086 }
Richard Trieub80728f2011-09-06 21:43:51 +00007087 if ((LHSType->isAnyPointerType() && RHSType->isIntegerType()) ||
7088 (LHSType->isIntegerType() && RHSType->isAnyPointerType())) {
Chris Lattnerd99bd522009-08-23 00:03:44 +00007089 unsigned DiagID = 0;
Douglas Gregorf267edd2010-06-15 21:38:40 +00007090 bool isError = false;
Richard Trieub80728f2011-09-06 21:43:51 +00007091 if ((LHSIsNull && LHSType->isIntegerType()) ||
7092 (RHSIsNull && RHSType->isIntegerType())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00007093 if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007094 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_and_zero;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007095 } else if (IsRelational && !getLangOpts().CPlusPlus)
Chris Lattnerd99bd522009-08-23 00:03:44 +00007096 DiagID = diag::ext_typecheck_ordered_comparison_of_pointer_integer;
David Blaikiebbafb8a2012-03-11 07:00:24 +00007097 else if (getLangOpts().CPlusPlus) {
Douglas Gregorf267edd2010-06-15 21:38:40 +00007098 DiagID = diag::err_typecheck_comparison_of_pointer_integer;
7099 isError = true;
7100 } else
Chris Lattnerd99bd522009-08-23 00:03:44 +00007101 DiagID = diag::ext_typecheck_comparison_of_pointer_integer;
Mike Stump11289f42009-09-09 15:08:12 +00007102
Chris Lattnerd99bd522009-08-23 00:03:44 +00007103 if (DiagID) {
Chris Lattnerf8344db2009-08-22 18:58:31 +00007104 Diag(Loc, DiagID)
Richard Trieub80728f2011-09-06 21:43:51 +00007105 << LHSType << RHSType << LHS.get()->getSourceRange()
7106 << RHS.get()->getSourceRange();
Douglas Gregorf267edd2010-06-15 21:38:40 +00007107 if (isError)
7108 return QualType();
Chris Lattnerf8344db2009-08-22 18:58:31 +00007109 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007110
Richard Trieub80728f2011-09-06 21:43:51 +00007111 if (LHSType->isIntegerType())
7112 LHS = ImpCastExprToType(LHS.take(), RHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007113 LHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Chris Lattnerd99bd522009-08-23 00:03:44 +00007114 else
Richard Trieub80728f2011-09-06 21:43:51 +00007115 RHS = ImpCastExprToType(RHS.take(), LHSType,
John McCalle84af4e2010-11-13 01:35:44 +00007116 RHSIsNull ? CK_NullToPointer : CK_IntegralToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007117 return ResultTy;
Steve Naroff043d45d2007-05-15 02:32:35 +00007118 }
Douglas Gregorf267edd2010-06-15 21:38:40 +00007119
Steve Naroff4b191572008-09-04 16:56:14 +00007120 // Handle block pointers.
Richard Trieuba63ce62011-09-09 01:45:06 +00007121 if (!IsRelational && RHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007122 && LHSType->isBlockPointerType() && RHSType->isIntegerType()) {
7123 RHS = ImpCastExprToType(RHS.take(), LHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007124 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007125 }
Richard Trieuba63ce62011-09-09 01:45:06 +00007126 if (!IsRelational && LHSIsNull
Richard Trieub80728f2011-09-06 21:43:51 +00007127 && LHSType->isIntegerType() && RHSType->isBlockPointerType()) {
7128 LHS = ImpCastExprToType(LHS.take(), RHSType, CK_NullToPointer);
Douglas Gregorca63811b2008-11-19 03:25:36 +00007129 return ResultTy;
Steve Naroff4b191572008-09-04 16:56:14 +00007130 }
Douglas Gregor48e6bbf2011-03-01 17:16:20 +00007131
Richard Trieub80728f2011-09-06 21:43:51 +00007132 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007133}
7134
Tanya Lattner20248222012-01-16 21:02:28 +00007135
7136// Return a signed type that is of identical size and number of elements.
7137// For floating point vectors, return an integer type of identical size
7138// and number of elements.
7139QualType Sema::GetSignedVectorType(QualType V) {
7140 const VectorType *VTy = V->getAs<VectorType>();
7141 unsigned TypeSize = Context.getTypeSize(VTy->getElementType());
7142 if (TypeSize == Context.getTypeSize(Context.CharTy))
7143 return Context.getExtVectorType(Context.CharTy, VTy->getNumElements());
7144 else if (TypeSize == Context.getTypeSize(Context.ShortTy))
7145 return Context.getExtVectorType(Context.ShortTy, VTy->getNumElements());
7146 else if (TypeSize == Context.getTypeSize(Context.IntTy))
7147 return Context.getExtVectorType(Context.IntTy, VTy->getNumElements());
7148 else if (TypeSize == Context.getTypeSize(Context.LongTy))
7149 return Context.getExtVectorType(Context.LongTy, VTy->getNumElements());
7150 assert(TypeSize == Context.getTypeSize(Context.LongLongTy) &&
7151 "Unhandled vector element size in vector compare");
7152 return Context.getExtVectorType(Context.LongLongTy, VTy->getNumElements());
7153}
7154
Nate Begeman191a6b12008-07-14 18:02:46 +00007155/// CheckVectorCompareOperands - vector comparisons are a clang extension that
Mike Stump4e1f26a2009-02-19 03:04:26 +00007156/// operates on extended vector types. Instead of producing an IntTy result,
Nate Begeman191a6b12008-07-14 18:02:46 +00007157/// like a scalar comparison, a vector comparison produces a vector of integer
7158/// types.
Richard Trieubcce2f72011-09-07 01:19:57 +00007159QualType Sema::CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007160 SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007161 bool IsRelational) {
Nate Begeman191a6b12008-07-14 18:02:46 +00007162 // Check to make sure we're operating on vectors of the same type and width,
7163 // Allowing one side to be a scalar of element type.
Richard Trieubcce2f72011-09-07 01:19:57 +00007164 QualType vType = CheckVectorOperands(LHS, RHS, Loc, /*isCompAssign*/false);
Nate Begeman191a6b12008-07-14 18:02:46 +00007165 if (vType.isNull())
7166 return vType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007167
Richard Trieubcce2f72011-09-07 01:19:57 +00007168 QualType LHSType = LHS.get()->getType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007169
Anton Yartsev530deb92011-03-27 15:36:07 +00007170 // If AltiVec, the comparison results in a numeric type, i.e.
7171 // bool for C++, int for C
Anton Yartsev93900c72011-03-28 21:00:05 +00007172 if (vType->getAs<VectorType>()->getVectorKind() == VectorType::AltiVecVector)
Anton Yartsev530deb92011-03-27 15:36:07 +00007173 return Context.getLogicalOperationType();
7174
Nate Begeman191a6b12008-07-14 18:02:46 +00007175 // For non-floating point types, check for self-comparisons of the form
7176 // x == x, x != x, x < x, etc. These always evaluate to a constant, and
7177 // often indicate logic errors in the program.
Richard Trieubcce2f72011-09-07 01:19:57 +00007178 if (!LHSType->hasFloatingRepresentation()) {
Richard Smith508ebf32011-10-28 03:31:48 +00007179 if (DeclRefExpr* DRL
7180 = dyn_cast<DeclRefExpr>(LHS.get()->IgnoreParenImpCasts()))
7181 if (DeclRefExpr* DRR
7182 = dyn_cast<DeclRefExpr>(RHS.get()->IgnoreParenImpCasts()))
Nate Begeman191a6b12008-07-14 18:02:46 +00007183 if (DRL->getDecl() == DRR->getDecl())
Ted Kremenek3427fac2011-02-23 01:52:04 +00007184 DiagRuntimeBehavior(Loc, 0,
Douglas Gregorec170db2010-06-08 19:50:34 +00007185 PDiag(diag::warn_comparison_always)
7186 << 0 // self-
7187 << 2 // "a constant"
7188 );
Nate Begeman191a6b12008-07-14 18:02:46 +00007189 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007190
Nate Begeman191a6b12008-07-14 18:02:46 +00007191 // Check for comparisons of floating point operands using != and ==.
Richard Trieuba63ce62011-09-09 01:45:06 +00007192 if (!IsRelational && LHSType->hasFloatingRepresentation()) {
David Blaikieca043222012-01-16 05:16:03 +00007193 assert (RHS.get()->getType()->hasFloatingRepresentation());
Richard Trieubcce2f72011-09-07 01:19:57 +00007194 CheckFloatComparison(Loc, LHS.get(), RHS.get());
Nate Begeman191a6b12008-07-14 18:02:46 +00007195 }
Tanya Lattner20248222012-01-16 21:02:28 +00007196
7197 // Return a signed type for the vector.
7198 return GetSignedVectorType(LHSType);
7199}
Mike Stump4e1f26a2009-02-19 03:04:26 +00007200
Tanya Lattner3dd33b22012-01-19 01:16:16 +00007201QualType Sema::CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS,
7202 SourceLocation Loc) {
Tanya Lattner20248222012-01-16 21:02:28 +00007203 // Ensure that either both operands are of the same vector type, or
7204 // one operand is of a vector type and the other is of its element type.
7205 QualType vType = CheckVectorOperands(LHS, RHS, Loc, false);
7206 if (vType.isNull() || vType->isFloatingType())
7207 return InvalidOperands(Loc, LHS, RHS);
7208
7209 return GetSignedVectorType(LHS.get()->getType());
Nate Begeman191a6b12008-07-14 18:02:46 +00007210}
7211
Steve Naroff218bc2b2007-05-04 21:54:46 +00007212inline QualType Sema::CheckBitwiseOperands(
Richard Trieuba63ce62011-09-09 01:45:06 +00007213 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign) {
Richard Trieuf8916e12011-09-16 00:53:10 +00007214 checkArithmeticNull(*this, LHS, RHS, Loc, /*isCompare=*/false);
7215
Richard Trieubcce2f72011-09-07 01:19:57 +00007216 if (LHS.get()->getType()->isVectorType() ||
7217 RHS.get()->getType()->isVectorType()) {
7218 if (LHS.get()->getType()->hasIntegerRepresentation() &&
7219 RHS.get()->getType()->hasIntegerRepresentation())
Richard Trieuba63ce62011-09-09 01:45:06 +00007220 return CheckVectorOperands(LHS, RHS, Loc, IsCompAssign);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007221
Richard Trieubcce2f72011-09-07 01:19:57 +00007222 return InvalidOperands(Loc, LHS, RHS);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00007223 }
Steve Naroffb8ea4fb2007-07-13 23:32:42 +00007224
Richard Trieubcce2f72011-09-07 01:19:57 +00007225 ExprResult LHSResult = Owned(LHS), RHSResult = Owned(RHS);
7226 QualType compType = UsualArithmeticConversions(LHSResult, RHSResult,
Richard Trieuba63ce62011-09-09 01:45:06 +00007227 IsCompAssign);
Richard Trieubcce2f72011-09-07 01:19:57 +00007228 if (LHSResult.isInvalid() || RHSResult.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007229 return QualType();
Richard Trieubcce2f72011-09-07 01:19:57 +00007230 LHS = LHSResult.take();
7231 RHS = RHSResult.take();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007232
Eli Friedman93ee5ca2012-06-16 02:19:17 +00007233 if (!compType.isNull() && compType->isIntegralOrUnscopedEnumerationType())
Steve Naroffbe4c4d12007-08-24 19:07:16 +00007234 return compType;
Richard Trieubcce2f72011-09-07 01:19:57 +00007235 return InvalidOperands(Loc, LHS, RHS);
Steve Naroff26c8ea52007-03-21 21:08:52 +00007236}
7237
Steve Naroff218bc2b2007-05-04 21:54:46 +00007238inline QualType Sema::CheckLogicalOperands( // C99 6.5.[13,14]
Richard Trieubcce2f72011-09-07 01:19:57 +00007239 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, unsigned Opc) {
Chris Lattner8406c512010-07-13 19:41:32 +00007240
Tanya Lattner20248222012-01-16 21:02:28 +00007241 // Check vector operands differently.
7242 if (LHS.get()->getType()->isVectorType() || RHS.get()->getType()->isVectorType())
7243 return CheckVectorLogicalOperands(LHS, RHS, Loc);
7244
Chris Lattner8406c512010-07-13 19:41:32 +00007245 // Diagnose cases where the user write a logical and/or but probably meant a
7246 // bitwise one. We do this when the LHS is a non-bool integer and the RHS
7247 // is a constant.
Richard Trieubcce2f72011-09-07 01:19:57 +00007248 if (LHS.get()->getType()->isIntegerType() &&
7249 !LHS.get()->getType()->isBooleanType() &&
7250 RHS.get()->getType()->isIntegerType() && !RHS.get()->isValueDependent() &&
Richard Trieucfe39262011-07-15 00:00:51 +00007251 // Don't warn in macros or template instantiations.
7252 !Loc.isMacroID() && ActiveTemplateInstantiations.empty()) {
Chris Lattner938533d2010-07-24 01:10:11 +00007253 // If the RHS can be constant folded, and if it constant folds to something
7254 // that isn't 0 or 1 (which indicate a potential logical operation that
7255 // happened to fold to true/false) then warn.
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007256 // Parens on the RHS are ignored.
Richard Smith00ab3ae2011-10-16 23:01:09 +00007257 llvm::APSInt Result;
7258 if (RHS.get()->EvaluateAsInt(Result, Context))
David Blaikiebbafb8a2012-03-11 07:00:24 +00007259 if ((getLangOpts().Bool && !RHS.get()->getType()->isBooleanType()) ||
Richard Smith00ab3ae2011-10-16 23:01:09 +00007260 (Result != 0 && Result != 1)) {
Chandler Carruthe54ff6c2011-05-31 05:41:42 +00007261 Diag(Loc, diag::warn_logical_instead_of_bitwise)
Richard Trieubcce2f72011-09-07 01:19:57 +00007262 << RHS.get()->getSourceRange()
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007263 << (Opc == BO_LAnd ? "&&" : "||");
7264 // Suggest replacing the logical operator with the bitwise version
7265 Diag(Loc, diag::note_logical_instead_of_bitwise_change_operator)
7266 << (Opc == BO_LAnd ? "&" : "|")
7267 << FixItHint::CreateReplacement(SourceRange(
7268 Loc, Lexer::getLocForEndOfToken(Loc, 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007269 getLangOpts())),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007270 Opc == BO_LAnd ? "&" : "|");
7271 if (Opc == BO_LAnd)
7272 // Suggest replacing "Foo() && kNonZero" with "Foo()"
7273 Diag(Loc, diag::note_logical_instead_of_bitwise_remove_constant)
7274 << FixItHint::CreateRemoval(
7275 SourceRange(
Richard Trieubcce2f72011-09-07 01:19:57 +00007276 Lexer::getLocForEndOfToken(LHS.get()->getLocEnd(),
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007277 0, getSourceManager(),
David Blaikiebbafb8a2012-03-11 07:00:24 +00007278 getLangOpts()),
Richard Trieubcce2f72011-09-07 01:19:57 +00007279 RHS.get()->getLocEnd()));
Matt Beaumont-Gay0a0ba9d2011-08-15 17:50:06 +00007280 }
Chris Lattner938533d2010-07-24 01:10:11 +00007281 }
Chris Lattner8406c512010-07-13 19:41:32 +00007282
David Blaikiebbafb8a2012-03-11 07:00:24 +00007283 if (!Context.getLangOpts().CPlusPlus) {
Richard Trieubcce2f72011-09-07 01:19:57 +00007284 LHS = UsualUnaryConversions(LHS.take());
7285 if (LHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007286 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007287
Richard Trieubcce2f72011-09-07 01:19:57 +00007288 RHS = UsualUnaryConversions(RHS.take());
7289 if (RHS.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00007290 return QualType();
7291
Richard Trieubcce2f72011-09-07 01:19:57 +00007292 if (!LHS.get()->getType()->isScalarType() ||
7293 !RHS.get()->getType()->isScalarType())
7294 return InvalidOperands(Loc, LHS, RHS);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007295
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007296 return Context.IntTy;
Anders Carlsson35a99d92009-10-16 01:44:21 +00007297 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007298
John McCall4a2429a2010-06-04 00:29:51 +00007299 // The following is safe because we only use this method for
7300 // non-overloadable operands.
7301
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007302 // C++ [expr.log.and]p1
7303 // C++ [expr.log.or]p1
John McCall4a2429a2010-06-04 00:29:51 +00007304 // The operands are both contextually converted to type bool.
Richard Trieubcce2f72011-09-07 01:19:57 +00007305 ExprResult LHSRes = PerformContextuallyConvertToBool(LHS.get());
7306 if (LHSRes.isInvalid())
7307 return InvalidOperands(Loc, LHS, RHS);
7308 LHS = move(LHSRes);
John Wiegley01296292011-04-08 18:41:53 +00007309
Richard Trieubcce2f72011-09-07 01:19:57 +00007310 ExprResult RHSRes = PerformContextuallyConvertToBool(RHS.get());
7311 if (RHSRes.isInvalid())
7312 return InvalidOperands(Loc, LHS, RHS);
7313 RHS = move(RHSRes);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00007314
Anders Carlsson2e7bc112009-11-23 21:47:44 +00007315 // C++ [expr.log.and]p2
7316 // C++ [expr.log.or]p2
7317 // The result is a bool.
7318 return Context.BoolTy;
Steve Naroffae4143e2007-04-26 20:39:23 +00007319}
7320
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007321/// IsReadonlyProperty - Verify that otherwise a valid l-value expression
7322/// is a read-only property; return true if so. A readonly property expression
7323/// depends on various declarations and thus must be treated specially.
7324///
Mike Stump11289f42009-09-09 15:08:12 +00007325static bool IsReadonlyProperty(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007326 const ObjCPropertyRefExpr *PropExpr = dyn_cast<ObjCPropertyRefExpr>(E);
7327 if (!PropExpr) return false;
7328 if (PropExpr->isImplicitProperty()) return false;
John McCallb7bd14f2010-12-02 01:19:52 +00007329
John McCall526ab472011-10-25 17:37:35 +00007330 ObjCPropertyDecl *PDecl = PropExpr->getExplicitProperty();
7331 QualType BaseType = PropExpr->isSuperReceiver() ?
John McCallb7bd14f2010-12-02 01:19:52 +00007332 PropExpr->getSuperReceiverType() :
Fariborz Jahanian681c0752010-10-14 16:04:05 +00007333 PropExpr->getBase()->getType();
7334
John McCall526ab472011-10-25 17:37:35 +00007335 if (const ObjCObjectPointerType *OPT =
7336 BaseType->getAsObjCInterfacePointerType())
7337 if (ObjCInterfaceDecl *IFace = OPT->getInterfaceDecl())
7338 if (S.isPropertyReadonly(PDecl, IFace))
7339 return true;
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007340 return false;
7341}
7342
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007343static bool IsReadonlyMessage(Expr *E, Sema &S) {
John McCall526ab472011-10-25 17:37:35 +00007344 const MemberExpr *ME = dyn_cast<MemberExpr>(E);
7345 if (!ME) return false;
7346 if (!isa<FieldDecl>(ME->getMemberDecl())) return false;
7347 ObjCMessageExpr *Base =
7348 dyn_cast<ObjCMessageExpr>(ME->getBase()->IgnoreParenImpCasts());
7349 if (!Base) return false;
7350 return Base->getMethodDecl() != 0;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007351}
7352
John McCall5fa2ef42012-03-13 00:37:01 +00007353/// Is the given expression (which must be 'const') a reference to a
7354/// variable which was originally non-const, but which has become
7355/// 'const' due to being captured within a block?
7356enum NonConstCaptureKind { NCCK_None, NCCK_Block, NCCK_Lambda };
7357static NonConstCaptureKind isReferenceToNonConstCapture(Sema &S, Expr *E) {
7358 assert(E->isLValue() && E->getType().isConstQualified());
7359 E = E->IgnoreParens();
7360
7361 // Must be a reference to a declaration from an enclosing scope.
7362 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
7363 if (!DRE) return NCCK_None;
7364 if (!DRE->refersToEnclosingLocal()) return NCCK_None;
7365
7366 // The declaration must be a variable which is not declared 'const'.
7367 VarDecl *var = dyn_cast<VarDecl>(DRE->getDecl());
7368 if (!var) return NCCK_None;
7369 if (var->getType().isConstQualified()) return NCCK_None;
7370 assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
7371
7372 // Decide whether the first capture was for a block or a lambda.
7373 DeclContext *DC = S.CurContext;
7374 while (DC->getParent() != var->getDeclContext())
7375 DC = DC->getParent();
7376 return (isa<BlockDecl>(DC) ? NCCK_Block : NCCK_Lambda);
7377}
7378
Chris Lattner30bd3272008-11-18 01:22:49 +00007379/// CheckForModifiableLvalue - Verify that E is a modifiable lvalue. If not,
7380/// emit an error and return true. If so, return false.
7381static bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S) {
Fariborz Jahanianca5c5972012-04-10 17:30:10 +00007382 assert(!E->hasPlaceholderType(BuiltinType::PseudoObject));
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007383 SourceLocation OrigLoc = Loc;
Mike Stump11289f42009-09-09 15:08:12 +00007384 Expr::isModifiableLvalueResult IsLV = E->isModifiableLvalue(S.Context,
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007385 &Loc);
Fariborz Jahanian8e1555c2009-01-12 19:55:42 +00007386 if (IsLV == Expr::MLV_Valid && IsReadonlyProperty(E, S))
7387 IsLV = Expr::MLV_ReadonlyProperty;
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007388 else if (IsLV == Expr::MLV_ClassTemporary && IsReadonlyMessage(E, S))
7389 IsLV = Expr::MLV_InvalidMessageExpression;
Chris Lattner30bd3272008-11-18 01:22:49 +00007390 if (IsLV == Expr::MLV_Valid)
7391 return false;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007392
Chris Lattner30bd3272008-11-18 01:22:49 +00007393 unsigned Diag = 0;
7394 bool NeedType = false;
7395 switch (IsLV) { // C99 6.5.16p2
John McCall31168b02011-06-15 23:02:42 +00007396 case Expr::MLV_ConstQualified:
7397 Diag = diag::err_typecheck_assign_const;
7398
John McCall5fa2ef42012-03-13 00:37:01 +00007399 // Use a specialized diagnostic when we're assigning to an object
7400 // from an enclosing function or block.
7401 if (NonConstCaptureKind NCCK = isReferenceToNonConstCapture(S, E)) {
7402 if (NCCK == NCCK_Block)
7403 Diag = diag::err_block_decl_ref_not_modifiable_lvalue;
7404 else
7405 Diag = diag::err_lambda_decl_ref_not_modifiable_lvalue;
7406 break;
7407 }
7408
John McCalld4631322011-06-17 06:42:21 +00007409 // In ARC, use some specialized diagnostics for occasions where we
7410 // infer 'const'. These are always pseudo-strong variables.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007411 if (S.getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00007412 DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(E->IgnoreParenCasts());
7413 if (declRef && isa<VarDecl>(declRef->getDecl())) {
7414 VarDecl *var = cast<VarDecl>(declRef->getDecl());
7415
John McCalld4631322011-06-17 06:42:21 +00007416 // Use the normal diagnostic if it's pseudo-__strong but the
7417 // user actually wrote 'const'.
7418 if (var->isARCPseudoStrong() &&
7419 (!var->getTypeSourceInfo() ||
7420 !var->getTypeSourceInfo()->getType().isConstQualified())) {
7421 // There are two pseudo-strong cases:
7422 // - self
John McCall31168b02011-06-15 23:02:42 +00007423 ObjCMethodDecl *method = S.getCurMethodDecl();
7424 if (method && var == method->getSelfDecl())
Ted Kremenek1fcdaa92011-11-14 21:59:25 +00007425 Diag = method->isClassMethod()
7426 ? diag::err_typecheck_arc_assign_self_class_method
7427 : diag::err_typecheck_arc_assign_self;
John McCalld4631322011-06-17 06:42:21 +00007428
7429 // - fast enumeration variables
7430 else
John McCall31168b02011-06-15 23:02:42 +00007431 Diag = diag::err_typecheck_arr_assign_enumeration;
John McCalld4631322011-06-17 06:42:21 +00007432
John McCall31168b02011-06-15 23:02:42 +00007433 SourceRange Assign;
7434 if (Loc != OrigLoc)
7435 Assign = SourceRange(OrigLoc, OrigLoc);
7436 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
7437 // We need to preserve the AST regardless, so migration tool
7438 // can do its job.
7439 return false;
7440 }
7441 }
7442 }
7443
7444 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007445 case Expr::MLV_ArrayType:
Richard Smitheb3cad52012-06-04 22:27:30 +00007446 case Expr::MLV_ArrayTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007447 Diag = diag::err_typecheck_array_not_modifiable_lvalue;
7448 NeedType = true;
7449 break;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007450 case Expr::MLV_NotObjectType:
Chris Lattner30bd3272008-11-18 01:22:49 +00007451 Diag = diag::err_typecheck_non_object_not_modifiable_lvalue;
7452 NeedType = true;
7453 break;
Chris Lattner9b3bbe92008-11-17 19:51:54 +00007454 case Expr::MLV_LValueCast:
Chris Lattner30bd3272008-11-18 01:22:49 +00007455 Diag = diag::err_typecheck_lvalue_casts_not_supported;
7456 break;
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007457 case Expr::MLV_Valid:
7458 llvm_unreachable("did not take early return for MLV_Valid");
Chris Lattner9bad62c2008-01-04 18:04:52 +00007459 case Expr::MLV_InvalidExpression:
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007460 case Expr::MLV_MemberFunction:
7461 case Expr::MLV_ClassTemporary:
Chris Lattner30bd3272008-11-18 01:22:49 +00007462 Diag = diag::err_typecheck_expression_not_modifiable_lvalue;
7463 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007464 case Expr::MLV_IncompleteType:
7465 case Expr::MLV_IncompleteVoidType:
Douglas Gregored0cfbd2009-03-09 16:13:40 +00007466 return S.RequireCompleteType(Loc, E->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00007467 diag::err_typecheck_incomplete_type_not_modifiable_lvalue, E);
Chris Lattner9bad62c2008-01-04 18:04:52 +00007468 case Expr::MLV_DuplicateVectorComponents:
Chris Lattner30bd3272008-11-18 01:22:49 +00007469 Diag = diag::err_typecheck_duplicate_vector_components_not_mlvalue;
7470 break;
Fariborz Jahanian8a1810f2008-11-22 18:39:36 +00007471 case Expr::MLV_ReadonlyProperty:
Fariborz Jahanian5118c412008-11-22 20:25:50 +00007472 case Expr::MLV_NoSetterProperty:
John McCall526ab472011-10-25 17:37:35 +00007473 llvm_unreachable("readonly properties should be processed differently");
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007474 case Expr::MLV_InvalidMessageExpression:
7475 Diag = diag::error_readonly_message_assignment;
7476 break;
Fariborz Jahaniane8d28902009-12-15 23:59:41 +00007477 case Expr::MLV_SubObjCPropertySetting:
7478 Diag = diag::error_no_subobject_property_setting;
7479 break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007480 }
Steve Naroffad373bd2007-07-31 12:34:36 +00007481
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007482 SourceRange Assign;
7483 if (Loc != OrigLoc)
7484 Assign = SourceRange(OrigLoc, OrigLoc);
Chris Lattner30bd3272008-11-18 01:22:49 +00007485 if (NeedType)
Daniel Dunbarc2223ab2009-04-15 00:08:05 +00007486 S.Diag(Loc, Diag) << E->getType() << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007487 else
Mike Stump11289f42009-09-09 15:08:12 +00007488 S.Diag(Loc, Diag) << E->getSourceRange() << Assign;
Chris Lattner30bd3272008-11-18 01:22:49 +00007489 return true;
7490}
7491
7492
7493
7494// C99 6.5.16.1
Richard Trieuda4f43a62011-09-07 01:33:52 +00007495QualType Sema::CheckAssignmentOperands(Expr *LHSExpr, ExprResult &RHS,
Chris Lattner326f7572008-11-18 01:30:42 +00007496 SourceLocation Loc,
7497 QualType CompoundType) {
John McCall526ab472011-10-25 17:37:35 +00007498 assert(!LHSExpr->hasPlaceholderType(BuiltinType::PseudoObject));
7499
Chris Lattner326f7572008-11-18 01:30:42 +00007500 // Verify that LHS is a modifiable lvalue, and emit error if not.
Richard Trieuda4f43a62011-09-07 01:33:52 +00007501 if (CheckForModifiableLvalue(LHSExpr, Loc, *this))
Chris Lattner30bd3272008-11-18 01:22:49 +00007502 return QualType();
Chris Lattner326f7572008-11-18 01:30:42 +00007503
Richard Trieuda4f43a62011-09-07 01:33:52 +00007504 QualType LHSType = LHSExpr->getType();
Richard Trieucfc491d2011-08-02 04:35:43 +00007505 QualType RHSType = CompoundType.isNull() ? RHS.get()->getType() :
7506 CompoundType;
Chris Lattner9bad62c2008-01-04 18:04:52 +00007507 AssignConvertType ConvTy;
Chris Lattner326f7572008-11-18 01:30:42 +00007508 if (CompoundType.isNull()) {
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007509 QualType LHSTy(LHSType);
Fariborz Jahanianbe21aa32010-06-07 22:02:01 +00007510 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
John Wiegley01296292011-04-08 18:41:53 +00007511 if (RHS.isInvalid())
7512 return QualType();
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007513 // Special case of NSObject attributes on c-style pointer types.
7514 if (ConvTy == IncompatiblePointer &&
7515 ((Context.isObjCNSObjectType(LHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007516 RHSType->isObjCObjectPointerType()) ||
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007517 (Context.isObjCNSObjectType(RHSType) &&
Steve Naroff79d12152009-07-16 15:41:00 +00007518 LHSType->isObjCObjectPointerType())))
Fariborz Jahanian255c0952009-01-13 23:34:40 +00007519 ConvTy = Compatible;
Mike Stump4e1f26a2009-02-19 03:04:26 +00007520
John McCall7decc9e2010-11-18 06:31:45 +00007521 if (ConvTy == Compatible &&
Fariborz Jahaniane2a77762012-01-24 19:40:13 +00007522 LHSType->isObjCObjectType())
Fariborz Jahanian3c4225a2012-01-24 18:05:45 +00007523 Diag(Loc, diag::err_objc_object_assignment)
7524 << LHSType;
John McCall7decc9e2010-11-18 06:31:45 +00007525
Chris Lattnerea714382008-08-21 18:04:13 +00007526 // If the RHS is a unary plus or minus, check to see if they = and + are
7527 // right next to each other. If so, the user may have typo'd "x =+ 4"
7528 // instead of "x += 4".
John Wiegley01296292011-04-08 18:41:53 +00007529 Expr *RHSCheck = RHS.get();
Chris Lattnerea714382008-08-21 18:04:13 +00007530 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(RHSCheck))
7531 RHSCheck = ICE->getSubExpr();
7532 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(RHSCheck)) {
John McCalle3027922010-08-25 11:45:40 +00007533 if ((UO->getOpcode() == UO_Plus ||
7534 UO->getOpcode() == UO_Minus) &&
Chris Lattner326f7572008-11-18 01:30:42 +00007535 Loc.isFileID() && UO->getOperatorLoc().isFileID() &&
Chris Lattnerea714382008-08-21 18:04:13 +00007536 // Only if the two operators are exactly adjacent.
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007537 Loc.getLocWithOffset(1) == UO->getOperatorLoc() &&
Chris Lattner36c39c92009-03-08 06:51:10 +00007538 // And there is a space or other character before the subexpr of the
7539 // unary +/-. We don't want to warn on "x=-1".
Argyrios Kyrtzidise6e67de2011-09-19 20:40:19 +00007540 Loc.getLocWithOffset(2) != UO->getSubExpr()->getLocStart() &&
Chris Lattnered9f14c2009-03-09 07:11:10 +00007541 UO->getSubExpr()->getLocStart().isFileID()) {
Chris Lattner29e812b2008-11-20 06:06:08 +00007542 Diag(Loc, diag::warn_not_compound_assign)
John McCalle3027922010-08-25 11:45:40 +00007543 << (UO->getOpcode() == UO_Plus ? "+" : "-")
Chris Lattner29e812b2008-11-20 06:06:08 +00007544 << SourceRange(UO->getOperatorLoc(), UO->getOperatorLoc());
Chris Lattner36c39c92009-03-08 06:51:10 +00007545 }
Chris Lattnerea714382008-08-21 18:04:13 +00007546 }
John McCall31168b02011-06-15 23:02:42 +00007547
7548 if (ConvTy == Compatible) {
7549 if (LHSType.getObjCLifetime() == Qualifiers::OCL_Strong)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007550 checkRetainCycles(LHSExpr, RHS.get());
David Blaikiebbafb8a2012-03-11 07:00:24 +00007551 else if (getLangOpts().ObjCAutoRefCount)
Richard Trieuda4f43a62011-09-07 01:33:52 +00007552 checkUnsafeExprAssigns(Loc, LHSExpr, RHS.get());
John McCall31168b02011-06-15 23:02:42 +00007553 }
Chris Lattnerea714382008-08-21 18:04:13 +00007554 } else {
7555 // Compound assignment "x += y"
Douglas Gregorc03a1082011-01-28 02:26:04 +00007556 ConvTy = CheckAssignmentConstraints(Loc, LHSType, RHSType);
Chris Lattnerea714382008-08-21 18:04:13 +00007557 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00007558
Chris Lattner326f7572008-11-18 01:30:42 +00007559 if (DiagnoseAssignmentResult(ConvTy, Loc, LHSType, RHSType,
John Wiegley01296292011-04-08 18:41:53 +00007560 RHS.get(), AA_Assigning))
Chris Lattner9bad62c2008-01-04 18:04:52 +00007561 return QualType();
Mike Stump4e1f26a2009-02-19 03:04:26 +00007562
Richard Trieuda4f43a62011-09-07 01:33:52 +00007563 CheckForNullPointerDereference(*this, LHSExpr);
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00007564
Steve Naroff98cf3e92007-06-06 18:38:38 +00007565 // C99 6.5.16p3: The type of an assignment expression is the type of the
7566 // left operand unless the left operand has qualified type, in which case
Mike Stump4e1f26a2009-02-19 03:04:26 +00007567 // it is the unqualified version of the type of the left operand.
Steve Naroff98cf3e92007-06-06 18:38:38 +00007568 // C99 6.5.16.1p2: In simple assignment, the value of the right operand
7569 // is converted to the type of the assignment expression (above).
Chris Lattnerf17bd422007-08-30 17:45:32 +00007570 // C++ 5.17p1: the type of the assignment expression is that of its left
Douglas Gregord2c2d172009-05-02 00:36:19 +00007571 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007572 return (getLangOpts().CPlusPlus
John McCall01cbf2d2010-10-12 02:19:57 +00007573 ? LHSType : LHSType.getUnqualifiedType());
Steve Naroffae4143e2007-04-26 20:39:23 +00007574}
7575
Chris Lattner326f7572008-11-18 01:30:42 +00007576// C99 6.5.17
John Wiegley01296292011-04-08 18:41:53 +00007577static QualType CheckCommaOperands(Sema &S, ExprResult &LHS, ExprResult &RHS,
John McCall4bc41ae2010-11-18 19:01:18 +00007578 SourceLocation Loc) {
John McCall3aef3d82011-04-10 19:13:55 +00007579 LHS = S.CheckPlaceholderExpr(LHS.take());
7580 RHS = S.CheckPlaceholderExpr(RHS.take());
John Wiegley01296292011-04-08 18:41:53 +00007581 if (LHS.isInvalid() || RHS.isInvalid())
Douglas Gregor0124e9b2010-11-09 21:07:58 +00007582 return QualType();
7583
John McCall73d36182010-10-12 07:14:40 +00007584 // C's comma performs lvalue conversion (C99 6.3.2.1) on both its
7585 // operands, but not unary promotions.
7586 // C++'s comma does not do any conversions at all (C++ [expr.comma]p1).
Eli Friedmanba961a92009-03-23 00:24:07 +00007587
John McCall34376a62010-12-04 03:47:34 +00007588 // So we treat the LHS as a ignored value, and in C++ we allow the
7589 // containing site to determine what should be done with the RHS.
John Wiegley01296292011-04-08 18:41:53 +00007590 LHS = S.IgnoredValueConversions(LHS.take());
7591 if (LHS.isInvalid())
7592 return QualType();
John McCall34376a62010-12-04 03:47:34 +00007593
Eli Friedmanc11535c2012-05-24 00:47:05 +00007594 S.DiagnoseUnusedExprResult(LHS.get());
7595
David Blaikiebbafb8a2012-03-11 07:00:24 +00007596 if (!S.getLangOpts().CPlusPlus) {
John Wiegley01296292011-04-08 18:41:53 +00007597 RHS = S.DefaultFunctionArrayLvalueConversion(RHS.take());
7598 if (RHS.isInvalid())
7599 return QualType();
7600 if (!RHS.get()->getType()->isVoidType())
Richard Trieucfc491d2011-08-02 04:35:43 +00007601 S.RequireCompleteType(Loc, RHS.get()->getType(),
7602 diag::err_incomplete_type);
John McCall73d36182010-10-12 07:14:40 +00007603 }
Eli Friedmanba961a92009-03-23 00:24:07 +00007604
John Wiegley01296292011-04-08 18:41:53 +00007605 return RHS.get()->getType();
Steve Naroff95af0132007-03-30 23:47:58 +00007606}
7607
Steve Naroff7a5af782007-07-13 16:58:59 +00007608/// CheckIncrementDecrementOperand - unlike most "Check" methods, this routine
7609/// doesn't need to call UsualUnaryConversions or UsualArithmeticConversions.
John McCall4bc41ae2010-11-18 19:01:18 +00007610static QualType CheckIncrementDecrementOperand(Sema &S, Expr *Op,
7611 ExprValueKind &VK,
7612 SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007613 bool IsInc, bool IsPrefix) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007614 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007615 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007616
Chris Lattner6b0cf142008-11-21 07:05:48 +00007617 QualType ResType = Op->getType();
David Chisnallfa35df62012-01-16 17:27:18 +00007618 // Atomic types can be used for increment / decrement where the non-atomic
7619 // versions can, so ignore the _Atomic() specifier for the purpose of
7620 // checking.
7621 if (const AtomicType *ResAtomicType = ResType->getAs<AtomicType>())
7622 ResType = ResAtomicType->getValueType();
7623
Chris Lattner6b0cf142008-11-21 07:05:48 +00007624 assert(!ResType.isNull() && "no type for increment/decrement expression");
Steve Naroffd50c88e2007-04-05 21:15:20 +00007625
David Blaikiebbafb8a2012-03-11 07:00:24 +00007626 if (S.getLangOpts().CPlusPlus && ResType->isBooleanType()) {
Sebastian Redle10c2c32008-12-20 09:35:34 +00007627 // Decrement of bool is not allowed.
Richard Trieuba63ce62011-09-09 01:45:06 +00007628 if (!IsInc) {
John McCall4bc41ae2010-11-18 19:01:18 +00007629 S.Diag(OpLoc, diag::err_decrement_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007630 return QualType();
7631 }
7632 // Increment of bool sets it to true, but is deprecated.
John McCall4bc41ae2010-11-18 19:01:18 +00007633 S.Diag(OpLoc, diag::warn_increment_bool) << Op->getSourceRange();
Sebastian Redle10c2c32008-12-20 09:35:34 +00007634 } else if (ResType->isRealType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007635 // OK!
Steve Naroff6b712a72009-07-14 18:25:06 +00007636 } else if (ResType->isAnyPointerType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007637 // C99 6.5.2.4p2, 6.5.6p2
Chandler Carruthc9332212011-06-27 08:02:19 +00007638 if (!checkArithmeticOpPointerOperand(S, OpLoc, Op))
Douglas Gregordd430f72009-01-19 19:26:10 +00007639 return QualType();
Chandler Carruthc9332212011-06-27 08:02:19 +00007640
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007641 // Diagnose bad cases where we step over interface counts.
Richard Trieub10c6312011-09-01 22:53:23 +00007642 else if (!checkArithmethicPointerOnNonFragileABI(S, OpLoc, Op))
Fariborz Jahanianca75db72009-07-16 17:59:14 +00007643 return QualType();
Eli Friedman090addd2010-01-03 00:20:48 +00007644 } else if (ResType->isAnyComplexType()) {
Chris Lattner6b0cf142008-11-21 07:05:48 +00007645 // C99 does not support ++/-- on complex types, we allow as an extension.
John McCall4bc41ae2010-11-18 19:01:18 +00007646 S.Diag(OpLoc, diag::ext_integer_increment_complex)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007647 << ResType << Op->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00007648 } else if (ResType->isPlaceholderType()) {
John McCall3aef3d82011-04-10 19:13:55 +00007649 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007650 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007651 return CheckIncrementDecrementOperand(S, PR.take(), VK, OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00007652 IsInc, IsPrefix);
David Blaikiebbafb8a2012-03-11 07:00:24 +00007653 } else if (S.getLangOpts().AltiVec && ResType->isVectorType()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00007654 // OK! ( C/C++ Language Extensions for CBEA(Version 2.6) 10.3 )
Chris Lattner6b0cf142008-11-21 07:05:48 +00007655 } else {
John McCall4bc41ae2010-11-18 19:01:18 +00007656 S.Diag(OpLoc, diag::err_typecheck_illegal_increment_decrement)
Richard Trieuba63ce62011-09-09 01:45:06 +00007657 << ResType << int(IsInc) << Op->getSourceRange();
Chris Lattner6b0cf142008-11-21 07:05:48 +00007658 return QualType();
Steve Naroff46ba1eb2007-04-03 23:13:13 +00007659 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007660 // At this point, we know we have a real, complex or pointer type.
Steve Naroff9e1e5512007-08-23 21:37:33 +00007661 // Now make sure the operand is a modifiable lvalue.
John McCall4bc41ae2010-11-18 19:01:18 +00007662 if (CheckForModifiableLvalue(Op, OpLoc, S))
Steve Naroff35d85152007-05-07 00:24:15 +00007663 return QualType();
Alexis Huntc46382e2010-04-28 23:02:27 +00007664 // In C++, a prefix increment is the same type as the operand. Otherwise
7665 // (in C or with postfix), the increment is the unqualified type of the
7666 // operand.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007667 if (IsPrefix && S.getLangOpts().CPlusPlus) {
John McCall4bc41ae2010-11-18 19:01:18 +00007668 VK = VK_LValue;
7669 return ResType;
7670 } else {
7671 VK = VK_RValue;
7672 return ResType.getUnqualifiedType();
7673 }
Steve Naroff26c8ea52007-03-21 21:08:52 +00007674}
Fariborz Jahanian805b74e2010-09-14 23:02:38 +00007675
7676
Anders Carlsson806700f2008-02-01 07:15:58 +00007677/// getPrimaryDecl - Helper function for CheckAddressOfOperand().
Steve Naroff47500512007-04-19 23:00:49 +00007678/// This routine allows us to typecheck complex/recursive expressions
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007679/// where the declaration is needed for type checking. We only need to
7680/// handle cases when the expression references a function designator
7681/// or is an lvalue. Here are some examples:
7682/// - &(x) => x
7683/// - &*****f => f for f a function designator.
7684/// - &s.xx => s
7685/// - &s.zz[1].yy -> s, if zz is an array
7686/// - *(x + 1) -> x, if x is an array
7687/// - &"123"[2] -> 0
7688/// - & __real__ x -> x
John McCallf3a88602011-02-03 08:15:49 +00007689static ValueDecl *getPrimaryDecl(Expr *E) {
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007690 switch (E->getStmtClass()) {
Steve Naroff47500512007-04-19 23:00:49 +00007691 case Stmt::DeclRefExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007692 return cast<DeclRefExpr>(E)->getDecl();
Steve Naroff47500512007-04-19 23:00:49 +00007693 case Stmt::MemberExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007694 // If this is an arrow operator, the address is an offset from
7695 // the base's value, so the object the base refers to is
7696 // irrelevant.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007697 if (cast<MemberExpr>(E)->isArrow())
Chris Lattner48d52842007-11-16 17:46:48 +00007698 return 0;
Eli Friedman3a1e6922009-04-20 08:23:18 +00007699 // Otherwise, the expression refers to a part of the base
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007700 return getPrimaryDecl(cast<MemberExpr>(E)->getBase());
Anders Carlsson806700f2008-02-01 07:15:58 +00007701 case Stmt::ArraySubscriptExprClass: {
Mike Stump87c57ac2009-05-16 07:39:55 +00007702 // FIXME: This code shouldn't be necessary! We should catch the implicit
7703 // promotion of register arrays earlier.
Eli Friedman3a1e6922009-04-20 08:23:18 +00007704 Expr* Base = cast<ArraySubscriptExpr>(E)->getBase();
7705 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Base)) {
7706 if (ICE->getSubExpr()->getType()->isArrayType())
7707 return getPrimaryDecl(ICE->getSubExpr());
7708 }
7709 return 0;
Anders Carlsson806700f2008-02-01 07:15:58 +00007710 }
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007711 case Stmt::UnaryOperatorClass: {
7712 UnaryOperator *UO = cast<UnaryOperator>(E);
Mike Stump4e1f26a2009-02-19 03:04:26 +00007713
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007714 switch(UO->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00007715 case UO_Real:
7716 case UO_Imag:
7717 case UO_Extension:
Daniel Dunbarb692ef42008-08-04 20:02:37 +00007718 return getPrimaryDecl(UO->getSubExpr());
7719 default:
7720 return 0;
7721 }
7722 }
Steve Naroff47500512007-04-19 23:00:49 +00007723 case Stmt::ParenExprClass:
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007724 return getPrimaryDecl(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner48d52842007-11-16 17:46:48 +00007725 case Stmt::ImplicitCastExprClass:
Eli Friedman3a1e6922009-04-20 08:23:18 +00007726 // If the result of an implicit cast is an l-value, we care about
7727 // the sub-expression; otherwise, the result here doesn't matter.
Chris Lattner24d5bfe2008-04-02 04:24:33 +00007728 return getPrimaryDecl(cast<ImplicitCastExpr>(E)->getSubExpr());
Steve Naroff47500512007-04-19 23:00:49 +00007729 default:
7730 return 0;
7731 }
7732}
7733
Richard Trieu5f376f62011-09-07 21:46:33 +00007734namespace {
7735 enum {
7736 AO_Bit_Field = 0,
7737 AO_Vector_Element = 1,
7738 AO_Property_Expansion = 2,
7739 AO_Register_Variable = 3,
7740 AO_No_Error = 4
7741 };
7742}
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007743/// \brief Diagnose invalid operand for address of operations.
7744///
7745/// \param Type The type of operand which cannot have its address taken.
Richard Trieu3fd7bb82011-09-02 00:47:55 +00007746static void diagnoseAddressOfInvalidType(Sema &S, SourceLocation Loc,
7747 Expr *E, unsigned Type) {
7748 S.Diag(Loc, diag::err_typecheck_address_of) << Type << E->getSourceRange();
7749}
7750
Steve Naroff47500512007-04-19 23:00:49 +00007751/// CheckAddressOfOperand - The operand of & must be either a function
Mike Stump4e1f26a2009-02-19 03:04:26 +00007752/// designator or an lvalue designating an object. If it is an lvalue, the
Steve Naroff47500512007-04-19 23:00:49 +00007753/// object cannot be declared with storage class register or be a bit field.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007754/// Note: The usual conversions are *not* applied to the operand of the &
Steve Naroffa78fe7e2007-05-16 19:47:19 +00007755/// operator (C99 6.3.2.1p[2-4]), and its result is never an lvalue.
Mike Stump4e1f26a2009-02-19 03:04:26 +00007756/// In C++, the operand might be an overloaded function name, in which case
Douglas Gregorcd695e52008-11-10 20:40:00 +00007757/// we allow the '&' but retain the overloaded-function type.
John McCall526ab472011-10-25 17:37:35 +00007758static QualType CheckAddressOfOperand(Sema &S, ExprResult &OrigOp,
John McCall4bc41ae2010-11-18 19:01:18 +00007759 SourceLocation OpLoc) {
John McCall526ab472011-10-25 17:37:35 +00007760 if (const BuiltinType *PTy = OrigOp.get()->getType()->getAsPlaceholderType()){
7761 if (PTy->getKind() == BuiltinType::Overload) {
7762 if (!isa<OverloadExpr>(OrigOp.get()->IgnoreParens())) {
7763 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7764 << OrigOp.get()->getSourceRange();
7765 return QualType();
7766 }
7767
7768 return S.Context.OverloadTy;
7769 }
7770
7771 if (PTy->getKind() == BuiltinType::UnknownAny)
7772 return S.Context.UnknownAnyTy;
7773
7774 if (PTy->getKind() == BuiltinType::BoundMember) {
7775 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
7776 << OrigOp.get()->getSourceRange();
Douglas Gregor668d3622011-10-09 19:10:41 +00007777 return QualType();
7778 }
John McCall526ab472011-10-25 17:37:35 +00007779
7780 OrigOp = S.CheckPlaceholderExpr(OrigOp.take());
7781 if (OrigOp.isInvalid()) return QualType();
John McCall0009fcc2011-04-26 20:42:42 +00007782 }
John McCall8d08b9b2010-08-27 09:08:28 +00007783
John McCall526ab472011-10-25 17:37:35 +00007784 if (OrigOp.get()->isTypeDependent())
7785 return S.Context.DependentTy;
7786
7787 assert(!OrigOp.get()->getType()->isPlaceholderType());
John McCall36226622010-10-12 02:09:17 +00007788
John McCall8d08b9b2010-08-27 09:08:28 +00007789 // Make sure to ignore parentheses in subsequent checks
John McCall526ab472011-10-25 17:37:35 +00007790 Expr *op = OrigOp.get()->IgnoreParens();
Douglas Gregor19b8c4f2008-12-17 22:52:20 +00007791
David Blaikiebbafb8a2012-03-11 07:00:24 +00007792 if (S.getLangOpts().C99) {
Steve Naroff826e91a2008-01-13 17:10:08 +00007793 // Implement C99-only parts of addressof rules.
7794 if (UnaryOperator* uOp = dyn_cast<UnaryOperator>(op)) {
John McCalle3027922010-08-25 11:45:40 +00007795 if (uOp->getOpcode() == UO_Deref)
Steve Naroff826e91a2008-01-13 17:10:08 +00007796 // Per C99 6.5.3.2, the address of a deref always returns a valid result
7797 // (assuming the deref expression is valid).
7798 return uOp->getSubExpr()->getType();
7799 }
7800 // Technically, there should be a check for array subscript
7801 // expressions here, but the result of one is always an lvalue anyway.
7802 }
John McCallf3a88602011-02-03 08:15:49 +00007803 ValueDecl *dcl = getPrimaryDecl(op);
John McCall086a4642010-11-24 05:12:34 +00007804 Expr::LValueClassification lval = op->ClassifyLValue(S.Context);
Richard Trieu5f376f62011-09-07 21:46:33 +00007805 unsigned AddressOfError = AO_No_Error;
Nuno Lopes17f345f2008-12-16 22:59:47 +00007806
Fariborz Jahanian071caef2011-03-26 19:48:30 +00007807 if (lval == Expr::LV_ClassTemporary) {
John McCall4bc41ae2010-11-18 19:01:18 +00007808 bool sfinae = S.isSFINAEContext();
7809 S.Diag(OpLoc, sfinae ? diag::err_typecheck_addrof_class_temporary
7810 : diag::ext_typecheck_addrof_class_temporary)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007811 << op->getType() << op->getSourceRange();
John McCall4bc41ae2010-11-18 19:01:18 +00007812 if (sfinae)
Douglas Gregorb154fdc2010-02-16 21:39:57 +00007813 return QualType();
John McCall8d08b9b2010-08-27 09:08:28 +00007814 } else if (isa<ObjCSelectorExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007815 return S.Context.getPointerType(op->getType());
John McCall8d08b9b2010-08-27 09:08:28 +00007816 } else if (lval == Expr::LV_MemberFunction) {
7817 // If it's an instance method, make a member pointer.
7818 // The expression must have exactly the form &A::foo.
7819
7820 // If the underlying expression isn't a decl ref, give up.
7821 if (!isa<DeclRefExpr>(op)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007822 S.Diag(OpLoc, diag::err_invalid_form_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007823 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007824 return QualType();
7825 }
7826 DeclRefExpr *DRE = cast<DeclRefExpr>(op);
7827 CXXMethodDecl *MD = cast<CXXMethodDecl>(DRE->getDecl());
7828
7829 // The id-expression was parenthesized.
John McCall526ab472011-10-25 17:37:35 +00007830 if (OrigOp.get() != DRE) {
John McCall4bc41ae2010-11-18 19:01:18 +00007831 S.Diag(OpLoc, diag::err_parens_pointer_member_function)
John McCall526ab472011-10-25 17:37:35 +00007832 << OrigOp.get()->getSourceRange();
John McCall8d08b9b2010-08-27 09:08:28 +00007833
7834 // The method was named without a qualifier.
7835 } else if (!DRE->getQualifier()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007836 S.Diag(OpLoc, diag::err_unqualified_pointer_member_function)
John McCall8d08b9b2010-08-27 09:08:28 +00007837 << op->getSourceRange();
7838 }
7839
John McCall4bc41ae2010-11-18 19:01:18 +00007840 return S.Context.getMemberPointerType(op->getType(),
7841 S.Context.getTypeDeclType(MD->getParent()).getTypePtr());
John McCall8d08b9b2010-08-27 09:08:28 +00007842 } else if (lval != Expr::LV_Valid && lval != Expr::LV_IncompleteVoidType) {
Eli Friedmance7f9002009-05-16 23:27:50 +00007843 // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007844 // The operand must be either an l-value or a function designator
Eli Friedmance7f9002009-05-16 23:27:50 +00007845 if (!op->getType()->isFunctionType()) {
John McCall526ab472011-10-25 17:37:35 +00007846 // Use a special diagnostic for loads from property references.
John McCallfe96e0b2011-11-06 09:01:30 +00007847 if (isa<PseudoObjectExpr>(op)) {
John McCall526ab472011-10-25 17:37:35 +00007848 AddressOfError = AO_Property_Expansion;
7849 } else {
7850 // FIXME: emit more specific diag...
7851 S.Diag(OpLoc, diag::err_typecheck_invalid_lvalue_addrof)
7852 << op->getSourceRange();
7853 return QualType();
7854 }
Steve Naroff35d85152007-05-07 00:24:15 +00007855 }
John McCall086a4642010-11-24 05:12:34 +00007856 } else if (op->getObjectKind() == OK_BitField) { // C99 6.5.3.2p1
Eli Friedman3a1e6922009-04-20 08:23:18 +00007857 // The operand cannot be a bit-field
Richard Trieu5f376f62011-09-07 21:46:33 +00007858 AddressOfError = AO_Bit_Field;
John McCall086a4642010-11-24 05:12:34 +00007859 } else if (op->getObjectKind() == OK_VectorComponent) {
Eli Friedman3a1e6922009-04-20 08:23:18 +00007860 // The operand cannot be an element of a vector
Richard Trieu5f376f62011-09-07 21:46:33 +00007861 AddressOfError = AO_Vector_Element;
Steve Naroffb96e4ab62008-02-29 23:30:25 +00007862 } else if (dcl) { // C99 6.5.3.2p1
Mike Stump4e1f26a2009-02-19 03:04:26 +00007863 // We have an lvalue with a decl. Make sure the decl is not declared
Steve Naroff47500512007-04-19 23:00:49 +00007864 // with the register storage-class specifier.
7865 if (const VarDecl *vd = dyn_cast<VarDecl>(dcl)) {
Fariborz Jahaniane0fd5a92010-08-24 22:21:48 +00007866 // in C++ it is not error to take address of a register
7867 // variable (c++03 7.1.1P3)
John McCall8e7d6562010-08-26 03:08:43 +00007868 if (vd->getStorageClass() == SC_Register &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00007869 !S.getLangOpts().CPlusPlus) {
Richard Trieu5f376f62011-09-07 21:46:33 +00007870 AddressOfError = AO_Register_Variable;
Steve Naroff35d85152007-05-07 00:24:15 +00007871 }
John McCalld14a8642009-11-21 08:51:07 +00007872 } else if (isa<FunctionTemplateDecl>(dcl)) {
John McCall4bc41ae2010-11-18 19:01:18 +00007873 return S.Context.OverloadTy;
John McCallf3a88602011-02-03 08:15:49 +00007874 } else if (isa<FieldDecl>(dcl) || isa<IndirectFieldDecl>(dcl)) {
Douglas Gregor9aa8b552008-12-10 21:26:49 +00007875 // Okay: we can take the address of a field.
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007876 // Could be a pointer to member, though, if there is an explicit
7877 // scope qualifier for the class.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00007878 if (isa<DeclRefExpr>(op) && cast<DeclRefExpr>(op)->getQualifier()) {
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007879 DeclContext *Ctx = dcl->getDeclContext();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007880 if (Ctx && Ctx->isRecord()) {
John McCallf3a88602011-02-03 08:15:49 +00007881 if (dcl->getType()->isReferenceType()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007882 S.Diag(OpLoc,
7883 diag::err_cannot_form_pointer_to_member_of_reference_type)
John McCallf3a88602011-02-03 08:15:49 +00007884 << dcl->getDeclName() << dcl->getType();
Anders Carlsson0b675f52009-07-08 21:45:58 +00007885 return QualType();
7886 }
Mike Stump11289f42009-09-09 15:08:12 +00007887
Argyrios Kyrtzidis8322b422011-01-31 07:04:29 +00007888 while (cast<RecordDecl>(Ctx)->isAnonymousStructOrUnion())
7889 Ctx = Ctx->getParent();
John McCall4bc41ae2010-11-18 19:01:18 +00007890 return S.Context.getMemberPointerType(op->getType(),
7891 S.Context.getTypeDeclType(cast<RecordDecl>(Ctx)).getTypePtr());
Anders Carlsson0b675f52009-07-08 21:45:58 +00007892 }
Sebastian Redl3d3f75a2009-02-03 20:19:35 +00007893 }
Eli Friedman755c0c92011-08-26 20:28:17 +00007894 } else if (!isa<FunctionDecl>(dcl) && !isa<NonTypeTemplateParmDecl>(dcl))
David Blaikie83d382b2011-09-23 05:06:16 +00007895 llvm_unreachable("Unknown/unexpected decl type");
Steve Naroff47500512007-04-19 23:00:49 +00007896 }
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007897
Richard Trieu5f376f62011-09-07 21:46:33 +00007898 if (AddressOfError != AO_No_Error) {
7899 diagnoseAddressOfInvalidType(S, OpLoc, op, AddressOfError);
7900 return QualType();
7901 }
7902
Eli Friedmance7f9002009-05-16 23:27:50 +00007903 if (lval == Expr::LV_IncompleteVoidType) {
7904 // Taking the address of a void variable is technically illegal, but we
7905 // allow it in cases which are otherwise valid.
7906 // Example: "extern void x; void* y = &x;".
John McCall4bc41ae2010-11-18 19:01:18 +00007907 S.Diag(OpLoc, diag::ext_typecheck_addrof_void) << op->getSourceRange();
Eli Friedmance7f9002009-05-16 23:27:50 +00007908 }
7909
Steve Naroff47500512007-04-19 23:00:49 +00007910 // If the operand has type "type", the result has type "pointer to type".
Douglas Gregor0bdcb8a2010-07-29 16:05:45 +00007911 if (op->getType()->isObjCObjectType())
John McCall4bc41ae2010-11-18 19:01:18 +00007912 return S.Context.getObjCObjectPointerType(op->getType());
7913 return S.Context.getPointerType(op->getType());
Steve Naroff47500512007-04-19 23:00:49 +00007914}
7915
Chris Lattner9156f1b2010-07-05 19:17:26 +00007916/// CheckIndirectionOperand - Type check unary indirection (prefix '*').
John McCall4bc41ae2010-11-18 19:01:18 +00007917static QualType CheckIndirectionOperand(Sema &S, Expr *Op, ExprValueKind &VK,
7918 SourceLocation OpLoc) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007919 if (Op->isTypeDependent())
John McCall4bc41ae2010-11-18 19:01:18 +00007920 return S.Context.DependentTy;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00007921
John Wiegley01296292011-04-08 18:41:53 +00007922 ExprResult ConvResult = S.UsualUnaryConversions(Op);
7923 if (ConvResult.isInvalid())
7924 return QualType();
7925 Op = ConvResult.take();
Chris Lattner9156f1b2010-07-05 19:17:26 +00007926 QualType OpTy = Op->getType();
7927 QualType Result;
Argyrios Kyrtzidis69a2c922011-05-02 18:21:19 +00007928
7929 if (isa<CXXReinterpretCastExpr>(Op)) {
7930 QualType OpOrigType = Op->IgnoreParenCasts()->getType();
7931 S.CheckCompatibleReinterpretCast(OpOrigType, OpTy, /*IsDereference*/true,
7932 Op->getSourceRange());
7933 }
7934
Chris Lattner9156f1b2010-07-05 19:17:26 +00007935 // Note that per both C89 and C99, indirection is always legal, even if OpTy
7936 // is an incomplete type or void. It would be possible to warn about
7937 // dereferencing a void pointer, but it's completely well-defined, and such a
7938 // warning is unlikely to catch any mistakes.
7939 if (const PointerType *PT = OpTy->getAs<PointerType>())
7940 Result = PT->getPointeeType();
7941 else if (const ObjCObjectPointerType *OPT =
7942 OpTy->getAs<ObjCObjectPointerType>())
7943 Result = OPT->getPointeeType();
John McCall36226622010-10-12 02:09:17 +00007944 else {
John McCall3aef3d82011-04-10 19:13:55 +00007945 ExprResult PR = S.CheckPlaceholderExpr(Op);
John McCall36226622010-10-12 02:09:17 +00007946 if (PR.isInvalid()) return QualType();
John McCall4bc41ae2010-11-18 19:01:18 +00007947 if (PR.take() != Op)
7948 return CheckIndirectionOperand(S, PR.take(), VK, OpLoc);
John McCall36226622010-10-12 02:09:17 +00007949 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00007950
Chris Lattner9156f1b2010-07-05 19:17:26 +00007951 if (Result.isNull()) {
John McCall4bc41ae2010-11-18 19:01:18 +00007952 S.Diag(OpLoc, diag::err_typecheck_indirection_requires_pointer)
Chris Lattner9156f1b2010-07-05 19:17:26 +00007953 << OpTy << Op->getSourceRange();
7954 return QualType();
7955 }
John McCall4bc41ae2010-11-18 19:01:18 +00007956
7957 // Dereferences are usually l-values...
7958 VK = VK_LValue;
7959
7960 // ...except that certain expressions are never l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00007961 if (!S.getLangOpts().CPlusPlus && Result.isCForbiddenLValueType())
John McCall4bc41ae2010-11-18 19:01:18 +00007962 VK = VK_RValue;
Chris Lattner9156f1b2010-07-05 19:17:26 +00007963
7964 return Result;
Steve Naroff1926c832007-04-24 00:23:05 +00007965}
Steve Naroff218bc2b2007-05-04 21:54:46 +00007966
John McCalle3027922010-08-25 11:45:40 +00007967static inline BinaryOperatorKind ConvertTokenKindToBinaryOpcode(
Steve Naroff218bc2b2007-05-04 21:54:46 +00007968 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00007969 BinaryOperatorKind Opc;
Steve Naroff218bc2b2007-05-04 21:54:46 +00007970 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00007971 default: llvm_unreachable("Unknown binop!");
John McCalle3027922010-08-25 11:45:40 +00007972 case tok::periodstar: Opc = BO_PtrMemD; break;
7973 case tok::arrowstar: Opc = BO_PtrMemI; break;
7974 case tok::star: Opc = BO_Mul; break;
7975 case tok::slash: Opc = BO_Div; break;
7976 case tok::percent: Opc = BO_Rem; break;
7977 case tok::plus: Opc = BO_Add; break;
7978 case tok::minus: Opc = BO_Sub; break;
7979 case tok::lessless: Opc = BO_Shl; break;
7980 case tok::greatergreater: Opc = BO_Shr; break;
7981 case tok::lessequal: Opc = BO_LE; break;
7982 case tok::less: Opc = BO_LT; break;
7983 case tok::greaterequal: Opc = BO_GE; break;
7984 case tok::greater: Opc = BO_GT; break;
7985 case tok::exclaimequal: Opc = BO_NE; break;
7986 case tok::equalequal: Opc = BO_EQ; break;
7987 case tok::amp: Opc = BO_And; break;
7988 case tok::caret: Opc = BO_Xor; break;
7989 case tok::pipe: Opc = BO_Or; break;
7990 case tok::ampamp: Opc = BO_LAnd; break;
7991 case tok::pipepipe: Opc = BO_LOr; break;
7992 case tok::equal: Opc = BO_Assign; break;
7993 case tok::starequal: Opc = BO_MulAssign; break;
7994 case tok::slashequal: Opc = BO_DivAssign; break;
7995 case tok::percentequal: Opc = BO_RemAssign; break;
7996 case tok::plusequal: Opc = BO_AddAssign; break;
7997 case tok::minusequal: Opc = BO_SubAssign; break;
7998 case tok::lesslessequal: Opc = BO_ShlAssign; break;
7999 case tok::greatergreaterequal: Opc = BO_ShrAssign; break;
8000 case tok::ampequal: Opc = BO_AndAssign; break;
8001 case tok::caretequal: Opc = BO_XorAssign; break;
8002 case tok::pipeequal: Opc = BO_OrAssign; break;
8003 case tok::comma: Opc = BO_Comma; break;
Steve Naroff218bc2b2007-05-04 21:54:46 +00008004 }
8005 return Opc;
8006}
8007
John McCalle3027922010-08-25 11:45:40 +00008008static inline UnaryOperatorKind ConvertTokenKindToUnaryOpcode(
Steve Naroff35d85152007-05-07 00:24:15 +00008009 tok::TokenKind Kind) {
John McCalle3027922010-08-25 11:45:40 +00008010 UnaryOperatorKind Opc;
Steve Naroff35d85152007-05-07 00:24:15 +00008011 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00008012 default: llvm_unreachable("Unknown unary op!");
John McCalle3027922010-08-25 11:45:40 +00008013 case tok::plusplus: Opc = UO_PreInc; break;
8014 case tok::minusminus: Opc = UO_PreDec; break;
8015 case tok::amp: Opc = UO_AddrOf; break;
8016 case tok::star: Opc = UO_Deref; break;
8017 case tok::plus: Opc = UO_Plus; break;
8018 case tok::minus: Opc = UO_Minus; break;
8019 case tok::tilde: Opc = UO_Not; break;
8020 case tok::exclaim: Opc = UO_LNot; break;
8021 case tok::kw___real: Opc = UO_Real; break;
8022 case tok::kw___imag: Opc = UO_Imag; break;
8023 case tok::kw___extension__: Opc = UO_Extension; break;
Steve Naroff35d85152007-05-07 00:24:15 +00008024 }
8025 return Opc;
8026}
8027
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008028/// DiagnoseSelfAssignment - Emits a warning if a value is assigned to itself.
8029/// This warning is only emitted for builtin assignment operations. It is also
8030/// suppressed in the event of macro expansions.
Richard Trieuda4f43a62011-09-07 01:33:52 +00008031static void DiagnoseSelfAssignment(Sema &S, Expr *LHSExpr, Expr *RHSExpr,
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008032 SourceLocation OpLoc) {
8033 if (!S.ActiveTemplateInstantiations.empty())
8034 return;
8035 if (OpLoc.isInvalid() || OpLoc.isMacroID())
8036 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008037 LHSExpr = LHSExpr->IgnoreParenImpCasts();
8038 RHSExpr = RHSExpr->IgnoreParenImpCasts();
8039 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
8040 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
8041 if (!LHSDeclRef || !RHSDeclRef ||
8042 LHSDeclRef->getLocation().isMacroID() ||
8043 RHSDeclRef->getLocation().isMacroID())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008044 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008045 const ValueDecl *LHSDecl =
8046 cast<ValueDecl>(LHSDeclRef->getDecl()->getCanonicalDecl());
8047 const ValueDecl *RHSDecl =
8048 cast<ValueDecl>(RHSDeclRef->getDecl()->getCanonicalDecl());
8049 if (LHSDecl != RHSDecl)
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008050 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008051 if (LHSDecl->getType().isVolatileQualified())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008052 return;
Richard Trieuda4f43a62011-09-07 01:33:52 +00008053 if (const ReferenceType *RefTy = LHSDecl->getType()->getAs<ReferenceType>())
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008054 if (RefTy->getPointeeType().isVolatileQualified())
8055 return;
8056
8057 S.Diag(OpLoc, diag::warn_self_assignment)
Richard Trieuda4f43a62011-09-07 01:33:52 +00008058 << LHSDeclRef->getType()
8059 << LHSExpr->getSourceRange() << RHSExpr->getSourceRange();
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008060}
8061
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008062/// CreateBuiltinBinOp - Creates a new built-in binary operation with
8063/// operator @p Opc at location @c TokLoc. This routine only supports
8064/// built-in operations; ActOnBinOp handles overloaded operators.
John McCalldadc5752010-08-24 06:29:42 +00008065ExprResult Sema::CreateBuiltinBinOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008066 BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008067 Expr *LHSExpr, Expr *RHSExpr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008068 if (getLangOpts().CPlusPlus0x && isa<InitListExpr>(RHSExpr)) {
Sebastian Redl67766732012-02-27 20:34:02 +00008069 // The syntax only allows initializer lists on the RHS of assignment,
8070 // so we don't need to worry about accepting invalid code for
8071 // non-assignment operators.
8072 // C++11 5.17p9:
8073 // The meaning of x = {v} [...] is that of x = T(v) [...]. The meaning
8074 // of x = {} is x = T().
8075 InitializationKind Kind =
8076 InitializationKind::CreateDirectList(RHSExpr->getLocStart());
8077 InitializedEntity Entity =
8078 InitializedEntity::InitializeTemporary(LHSExpr->getType());
8079 InitializationSequence InitSeq(*this, Entity, Kind, &RHSExpr, 1);
8080 ExprResult Init = InitSeq.Perform(*this, Entity, Kind,
8081 MultiExprArg(&RHSExpr, 1));
8082 if (Init.isInvalid())
8083 return Init;
8084 RHSExpr = Init.take();
8085 }
8086
Richard Trieu4a287fb2011-09-07 01:49:20 +00008087 ExprResult LHS = Owned(LHSExpr), RHS = Owned(RHSExpr);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008088 QualType ResultTy; // Result type of the binary operator.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008089 // The following two variables are used for compound assignment operators
8090 QualType CompLHSTy; // Type of LHS after promotions for computation
8091 QualType CompResultTy; // Type of computation result
John McCall7decc9e2010-11-18 06:31:45 +00008092 ExprValueKind VK = VK_RValue;
8093 ExprObjectKind OK = OK_Ordinary;
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008094
8095 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008096 case BO_Assign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008097 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, QualType());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008098 if (getLangOpts().CPlusPlus &&
Richard Trieu4a287fb2011-09-07 01:49:20 +00008099 LHS.get()->getObjectKind() != OK_ObjCProperty) {
8100 VK = LHS.get()->getValueKind();
8101 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008102 }
Chandler Carruthe0cee6a2011-01-04 06:52:15 +00008103 if (!ResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008104 DiagnoseSelfAssignment(*this, LHS.get(), RHS.get(), OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008105 break;
John McCalle3027922010-08-25 11:45:40 +00008106 case BO_PtrMemD:
8107 case BO_PtrMemI:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008108 ResultTy = CheckPointerToMemberOperands(LHS, RHS, VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008109 Opc == BO_PtrMemI);
Sebastian Redl112a97662009-02-07 00:15:38 +00008110 break;
John McCalle3027922010-08-25 11:45:40 +00008111 case BO_Mul:
8112 case BO_Div:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008113 ResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, false,
John McCalle3027922010-08-25 11:45:40 +00008114 Opc == BO_Div);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008115 break;
John McCalle3027922010-08-25 11:45:40 +00008116 case BO_Rem:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008117 ResultTy = CheckRemainderOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008118 break;
John McCalle3027922010-08-25 11:45:40 +00008119 case BO_Add:
Nico Weberccec40d2012-03-02 22:01:22 +00008120 ResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008121 break;
John McCalle3027922010-08-25 11:45:40 +00008122 case BO_Sub:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008123 ResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008124 break;
John McCalle3027922010-08-25 11:45:40 +00008125 case BO_Shl:
8126 case BO_Shr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008127 ResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008128 break;
John McCalle3027922010-08-25 11:45:40 +00008129 case BO_LE:
8130 case BO_LT:
8131 case BO_GE:
8132 case BO_GT:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008133 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, true);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008134 break;
John McCalle3027922010-08-25 11:45:40 +00008135 case BO_EQ:
8136 case BO_NE:
Jordan Rosed49a33e2012-06-08 21:14:25 +00008137 if (isObjCObjectLiteral(LHS) || isObjCObjectLiteral(RHS)) {
8138 ExprResult IsEqualCall = fixObjCLiteralComparison(*this, OpLoc,
8139 LHS, RHS, Opc);
8140 if (IsEqualCall.isUsable())
8141 return IsEqualCall;
8142 // Otherwise, fall back to the normal diagnostic in CheckCompareOperands.
8143 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008144 ResultTy = CheckCompareOperands(LHS, RHS, OpLoc, Opc, false);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008145 break;
John McCalle3027922010-08-25 11:45:40 +00008146 case BO_And:
8147 case BO_Xor:
8148 case BO_Or:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008149 ResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008150 break;
John McCalle3027922010-08-25 11:45:40 +00008151 case BO_LAnd:
8152 case BO_LOr:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008153 ResultTy = CheckLogicalOperands(LHS, RHS, OpLoc, Opc);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008154 break;
John McCalle3027922010-08-25 11:45:40 +00008155 case BO_MulAssign:
8156 case BO_DivAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008157 CompResultTy = CheckMultiplyDivideOperands(LHS, RHS, OpLoc, true,
John McCall7decc9e2010-11-18 06:31:45 +00008158 Opc == BO_DivAssign);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008159 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008160 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8161 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008162 break;
John McCalle3027922010-08-25 11:45:40 +00008163 case BO_RemAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008164 CompResultTy = CheckRemainderOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008165 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008166 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8167 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008168 break;
John McCalle3027922010-08-25 11:45:40 +00008169 case BO_AddAssign:
Nico Weberccec40d2012-03-02 22:01:22 +00008170 CompResultTy = CheckAdditionOperands(LHS, RHS, OpLoc, Opc, &CompLHSTy);
Richard Trieu4a287fb2011-09-07 01:49:20 +00008171 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8172 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008173 break;
John McCalle3027922010-08-25 11:45:40 +00008174 case BO_SubAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008175 CompResultTy = CheckSubtractionOperands(LHS, RHS, OpLoc, &CompLHSTy);
8176 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8177 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008178 break;
John McCalle3027922010-08-25 11:45:40 +00008179 case BO_ShlAssign:
8180 case BO_ShrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008181 CompResultTy = CheckShiftOperands(LHS, RHS, OpLoc, Opc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008182 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008183 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8184 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008185 break;
John McCalle3027922010-08-25 11:45:40 +00008186 case BO_AndAssign:
8187 case BO_XorAssign:
8188 case BO_OrAssign:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008189 CompResultTy = CheckBitwiseOperands(LHS, RHS, OpLoc, true);
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008190 CompLHSTy = CompResultTy;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008191 if (!CompResultTy.isNull() && !LHS.isInvalid() && !RHS.isInvalid())
8192 ResultTy = CheckAssignmentOperands(LHS.get(), RHS, OpLoc, CompResultTy);
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008193 break;
John McCalle3027922010-08-25 11:45:40 +00008194 case BO_Comma:
Richard Trieu4a287fb2011-09-07 01:49:20 +00008195 ResultTy = CheckCommaOperands(*this, LHS, RHS, OpLoc);
David Blaikiebbafb8a2012-03-11 07:00:24 +00008196 if (getLangOpts().CPlusPlus && !RHS.isInvalid()) {
Richard Trieu4a287fb2011-09-07 01:49:20 +00008197 VK = RHS.get()->getValueKind();
8198 OK = RHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008199 }
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008200 break;
8201 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008202 if (ResultTy.isNull() || LHS.isInvalid() || RHS.isInvalid())
Sebastian Redlb5d49352009-01-19 22:31:54 +00008203 return ExprError();
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008204
8205 // Check for array bounds violations for both sides of the BinaryOperator
Richard Trieu4a287fb2011-09-07 01:49:20 +00008206 CheckArrayAccess(LHS.get());
8207 CheckArrayAccess(RHS.get());
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008208
Eli Friedman8b7b1b12009-03-28 01:22:36 +00008209 if (CompResultTy.isNull())
Richard Trieu4a287fb2011-09-07 01:49:20 +00008210 return Owned(new (Context) BinaryOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008211 ResultTy, VK, OK, OpLoc));
David Blaikiebbafb8a2012-03-11 07:00:24 +00008212 if (getLangOpts().CPlusPlus && LHS.get()->getObjectKind() !=
Richard Trieucfc491d2011-08-02 04:35:43 +00008213 OK_ObjCProperty) {
John McCall7decc9e2010-11-18 06:31:45 +00008214 VK = VK_LValue;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008215 OK = LHS.get()->getObjectKind();
John McCall7decc9e2010-11-18 06:31:45 +00008216 }
Richard Trieu4a287fb2011-09-07 01:49:20 +00008217 return Owned(new (Context) CompoundAssignOperator(LHS.take(), RHS.take(), Opc,
John Wiegley01296292011-04-08 18:41:53 +00008218 ResultTy, VK, OK, CompLHSTy,
John McCall7decc9e2010-11-18 06:31:45 +00008219 CompResultTy, OpLoc));
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008220}
8221
Sebastian Redl44615072009-10-27 12:10:02 +00008222/// DiagnoseBitwisePrecedence - Emit a warning when bitwise and comparison
8223/// operators are mixed in a way that suggests that the programmer forgot that
8224/// comparison operators have higher precedence. The most typical example of
8225/// such code is "flags & 0x0020 != 0", which is equivalent to "flags & 1".
John McCalle3027922010-08-25 11:45:40 +00008226static void DiagnoseBitwisePrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieu4a287fb2011-09-07 01:49:20 +00008227 SourceLocation OpLoc, Expr *LHSExpr,
8228 Expr *RHSExpr) {
Sebastian Redl44615072009-10-27 12:10:02 +00008229 typedef BinaryOperator BinOp;
Richard Trieu4a287fb2011-09-07 01:49:20 +00008230 BinOp::Opcode LHSopc = static_cast<BinOp::Opcode>(-1),
8231 RHSopc = static_cast<BinOp::Opcode>(-1);
8232 if (BinOp *BO = dyn_cast<BinOp>(LHSExpr))
8233 LHSopc = BO->getOpcode();
8234 if (BinOp *BO = dyn_cast<BinOp>(RHSExpr))
8235 RHSopc = BO->getOpcode();
Sebastian Redl43028242009-10-26 15:24:15 +00008236
8237 // Subs are not binary operators.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008238 if (LHSopc == -1 && RHSopc == -1)
Sebastian Redl43028242009-10-26 15:24:15 +00008239 return;
8240
8241 // Bitwise operations are sometimes used as eager logical ops.
8242 // Don't diagnose this.
Richard Trieu4a287fb2011-09-07 01:49:20 +00008243 if ((BinOp::isComparisonOp(LHSopc) || BinOp::isBitwiseOp(LHSopc)) &&
8244 (BinOp::isComparisonOp(RHSopc) || BinOp::isBitwiseOp(RHSopc)))
Sebastian Redl43028242009-10-26 15:24:15 +00008245 return;
8246
Richard Trieu4a287fb2011-09-07 01:49:20 +00008247 bool isLeftComp = BinOp::isComparisonOp(LHSopc);
8248 bool isRightComp = BinOp::isComparisonOp(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008249 if (!isLeftComp && !isRightComp) return;
8250
Richard Trieu4a287fb2011-09-07 01:49:20 +00008251 SourceRange DiagRange = isLeftComp ? SourceRange(LHSExpr->getLocStart(),
8252 OpLoc)
8253 : SourceRange(OpLoc, RHSExpr->getLocEnd());
8254 std::string OpStr = isLeftComp ? BinOp::getOpcodeStr(LHSopc)
8255 : BinOp::getOpcodeStr(RHSopc);
Richard Trieu73088052011-08-10 22:41:34 +00008256 SourceRange ParensRange = isLeftComp ?
Richard Trieu4a287fb2011-09-07 01:49:20 +00008257 SourceRange(cast<BinOp>(LHSExpr)->getRHS()->getLocStart(),
8258 RHSExpr->getLocEnd())
8259 : SourceRange(LHSExpr->getLocStart(),
8260 cast<BinOp>(RHSExpr)->getLHS()->getLocStart());
Richard Trieu73088052011-08-10 22:41:34 +00008261
8262 Self.Diag(OpLoc, diag::warn_precedence_bitwise_rel)
8263 << DiagRange << BinOp::getOpcodeStr(Opc) << OpStr;
8264 SuggestParentheses(Self, OpLoc,
8265 Self.PDiag(diag::note_precedence_bitwise_silence) << OpStr,
Nico Webercdfb1ae2012-06-03 07:07:00 +00008266 (isLeftComp ? LHSExpr : RHSExpr)->getSourceRange());
Richard Trieu73088052011-08-10 22:41:34 +00008267 SuggestParentheses(Self, OpLoc,
8268 Self.PDiag(diag::note_precedence_bitwise_first) << BinOp::getOpcodeStr(Opc),
8269 ParensRange);
Sebastian Redl43028242009-10-26 15:24:15 +00008270}
8271
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008272/// \brief It accepts a '&' expr that is inside a '|' one.
8273/// Emit a diagnostic together with a fixit hint that wraps the '&' expression
8274/// in parentheses.
8275static void
8276EmitDiagnosticForBitwiseAndInBitwiseOr(Sema &Self, SourceLocation OpLoc,
8277 BinaryOperator *Bop) {
8278 assert(Bop->getOpcode() == BO_And);
8279 Self.Diag(Bop->getOperatorLoc(), diag::warn_bitwise_and_in_bitwise_or)
8280 << Bop->getSourceRange() << OpLoc;
8281 SuggestParentheses(Self, Bop->getOperatorLoc(),
8282 Self.PDiag(diag::note_bitwise_and_in_bitwise_or_silence),
8283 Bop->getSourceRange());
8284}
8285
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008286/// \brief It accepts a '&&' expr that is inside a '||' one.
8287/// Emit a diagnostic together with a fixit hint that wraps the '&&' expression
8288/// in parentheses.
8289static void
8290EmitDiagnosticForLogicalAndInLogicalOr(Sema &Self, SourceLocation OpLoc,
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008291 BinaryOperator *Bop) {
8292 assert(Bop->getOpcode() == BO_LAnd);
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008293 Self.Diag(Bop->getOperatorLoc(), diag::warn_logical_and_in_logical_or)
8294 << Bop->getSourceRange() << OpLoc;
Argyrios Kyrtzidisad8b4d42011-04-22 19:16:27 +00008295 SuggestParentheses(Self, Bop->getOperatorLoc(),
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008296 Self.PDiag(diag::note_logical_and_in_logical_or_silence),
Chandler Carruthb00e8c02011-06-16 01:05:14 +00008297 Bop->getSourceRange());
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008298}
8299
8300/// \brief Returns true if the given expression can be evaluated as a constant
8301/// 'true'.
8302static bool EvaluatesAsTrue(Sema &S, Expr *E) {
8303 bool Res;
8304 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && Res;
8305}
8306
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008307/// \brief Returns true if the given expression can be evaluated as a constant
8308/// 'false'.
8309static bool EvaluatesAsFalse(Sema &S, Expr *E) {
8310 bool Res;
8311 return E->EvaluateAsBooleanCondition(Res, S.getASTContext()) && !Res;
8312}
8313
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008314/// \brief Look for '&&' in the left hand of a '||' expr.
8315static void DiagnoseLogicalAndInLogicalOrLHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008316 Expr *LHSExpr, Expr *RHSExpr) {
8317 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(LHSExpr)) {
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008318 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008319 // If it's "a && b || 0" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008320 if (EvaluatesAsFalse(S, RHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008321 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008322 // If it's "1 && a || b" don't warn since the precedence doesn't matter.
8323 if (!EvaluatesAsTrue(S, Bop->getLHS()))
8324 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
8325 } else if (Bop->getOpcode() == BO_LOr) {
8326 if (BinaryOperator *RBop = dyn_cast<BinaryOperator>(Bop->getRHS())) {
8327 // If it's "a || b && 1 || c" we didn't warn earlier for
8328 // "a || b && 1", but warn now.
8329 if (RBop->getOpcode() == BO_LAnd && EvaluatesAsTrue(S, RBop->getRHS()))
8330 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, RBop);
8331 }
8332 }
8333 }
8334}
8335
8336/// \brief Look for '&&' in the right hand of a '||' expr.
8337static void DiagnoseLogicalAndInLogicalOrRHS(Sema &S, SourceLocation OpLoc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008338 Expr *LHSExpr, Expr *RHSExpr) {
8339 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(RHSExpr)) {
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008340 if (Bop->getOpcode() == BO_LAnd) {
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008341 // If it's "0 || a && b" don't warn since the precedence doesn't matter.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008342 if (EvaluatesAsFalse(S, LHSExpr))
Argyrios Kyrtzidis56e879d2010-11-17 19:18:19 +00008343 return;
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008344 // If it's "a || b && 1" don't warn since the precedence doesn't matter.
8345 if (!EvaluatesAsTrue(S, Bop->getRHS()))
8346 return EmitDiagnosticForLogicalAndInLogicalOr(S, OpLoc, Bop);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008347 }
8348 }
8349}
8350
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008351/// \brief Look for '&' in the left or right hand of a '|' expr.
8352static void DiagnoseBitwiseAndInBitwiseOr(Sema &S, SourceLocation OpLoc,
8353 Expr *OrArg) {
8354 if (BinaryOperator *Bop = dyn_cast<BinaryOperator>(OrArg)) {
8355 if (Bop->getOpcode() == BO_And)
8356 return EmitDiagnosticForBitwiseAndInBitwiseOr(S, OpLoc, Bop);
8357 }
8358}
8359
Sebastian Redl43028242009-10-26 15:24:15 +00008360/// DiagnoseBinOpPrecedence - Emit warnings for expressions with tricky
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008361/// precedence.
John McCalle3027922010-08-25 11:45:40 +00008362static void DiagnoseBinOpPrecedence(Sema &Self, BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008363 SourceLocation OpLoc, Expr *LHSExpr,
8364 Expr *RHSExpr){
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008365 // Diagnose "arg1 'bitwise' arg2 'eq' arg3".
Sebastian Redl44615072009-10-27 12:10:02 +00008366 if (BinaryOperator::isBitwiseOp(Opc))
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008367 DiagnoseBitwisePrecedence(Self, Opc, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008368
8369 // Diagnose "arg1 & arg2 | arg3"
8370 if (Opc == BO_Or && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008371 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, LHSExpr);
8372 DiagnoseBitwiseAndInBitwiseOr(Self, OpLoc, RHSExpr);
Argyrios Kyrtzidis01bf7772011-06-20 18:41:26 +00008373 }
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008374
Argyrios Kyrtzidis14a96622010-11-17 18:26:36 +00008375 // Warn about arg1 || arg2 && arg3, as GCC 4.3+ does.
8376 // We don't warn for 'assert(a || b && "bad")' since this is safe.
Argyrios Kyrtzidisb94e5a32010-11-17 18:54:22 +00008377 if (Opc == BO_LOr && !OpLoc.isMacroID()/* Don't warn in macros. */) {
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008378 DiagnoseLogicalAndInLogicalOrLHS(Self, OpLoc, LHSExpr, RHSExpr);
8379 DiagnoseLogicalAndInLogicalOrRHS(Self, OpLoc, LHSExpr, RHSExpr);
Argyrios Kyrtzidisf89a56c2010-11-16 21:00:12 +00008380 }
Sebastian Redl43028242009-10-26 15:24:15 +00008381}
8382
Steve Naroff218bc2b2007-05-04 21:54:46 +00008383// Binary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008384ExprResult Sema::ActOnBinOp(Scope *S, SourceLocation TokLoc,
John McCalle3027922010-08-25 11:45:40 +00008385 tok::TokenKind Kind,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008386 Expr *LHSExpr, Expr *RHSExpr) {
John McCalle3027922010-08-25 11:45:40 +00008387 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Kind);
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008388 assert((LHSExpr != 0) && "ActOnBinOp(): missing left expression");
8389 assert((RHSExpr != 0) && "ActOnBinOp(): missing right expression");
Steve Naroff218bc2b2007-05-04 21:54:46 +00008390
Sebastian Redl43028242009-10-26 15:24:15 +00008391 // Emit warnings for tricky precedence issues, e.g. "bitfield & 0x4 == 0"
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008392 DiagnoseBinOpPrecedence(*this, Opc, TokLoc, LHSExpr, RHSExpr);
Sebastian Redl43028242009-10-26 15:24:15 +00008393
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008394 return BuildBinOp(S, TokLoc, Opc, LHSExpr, RHSExpr);
Douglas Gregor5287f092009-11-05 00:51:44 +00008395}
8396
John McCall526ab472011-10-25 17:37:35 +00008397/// Build an overloaded binary operator expression in the given scope.
8398static ExprResult BuildOverloadedBinOp(Sema &S, Scope *Sc, SourceLocation OpLoc,
8399 BinaryOperatorKind Opc,
8400 Expr *LHS, Expr *RHS) {
8401 // Find all of the overloaded operators visible from this
8402 // point. We perform both an operator-name lookup from the local
8403 // scope and an argument-dependent lookup based on the types of
8404 // the arguments.
8405 UnresolvedSet<16> Functions;
8406 OverloadedOperatorKind OverOp
8407 = BinaryOperator::getOverloadedOperator(Opc);
8408 if (Sc && OverOp != OO_None)
8409 S.LookupOverloadedOperatorName(OverOp, Sc, LHS->getType(),
8410 RHS->getType(), Functions);
8411
8412 // Build the (potentially-overloaded, potentially-dependent)
8413 // binary operation.
8414 return S.CreateOverloadedBinOp(OpLoc, Opc, Functions, LHS, RHS);
8415}
8416
John McCalldadc5752010-08-24 06:29:42 +00008417ExprResult Sema::BuildBinOp(Scope *S, SourceLocation OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008418 BinaryOperatorKind Opc,
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008419 Expr *LHSExpr, Expr *RHSExpr) {
John McCall9a43e122011-10-28 01:04:34 +00008420 // We want to end up calling one of checkPseudoObjectAssignment
8421 // (if the LHS is a pseudo-object), BuildOverloadedBinOp (if
8422 // both expressions are overloadable or either is type-dependent),
8423 // or CreateBuiltinBinOp (in any other case). We also want to get
8424 // any placeholder types out of the way.
8425
John McCall526ab472011-10-25 17:37:35 +00008426 // Handle pseudo-objects in the LHS.
8427 if (const BuiltinType *pty = LHSExpr->getType()->getAsPlaceholderType()) {
8428 // Assignments with a pseudo-object l-value need special analysis.
8429 if (pty->getKind() == BuiltinType::PseudoObject &&
8430 BinaryOperator::isAssignmentOp(Opc))
8431 return checkPseudoObjectAssignment(S, OpLoc, Opc, LHSExpr, RHSExpr);
8432
8433 // Don't resolve overloads if the other type is overloadable.
8434 if (pty->getKind() == BuiltinType::Overload) {
8435 // We can't actually test that if we still have a placeholder,
8436 // though. Fortunately, none of the exceptions we see in that
John McCall9a43e122011-10-28 01:04:34 +00008437 // code below are valid when the LHS is an overload set. Note
8438 // that an overload set can be dependently-typed, but it never
8439 // instantiates to having an overloadable type.
John McCall526ab472011-10-25 17:37:35 +00008440 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8441 if (resolvedRHS.isInvalid()) return ExprError();
8442 RHSExpr = resolvedRHS.take();
8443
John McCall9a43e122011-10-28 01:04:34 +00008444 if (RHSExpr->isTypeDependent() ||
8445 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008446 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8447 }
8448
8449 ExprResult LHS = CheckPlaceholderExpr(LHSExpr);
8450 if (LHS.isInvalid()) return ExprError();
8451 LHSExpr = LHS.take();
8452 }
8453
8454 // Handle pseudo-objects in the RHS.
8455 if (const BuiltinType *pty = RHSExpr->getType()->getAsPlaceholderType()) {
8456 // An overload in the RHS can potentially be resolved by the type
8457 // being assigned to.
John McCall9a43e122011-10-28 01:04:34 +00008458 if (Opc == BO_Assign && pty->getKind() == BuiltinType::Overload) {
8459 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8460 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8461
Eli Friedman419b1ff2012-01-17 21:27:43 +00008462 if (LHSExpr->getType()->isOverloadableType())
8463 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8464
John McCall526ab472011-10-25 17:37:35 +00008465 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
John McCall9a43e122011-10-28 01:04:34 +00008466 }
John McCall526ab472011-10-25 17:37:35 +00008467
8468 // Don't resolve overloads if the other type is overloadable.
8469 if (pty->getKind() == BuiltinType::Overload &&
8470 LHSExpr->getType()->isOverloadableType())
8471 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
8472
8473 ExprResult resolvedRHS = CheckPlaceholderExpr(RHSExpr);
8474 if (!resolvedRHS.isUsable()) return ExprError();
8475 RHSExpr = resolvedRHS.take();
8476 }
8477
David Blaikiebbafb8a2012-03-11 07:00:24 +00008478 if (getLangOpts().CPlusPlus) {
John McCall9a43e122011-10-28 01:04:34 +00008479 // If either expression is type-dependent, always build an
8480 // overloaded op.
8481 if (LHSExpr->isTypeDependent() || RHSExpr->isTypeDependent())
8482 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008483
John McCall9a43e122011-10-28 01:04:34 +00008484 // Otherwise, build an overloaded op if either expression has an
8485 // overloadable type.
8486 if (LHSExpr->getType()->isOverloadableType() ||
8487 RHSExpr->getType()->isOverloadableType())
John McCall526ab472011-10-25 17:37:35 +00008488 return BuildOverloadedBinOp(*this, S, OpLoc, Opc, LHSExpr, RHSExpr);
Sebastian Redlb5d49352009-01-19 22:31:54 +00008489 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008490
Douglas Gregor7d5fc7e2008-11-06 23:29:22 +00008491 // Build a built-in binary operation.
Richard Trieuf9bd0f52011-09-07 02:02:10 +00008492 return CreateBuiltinBinOp(OpLoc, Opc, LHSExpr, RHSExpr);
Steve Naroff218bc2b2007-05-04 21:54:46 +00008493}
8494
John McCalldadc5752010-08-24 06:29:42 +00008495ExprResult Sema::CreateBuiltinUnaryOp(SourceLocation OpLoc,
Argyrios Kyrtzidis7a808c02011-01-05 20:09:36 +00008496 UnaryOperatorKind Opc,
John Wiegley01296292011-04-08 18:41:53 +00008497 Expr *InputExpr) {
8498 ExprResult Input = Owned(InputExpr);
John McCall7decc9e2010-11-18 06:31:45 +00008499 ExprValueKind VK = VK_RValue;
8500 ExprObjectKind OK = OK_Ordinary;
Steve Naroff35d85152007-05-07 00:24:15 +00008501 QualType resultType;
8502 switch (Opc) {
John McCalle3027922010-08-25 11:45:40 +00008503 case UO_PreInc:
8504 case UO_PreDec:
8505 case UO_PostInc:
8506 case UO_PostDec:
John Wiegley01296292011-04-08 18:41:53 +00008507 resultType = CheckIncrementDecrementOperand(*this, Input.get(), VK, OpLoc,
John McCalle3027922010-08-25 11:45:40 +00008508 Opc == UO_PreInc ||
8509 Opc == UO_PostInc,
8510 Opc == UO_PreInc ||
8511 Opc == UO_PreDec);
Steve Naroff35d85152007-05-07 00:24:15 +00008512 break;
John McCalle3027922010-08-25 11:45:40 +00008513 case UO_AddrOf:
John McCall526ab472011-10-25 17:37:35 +00008514 resultType = CheckAddressOfOperand(*this, Input, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008515 break;
John McCall31996342011-04-07 08:22:57 +00008516 case UO_Deref: {
John Wiegley01296292011-04-08 18:41:53 +00008517 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8518 resultType = CheckIndirectionOperand(*this, Input.get(), VK, OpLoc);
Steve Naroff35d85152007-05-07 00:24:15 +00008519 break;
John McCall31996342011-04-07 08:22:57 +00008520 }
John McCalle3027922010-08-25 11:45:40 +00008521 case UO_Plus:
8522 case UO_Minus:
John Wiegley01296292011-04-08 18:41:53 +00008523 Input = UsualUnaryConversions(Input.take());
8524 if (Input.isInvalid()) return ExprError();
8525 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008526 if (resultType->isDependentType())
8527 break;
Douglas Gregora3208f92010-06-22 23:41:02 +00008528 if (resultType->isArithmeticType() || // C99 6.5.3.3p1
8529 resultType->isVectorType())
Douglas Gregord08452f2008-11-19 15:42:04 +00008530 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008531 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6-7
Douglas Gregord08452f2008-11-19 15:42:04 +00008532 resultType->isEnumeralType())
8533 break;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008534 else if (getLangOpts().CPlusPlus && // C++ [expr.unary.op]p6
John McCalle3027922010-08-25 11:45:40 +00008535 Opc == UO_Plus &&
Douglas Gregord08452f2008-11-19 15:42:04 +00008536 resultType->isPointerType())
8537 break;
8538
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008539 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008540 << resultType << Input.get()->getSourceRange());
8541
John McCalle3027922010-08-25 11:45:40 +00008542 case UO_Not: // bitwise complement
John Wiegley01296292011-04-08 18:41:53 +00008543 Input = UsualUnaryConversions(Input.take());
8544 if (Input.isInvalid()) return ExprError();
8545 resultType = Input.get()->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008546 if (resultType->isDependentType())
8547 break;
Chris Lattner0d707612008-07-25 23:52:49 +00008548 // C99 6.5.3.3p1. We allow complex int and float as a GCC extension.
8549 if (resultType->isComplexType() || resultType->isComplexIntegerType())
8550 // C99 does not support '~' for complex conjugation.
Chris Lattner29e812b2008-11-20 06:06:08 +00008551 Diag(OpLoc, diag::ext_integer_complement_complex)
John Wiegley01296292011-04-08 18:41:53 +00008552 << resultType << Input.get()->getSourceRange();
John McCall36226622010-10-12 02:09:17 +00008553 else if (resultType->hasIntegerRepresentation())
8554 break;
John McCall526ab472011-10-25 17:37:35 +00008555 else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008556 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008557 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008558 }
Steve Naroff35d85152007-05-07 00:24:15 +00008559 break;
John Wiegley01296292011-04-08 18:41:53 +00008560
John McCalle3027922010-08-25 11:45:40 +00008561 case UO_LNot: // logical negation
Steve Naroff71b59a92007-06-04 22:22:31 +00008562 // Unlike +/-/~, integer promotions aren't done here (C99 6.5.3.3p5).
John Wiegley01296292011-04-08 18:41:53 +00008563 Input = DefaultFunctionArrayLvalueConversion(Input.take());
8564 if (Input.isInvalid()) return ExprError();
8565 resultType = Input.get()->getType();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00008566
8567 // Though we still have to promote half FP to float...
8568 if (resultType->isHalfType()) {
8569 Input = ImpCastExprToType(Input.take(), Context.FloatTy, CK_FloatingCast).take();
8570 resultType = Context.FloatTy;
8571 }
8572
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008573 if (resultType->isDependentType())
8574 break;
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008575 if (resultType->isScalarType()) {
8576 // C99 6.5.3.3p1: ok, fallthrough;
David Blaikiebbafb8a2012-03-11 07:00:24 +00008577 if (Context.getLangOpts().CPlusPlus) {
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008578 // C++03 [expr.unary.op]p8, C++0x [expr.unary.op]p9:
8579 // operand contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00008580 Input = ImpCastExprToType(Input.take(), Context.BoolTy,
8581 ScalarTypeToBooleanCastKind(resultType));
Abramo Bagnara7ccce982011-04-07 09:26:19 +00008582 }
Tanya Lattner3dd33b22012-01-19 01:16:16 +00008583 } else if (resultType->isExtVectorType()) {
Tanya Lattner20248222012-01-16 21:02:28 +00008584 // Vector logical not returns the signed variant of the operand type.
8585 resultType = GetSignedVectorType(resultType);
8586 break;
John McCall36226622010-10-12 02:09:17 +00008587 } else {
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008588 return ExprError(Diag(OpLoc, diag::err_typecheck_unary_expr)
John Wiegley01296292011-04-08 18:41:53 +00008589 << resultType << Input.get()->getSourceRange());
John McCall36226622010-10-12 02:09:17 +00008590 }
Douglas Gregordb8c6fd2010-09-20 17:13:33 +00008591
Chris Lattnerbe31ed82007-06-02 19:11:33 +00008592 // LNot always has type int. C99 6.5.3.3p5.
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008593 // In C++, it's bool. C++ 5.3.1p8
Argyrios Kyrtzidis1bdd6882011-02-18 20:55:15 +00008594 resultType = Context.getLogicalOperationType();
Steve Naroff35d85152007-05-07 00:24:15 +00008595 break;
John McCalle3027922010-08-25 11:45:40 +00008596 case UO_Real:
8597 case UO_Imag:
John McCall4bc41ae2010-11-18 19:01:18 +00008598 resultType = CheckRealImagOperand(*this, Input, OpLoc, Opc == UO_Real);
Richard Smith0b6b8e42012-02-18 20:53:32 +00008599 // _Real maps ordinary l-values into ordinary l-values. _Imag maps ordinary
8600 // complex l-values to ordinary l-values and all other values to r-values.
John Wiegley01296292011-04-08 18:41:53 +00008601 if (Input.isInvalid()) return ExprError();
Richard Smith0b6b8e42012-02-18 20:53:32 +00008602 if (Opc == UO_Real || Input.get()->getType()->isAnyComplexType()) {
8603 if (Input.get()->getValueKind() != VK_RValue &&
8604 Input.get()->getObjectKind() == OK_Ordinary)
8605 VK = Input.get()->getValueKind();
David Blaikiebbafb8a2012-03-11 07:00:24 +00008606 } else if (!getLangOpts().CPlusPlus) {
Richard Smith0b6b8e42012-02-18 20:53:32 +00008607 // In C, a volatile scalar is read by __imag. In C++, it is not.
8608 Input = DefaultLvalueConversion(Input.take());
8609 }
Chris Lattner30b5dd02007-08-24 21:16:53 +00008610 break;
John McCalle3027922010-08-25 11:45:40 +00008611 case UO_Extension:
John Wiegley01296292011-04-08 18:41:53 +00008612 resultType = Input.get()->getType();
8613 VK = Input.get()->getValueKind();
8614 OK = Input.get()->getObjectKind();
Steve Naroff043d45d2007-05-15 02:32:35 +00008615 break;
Steve Naroff35d85152007-05-07 00:24:15 +00008616 }
John Wiegley01296292011-04-08 18:41:53 +00008617 if (resultType.isNull() || Input.isInvalid())
Sebastian Redlc215cfc2009-01-19 00:08:26 +00008618 return ExprError();
Douglas Gregor084d8552009-03-13 23:49:33 +00008619
Kaelyn Uhrain2e7aa5a2011-08-05 23:18:04 +00008620 // Check for array bounds violations in the operand of the UnaryOperator,
8621 // except for the '*' and '&' operators that have to be handled specially
8622 // by CheckArrayAccess (as there are special cases like &array[arraysize]
8623 // that are explicitly defined as valid by the standard).
8624 if (Opc != UO_AddrOf && Opc != UO_Deref)
8625 CheckArrayAccess(Input.get());
8626
John Wiegley01296292011-04-08 18:41:53 +00008627 return Owned(new (Context) UnaryOperator(Input.take(), Opc, resultType,
John McCall7decc9e2010-11-18 06:31:45 +00008628 VK, OK, OpLoc));
Steve Naroff35d85152007-05-07 00:24:15 +00008629}
Chris Lattnereefa10e2007-05-28 06:56:27 +00008630
Douglas Gregor72341032011-12-14 21:23:13 +00008631/// \brief Determine whether the given expression is a qualified member
8632/// access expression, of a form that could be turned into a pointer to member
8633/// with the address-of operator.
8634static bool isQualifiedMemberAccess(Expr *E) {
8635 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
8636 if (!DRE->getQualifier())
8637 return false;
8638
8639 ValueDecl *VD = DRE->getDecl();
8640 if (!VD->isCXXClassMember())
8641 return false;
8642
8643 if (isa<FieldDecl>(VD) || isa<IndirectFieldDecl>(VD))
8644 return true;
8645 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(VD))
8646 return Method->isInstance();
8647
8648 return false;
8649 }
8650
8651 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
8652 if (!ULE->getQualifier())
8653 return false;
8654
8655 for (UnresolvedLookupExpr::decls_iterator D = ULE->decls_begin(),
8656 DEnd = ULE->decls_end();
8657 D != DEnd; ++D) {
8658 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*D)) {
8659 if (Method->isInstance())
8660 return true;
8661 } else {
8662 // Overload set does not contain methods.
8663 break;
8664 }
8665 }
8666
8667 return false;
8668 }
8669
8670 return false;
8671}
8672
John McCalldadc5752010-08-24 06:29:42 +00008673ExprResult Sema::BuildUnaryOp(Scope *S, SourceLocation OpLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00008674 UnaryOperatorKind Opc, Expr *Input) {
John McCall526ab472011-10-25 17:37:35 +00008675 // First things first: handle placeholders so that the
8676 // overloaded-operator check considers the right type.
8677 if (const BuiltinType *pty = Input->getType()->getAsPlaceholderType()) {
8678 // Increment and decrement of pseudo-object references.
8679 if (pty->getKind() == BuiltinType::PseudoObject &&
8680 UnaryOperator::isIncrementDecrementOp(Opc))
8681 return checkPseudoObjectIncDec(S, OpLoc, Opc, Input);
8682
8683 // extension is always a builtin operator.
8684 if (Opc == UO_Extension)
8685 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8686
8687 // & gets special logic for several kinds of placeholder.
8688 // The builtin code knows what to do.
8689 if (Opc == UO_AddrOf &&
8690 (pty->getKind() == BuiltinType::Overload ||
8691 pty->getKind() == BuiltinType::UnknownAny ||
8692 pty->getKind() == BuiltinType::BoundMember))
8693 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8694
8695 // Anything else needs to be handled now.
8696 ExprResult Result = CheckPlaceholderExpr(Input);
8697 if (Result.isInvalid()) return ExprError();
8698 Input = Result.take();
8699 }
8700
David Blaikiebbafb8a2012-03-11 07:00:24 +00008701 if (getLangOpts().CPlusPlus && Input->getType()->isOverloadableType() &&
Douglas Gregor72341032011-12-14 21:23:13 +00008702 UnaryOperator::getOverloadedOperator(Opc) != OO_None &&
8703 !(Opc == UO_AddrOf && isQualifiedMemberAccess(Input))) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008704 // Find all of the overloaded operators visible from this
8705 // point. We perform both an operator-name lookup from the local
8706 // scope and an argument-dependent lookup based on the types of
8707 // the arguments.
John McCall4c4c1df2010-01-26 03:27:55 +00008708 UnresolvedSet<16> Functions;
Douglas Gregor084d8552009-03-13 23:49:33 +00008709 OverloadedOperatorKind OverOp = UnaryOperator::getOverloadedOperator(Opc);
John McCall4c4c1df2010-01-26 03:27:55 +00008710 if (S && OverOp != OO_None)
8711 LookupOverloadedOperatorName(OverOp, S, Input->getType(), QualType(),
8712 Functions);
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008713
John McCallb268a282010-08-23 23:25:46 +00008714 return CreateOverloadedUnaryOp(OpLoc, Opc, Functions, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008715 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00008716
John McCallb268a282010-08-23 23:25:46 +00008717 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008718}
8719
Douglas Gregor5287f092009-11-05 00:51:44 +00008720// Unary Operators. 'Tok' is the token for the operator.
John McCalldadc5752010-08-24 06:29:42 +00008721ExprResult Sema::ActOnUnaryOp(Scope *S, SourceLocation OpLoc,
John McCall424cec92011-01-19 06:33:43 +00008722 tok::TokenKind Op, Expr *Input) {
John McCallb268a282010-08-23 23:25:46 +00008723 return BuildUnaryOp(S, OpLoc, ConvertTokenKindToUnaryOpcode(Op), Input);
Douglas Gregor5287f092009-11-05 00:51:44 +00008724}
8725
Steve Naroff66356bd2007-09-16 14:56:35 +00008726/// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo".
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008727ExprResult Sema::ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc,
Chris Lattnercab02a62011-02-17 20:34:02 +00008728 LabelDecl *TheDecl) {
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008729 TheDecl->setUsed();
Chris Lattnereefa10e2007-05-28 06:56:27 +00008730 // Create the AST node. The address of a label always has type 'void*'.
Chris Lattnerc8e630e2011-02-17 07:39:24 +00008731 return Owned(new (Context) AddrLabelExpr(OpLoc, LabLoc, TheDecl,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008732 Context.getPointerType(Context.VoidTy)));
Chris Lattnereefa10e2007-05-28 06:56:27 +00008733}
8734
John McCall31168b02011-06-15 23:02:42 +00008735/// Given the last statement in a statement-expression, check whether
8736/// the result is a producing expression (like a call to an
8737/// ns_returns_retained function) and, if so, rebuild it to hoist the
8738/// release out of the full-expression. Otherwise, return null.
8739/// Cannot fail.
Richard Trieuba63ce62011-09-09 01:45:06 +00008740static Expr *maybeRebuildARCConsumingStmt(Stmt *Statement) {
John McCall31168b02011-06-15 23:02:42 +00008741 // Should always be wrapped with one of these.
Richard Trieuba63ce62011-09-09 01:45:06 +00008742 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Statement);
John McCall31168b02011-06-15 23:02:42 +00008743 if (!cleanups) return 0;
8744
8745 ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(cleanups->getSubExpr());
John McCall2d637d22011-09-10 06:18:15 +00008746 if (!cast || cast->getCastKind() != CK_ARCConsumeObject)
John McCall31168b02011-06-15 23:02:42 +00008747 return 0;
8748
8749 // Splice out the cast. This shouldn't modify any interesting
8750 // features of the statement.
8751 Expr *producer = cast->getSubExpr();
8752 assert(producer->getType() == cast->getType());
8753 assert(producer->getValueKind() == cast->getValueKind());
8754 cleanups->setSubExpr(producer);
8755 return cleanups;
8756}
8757
John McCall3abee492012-04-04 01:27:53 +00008758void Sema::ActOnStartStmtExpr() {
8759 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
8760}
8761
8762void Sema::ActOnStmtExprError() {
John McCalled7b2782012-04-06 18:20:53 +00008763 // Note that function is also called by TreeTransform when leaving a
8764 // StmtExpr scope without rebuilding anything.
8765
John McCall3abee492012-04-04 01:27:53 +00008766 DiscardCleanupsInEvaluationContext();
8767 PopExpressionEvaluationContext();
8768}
8769
John McCalldadc5752010-08-24 06:29:42 +00008770ExprResult
John McCallb268a282010-08-23 23:25:46 +00008771Sema::ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008772 SourceLocation RPLoc) { // "({..})"
Chris Lattner366727f2007-07-24 16:58:17 +00008773 assert(SubStmt && isa<CompoundStmt>(SubStmt) && "Invalid action invocation!");
8774 CompoundStmt *Compound = cast<CompoundStmt>(SubStmt);
8775
John McCall3abee492012-04-04 01:27:53 +00008776 if (hasAnyUnrecoverableErrorsInThisFunction())
8777 DiscardCleanupsInEvaluationContext();
8778 assert(!ExprNeedsCleanups && "cleanups within StmtExpr not correctly bound!");
8779 PopExpressionEvaluationContext();
8780
Douglas Gregor6cf3f3c2010-03-10 04:54:39 +00008781 bool isFileScope
8782 = (getCurFunctionOrMethodDecl() == 0) && (getCurBlock() == 0);
Chris Lattnera69b0762009-04-25 19:11:05 +00008783 if (isFileScope)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00008784 return ExprError(Diag(LPLoc, diag::err_stmtexpr_file_scope));
Eli Friedman52cc0162009-01-24 23:09:00 +00008785
Chris Lattner366727f2007-07-24 16:58:17 +00008786 // FIXME: there are a variety of strange constraints to enforce here, for
8787 // example, it is not possible to goto into a stmt expression apparently.
8788 // More semantic analysis is needed.
Mike Stump4e1f26a2009-02-19 03:04:26 +00008789
Chris Lattner366727f2007-07-24 16:58:17 +00008790 // If there are sub stmts in the compound stmt, take the type of the last one
8791 // as the type of the stmtexpr.
8792 QualType Ty = Context.VoidTy;
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008793 bool StmtExprMayBindToTemp = false;
Chris Lattner944d3062008-07-26 19:51:01 +00008794 if (!Compound->body_empty()) {
8795 Stmt *LastStmt = Compound->body_back();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008796 LabelStmt *LastLabelStmt = 0;
Chris Lattner944d3062008-07-26 19:51:01 +00008797 // If LastStmt is a label, skip down through into the body.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008798 while (LabelStmt *Label = dyn_cast<LabelStmt>(LastStmt)) {
8799 LastLabelStmt = Label;
Chris Lattner944d3062008-07-26 19:51:01 +00008800 LastStmt = Label->getSubStmt();
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008801 }
John McCall31168b02011-06-15 23:02:42 +00008802
John Wiegley01296292011-04-08 18:41:53 +00008803 if (Expr *LastE = dyn_cast<Expr>(LastStmt)) {
John McCall34376a62010-12-04 03:47:34 +00008804 // Do function/array conversion on the last expression, but not
8805 // lvalue-to-rvalue. However, initialize an unqualified type.
John Wiegley01296292011-04-08 18:41:53 +00008806 ExprResult LastExpr = DefaultFunctionArrayConversion(LastE);
8807 if (LastExpr.isInvalid())
8808 return ExprError();
8809 Ty = LastExpr.get()->getType().getUnqualifiedType();
John McCall34376a62010-12-04 03:47:34 +00008810
John Wiegley01296292011-04-08 18:41:53 +00008811 if (!Ty->isDependentType() && !LastExpr.get()->isTypeDependent()) {
John McCall31168b02011-06-15 23:02:42 +00008812 // In ARC, if the final expression ends in a consume, splice
8813 // the consume out and bind it later. In the alternate case
8814 // (when dealing with a retainable type), the result
8815 // initialization will create a produce. In both cases the
8816 // result will be +1, and we'll need to balance that out with
8817 // a bind.
8818 if (Expr *rebuiltLastStmt
8819 = maybeRebuildARCConsumingStmt(LastExpr.get())) {
8820 LastExpr = rebuiltLastStmt;
8821 } else {
8822 LastExpr = PerformCopyInitialization(
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008823 InitializedEntity::InitializeResult(LPLoc,
8824 Ty,
8825 false),
8826 SourceLocation(),
John McCall31168b02011-06-15 23:02:42 +00008827 LastExpr);
8828 }
8829
John Wiegley01296292011-04-08 18:41:53 +00008830 if (LastExpr.isInvalid())
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008831 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008832 if (LastExpr.get() != 0) {
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008833 if (!LastLabelStmt)
John Wiegley01296292011-04-08 18:41:53 +00008834 Compound->setLastStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008835 else
John Wiegley01296292011-04-08 18:41:53 +00008836 LastLabelStmt->setSubStmt(LastExpr.take());
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008837 StmtExprMayBindToTemp = true;
8838 }
8839 }
8840 }
Chris Lattner944d3062008-07-26 19:51:01 +00008841 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00008842
Eli Friedmanba961a92009-03-23 00:24:07 +00008843 // FIXME: Check that expression type is complete/non-abstract; statement
8844 // expressions are not lvalues.
Fariborz Jahanian56143ae2010-10-25 23:27:26 +00008845 Expr *ResStmtExpr = new (Context) StmtExpr(Compound, Ty, LPLoc, RPLoc);
8846 if (StmtExprMayBindToTemp)
8847 return MaybeBindToTemporary(ResStmtExpr);
8848 return Owned(ResStmtExpr);
Chris Lattner366727f2007-07-24 16:58:17 +00008849}
Steve Naroff78864672007-08-01 22:05:33 +00008850
John McCalldadc5752010-08-24 06:29:42 +00008851ExprResult Sema::BuildBuiltinOffsetOf(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00008852 TypeSourceInfo *TInfo,
8853 OffsetOfComponent *CompPtr,
8854 unsigned NumComponents,
8855 SourceLocation RParenLoc) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008856 QualType ArgTy = TInfo->getType();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008857 bool Dependent = ArgTy->isDependentType();
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00008858 SourceRange TypeRange = TInfo->getTypeLoc().getLocalSourceRange();
Douglas Gregor882211c2010-04-28 22:16:22 +00008859
Chris Lattnerf17bd422007-08-30 17:45:32 +00008860 // We must have at least one component that refers to the type, and the first
8861 // one is known to be a field designator. Verify that the ArgTy represents
8862 // a struct/union/class.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00008863 if (!Dependent && !ArgTy->isRecordType())
Douglas Gregor882211c2010-04-28 22:16:22 +00008864 return ExprError(Diag(BuiltinLoc, diag::err_offsetof_record_type)
8865 << ArgTy << TypeRange);
8866
8867 // Type must be complete per C99 7.17p3 because a declaring a variable
8868 // with an incomplete type would be ill-formed.
8869 if (!Dependent
8870 && RequireCompleteType(BuiltinLoc, ArgTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00008871 diag::err_offsetof_incomplete_type, TypeRange))
Douglas Gregor882211c2010-04-28 22:16:22 +00008872 return ExprError();
8873
Chris Lattner78502cf2007-08-31 21:49:13 +00008874 // offsetof with non-identifier designators (e.g. "offsetof(x, a.b[c])") are a
8875 // GCC extension, diagnose them.
Eli Friedman988a16b2009-02-27 06:44:11 +00008876 // FIXME: This diagnostic isn't actually visible because the location is in
8877 // a system header!
Chris Lattner78502cf2007-08-31 21:49:13 +00008878 if (NumComponents != 1)
Chris Lattnerf490e152008-11-19 05:27:50 +00008879 Diag(BuiltinLoc, diag::ext_offsetof_extended_field_designator)
8880 << SourceRange(CompPtr[1].LocStart, CompPtr[NumComponents-1].LocEnd);
Douglas Gregor882211c2010-04-28 22:16:22 +00008881
8882 bool DidWarnAboutNonPOD = false;
8883 QualType CurrentType = ArgTy;
8884 typedef OffsetOfExpr::OffsetOfNode OffsetOfNode;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008885 SmallVector<OffsetOfNode, 4> Comps;
8886 SmallVector<Expr*, 4> Exprs;
Douglas Gregor882211c2010-04-28 22:16:22 +00008887 for (unsigned i = 0; i != NumComponents; ++i) {
8888 const OffsetOfComponent &OC = CompPtr[i];
8889 if (OC.isBrackets) {
8890 // Offset of an array sub-field. TODO: Should we allow vector elements?
8891 if (!CurrentType->isDependentType()) {
8892 const ArrayType *AT = Context.getAsArrayType(CurrentType);
8893 if(!AT)
8894 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_array_type)
8895 << CurrentType);
8896 CurrentType = AT->getElementType();
8897 } else
8898 CurrentType = Context.DependentTy;
8899
Richard Smith9fcc5c32011-10-17 23:29:39 +00008900 ExprResult IdxRval = DefaultLvalueConversion(static_cast<Expr*>(OC.U.E));
8901 if (IdxRval.isInvalid())
8902 return ExprError();
8903 Expr *Idx = IdxRval.take();
8904
Douglas Gregor882211c2010-04-28 22:16:22 +00008905 // The expression must be an integral expression.
8906 // FIXME: An integral constant expression?
Douglas Gregor882211c2010-04-28 22:16:22 +00008907 if (!Idx->isTypeDependent() && !Idx->isValueDependent() &&
8908 !Idx->getType()->isIntegerType())
8909 return ExprError(Diag(Idx->getLocStart(),
8910 diag::err_typecheck_subscript_not_integer)
8911 << Idx->getSourceRange());
Richard Smitheda612882011-10-17 05:48:07 +00008912
Douglas Gregor882211c2010-04-28 22:16:22 +00008913 // Record this array index.
8914 Comps.push_back(OffsetOfNode(OC.LocStart, Exprs.size(), OC.LocEnd));
Richard Smith9fcc5c32011-10-17 23:29:39 +00008915 Exprs.push_back(Idx);
Douglas Gregor882211c2010-04-28 22:16:22 +00008916 continue;
8917 }
8918
8919 // Offset of a field.
8920 if (CurrentType->isDependentType()) {
8921 // We have the offset of a field, but we can't look into the dependent
8922 // type. Just record the identifier of the field.
8923 Comps.push_back(OffsetOfNode(OC.LocStart, OC.U.IdentInfo, OC.LocEnd));
8924 CurrentType = Context.DependentTy;
8925 continue;
8926 }
8927
8928 // We need to have a complete type to look into.
8929 if (RequireCompleteType(OC.LocStart, CurrentType,
8930 diag::err_offsetof_incomplete_type))
8931 return ExprError();
8932
8933 // Look for the designated field.
8934 const RecordType *RC = CurrentType->getAs<RecordType>();
8935 if (!RC)
8936 return ExprError(Diag(OC.LocEnd, diag::err_offsetof_record_type)
8937 << CurrentType);
8938 RecordDecl *RD = RC->getDecl();
8939
8940 // C++ [lib.support.types]p5:
8941 // The macro offsetof accepts a restricted set of type arguments in this
8942 // International Standard. type shall be a POD structure or a POD union
8943 // (clause 9).
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008944 // C++11 [support.types]p4:
8945 // If type is not a standard-layout class (Clause 9), the results are
8946 // undefined.
Douglas Gregor882211c2010-04-28 22:16:22 +00008947 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008948 bool IsSafe = LangOpts.CPlusPlus0x? CRD->isStandardLayout() : CRD->isPOD();
8949 unsigned DiagID =
8950 LangOpts.CPlusPlus0x? diag::warn_offsetof_non_standardlayout_type
8951 : diag::warn_offsetof_non_pod_type;
8952
8953 if (!IsSafe && !DidWarnAboutNonPOD &&
Ted Kremenek55ae3192011-02-23 01:51:43 +00008954 DiagRuntimeBehavior(BuiltinLoc, 0,
Benjamin Kramer9e7876b2012-04-28 11:14:51 +00008955 PDiag(DiagID)
Douglas Gregor882211c2010-04-28 22:16:22 +00008956 << SourceRange(CompPtr[0].LocStart, OC.LocEnd)
8957 << CurrentType))
8958 DidWarnAboutNonPOD = true;
8959 }
8960
8961 // Look for the field.
8962 LookupResult R(*this, OC.U.IdentInfo, OC.LocStart, LookupMemberName);
8963 LookupQualifiedName(R, RD);
8964 FieldDecl *MemberDecl = R.getAsSingle<FieldDecl>();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008965 IndirectFieldDecl *IndirectMemberDecl = 0;
8966 if (!MemberDecl) {
Benjamin Kramer39593702010-11-21 14:11:41 +00008967 if ((IndirectMemberDecl = R.getAsSingle<IndirectFieldDecl>()))
Francois Pichet783dd6e2010-11-21 06:08:52 +00008968 MemberDecl = IndirectMemberDecl->getAnonField();
8969 }
8970
Douglas Gregor882211c2010-04-28 22:16:22 +00008971 if (!MemberDecl)
8972 return ExprError(Diag(BuiltinLoc, diag::err_no_member)
8973 << OC.U.IdentInfo << RD << SourceRange(OC.LocStart,
8974 OC.LocEnd));
8975
Douglas Gregor10982ea2010-04-28 22:36:06 +00008976 // C99 7.17p3:
8977 // (If the specified member is a bit-field, the behavior is undefined.)
8978 //
8979 // We diagnose this as an error.
Richard Smithcaf33902011-10-10 18:28:20 +00008980 if (MemberDecl->isBitField()) {
Douglas Gregor10982ea2010-04-28 22:36:06 +00008981 Diag(OC.LocEnd, diag::err_offsetof_bitfield)
8982 << MemberDecl->getDeclName()
8983 << SourceRange(BuiltinLoc, RParenLoc);
8984 Diag(MemberDecl->getLocation(), diag::note_bitfield_decl);
8985 return ExprError();
8986 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008987
8988 RecordDecl *Parent = MemberDecl->getParent();
Francois Pichet783dd6e2010-11-21 06:08:52 +00008989 if (IndirectMemberDecl)
8990 Parent = cast<RecordDecl>(IndirectMemberDecl->getDeclContext());
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008991
Douglas Gregord1702062010-04-29 00:18:15 +00008992 // If the member was found in a base class, introduce OffsetOfNodes for
8993 // the base class indirections.
8994 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
8995 /*DetectVirtual=*/false);
Eli Friedman74ef7cf2010-08-05 10:11:36 +00008996 if (IsDerivedFrom(CurrentType, Context.getTypeDeclType(Parent), Paths)) {
Douglas Gregord1702062010-04-29 00:18:15 +00008997 CXXBasePath &Path = Paths.front();
8998 for (CXXBasePath::iterator B = Path.begin(), BEnd = Path.end();
8999 B != BEnd; ++B)
9000 Comps.push_back(OffsetOfNode(B->Base));
9001 }
Eli Friedman74ef7cf2010-08-05 10:11:36 +00009002
Francois Pichet783dd6e2010-11-21 06:08:52 +00009003 if (IndirectMemberDecl) {
9004 for (IndirectFieldDecl::chain_iterator FI =
9005 IndirectMemberDecl->chain_begin(),
9006 FEnd = IndirectMemberDecl->chain_end(); FI != FEnd; FI++) {
9007 assert(isa<FieldDecl>(*FI));
9008 Comps.push_back(OffsetOfNode(OC.LocStart,
9009 cast<FieldDecl>(*FI), OC.LocEnd));
9010 }
9011 } else
Douglas Gregor882211c2010-04-28 22:16:22 +00009012 Comps.push_back(OffsetOfNode(OC.LocStart, MemberDecl, OC.LocEnd));
Francois Pichet783dd6e2010-11-21 06:08:52 +00009013
Douglas Gregor882211c2010-04-28 22:16:22 +00009014 CurrentType = MemberDecl->getType().getNonReferenceType();
9015 }
9016
9017 return Owned(OffsetOfExpr::Create(Context, Context.getSizeType(), BuiltinLoc,
9018 TInfo, Comps.data(), Comps.size(),
9019 Exprs.data(), Exprs.size(), RParenLoc));
9020}
Mike Stump4e1f26a2009-02-19 03:04:26 +00009021
John McCalldadc5752010-08-24 06:29:42 +00009022ExprResult Sema::ActOnBuiltinOffsetOf(Scope *S,
John McCall36226622010-10-12 02:09:17 +00009023 SourceLocation BuiltinLoc,
9024 SourceLocation TypeLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009025 ParsedType ParsedArgTy,
John McCall36226622010-10-12 02:09:17 +00009026 OffsetOfComponent *CompPtr,
9027 unsigned NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009028 SourceLocation RParenLoc) {
John McCall36226622010-10-12 02:09:17 +00009029
Douglas Gregor882211c2010-04-28 22:16:22 +00009030 TypeSourceInfo *ArgTInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009031 QualType ArgTy = GetTypeFromParser(ParsedArgTy, &ArgTInfo);
Douglas Gregor882211c2010-04-28 22:16:22 +00009032 if (ArgTy.isNull())
9033 return ExprError();
9034
Eli Friedman06dcfd92010-08-05 10:15:45 +00009035 if (!ArgTInfo)
9036 ArgTInfo = Context.getTrivialTypeSourceInfo(ArgTy, TypeLoc);
9037
9038 return BuildBuiltinOffsetOf(BuiltinLoc, ArgTInfo, CompPtr, NumComponents,
Richard Trieuba63ce62011-09-09 01:45:06 +00009039 RParenLoc);
Chris Lattnerf17bd422007-08-30 17:45:32 +00009040}
9041
9042
John McCalldadc5752010-08-24 06:29:42 +00009043ExprResult Sema::ActOnChooseExpr(SourceLocation BuiltinLoc,
John McCall36226622010-10-12 02:09:17 +00009044 Expr *CondExpr,
9045 Expr *LHSExpr, Expr *RHSExpr,
9046 SourceLocation RPLoc) {
Steve Naroff9efdabc2007-08-03 21:21:27 +00009047 assert((CondExpr && LHSExpr && RHSExpr) && "Missing type argument(s)");
9048
John McCall7decc9e2010-11-18 06:31:45 +00009049 ExprValueKind VK = VK_RValue;
9050 ExprObjectKind OK = OK_Ordinary;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009051 QualType resType;
Douglas Gregor56751b52009-09-25 04:25:58 +00009052 bool ValueDependent = false;
Douglas Gregor0df91122009-05-19 22:43:30 +00009053 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent()) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009054 resType = Context.DependentTy;
Douglas Gregor56751b52009-09-25 04:25:58 +00009055 ValueDependent = true;
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009056 } else {
9057 // The conditional expression is required to be a constant expression.
9058 llvm::APSInt condEval(32);
Douglas Gregore2b37442012-05-04 22:38:52 +00009059 ExprResult CondICE
9060 = VerifyIntegerConstantExpression(CondExpr, &condEval,
9061 diag::err_typecheck_choose_expr_requires_constant, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009062 if (CondICE.isInvalid())
9063 return ExprError();
9064 CondExpr = CondICE.take();
Steve Naroff9efdabc2007-08-03 21:21:27 +00009065
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009066 // If the condition is > zero, then the AST type is the same as the LSHExpr.
John McCall7decc9e2010-11-18 06:31:45 +00009067 Expr *ActiveExpr = condEval.getZExtValue() ? LHSExpr : RHSExpr;
9068
9069 resType = ActiveExpr->getType();
9070 ValueDependent = ActiveExpr->isValueDependent();
9071 VK = ActiveExpr->getValueKind();
9072 OK = ActiveExpr->getObjectKind();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00009073 }
9074
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009075 return Owned(new (Context) ChooseExpr(BuiltinLoc, CondExpr, LHSExpr, RHSExpr,
John McCall7decc9e2010-11-18 06:31:45 +00009076 resType, VK, OK, RPLoc,
Douglas Gregor56751b52009-09-25 04:25:58 +00009077 resType->isDependentType(),
9078 ValueDependent));
Steve Naroff9efdabc2007-08-03 21:21:27 +00009079}
9080
Steve Naroffc540d662008-09-03 18:15:37 +00009081//===----------------------------------------------------------------------===//
9082// Clang Extensions.
9083//===----------------------------------------------------------------------===//
9084
9085/// ActOnBlockStart - This callback is invoked when a block literal is started.
Richard Trieuba63ce62011-09-09 01:45:06 +00009086void Sema::ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope) {
Douglas Gregor9a28e842010-03-01 23:15:13 +00009087 BlockDecl *Block = BlockDecl::Create(Context, CurContext, CaretLoc);
Richard Trieuba63ce62011-09-09 01:45:06 +00009088 PushBlockScope(CurScope, Block);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009089 CurContext->addDecl(Block);
Richard Trieuba63ce62011-09-09 01:45:06 +00009090 if (CurScope)
9091 PushDeclContext(CurScope, Block);
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009092 else
9093 CurContext = Block;
John McCallf1a3c2a2011-11-11 03:19:12 +00009094
Eli Friedman34b49062012-01-26 03:00:14 +00009095 getCurBlock()->HasImplicitReturnType = true;
9096
John McCallf1a3c2a2011-11-11 03:19:12 +00009097 // Enter a new evaluation context to insulate the block from any
9098 // cleanups from the enclosing full-expression.
9099 PushExpressionEvaluationContext(PotentiallyEvaluated);
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009100}
9101
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009102void Sema::ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo,
9103 Scope *CurScope) {
Mike Stumpf70bcf72009-05-07 18:43:07 +00009104 assert(ParamInfo.getIdentifier()==0 && "block-id should have no identifier!");
John McCall3882ace2011-01-05 12:14:39 +00009105 assert(ParamInfo.getContext() == Declarator::BlockLiteralContext);
Douglas Gregor9a28e842010-03-01 23:15:13 +00009106 BlockScopeInfo *CurBlock = getCurBlock();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009107
John McCall8cb7bdf2010-06-04 23:28:52 +00009108 TypeSourceInfo *Sig = GetTypeForDeclarator(ParamInfo, CurScope);
John McCall8cb7bdf2010-06-04 23:28:52 +00009109 QualType T = Sig->getType();
Mike Stump82f071f2009-02-04 22:31:32 +00009110
Douglas Gregor7efd007c2012-06-15 16:59:29 +00009111 // FIXME: We should allow unexpanded parameter packs here, but that would,
9112 // in turn, make the block expression contain unexpanded parameter packs.
9113 if (DiagnoseUnexpandedParameterPack(CaretLoc, Sig, UPPC_Block)) {
9114 // Drop the parameters.
9115 FunctionProtoType::ExtProtoInfo EPI;
9116 EPI.HasTrailingReturn = false;
9117 EPI.TypeQuals |= DeclSpec::TQ_const;
9118 T = Context.getFunctionType(Context.DependentTy, /*Args=*/0, /*NumArgs=*/0,
9119 EPI);
9120 Sig = Context.getTrivialTypeSourceInfo(T);
9121 }
9122
John McCall3882ace2011-01-05 12:14:39 +00009123 // GetTypeForDeclarator always produces a function type for a block
9124 // literal signature. Furthermore, it is always a FunctionProtoType
9125 // unless the function was written with a typedef.
9126 assert(T->isFunctionType() &&
9127 "GetTypeForDeclarator made a non-function block signature");
9128
9129 // Look for an explicit signature in that function type.
9130 FunctionProtoTypeLoc ExplicitSignature;
9131
9132 TypeLoc tmp = Sig->getTypeLoc().IgnoreParens();
9133 if (isa<FunctionProtoTypeLoc>(tmp)) {
9134 ExplicitSignature = cast<FunctionProtoTypeLoc>(tmp);
9135
9136 // Check whether that explicit signature was synthesized by
9137 // GetTypeForDeclarator. If so, don't save that as part of the
9138 // written signature.
Abramo Bagnaraf2a79d92011-03-12 11:17:06 +00009139 if (ExplicitSignature.getLocalRangeBegin() ==
9140 ExplicitSignature.getLocalRangeEnd()) {
John McCall3882ace2011-01-05 12:14:39 +00009141 // This would be much cheaper if we stored TypeLocs instead of
9142 // TypeSourceInfos.
9143 TypeLoc Result = ExplicitSignature.getResultLoc();
9144 unsigned Size = Result.getFullDataSize();
9145 Sig = Context.CreateTypeSourceInfo(Result.getType(), Size);
9146 Sig->getTypeLoc().initializeFullCopy(Result, Size);
9147
9148 ExplicitSignature = FunctionProtoTypeLoc();
9149 }
John McCalla3ccba02010-06-04 11:21:44 +00009150 }
Mike Stump11289f42009-09-09 15:08:12 +00009151
John McCall3882ace2011-01-05 12:14:39 +00009152 CurBlock->TheDecl->setSignatureAsWritten(Sig);
9153 CurBlock->FunctionType = T;
9154
9155 const FunctionType *Fn = T->getAs<FunctionType>();
9156 QualType RetTy = Fn->getResultType();
9157 bool isVariadic =
9158 (isa<FunctionProtoType>(Fn) && cast<FunctionProtoType>(Fn)->isVariadic());
9159
John McCall8e346702010-06-04 19:02:56 +00009160 CurBlock->TheDecl->setIsVariadic(isVariadic);
Douglas Gregorb92a1562010-02-03 00:27:59 +00009161
John McCalla3ccba02010-06-04 11:21:44 +00009162 // Don't allow returning a objc interface by value.
9163 if (RetTy->isObjCObjectType()) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009164 Diag(ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009165 diag::err_object_cannot_be_passed_returned_by_value) << 0 << RetTy;
9166 return;
9167 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009168
John McCalla3ccba02010-06-04 11:21:44 +00009169 // Context.DependentTy is used as a placeholder for a missing block
John McCall8e346702010-06-04 19:02:56 +00009170 // return type. TODO: what should we do with declarators like:
9171 // ^ * { ... }
9172 // If the answer is "apply template argument deduction"....
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009173 if (RetTy != Context.DependentTy) {
John McCalla3ccba02010-06-04 11:21:44 +00009174 CurBlock->ReturnType = RetTy;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009175 CurBlock->TheDecl->setBlockMissingReturnType(false);
Eli Friedman34b49062012-01-26 03:00:14 +00009176 CurBlock->HasImplicitReturnType = false;
Fariborz Jahaniandd5eb9d2011-12-03 17:47:53 +00009177 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009178
John McCalla3ccba02010-06-04 11:21:44 +00009179 // Push block parameters from the declarator if we had them.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009180 SmallVector<ParmVarDecl*, 8> Params;
John McCall3882ace2011-01-05 12:14:39 +00009181 if (ExplicitSignature) {
9182 for (unsigned I = 0, E = ExplicitSignature.getNumArgs(); I != E; ++I) {
9183 ParmVarDecl *Param = ExplicitSignature.getArg(I);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009184 if (Param->getIdentifier() == 0 &&
9185 !Param->isImplicit() &&
9186 !Param->isInvalidDecl() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00009187 !getLangOpts().CPlusPlus)
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009188 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
John McCall8e346702010-06-04 19:02:56 +00009189 Params.push_back(Param);
Fariborz Jahanian5ec502e2010-02-12 21:53:14 +00009190 }
John McCalla3ccba02010-06-04 11:21:44 +00009191
9192 // Fake up parameter variables if we have a typedef, like
9193 // ^ fntype { ... }
9194 } else if (const FunctionProtoType *Fn = T->getAs<FunctionProtoType>()) {
9195 for (FunctionProtoType::arg_type_iterator
9196 I = Fn->arg_type_begin(), E = Fn->arg_type_end(); I != E; ++I) {
9197 ParmVarDecl *Param =
9198 BuildParmVarDeclForTypedef(CurBlock->TheDecl,
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009199 ParamInfo.getLocStart(),
John McCalla3ccba02010-06-04 11:21:44 +00009200 *I);
John McCall8e346702010-06-04 19:02:56 +00009201 Params.push_back(Param);
John McCalla3ccba02010-06-04 11:21:44 +00009202 }
Steve Naroffc540d662008-09-03 18:15:37 +00009203 }
John McCalla3ccba02010-06-04 11:21:44 +00009204
John McCall8e346702010-06-04 19:02:56 +00009205 // Set the parameters on the block decl.
Douglas Gregorb524d902010-11-01 18:37:59 +00009206 if (!Params.empty()) {
David Blaikie9c70e042011-09-21 18:16:56 +00009207 CurBlock->TheDecl->setParams(Params);
Douglas Gregorb524d902010-11-01 18:37:59 +00009208 CheckParmsForFunctionDef(CurBlock->TheDecl->param_begin(),
9209 CurBlock->TheDecl->param_end(),
9210 /*CheckParameterNames=*/false);
9211 }
9212
John McCalla3ccba02010-06-04 11:21:44 +00009213 // Finally we can process decl attributes.
Douglas Gregor758a8692009-06-17 21:51:59 +00009214 ProcessDeclAttributes(CurScope, CurBlock->TheDecl, ParamInfo);
John McCalldf8b37c2010-03-22 09:20:08 +00009215
John McCalla3ccba02010-06-04 11:21:44 +00009216 // Put the parameter variables in scope. We can bail out immediately
9217 // if we don't have any.
John McCall8e346702010-06-04 19:02:56 +00009218 if (Params.empty())
John McCalla3ccba02010-06-04 11:21:44 +00009219 return;
9220
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009221 for (BlockDecl::param_iterator AI = CurBlock->TheDecl->param_begin(),
John McCallf7b2fb52010-01-22 00:28:27 +00009222 E = CurBlock->TheDecl->param_end(); AI != E; ++AI) {
9223 (*AI)->setOwningFunction(CurBlock->TheDecl);
9224
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009225 // If this has an identifier, add it to the scope stack.
John McCalldf8b37c2010-03-22 09:20:08 +00009226 if ((*AI)->getIdentifier()) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +00009227 CheckShadow(CurBlock->TheScope, *AI);
John McCalldf8b37c2010-03-22 09:20:08 +00009228
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009229 PushOnScopeChains(*AI, CurBlock->TheScope);
John McCalldf8b37c2010-03-22 09:20:08 +00009230 }
John McCallf7b2fb52010-01-22 00:28:27 +00009231 }
Steve Naroffc540d662008-09-03 18:15:37 +00009232}
9233
9234/// ActOnBlockError - If there is an error parsing a block, this callback
9235/// is invoked to pop the information about the block from the action impl.
9236void Sema::ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope) {
John McCallf1a3c2a2011-11-11 03:19:12 +00009237 // Leave the expression-evaluation context.
9238 DiscardCleanupsInEvaluationContext();
9239 PopExpressionEvaluationContext();
9240
Steve Naroffc540d662008-09-03 18:15:37 +00009241 // Pop off CurBlock, handle nested blocks.
Chris Lattner41b86942009-04-21 22:38:46 +00009242 PopDeclContext();
Eli Friedman71c80552012-01-05 03:35:19 +00009243 PopFunctionScopeInfo();
Steve Naroffc540d662008-09-03 18:15:37 +00009244}
9245
9246/// ActOnBlockStmtExpr - This is called when the body of a block statement
9247/// literal was successfully completed. ^(int x){...}
John McCalldadc5752010-08-24 06:29:42 +00009248ExprResult Sema::ActOnBlockStmtExpr(SourceLocation CaretLoc,
Chris Lattner60f84492011-02-17 23:58:47 +00009249 Stmt *Body, Scope *CurScope) {
Chris Lattner9eac9312009-03-27 04:18:06 +00009250 // If blocks are disabled, emit an error.
9251 if (!LangOpts.Blocks)
9252 Diag(CaretLoc, diag::err_blocks_disable);
Mike Stump11289f42009-09-09 15:08:12 +00009253
John McCallf1a3c2a2011-11-11 03:19:12 +00009254 // Leave the expression-evaluation context.
John McCall85110b42012-03-08 22:00:17 +00009255 if (hasAnyUnrecoverableErrorsInThisFunction())
9256 DiscardCleanupsInEvaluationContext();
John McCallf1a3c2a2011-11-11 03:19:12 +00009257 assert(!ExprNeedsCleanups && "cleanups within block not correctly bound!");
9258 PopExpressionEvaluationContext();
9259
Douglas Gregor9a28e842010-03-01 23:15:13 +00009260 BlockScopeInfo *BSI = cast<BlockScopeInfo>(FunctionScopes.back());
Fariborz Jahanian1babe772010-07-09 18:44:02 +00009261
Steve Naroff1d95e5a2008-10-10 01:28:17 +00009262 PopDeclContext();
9263
Steve Naroffc540d662008-09-03 18:15:37 +00009264 QualType RetTy = Context.VoidTy;
Fariborz Jahanian3fd73102009-06-19 23:37:08 +00009265 if (!BSI->ReturnType.isNull())
9266 RetTy = BSI->ReturnType;
Mike Stump4e1f26a2009-02-19 03:04:26 +00009267
Mike Stump3bf1ab42009-07-28 22:04:01 +00009268 bool NoReturn = BSI->TheDecl->getAttr<NoReturnAttr>();
Steve Naroffc540d662008-09-03 18:15:37 +00009269 QualType BlockTy;
John McCall8e346702010-06-04 19:02:56 +00009270
John McCallc63de662011-02-02 13:00:07 +00009271 // Set the captured variables on the block.
Eli Friedman20139d32012-01-11 02:36:31 +00009272 // FIXME: Share capture structure between BlockDecl and CapturingScopeInfo!
9273 SmallVector<BlockDecl::Capture, 4> Captures;
9274 for (unsigned i = 0, e = BSI->Captures.size(); i != e; i++) {
9275 CapturingScopeInfo::Capture &Cap = BSI->Captures[i];
9276 if (Cap.isThisCapture())
9277 continue;
Eli Friedman24af8502012-02-03 22:47:37 +00009278 BlockDecl::Capture NewCap(Cap.getVariable(), Cap.isBlockCapture(),
Eli Friedman20139d32012-01-11 02:36:31 +00009279 Cap.isNested(), Cap.getCopyExpr());
9280 Captures.push_back(NewCap);
9281 }
9282 BSI->TheDecl->setCaptures(Context, Captures.begin(), Captures.end(),
9283 BSI->CXXThisCaptureIndex != 0);
John McCallc63de662011-02-02 13:00:07 +00009284
John McCall8e346702010-06-04 19:02:56 +00009285 // If the user wrote a function type in some form, try to use that.
9286 if (!BSI->FunctionType.isNull()) {
9287 const FunctionType *FTy = BSI->FunctionType->getAs<FunctionType>();
9288
9289 FunctionType::ExtInfo Ext = FTy->getExtInfo();
9290 if (NoReturn && !Ext.getNoReturn()) Ext = Ext.withNoReturn(true);
9291
9292 // Turn protoless block types into nullary block types.
9293 if (isa<FunctionNoProtoType>(FTy)) {
John McCalldb40c7f2010-12-14 08:05:40 +00009294 FunctionProtoType::ExtProtoInfo EPI;
9295 EPI.ExtInfo = Ext;
9296 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009297
9298 // Otherwise, if we don't need to change anything about the function type,
9299 // preserve its sugar structure.
9300 } else if (FTy->getResultType() == RetTy &&
9301 (!NoReturn || FTy->getNoReturnAttr())) {
9302 BlockTy = BSI->FunctionType;
9303
9304 // Otherwise, make the minimal modifications to the function type.
9305 } else {
9306 const FunctionProtoType *FPT = cast<FunctionProtoType>(FTy);
John McCalldb40c7f2010-12-14 08:05:40 +00009307 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9308 EPI.TypeQuals = 0; // FIXME: silently?
9309 EPI.ExtInfo = Ext;
John McCall8e346702010-06-04 19:02:56 +00009310 BlockTy = Context.getFunctionType(RetTy,
9311 FPT->arg_type_begin(),
9312 FPT->getNumArgs(),
John McCalldb40c7f2010-12-14 08:05:40 +00009313 EPI);
John McCall8e346702010-06-04 19:02:56 +00009314 }
9315
9316 // If we don't have a function type, just build one from nothing.
9317 } else {
John McCalldb40c7f2010-12-14 08:05:40 +00009318 FunctionProtoType::ExtProtoInfo EPI;
John McCall31168b02011-06-15 23:02:42 +00009319 EPI.ExtInfo = FunctionType::ExtInfo().withNoReturn(NoReturn);
John McCalldb40c7f2010-12-14 08:05:40 +00009320 BlockTy = Context.getFunctionType(RetTy, 0, 0, EPI);
John McCall8e346702010-06-04 19:02:56 +00009321 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009322
John McCall8e346702010-06-04 19:02:56 +00009323 DiagnoseUnusedParameters(BSI->TheDecl->param_begin(),
9324 BSI->TheDecl->param_end());
Steve Naroffc540d662008-09-03 18:15:37 +00009325 BlockTy = Context.getBlockPointerType(BlockTy);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009326
Chris Lattner45542ea2009-04-19 05:28:12 +00009327 // If needed, diagnose invalid gotos and switches in the block.
John McCall31168b02011-06-15 23:02:42 +00009328 if (getCurFunction()->NeedsScopeChecking() &&
9329 !hasAnyUnrecoverableErrorsInThisFunction())
John McCallb268a282010-08-23 23:25:46 +00009330 DiagnoseInvalidJumps(cast<CompoundStmt>(Body));
Mike Stump11289f42009-09-09 15:08:12 +00009331
Chris Lattner60f84492011-02-17 23:58:47 +00009332 BSI->TheDecl->setBody(cast<CompoundStmt>(Body));
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009333
Douglas Gregor49695f02011-09-06 20:46:03 +00009334 computeNRVO(Body, getCurBlock());
9335
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009336 BlockExpr *Result = new (Context) BlockExpr(BSI->TheDecl, BlockTy);
9337 const AnalysisBasedWarnings::Policy &WP = AnalysisWarnings.getDefaultPolicy();
Eli Friedman71c80552012-01-05 03:35:19 +00009338 PopFunctionScopeInfo(&WP, Result->getBlockDecl(), Result);
Benjamin Kramera4fb8362011-07-12 14:11:05 +00009339
John McCall28fc7092011-11-10 05:35:25 +00009340 // If the block isn't obviously global, i.e. it captures anything at
John McCalld2393872012-04-13 01:08:17 +00009341 // all, then we need to do a few things in the surrounding context:
John McCall28fc7092011-11-10 05:35:25 +00009342 if (Result->getBlockDecl()->hasCaptures()) {
John McCalld2393872012-04-13 01:08:17 +00009343 // First, this expression has a new cleanup object.
John McCall28fc7092011-11-10 05:35:25 +00009344 ExprCleanupObjects.push_back(Result->getBlockDecl());
9345 ExprNeedsCleanups = true;
John McCalld2393872012-04-13 01:08:17 +00009346
9347 // It also gets a branch-protected scope if any of the captured
9348 // variables needs destruction.
9349 for (BlockDecl::capture_const_iterator
9350 ci = Result->getBlockDecl()->capture_begin(),
9351 ce = Result->getBlockDecl()->capture_end(); ci != ce; ++ci) {
9352 const VarDecl *var = ci->getVariable();
9353 if (var->getType().isDestructedType() != QualType::DK_none) {
9354 getCurFunction()->setHasBranchProtectedScope();
9355 break;
9356 }
9357 }
John McCall28fc7092011-11-10 05:35:25 +00009358 }
Fariborz Jahanian197c68c2012-03-06 18:41:35 +00009359
Douglas Gregor9a28e842010-03-01 23:15:13 +00009360 return Owned(Result);
Steve Naroffc540d662008-09-03 18:15:37 +00009361}
9362
John McCalldadc5752010-08-24 06:29:42 +00009363ExprResult Sema::ActOnVAArg(SourceLocation BuiltinLoc,
Richard Trieuba63ce62011-09-09 01:45:06 +00009364 Expr *E, ParsedType Ty,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009365 SourceLocation RPLoc) {
Abramo Bagnara27db2392010-08-10 10:06:15 +00009366 TypeSourceInfo *TInfo;
Richard Trieuba63ce62011-09-09 01:45:06 +00009367 GetTypeFromParser(Ty, &TInfo);
9368 return BuildVAArgExpr(BuiltinLoc, E, TInfo, RPLoc);
Abramo Bagnara27db2392010-08-10 10:06:15 +00009369}
9370
John McCalldadc5752010-08-24 06:29:42 +00009371ExprResult Sema::BuildVAArgExpr(SourceLocation BuiltinLoc,
John McCall7decc9e2010-11-18 06:31:45 +00009372 Expr *E, TypeSourceInfo *TInfo,
9373 SourceLocation RPLoc) {
Chris Lattner56382aa2009-04-05 15:49:53 +00009374 Expr *OrigExpr = E;
Mike Stump11289f42009-09-09 15:08:12 +00009375
Eli Friedman121ba0c2008-08-09 23:32:40 +00009376 // Get the va_list type
9377 QualType VaListType = Context.getBuiltinVaListType();
Eli Friedmane2cad652009-05-16 12:46:54 +00009378 if (VaListType->isArrayType()) {
9379 // Deal with implicit array decay; for example, on x86-64,
9380 // va_list is an array, but it's supposed to decay to
9381 // a pointer for va_arg.
Eli Friedman121ba0c2008-08-09 23:32:40 +00009382 VaListType = Context.getArrayDecayedType(VaListType);
Eli Friedmane2cad652009-05-16 12:46:54 +00009383 // Make sure the input expression also decays appropriately.
John Wiegley01296292011-04-08 18:41:53 +00009384 ExprResult Result = UsualUnaryConversions(E);
9385 if (Result.isInvalid())
9386 return ExprError();
9387 E = Result.take();
Eli Friedmane2cad652009-05-16 12:46:54 +00009388 } else {
9389 // Otherwise, the va_list argument must be an l-value because
9390 // it is modified by va_arg.
Mike Stump11289f42009-09-09 15:08:12 +00009391 if (!E->isTypeDependent() &&
Douglas Gregorad3150c2009-05-19 23:10:31 +00009392 CheckForModifiableLvalue(E, BuiltinLoc, *this))
Eli Friedmane2cad652009-05-16 12:46:54 +00009393 return ExprError();
9394 }
Eli Friedman121ba0c2008-08-09 23:32:40 +00009395
Douglas Gregorad3150c2009-05-19 23:10:31 +00009396 if (!E->isTypeDependent() &&
9397 !Context.hasSameType(VaListType, E->getType())) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009398 return ExprError(Diag(E->getLocStart(),
9399 diag::err_first_argument_to_va_arg_not_of_type_va_list)
Chris Lattner56382aa2009-04-05 15:49:53 +00009400 << OrigExpr->getType() << E->getSourceRange());
Chris Lattner3f5cd772009-04-05 00:59:53 +00009401 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009402
David Majnemerc75d1a12011-06-14 05:17:32 +00009403 if (!TInfo->getType()->isDependentType()) {
9404 if (RequireCompleteType(TInfo->getTypeLoc().getBeginLoc(), TInfo->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00009405 diag::err_second_parameter_to_va_arg_incomplete,
9406 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009407 return ExprError();
David Majnemer254a5c02011-06-13 06:37:03 +00009408
David Majnemerc75d1a12011-06-14 05:17:32 +00009409 if (RequireNonAbstractType(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregorae298422012-05-04 17:09:59 +00009410 TInfo->getType(),
9411 diag::err_second_parameter_to_va_arg_abstract,
9412 TInfo->getTypeLoc()))
David Majnemerc75d1a12011-06-14 05:17:32 +00009413 return ExprError();
9414
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009415 if (!TInfo->getType().isPODType(Context)) {
David Majnemerc75d1a12011-06-14 05:17:32 +00009416 Diag(TInfo->getTypeLoc().getBeginLoc(),
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009417 TInfo->getType()->isObjCLifetimeType()
9418 ? diag::warn_second_parameter_to_va_arg_ownership_qualified
9419 : diag::warn_second_parameter_to_va_arg_not_pod)
David Majnemerc75d1a12011-06-14 05:17:32 +00009420 << TInfo->getType()
9421 << TInfo->getTypeLoc().getSourceRange();
Douglas Gregor7e1eb932011-07-30 06:45:27 +00009422 }
Eli Friedman6290ae42011-07-11 21:45:59 +00009423
9424 // Check for va_arg where arguments of the given type will be promoted
9425 // (i.e. this va_arg is guaranteed to have undefined behavior).
9426 QualType PromoteType;
9427 if (TInfo->getType()->isPromotableIntegerType()) {
9428 PromoteType = Context.getPromotedIntegerType(TInfo->getType());
9429 if (Context.typesAreCompatible(PromoteType, TInfo->getType()))
9430 PromoteType = QualType();
9431 }
9432 if (TInfo->getType()->isSpecificBuiltinType(BuiltinType::Float))
9433 PromoteType = Context.DoubleTy;
9434 if (!PromoteType.isNull())
9435 Diag(TInfo->getTypeLoc().getBeginLoc(),
9436 diag::warn_second_parameter_to_va_arg_never_compatible)
9437 << TInfo->getType()
9438 << PromoteType
9439 << TInfo->getTypeLoc().getSourceRange();
David Majnemerc75d1a12011-06-14 05:17:32 +00009440 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009441
Abramo Bagnara27db2392010-08-10 10:06:15 +00009442 QualType T = TInfo->getType().getNonLValueExprType(Context);
9443 return Owned(new (Context) VAArgExpr(BuiltinLoc, E, TInfo, RPLoc, T));
Anders Carlsson7e13ab82007-10-15 20:28:48 +00009444}
9445
John McCalldadc5752010-08-24 06:29:42 +00009446ExprResult Sema::ActOnGNUNullExpr(SourceLocation TokenLoc) {
Douglas Gregor3be4b122008-11-29 04:51:27 +00009447 // The type of __null will be int or long, depending on the size of
9448 // pointers on the target.
9449 QualType Ty;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009450 unsigned pw = Context.getTargetInfo().getPointerWidth(0);
9451 if (pw == Context.getTargetInfo().getIntWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009452 Ty = Context.IntTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009453 else if (pw == Context.getTargetInfo().getLongWidth())
Douglas Gregor3be4b122008-11-29 04:51:27 +00009454 Ty = Context.LongTy;
Douglas Gregore8bbc122011-09-02 00:18:52 +00009455 else if (pw == Context.getTargetInfo().getLongLongWidth())
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009456 Ty = Context.LongLongTy;
9457 else {
David Blaikie83d382b2011-09-23 05:06:16 +00009458 llvm_unreachable("I don't know size of pointer!");
NAKAMURA Takumi0d13fd32011-01-19 00:11:41 +00009459 }
Douglas Gregor3be4b122008-11-29 04:51:27 +00009460
Sebastian Redl6d4256c2009-03-15 17:47:39 +00009461 return Owned(new (Context) GNUNullExpr(Ty, TokenLoc));
Douglas Gregor3be4b122008-11-29 04:51:27 +00009462}
9463
Alexis Huntc46382e2010-04-28 23:02:27 +00009464static void MakeObjCStringLiteralFixItHint(Sema& SemaRef, QualType DstType,
Douglas Gregora771f462010-03-31 17:46:05 +00009465 Expr *SrcExpr, FixItHint &Hint) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009466 if (!SemaRef.getLangOpts().ObjC1)
Anders Carlssonace5d072009-11-10 04:46:30 +00009467 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009468
Anders Carlssonace5d072009-11-10 04:46:30 +00009469 const ObjCObjectPointerType *PT = DstType->getAs<ObjCObjectPointerType>();
9470 if (!PT)
9471 return;
9472
9473 // Check if the destination is of type 'id'.
9474 if (!PT->isObjCIdType()) {
9475 // Check if the destination is the 'NSString' interface.
9476 const ObjCInterfaceDecl *ID = PT->getInterfaceDecl();
9477 if (!ID || !ID->getIdentifier()->isStr("NSString"))
9478 return;
9479 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009480
John McCallfe96e0b2011-11-06 09:01:30 +00009481 // Ignore any parens, implicit casts (should only be
9482 // array-to-pointer decays), and not-so-opaque values. The last is
9483 // important for making this trigger for property assignments.
9484 SrcExpr = SrcExpr->IgnoreParenImpCasts();
9485 if (OpaqueValueExpr *OV = dyn_cast<OpaqueValueExpr>(SrcExpr))
9486 if (OV->getSourceExpr())
9487 SrcExpr = OV->getSourceExpr()->IgnoreParenImpCasts();
9488
9489 StringLiteral *SL = dyn_cast<StringLiteral>(SrcExpr);
Douglas Gregorfb65e592011-07-27 05:40:30 +00009490 if (!SL || !SL->isAscii())
Anders Carlssonace5d072009-11-10 04:46:30 +00009491 return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009492
Douglas Gregora771f462010-03-31 17:46:05 +00009493 Hint = FixItHint::CreateInsertion(SL->getLocStart(), "@");
Anders Carlssonace5d072009-11-10 04:46:30 +00009494}
9495
Chris Lattner9bad62c2008-01-04 18:04:52 +00009496bool Sema::DiagnoseAssignmentResult(AssignConvertType ConvTy,
9497 SourceLocation Loc,
9498 QualType DstType, QualType SrcType,
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009499 Expr *SrcExpr, AssignmentAction Action,
9500 bool *Complained) {
9501 if (Complained)
9502 *Complained = false;
9503
Chris Lattner9bad62c2008-01-04 18:04:52 +00009504 // Decode the result (notice that AST's are still created for extensions).
Douglas Gregor33823722011-06-11 01:09:30 +00009505 bool CheckInferredResultType = false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009506 bool isInvalid = false;
Eli Friedman381f4312012-02-29 20:59:56 +00009507 unsigned DiagKind = 0;
Douglas Gregora771f462010-03-31 17:46:05 +00009508 FixItHint Hint;
Anna Zaks3b402712011-07-28 19:51:27 +00009509 ConversionFixItGenerator ConvHints;
9510 bool MayHaveConvFixit = false;
Richard Trieucaff2472011-11-23 22:32:32 +00009511 bool MayHaveFunctionDiff = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +00009512
Chris Lattner9bad62c2008-01-04 18:04:52 +00009513 switch (ConvTy) {
Chris Lattner9bad62c2008-01-04 18:04:52 +00009514 case Compatible: return false;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009515 case PointerToInt:
Chris Lattner9bad62c2008-01-04 18:04:52 +00009516 DiagKind = diag::ext_typecheck_convert_pointer_int;
Anna Zaks3b402712011-07-28 19:51:27 +00009517 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9518 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009519 break;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009520 case IntToPointer:
9521 DiagKind = diag::ext_typecheck_convert_int_pointer;
Anna Zaks3b402712011-07-28 19:51:27 +00009522 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9523 MayHaveConvFixit = true;
Chris Lattner940cfeb2008-01-04 18:22:42 +00009524 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009525 case IncompatiblePointer:
Douglas Gregora771f462010-03-31 17:46:05 +00009526 MakeObjCStringLiteralFixItHint(*this, DstType, SrcExpr, Hint);
Chris Lattner9bad62c2008-01-04 18:04:52 +00009527 DiagKind = diag::ext_typecheck_convert_incompatible_pointer;
Douglas Gregor33823722011-06-11 01:09:30 +00009528 CheckInferredResultType = DstType->isObjCObjectPointerType() &&
9529 SrcType->isObjCObjectPointerType();
Anna Zaks3b402712011-07-28 19:51:27 +00009530 if (Hint.isNull() && !CheckInferredResultType) {
9531 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9532 }
9533 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009534 break;
Eli Friedman80160bd2009-03-22 23:59:44 +00009535 case IncompatiblePointerSign:
9536 DiagKind = diag::ext_typecheck_convert_incompatible_pointer_sign;
9537 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009538 case FunctionVoidPointer:
9539 DiagKind = diag::ext_typecheck_convert_pointer_void_func;
9540 break;
John McCall4fff8f62011-02-01 00:10:29 +00009541 case IncompatiblePointerDiscardsQualifiers: {
John McCall71de91c2011-02-01 23:28:01 +00009542 // Perform array-to-pointer decay if necessary.
9543 if (SrcType->isArrayType()) SrcType = Context.getArrayDecayedType(SrcType);
9544
John McCall4fff8f62011-02-01 00:10:29 +00009545 Qualifiers lhq = SrcType->getPointeeType().getQualifiers();
9546 Qualifiers rhq = DstType->getPointeeType().getQualifiers();
9547 if (lhq.getAddressSpace() != rhq.getAddressSpace()) {
9548 DiagKind = diag::err_typecheck_incompatible_address_space;
9549 break;
John McCall31168b02011-06-15 23:02:42 +00009550
9551
9552 } else if (lhq.getObjCLifetime() != rhq.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00009553 DiagKind = diag::err_typecheck_incompatible_ownership;
John McCall31168b02011-06-15 23:02:42 +00009554 break;
John McCall4fff8f62011-02-01 00:10:29 +00009555 }
9556
9557 llvm_unreachable("unknown error case for discarding qualifiers!");
9558 // fallthrough
9559 }
Chris Lattner9bad62c2008-01-04 18:04:52 +00009560 case CompatiblePointerDiscardsQualifiers:
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009561 // If the qualifiers lost were because we were applying the
9562 // (deprecated) C++ conversion from a string literal to a char*
9563 // (or wchar_t*), then there was no error (C++ 4.2p2). FIXME:
9564 // Ideally, this check would be performed in
John McCallaba90822011-01-31 23:13:11 +00009565 // checkPointerTypesForAssignment. However, that would require a
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009566 // bit of refactoring (so that the second argument is an
9567 // expression, rather than a type), which should be done as part
John McCallaba90822011-01-31 23:13:11 +00009568 // of a larger effort to fix checkPointerTypesForAssignment for
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009569 // C++ semantics.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009570 if (getLangOpts().CPlusPlus &&
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00009571 IsStringLiteralToNonConstPointerConversion(SrcExpr, DstType))
9572 return false;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009573 DiagKind = diag::ext_typecheck_convert_discards_qualifiers;
9574 break;
Alexis Hunt6f3de502009-11-08 07:46:34 +00009575 case IncompatibleNestedPointerQualifiers:
Fariborz Jahanianb98dade2009-11-09 22:16:37 +00009576 DiagKind = diag::ext_nested_pointer_qualifier_mismatch;
Fariborz Jahaniand7aa9d82009-11-07 20:20:40 +00009577 break;
Steve Naroff081c7422008-09-04 15:10:53 +00009578 case IntToBlockPointer:
9579 DiagKind = diag::err_int_to_block_pointer;
9580 break;
9581 case IncompatibleBlockPointer:
Mike Stumpd79b5a82009-04-21 22:51:42 +00009582 DiagKind = diag::err_typecheck_convert_incompatible_block_pointer;
Steve Naroff081c7422008-09-04 15:10:53 +00009583 break;
Steve Naroff8afa9892008-10-14 22:18:38 +00009584 case IncompatibleObjCQualifiedId:
Mike Stump4e1f26a2009-02-19 03:04:26 +00009585 // FIXME: Diagnose the problem in ObjCQualifiedIdTypesAreCompatible, since
Steve Naroff8afa9892008-10-14 22:18:38 +00009586 // it can give a more specific diagnostic.
9587 DiagKind = diag::warn_incompatible_qualified_id;
9588 break;
Anders Carlssondb5a9b62009-01-30 23:17:46 +00009589 case IncompatibleVectors:
9590 DiagKind = diag::warn_incompatible_vectors;
9591 break;
Fariborz Jahanian6f472e82011-07-07 18:55:47 +00009592 case IncompatibleObjCWeakRef:
9593 DiagKind = diag::err_arc_weak_unavailable_assign;
9594 break;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009595 case Incompatible:
9596 DiagKind = diag::err_typecheck_convert_incompatible;
Anna Zaks3b402712011-07-28 19:51:27 +00009597 ConvHints.tryToFixConversion(SrcExpr, SrcType, DstType, *this);
9598 MayHaveConvFixit = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009599 isInvalid = true;
Richard Trieucaff2472011-11-23 22:32:32 +00009600 MayHaveFunctionDiff = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009601 break;
9602 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009603
Douglas Gregorc68e1402010-04-09 00:35:39 +00009604 QualType FirstType, SecondType;
9605 switch (Action) {
9606 case AA_Assigning:
9607 case AA_Initializing:
9608 // The destination type comes first.
9609 FirstType = DstType;
9610 SecondType = SrcType;
9611 break;
Alexis Huntc46382e2010-04-28 23:02:27 +00009612
Douglas Gregorc68e1402010-04-09 00:35:39 +00009613 case AA_Returning:
9614 case AA_Passing:
9615 case AA_Converting:
9616 case AA_Sending:
9617 case AA_Casting:
9618 // The source type comes first.
9619 FirstType = SrcType;
9620 SecondType = DstType;
9621 break;
9622 }
Alexis Huntc46382e2010-04-28 23:02:27 +00009623
Anna Zaks3b402712011-07-28 19:51:27 +00009624 PartialDiagnostic FDiag = PDiag(DiagKind);
9625 FDiag << FirstType << SecondType << Action << SrcExpr->getSourceRange();
9626
9627 // If we can fix the conversion, suggest the FixIts.
9628 assert(ConvHints.isNull() || Hint.isNull());
9629 if (!ConvHints.isNull()) {
Benjamin Kramer490afa62012-01-14 21:05:10 +00009630 for (std::vector<FixItHint>::iterator HI = ConvHints.Hints.begin(),
9631 HE = ConvHints.Hints.end(); HI != HE; ++HI)
Anna Zaks3b402712011-07-28 19:51:27 +00009632 FDiag << *HI;
9633 } else {
9634 FDiag << Hint;
9635 }
9636 if (MayHaveConvFixit) { FDiag << (unsigned) (ConvHints.Kind); }
9637
Richard Trieucaff2472011-11-23 22:32:32 +00009638 if (MayHaveFunctionDiff)
9639 HandleFunctionTypeMismatch(FDiag, SecondType, FirstType);
9640
Anna Zaks3b402712011-07-28 19:51:27 +00009641 Diag(Loc, FDiag);
9642
Richard Trieucaff2472011-11-23 22:32:32 +00009643 if (SecondType == Context.OverloadTy)
9644 NoteAllOverloadCandidates(OverloadExpr::find(SrcExpr).Expression,
9645 FirstType);
9646
Douglas Gregor33823722011-06-11 01:09:30 +00009647 if (CheckInferredResultType)
9648 EmitRelatedResultTypeNote(SrcExpr);
9649
Douglas Gregor4f4946a2010-04-22 00:20:18 +00009650 if (Complained)
9651 *Complained = true;
Chris Lattner9bad62c2008-01-04 18:04:52 +00009652 return isInvalid;
9653}
Anders Carlssone54e8a12008-11-30 19:50:32 +00009654
Richard Smithf4c51d92012-02-04 09:53:13 +00009655ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9656 llvm::APSInt *Result) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009657 class SimpleICEDiagnoser : public VerifyICEDiagnoser {
9658 public:
9659 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9660 S.Diag(Loc, diag::err_expr_not_ice) << S.LangOpts.CPlusPlus << SR;
9661 }
9662 } Diagnoser;
9663
9664 return VerifyIntegerConstantExpression(E, Result, Diagnoser);
9665}
9666
9667ExprResult Sema::VerifyIntegerConstantExpression(Expr *E,
9668 llvm::APSInt *Result,
9669 unsigned DiagID,
9670 bool AllowFold) {
9671 class IDDiagnoser : public VerifyICEDiagnoser {
9672 unsigned DiagID;
9673
9674 public:
9675 IDDiagnoser(unsigned DiagID)
9676 : VerifyICEDiagnoser(DiagID == 0), DiagID(DiagID) { }
9677
9678 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
9679 S.Diag(Loc, DiagID) << SR;
9680 }
9681 } Diagnoser(DiagID);
9682
9683 return VerifyIntegerConstantExpression(E, Result, Diagnoser, AllowFold);
9684}
9685
9686void Sema::VerifyICEDiagnoser::diagnoseFold(Sema &S, SourceLocation Loc,
9687 SourceRange SR) {
9688 S.Diag(Loc, diag::ext_expr_not_ice) << SR << S.LangOpts.CPlusPlus;
Richard Smithf4c51d92012-02-04 09:53:13 +00009689}
9690
Benjamin Kramer33adaae2012-04-18 14:22:41 +00009691ExprResult
9692Sema::VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result,
Douglas Gregore2b37442012-05-04 22:38:52 +00009693 VerifyICEDiagnoser &Diagnoser,
9694 bool AllowFold) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00009695 SourceLocation DiagLoc = E->getLocStart();
Richard Smithf4c51d92012-02-04 09:53:13 +00009696
David Blaikiebbafb8a2012-03-11 07:00:24 +00009697 if (getLangOpts().CPlusPlus0x) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009698 // C++11 [expr.const]p5:
9699 // If an expression of literal class type is used in a context where an
9700 // integral constant expression is required, then that class type shall
9701 // have a single non-explicit conversion function to an integral or
9702 // unscoped enumeration type
9703 ExprResult Converted;
Douglas Gregore2b37442012-05-04 22:38:52 +00009704 if (!Diagnoser.Suppress) {
9705 class CXX11ConvertDiagnoser : public ICEConvertDiagnoser {
9706 public:
9707 CXX11ConvertDiagnoser() : ICEConvertDiagnoser(false, true) { }
9708
9709 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9710 QualType T) {
9711 return S.Diag(Loc, diag::err_ice_not_integral) << T;
9712 }
9713
9714 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9715 SourceLocation Loc,
9716 QualType T) {
9717 return S.Diag(Loc, diag::err_ice_incomplete_type) << T;
9718 }
9719
9720 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9721 SourceLocation Loc,
9722 QualType T,
9723 QualType ConvTy) {
9724 return S.Diag(Loc, diag::err_ice_explicit_conversion) << T << ConvTy;
9725 }
9726
9727 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9728 CXXConversionDecl *Conv,
9729 QualType ConvTy) {
9730 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9731 << ConvTy->isEnumeralType() << ConvTy;
9732 }
9733
9734 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9735 QualType T) {
9736 return S.Diag(Loc, diag::err_ice_ambiguous_conversion) << T;
9737 }
9738
9739 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9740 CXXConversionDecl *Conv,
9741 QualType ConvTy) {
9742 return S.Diag(Conv->getLocation(), diag::note_ice_conversion_here)
9743 << ConvTy->isEnumeralType() << ConvTy;
9744 }
9745
9746 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9747 SourceLocation Loc,
9748 QualType T,
9749 QualType ConvTy) {
9750 return DiagnosticBuilder::getEmpty();
9751 }
9752 } ConvertDiagnoser;
9753
9754 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9755 ConvertDiagnoser,
9756 /*AllowScopedEnumerations*/ false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009757 } else {
9758 // The caller wants to silently enquire whether this is an ICE. Don't
9759 // produce any diagnostics if it isn't.
Douglas Gregore2b37442012-05-04 22:38:52 +00009760 class SilentICEConvertDiagnoser : public ICEConvertDiagnoser {
9761 public:
9762 SilentICEConvertDiagnoser() : ICEConvertDiagnoser(true, true) { }
9763
9764 virtual DiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9765 QualType T) {
9766 return DiagnosticBuilder::getEmpty();
9767 }
9768
9769 virtual DiagnosticBuilder diagnoseIncomplete(Sema &S,
9770 SourceLocation Loc,
9771 QualType T) {
9772 return DiagnosticBuilder::getEmpty();
9773 }
9774
9775 virtual DiagnosticBuilder diagnoseExplicitConv(Sema &S,
9776 SourceLocation Loc,
9777 QualType T,
9778 QualType ConvTy) {
9779 return DiagnosticBuilder::getEmpty();
9780 }
9781
9782 virtual DiagnosticBuilder noteExplicitConv(Sema &S,
9783 CXXConversionDecl *Conv,
9784 QualType ConvTy) {
9785 return DiagnosticBuilder::getEmpty();
9786 }
9787
9788 virtual DiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9789 QualType T) {
9790 return DiagnosticBuilder::getEmpty();
9791 }
9792
9793 virtual DiagnosticBuilder noteAmbiguous(Sema &S,
9794 CXXConversionDecl *Conv,
9795 QualType ConvTy) {
9796 return DiagnosticBuilder::getEmpty();
9797 }
9798
9799 virtual DiagnosticBuilder diagnoseConversion(Sema &S,
9800 SourceLocation Loc,
9801 QualType T,
9802 QualType ConvTy) {
9803 return DiagnosticBuilder::getEmpty();
9804 }
9805 } ConvertDiagnoser;
9806
9807 Converted = ConvertToIntegralOrEnumerationType(DiagLoc, E,
9808 ConvertDiagnoser, false);
Richard Smithf4c51d92012-02-04 09:53:13 +00009809 }
9810 if (Converted.isInvalid())
9811 return Converted;
9812 E = Converted.take();
9813 if (!E->getType()->isIntegralOrUnscopedEnumerationType())
9814 return ExprError();
9815 } else if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
9816 // An ICE must be of integral or unscoped enumeration type.
Douglas Gregore2b37442012-05-04 22:38:52 +00009817 if (!Diagnoser.Suppress)
9818 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smithf4c51d92012-02-04 09:53:13 +00009819 return ExprError();
9820 }
9821
Richard Smith902ca212011-12-14 23:32:26 +00009822 // Circumvent ICE checking in C++11 to avoid evaluating the expression twice
9823 // in the non-ICE case.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009824 if (!getLangOpts().CPlusPlus0x && E->isIntegerConstantExpr(Context)) {
Richard Smithf4c51d92012-02-04 09:53:13 +00009825 if (Result)
9826 *Result = E->EvaluateKnownConstInt(Context);
9827 return Owned(E);
Eli Friedmanbb967cc2009-04-25 22:26:58 +00009828 }
9829
Anders Carlssone54e8a12008-11-30 19:50:32 +00009830 Expr::EvalResult EvalResult;
Richard Smith92b1ce02011-12-12 09:28:41 +00009831 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
9832 EvalResult.Diag = &Notes;
Anders Carlssone54e8a12008-11-30 19:50:32 +00009833
Richard Smith902ca212011-12-14 23:32:26 +00009834 // Try to evaluate the expression, and produce diagnostics explaining why it's
9835 // not a constant expression as a side-effect.
9836 bool Folded = E->EvaluateAsRValue(EvalResult, Context) &&
9837 EvalResult.Val.isInt() && !EvalResult.HasSideEffects;
9838
9839 // In C++11, we can rely on diagnostics being produced for any expression
9840 // which is not a constant expression. If no diagnostics were produced, then
9841 // this is a constant expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009842 if (Folded && getLangOpts().CPlusPlus0x && Notes.empty()) {
Richard Smith902ca212011-12-14 23:32:26 +00009843 if (Result)
9844 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009845 return Owned(E);
9846 }
9847
9848 // If our only note is the usual "invalid subexpression" note, just point
9849 // the caret at its location rather than producing an essentially
9850 // redundant note.
9851 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
9852 diag::note_invalid_subexpr_in_const_expr) {
9853 DiagLoc = Notes[0].first;
9854 Notes.clear();
Richard Smith902ca212011-12-14 23:32:26 +00009855 }
9856
9857 if (!Folded || !AllowFold) {
Douglas Gregore2b37442012-05-04 22:38:52 +00009858 if (!Diagnoser.Suppress) {
9859 Diagnoser.diagnoseNotICE(*this, DiagLoc, E->getSourceRange());
Richard Smith92b1ce02011-12-12 09:28:41 +00009860 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9861 Diag(Notes[I].first, Notes[I].second);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009862 }
Mike Stump4e1f26a2009-02-19 03:04:26 +00009863
Richard Smithf4c51d92012-02-04 09:53:13 +00009864 return ExprError();
Anders Carlssone54e8a12008-11-30 19:50:32 +00009865 }
9866
Douglas Gregore2b37442012-05-04 22:38:52 +00009867 Diagnoser.diagnoseFold(*this, DiagLoc, E->getSourceRange());
Richard Smith2ec40612012-01-15 03:51:30 +00009868 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
9869 Diag(Notes[I].first, Notes[I].second);
Mike Stump4e1f26a2009-02-19 03:04:26 +00009870
Anders Carlssone54e8a12008-11-30 19:50:32 +00009871 if (Result)
9872 *Result = EvalResult.Val.getInt();
Richard Smithf4c51d92012-02-04 09:53:13 +00009873 return Owned(E);
Anders Carlssone54e8a12008-11-30 19:50:32 +00009874}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009875
Eli Friedman456f0182012-01-20 01:26:23 +00009876namespace {
9877 // Handle the case where we conclude a expression which we speculatively
9878 // considered to be unevaluated is actually evaluated.
9879 class TransformToPE : public TreeTransform<TransformToPE> {
9880 typedef TreeTransform<TransformToPE> BaseTransform;
9881
9882 public:
9883 TransformToPE(Sema &SemaRef) : BaseTransform(SemaRef) { }
9884
9885 // Make sure we redo semantic analysis
9886 bool AlwaysRebuild() { return true; }
9887
Eli Friedman5f0ca242012-02-06 23:29:57 +00009888 // Make sure we handle LabelStmts correctly.
9889 // FIXME: This does the right thing, but maybe we need a more general
9890 // fix to TreeTransform?
9891 StmtResult TransformLabelStmt(LabelStmt *S) {
9892 S->getDecl()->setStmt(0);
9893 return BaseTransform::TransformLabelStmt(S);
9894 }
9895
Eli Friedman456f0182012-01-20 01:26:23 +00009896 // We need to special-case DeclRefExprs referring to FieldDecls which
9897 // are not part of a member pointer formation; normal TreeTransforming
9898 // doesn't catch this case because of the way we represent them in the AST.
9899 // FIXME: This is a bit ugly; is it really the best way to handle this
9900 // case?
9901 //
9902 // Error on DeclRefExprs referring to FieldDecls.
9903 ExprResult TransformDeclRefExpr(DeclRefExpr *E) {
9904 if (isa<FieldDecl>(E->getDecl()) &&
9905 SemaRef.ExprEvalContexts.back().Context != Sema::Unevaluated)
9906 return SemaRef.Diag(E->getLocation(),
9907 diag::err_invalid_non_static_member_use)
9908 << E->getDecl() << E->getSourceRange();
9909
9910 return BaseTransform::TransformDeclRefExpr(E);
9911 }
9912
9913 // Exception: filter out member pointer formation
9914 ExprResult TransformUnaryOperator(UnaryOperator *E) {
9915 if (E->getOpcode() == UO_AddrOf && E->getType()->isMemberPointerType())
9916 return E;
9917
9918 return BaseTransform::TransformUnaryOperator(E);
9919 }
9920
Douglas Gregor89625492012-02-09 08:14:43 +00009921 ExprResult TransformLambdaExpr(LambdaExpr *E) {
9922 // Lambdas never need to be transformed.
9923 return E;
9924 }
Eli Friedman456f0182012-01-20 01:26:23 +00009925 };
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009926}
9927
Eli Friedman456f0182012-01-20 01:26:23 +00009928ExprResult Sema::TranformToPotentiallyEvaluated(Expr *E) {
Eli Friedmane4f22df2012-02-29 04:03:55 +00009929 assert(ExprEvalContexts.back().Context == Unevaluated &&
9930 "Should only transform unevaluated expressions");
Eli Friedman456f0182012-01-20 01:26:23 +00009931 ExprEvalContexts.back().Context =
9932 ExprEvalContexts[ExprEvalContexts.size()-2].Context;
9933 if (ExprEvalContexts.back().Context == Unevaluated)
9934 return E;
9935 return TransformToPE(*this).TransformExpr(E);
Eli Friedmanfbc0dff2012-01-18 01:05:54 +00009936}
9937
Douglas Gregorff790f12009-11-26 00:44:06 +00009938void
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009939Sema::PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext,
Richard Smithfd555f62012-02-22 02:04:18 +00009940 Decl *LambdaContextDecl,
9941 bool IsDecltype) {
Douglas Gregorff790f12009-11-26 00:44:06 +00009942 ExprEvalContexts.push_back(
John McCall31168b02011-06-15 23:02:42 +00009943 ExpressionEvaluationContextRecord(NewContext,
John McCall28fc7092011-11-10 05:35:25 +00009944 ExprCleanupObjects.size(),
Douglas Gregor7fcbd902012-02-21 00:37:24 +00009945 ExprNeedsCleanups,
Richard Smithfd555f62012-02-22 02:04:18 +00009946 LambdaContextDecl,
9947 IsDecltype));
John McCall31168b02011-06-15 23:02:42 +00009948 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009949 if (!MaybeODRUseExprs.empty())
9950 std::swap(MaybeODRUseExprs, ExprEvalContexts.back().SavedMaybeODRUseExprs);
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009951}
9952
Richard Trieucfc491d2011-08-02 04:35:43 +00009953void Sema::PopExpressionEvaluationContext() {
Eli Friedmanfa0df832012-02-02 03:46:19 +00009954 ExpressionEvaluationContextRecord& Rec = ExprEvalContexts.back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009955
Douglas Gregor89625492012-02-09 08:14:43 +00009956 if (!Rec.Lambdas.empty()) {
9957 if (Rec.Context == Unevaluated) {
9958 // C++11 [expr.prim.lambda]p2:
9959 // A lambda-expression shall not appear in an unevaluated operand
9960 // (Clause 5).
9961 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I)
9962 Diag(Rec.Lambdas[I]->getLocStart(),
9963 diag::err_lambda_unevaluated_operand);
9964 } else {
9965 // Mark the capture expressions odr-used. This was deferred
9966 // during lambda expression creation.
9967 for (unsigned I = 0, N = Rec.Lambdas.size(); I != N; ++I) {
9968 LambdaExpr *Lambda = Rec.Lambdas[I];
9969 for (LambdaExpr::capture_init_iterator
9970 C = Lambda->capture_init_begin(),
9971 CEnd = Lambda->capture_init_end();
9972 C != CEnd; ++C) {
9973 MarkDeclarationsReferencedInExpr(*C);
9974 }
9975 }
9976 }
9977 }
9978
Douglas Gregorff790f12009-11-26 00:44:06 +00009979 // When are coming out of an unevaluated context, clear out any
9980 // temporaries that we may have created as part of the evaluation of
9981 // the expression in that context: they aren't relevant because they
9982 // will never be constructed.
Richard Smith764d2fe2011-12-20 02:08:33 +00009983 if (Rec.Context == Unevaluated || Rec.Context == ConstantEvaluated) {
John McCall28fc7092011-11-10 05:35:25 +00009984 ExprCleanupObjects.erase(ExprCleanupObjects.begin() + Rec.NumCleanupObjects,
9985 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +00009986 ExprNeedsCleanups = Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009987 CleanupVarDeclMarking();
9988 std::swap(MaybeODRUseExprs, Rec.SavedMaybeODRUseExprs);
John McCall31168b02011-06-15 23:02:42 +00009989 // Otherwise, merge the contexts together.
9990 } else {
9991 ExprNeedsCleanups |= Rec.ParentNeedsCleanups;
Eli Friedman3bda6b12012-02-02 23:15:15 +00009992 MaybeODRUseExprs.insert(Rec.SavedMaybeODRUseExprs.begin(),
9993 Rec.SavedMaybeODRUseExprs.end());
John McCall31168b02011-06-15 23:02:42 +00009994 }
Eli Friedmanfa0df832012-02-02 03:46:19 +00009995
9996 // Pop the current expression evaluation context off the stack.
9997 ExprEvalContexts.pop_back();
Douglas Gregor0b6a6242009-06-22 20:57:11 +00009998}
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00009999
John McCall31168b02011-06-15 23:02:42 +000010000void Sema::DiscardCleanupsInEvaluationContext() {
John McCall28fc7092011-11-10 05:35:25 +000010001 ExprCleanupObjects.erase(
10002 ExprCleanupObjects.begin() + ExprEvalContexts.back().NumCleanupObjects,
10003 ExprCleanupObjects.end());
John McCall31168b02011-06-15 23:02:42 +000010004 ExprNeedsCleanups = false;
Eli Friedman3bda6b12012-02-02 23:15:15 +000010005 MaybeODRUseExprs.clear();
John McCall31168b02011-06-15 23:02:42 +000010006}
10007
Eli Friedmane0afc982012-01-21 01:01:51 +000010008ExprResult Sema::HandleExprEvaluationContextForTypeof(Expr *E) {
10009 if (!E->getType()->isVariablyModifiedType())
10010 return E;
10011 return TranformToPotentiallyEvaluated(E);
10012}
10013
Benjamin Kramerbf8da9d2012-02-06 11:13:08 +000010014static bool IsPotentiallyEvaluatedContext(Sema &SemaRef) {
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010015 // Do not mark anything as "used" within a dependent context; wait for
10016 // an instantiation.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010017 if (SemaRef.CurContext->isDependentContext())
10018 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010019
Eli Friedmanfa0df832012-02-02 03:46:19 +000010020 switch (SemaRef.ExprEvalContexts.back().Context) {
10021 case Sema::Unevaluated:
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010022 // We are in an expression that is not potentially evaluated; do nothing.
Eli Friedman02b58512012-01-21 04:44:06 +000010023 // (Depending on how you read the standard, we actually do need to do
10024 // something here for null pointer constants, but the standard's
10025 // definition of a null pointer constant is completely crazy.)
Eli Friedmanfa0df832012-02-02 03:46:19 +000010026 return false;
Mike Stump11289f42009-09-09 15:08:12 +000010027
Eli Friedmanfa0df832012-02-02 03:46:19 +000010028 case Sema::ConstantEvaluated:
10029 case Sema::PotentiallyEvaluated:
Eli Friedman02b58512012-01-21 04:44:06 +000010030 // We are in a potentially evaluated expression (or a constant-expression
10031 // in C++03); we need to do implicit template instantiation, implicitly
10032 // define class members, and mark most declarations as used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010033 return true;
Mike Stump11289f42009-09-09 15:08:12 +000010034
Eli Friedmanfa0df832012-02-02 03:46:19 +000010035 case Sema::PotentiallyEvaluatedIfUsed:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010036 // Referenced declarations will only be used if the construct in the
10037 // containing expression is used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010038 return false;
Douglas Gregor0b6a6242009-06-22 20:57:11 +000010039 }
Matt Beaumont-Gay248bc722012-02-02 18:35:35 +000010040 llvm_unreachable("Invalid context");
Eli Friedmanfa0df832012-02-02 03:46:19 +000010041}
10042
10043/// \brief Mark a function referenced, and check whether it is odr-used
10044/// (C++ [basic.def.odr]p2, C99 6.9p3)
10045void Sema::MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func) {
10046 assert(Func && "No function?");
10047
10048 Func->setReferenced();
10049
Richard Smith4a941e22012-02-14 22:25:15 +000010050 // Don't mark this function as used multiple times, unless it's a constexpr
10051 // function which we need to instantiate.
10052 if (Func->isUsed(false) &&
10053 !(Func->isConstexpr() && !Func->getBody() &&
10054 Func->isImplicitlyInstantiable()))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010055 return;
10056
10057 if (!IsPotentiallyEvaluatedContext(*this))
10058 return;
Mike Stump11289f42009-09-09 15:08:12 +000010059
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010060 // Note that this declaration has been used.
Eli Friedmanfa0df832012-02-02 03:46:19 +000010061 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010062 if (Constructor->isDefaulted() && !Constructor->isDeleted()) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010063 if (Constructor->isDefaultConstructor()) {
10064 if (Constructor->isTrivial())
10065 return;
10066 if (!Constructor->isUsed(false))
10067 DefineImplicitDefaultConstructor(Loc, Constructor);
10068 } else if (Constructor->isCopyConstructor()) {
10069 if (!Constructor->isUsed(false))
10070 DefineImplicitCopyConstructor(Loc, Constructor);
10071 } else if (Constructor->isMoveConstructor()) {
10072 if (!Constructor->isUsed(false))
10073 DefineImplicitMoveConstructor(Loc, Constructor);
10074 }
Fariborz Jahanian477d2422009-06-22 23:34:40 +000010075 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010076
Douglas Gregor88d292c2010-05-13 16:44:06 +000010077 MarkVTableUsed(Loc, Constructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010078 } else if (CXXDestructorDecl *Destructor =
10079 dyn_cast<CXXDestructorDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010080 if (Destructor->isDefaulted() && !Destructor->isDeleted() &&
10081 !Destructor->isUsed(false))
Fariborz Jahanian24a175b2009-06-26 23:49:16 +000010082 DefineImplicitDestructor(Loc, Destructor);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010083 if (Destructor->isVirtual())
10084 MarkVTableUsed(Loc, Destructor->getParent());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010085 } else if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Func)) {
Richard Smith273c4e92012-02-26 07:51:39 +000010086 if (MethodDecl->isDefaulted() && !MethodDecl->isDeleted() &&
10087 MethodDecl->isOverloadedOperator() &&
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010088 MethodDecl->getOverloadedOperator() == OO_Equal) {
Sebastian Redl22653ba2011-08-30 19:58:05 +000010089 if (!MethodDecl->isUsed(false)) {
10090 if (MethodDecl->isCopyAssignmentOperator())
10091 DefineImplicitCopyAssignment(Loc, MethodDecl);
10092 else
10093 DefineImplicitMoveAssignment(Loc, MethodDecl);
10094 }
Douglas Gregord3b672c2012-02-16 01:06:16 +000010095 } else if (isa<CXXConversionDecl>(MethodDecl) &&
10096 MethodDecl->getParent()->isLambda()) {
10097 CXXConversionDecl *Conversion = cast<CXXConversionDecl>(MethodDecl);
10098 if (Conversion->isLambdaToBlockPointerConversion())
10099 DefineImplicitLambdaToBlockPointerConversion(Loc, Conversion);
10100 else
10101 DefineImplicitLambdaToFunctionPointerConversion(Loc, Conversion);
Douglas Gregor88d292c2010-05-13 16:44:06 +000010102 } else if (MethodDecl->isVirtual())
10103 MarkVTableUsed(Loc, MethodDecl->getParent());
Fariborz Jahanian41f79272009-06-25 21:45:19 +000010104 }
John McCall83779672011-02-19 02:53:41 +000010105
Eli Friedmanfa0df832012-02-02 03:46:19 +000010106 // Recursive functions should be marked when used from another function.
10107 // FIXME: Is this really right?
10108 if (CurContext == Func) return;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010109
Richard Smithf623c962012-04-17 00:58:00 +000010110 // Instantiate the exception specification for any function which is
10111 // used: CodeGen will need it.
Richard Smithd3729422012-04-19 00:08:28 +000010112 const FunctionProtoType *FPT = Func->getType()->getAs<FunctionProtoType>();
10113 if (FPT && FPT->getExceptionSpecType() == EST_Uninstantiated)
Richard Smithf623c962012-04-17 00:58:00 +000010114 InstantiateExceptionSpec(Loc, Func);
10115
Eli Friedmanfa0df832012-02-02 03:46:19 +000010116 // Implicit instantiation of function templates and member functions of
10117 // class templates.
10118 if (Func->isImplicitlyInstantiable()) {
10119 bool AlreadyInstantiated = false;
Richard Smith4a941e22012-02-14 22:25:15 +000010120 SourceLocation PointOfInstantiation = Loc;
Eli Friedmanfa0df832012-02-02 03:46:19 +000010121 if (FunctionTemplateSpecializationInfo *SpecInfo
10122 = Func->getTemplateSpecializationInfo()) {
10123 if (SpecInfo->getPointOfInstantiation().isInvalid())
10124 SpecInfo->setPointOfInstantiation(Loc);
10125 else if (SpecInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010126 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010127 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010128 PointOfInstantiation = SpecInfo->getPointOfInstantiation();
10129 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010130 } else if (MemberSpecializationInfo *MSInfo
10131 = Func->getMemberSpecializationInfo()) {
10132 if (MSInfo->getPointOfInstantiation().isInvalid())
Douglas Gregor06db9f52009-10-12 20:18:28 +000010133 MSInfo->setPointOfInstantiation(Loc);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010134 else if (MSInfo->getTemplateSpecializationKind()
Richard Smith4a941e22012-02-14 22:25:15 +000010135 == TSK_ImplicitInstantiation) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010136 AlreadyInstantiated = true;
Richard Smith4a941e22012-02-14 22:25:15 +000010137 PointOfInstantiation = MSInfo->getPointOfInstantiation();
10138 }
Douglas Gregor06db9f52009-10-12 20:18:28 +000010139 }
Mike Stump11289f42009-09-09 15:08:12 +000010140
Richard Smith4a941e22012-02-14 22:25:15 +000010141 if (!AlreadyInstantiated || Func->isConstexpr()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010142 if (isa<CXXRecordDecl>(Func->getDeclContext()) &&
10143 cast<CXXRecordDecl>(Func->getDeclContext())->isLocalClass())
Richard Smith4a941e22012-02-14 22:25:15 +000010144 PendingLocalImplicitInstantiations.push_back(
10145 std::make_pair(Func, PointOfInstantiation));
10146 else if (Func->isConstexpr())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010147 // Do not defer instantiations of constexpr functions, to avoid the
10148 // expression evaluator needing to call back into Sema if it sees a
10149 // call to such a function.
Richard Smith4a941e22012-02-14 22:25:15 +000010150 InstantiateFunctionDefinition(PointOfInstantiation, Func);
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010151 else {
Richard Smith4a941e22012-02-14 22:25:15 +000010152 PendingInstantiations.push_back(std::make_pair(Func,
10153 PointOfInstantiation));
Argyrios Kyrtzidise5dc5b32012-02-10 20:10:44 +000010154 // Notify the consumer that a function was implicitly instantiated.
10155 Consumer.HandleCXXImplicitFunctionInstantiation(Func);
10156 }
John McCall83779672011-02-19 02:53:41 +000010157 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010158 } else {
10159 // Walk redefinitions, as some of them may be instantiable.
10160 for (FunctionDecl::redecl_iterator i(Func->redecls_begin()),
10161 e(Func->redecls_end()); i != e; ++i) {
10162 if (!i->isUsed(false) && i->isImplicitlyInstantiable())
10163 MarkFunctionReferenced(Loc, *i);
10164 }
Sam Weinigbae69142009-09-11 03:29:30 +000010165 }
Eli Friedmanfa0df832012-02-02 03:46:19 +000010166
10167 // Keep track of used but undefined functions.
10168 if (!Func->isPure() && !Func->hasBody() &&
10169 Func->getLinkage() != ExternalLinkage) {
10170 SourceLocation &old = UndefinedInternals[Func->getCanonicalDecl()];
10171 if (old.isInvalid()) old = Loc;
10172 }
10173
10174 Func->setUsed(true);
10175}
10176
Eli Friedman9bb33f52012-02-03 02:04:35 +000010177static void
10178diagnoseUncapturableValueReference(Sema &S, SourceLocation loc,
10179 VarDecl *var, DeclContext *DC) {
Eli Friedmandd053f62012-02-07 00:15:00 +000010180 DeclContext *VarDC = var->getDeclContext();
10181
Eli Friedman9bb33f52012-02-03 02:04:35 +000010182 // If the parameter still belongs to the translation unit, then
10183 // we're actually just using one parameter in the declaration of
10184 // the next.
10185 if (isa<ParmVarDecl>(var) &&
Eli Friedmandd053f62012-02-07 00:15:00 +000010186 isa<TranslationUnitDecl>(VarDC))
Eli Friedman9bb33f52012-02-03 02:04:35 +000010187 return;
10188
Eli Friedmandd053f62012-02-07 00:15:00 +000010189 // For C code, don't diagnose about capture if we're not actually in code
10190 // right now; it's impossible to write a non-constant expression outside of
10191 // function context, so we'll get other (more useful) diagnostics later.
10192 //
10193 // For C++, things get a bit more nasty... it would be nice to suppress this
10194 // diagnostic for certain cases like using a local variable in an array bound
10195 // for a member of a local class, but the correct predicate is not obvious.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010196 if (!S.getLangOpts().CPlusPlus && !S.CurContext->isFunctionOrMethod())
Eli Friedman9bb33f52012-02-03 02:04:35 +000010197 return;
10198
Eli Friedmandd053f62012-02-07 00:15:00 +000010199 if (isa<CXXMethodDecl>(VarDC) &&
10200 cast<CXXRecordDecl>(VarDC->getParent())->isLambda()) {
10201 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_lambda)
10202 << var->getIdentifier();
10203 } else if (FunctionDecl *fn = dyn_cast<FunctionDecl>(VarDC)) {
10204 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_function)
10205 << var->getIdentifier() << fn->getDeclName();
10206 } else if (isa<BlockDecl>(VarDC)) {
10207 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_block)
10208 << var->getIdentifier();
10209 } else {
10210 // FIXME: Is there any other context where a local variable can be
10211 // declared?
10212 S.Diag(loc, diag::err_reference_to_local_var_in_enclosing_context)
10213 << var->getIdentifier();
10214 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010215
Eli Friedman9bb33f52012-02-03 02:04:35 +000010216 S.Diag(var->getLocation(), diag::note_local_variable_declared_here)
10217 << var->getIdentifier();
Eli Friedmandd053f62012-02-07 00:15:00 +000010218
10219 // FIXME: Add additional diagnostic info about class etc. which prevents
10220 // capture.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010221}
10222
Douglas Gregor81495f32012-02-12 18:42:33 +000010223/// \brief Capture the given variable in the given lambda expression.
10224static ExprResult captureInLambda(Sema &S, LambdaScopeInfo *LSI,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010225 VarDecl *Var, QualType FieldType,
10226 QualType DeclRefType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010227 SourceLocation Loc,
10228 bool RefersToEnclosingLocal) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010229 CXXRecordDecl *Lambda = LSI->Lambda;
Douglas Gregor81495f32012-02-12 18:42:33 +000010230
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010231 // Build the non-static data member.
10232 FieldDecl *Field
10233 = FieldDecl::Create(S.Context, Lambda, Loc, Loc, 0, FieldType,
10234 S.Context.getTrivialTypeSourceInfo(FieldType, Loc),
Richard Smith2b013182012-06-10 03:12:00 +000010235 0, false, ICIS_NoInit);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010236 Field->setImplicit(true);
10237 Field->setAccess(AS_private);
Douglas Gregor3d23f7882012-02-09 02:12:34 +000010238 Lambda->addDecl(Field);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010239
10240 // C++11 [expr.prim.lambda]p21:
10241 // When the lambda-expression is evaluated, the entities that
10242 // are captured by copy are used to direct-initialize each
10243 // corresponding non-static data member of the resulting closure
10244 // object. (For array members, the array elements are
10245 // direct-initialized in increasing subscript order.) These
10246 // initializations are performed in the (unspecified) order in
10247 // which the non-static data members are declared.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010248
Douglas Gregor89625492012-02-09 08:14:43 +000010249 // Introduce a new evaluation context for the initialization, so
10250 // that temporaries introduced as part of the capture are retained
10251 // to be re-"exported" from the lambda expression itself.
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010252 S.PushExpressionEvaluationContext(Sema::PotentiallyEvaluated);
10253
Douglas Gregorf02455e2012-02-10 09:26:04 +000010254 // C++ [expr.prim.labda]p12:
10255 // An entity captured by a lambda-expression is odr-used (3.2) in
10256 // the scope containing the lambda-expression.
Douglas Gregora8182f92012-05-16 17:01:33 +000010257 Expr *Ref = new (S.Context) DeclRefExpr(Var, RefersToEnclosingLocal,
10258 DeclRefType, VK_LValue, Loc);
Eli Friedman23b1be92012-03-01 21:32:56 +000010259 Var->setReferenced(true);
Douglas Gregorf02455e2012-02-10 09:26:04 +000010260 Var->setUsed(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010261
10262 // When the field has array type, create index variables for each
10263 // dimension of the array. We use these index variables to subscript
10264 // the source array, and other clients (e.g., CodeGen) will perform
10265 // the necessary iteration with these index variables.
10266 SmallVector<VarDecl *, 4> IndexVariables;
Douglas Gregor199cec72012-02-09 02:45:47 +000010267 QualType BaseType = FieldType;
10268 QualType SizeType = S.Context.getSizeType();
Douglas Gregor54fcea62012-02-13 16:35:30 +000010269 LSI->ArrayIndexStarts.push_back(LSI->ArrayIndexVars.size());
Douglas Gregor199cec72012-02-09 02:45:47 +000010270 while (const ConstantArrayType *Array
10271 = S.Context.getAsConstantArrayType(BaseType)) {
Douglas Gregor199cec72012-02-09 02:45:47 +000010272 // Create the iteration variable for this array index.
10273 IdentifierInfo *IterationVarName = 0;
10274 {
10275 SmallString<8> Str;
10276 llvm::raw_svector_ostream OS(Str);
10277 OS << "__i" << IndexVariables.size();
10278 IterationVarName = &S.Context.Idents.get(OS.str());
10279 }
10280 VarDecl *IterationVar
10281 = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
10282 IterationVarName, SizeType,
10283 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
10284 SC_None, SC_None);
10285 IndexVariables.push_back(IterationVar);
Douglas Gregor54fcea62012-02-13 16:35:30 +000010286 LSI->ArrayIndexVars.push_back(IterationVar);
10287
Douglas Gregor199cec72012-02-09 02:45:47 +000010288 // Create a reference to the iteration variable.
10289 ExprResult IterationVarRef
10290 = S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
10291 assert(!IterationVarRef.isInvalid() &&
10292 "Reference to invented variable cannot fail!");
10293 IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.take());
10294 assert(!IterationVarRef.isInvalid() &&
10295 "Conversion of invented variable cannot fail!");
10296
10297 // Subscript the array with this iteration variable.
10298 ExprResult Subscript = S.CreateBuiltinArraySubscriptExpr(
10299 Ref, Loc, IterationVarRef.take(), Loc);
10300 if (Subscript.isInvalid()) {
10301 S.CleanupVarDeclMarking();
10302 S.DiscardCleanupsInEvaluationContext();
10303 S.PopExpressionEvaluationContext();
10304 return ExprError();
10305 }
10306
10307 Ref = Subscript.take();
10308 BaseType = Array->getElementType();
10309 }
10310
10311 // Construct the entity that we will be initializing. For an array, this
10312 // will be first element in the array, which may require several levels
10313 // of array-subscript entities.
10314 SmallVector<InitializedEntity, 4> Entities;
10315 Entities.reserve(1 + IndexVariables.size());
Douglas Gregor19666fb2012-02-15 16:57:26 +000010316 Entities.push_back(
10317 InitializedEntity::InitializeLambdaCapture(Var, Field, Loc));
Douglas Gregor199cec72012-02-09 02:45:47 +000010318 for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
10319 Entities.push_back(InitializedEntity::InitializeElement(S.Context,
10320 0,
10321 Entities.back()));
10322
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010323 InitializationKind InitKind
10324 = InitializationKind::CreateDirect(Loc, Loc, Loc);
Douglas Gregor199cec72012-02-09 02:45:47 +000010325 InitializationSequence Init(S, Entities.back(), InitKind, &Ref, 1);
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010326 ExprResult Result(true);
Douglas Gregor199cec72012-02-09 02:45:47 +000010327 if (!Init.Diagnose(S, Entities.back(), InitKind, &Ref, 1))
10328 Result = Init.Perform(S, Entities.back(), InitKind,
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010329 MultiExprArg(S, &Ref, 1));
10330
10331 // If this initialization requires any cleanups (e.g., due to a
10332 // default argument to a copy constructor), note that for the
10333 // lambda.
10334 if (S.ExprNeedsCleanups)
10335 LSI->ExprNeedsCleanups = true;
10336
10337 // Exit the expression evaluation context used for the capture.
10338 S.CleanupVarDeclMarking();
10339 S.DiscardCleanupsInEvaluationContext();
10340 S.PopExpressionEvaluationContext();
10341 return Result;
Douglas Gregor199cec72012-02-09 02:45:47 +000010342}
Douglas Gregorabecb9c2012-02-09 01:56:40 +000010343
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010344bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10345 TryCaptureKind Kind, SourceLocation EllipsisLoc,
10346 bool BuildAndDiagnose,
10347 QualType &CaptureType,
10348 QualType &DeclRefType) {
10349 bool Nested = false;
Douglas Gregor81495f32012-02-12 18:42:33 +000010350
Eli Friedman24af8502012-02-03 22:47:37 +000010351 DeclContext *DC = CurContext;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010352 if (Var->getDeclContext() == DC) return true;
10353 if (!Var->hasLocalStorage()) return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010354
Douglas Gregor81495f32012-02-12 18:42:33 +000010355 bool HasBlocksAttr = Var->hasAttr<BlocksAttr>();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010356
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010357 // Walk up the stack to determine whether we can capture the variable,
10358 // performing the "simple" checks that don't depend on type. We stop when
10359 // we've either hit the declared scope of the variable or find an existing
10360 // capture of that variable.
10361 CaptureType = Var->getType();
10362 DeclRefType = CaptureType.getNonReferenceType();
10363 bool Explicit = (Kind != TryCapture_Implicit);
10364 unsigned FunctionScopesIndex = FunctionScopes.size() - 1;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010365 do {
Eli Friedman24af8502012-02-03 22:47:37 +000010366 // Only block literals and lambda expressions can capture; other
Eli Friedman9bb33f52012-02-03 02:04:35 +000010367 // scopes don't work.
Eli Friedman24af8502012-02-03 22:47:37 +000010368 DeclContext *ParentDC;
10369 if (isa<BlockDecl>(DC))
10370 ParentDC = DC->getParent();
10371 else if (isa<CXXMethodDecl>(DC) &&
Douglas Gregor81495f32012-02-12 18:42:33 +000010372 cast<CXXMethodDecl>(DC)->getOverloadedOperator() == OO_Call &&
Eli Friedman24af8502012-02-03 22:47:37 +000010373 cast<CXXRecordDecl>(DC->getParent())->isLambda())
10374 ParentDC = DC->getParent()->getParent();
Douglas Gregor81495f32012-02-12 18:42:33 +000010375 else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010376 if (BuildAndDiagnose)
Douglas Gregor81495f32012-02-12 18:42:33 +000010377 diagnoseUncapturableValueReference(*this, Loc, Var, DC);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010378 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010379 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010380
Eli Friedman24af8502012-02-03 22:47:37 +000010381 CapturingScopeInfo *CSI =
Douglas Gregor81495f32012-02-12 18:42:33 +000010382 cast<CapturingScopeInfo>(FunctionScopes[FunctionScopesIndex]);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010383
Eli Friedman24af8502012-02-03 22:47:37 +000010384 // Check whether we've already captured it.
Douglas Gregor81495f32012-02-12 18:42:33 +000010385 if (CSI->CaptureMap.count(Var)) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010386 // If we found a capture, any subcaptures are nested.
Eli Friedman9bb33f52012-02-03 02:04:35 +000010387 Nested = true;
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010388
10389 // Retrieve the capture type for this variable.
10390 CaptureType = CSI->getCapture(Var).getCaptureType();
10391
10392 // Compute the type of an expression that refers to this variable.
10393 DeclRefType = CaptureType.getNonReferenceType();
10394
10395 const CapturingScopeInfo::Capture &Cap = CSI->getCapture(Var);
10396 if (Cap.isCopyCapture() &&
10397 !(isa<LambdaScopeInfo>(CSI) && cast<LambdaScopeInfo>(CSI)->Mutable))
10398 DeclRefType.addConst();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010399 break;
10400 }
10401
Douglas Gregor81495f32012-02-12 18:42:33 +000010402 bool IsBlock = isa<BlockScopeInfo>(CSI);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010403 bool IsLambda = !IsBlock;
Eli Friedman24af8502012-02-03 22:47:37 +000010404
10405 // Lambdas are not allowed to capture unnamed variables
10406 // (e.g. anonymous unions).
10407 // FIXME: The C++11 rule don't actually state this explicitly, but I'm
10408 // assuming that's the intent.
Douglas Gregor81495f32012-02-12 18:42:33 +000010409 if (IsLambda && !Var->getDeclName()) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010410 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010411 Diag(Loc, diag::err_lambda_capture_anonymous_var);
10412 Diag(Var->getLocation(), diag::note_declared_at);
10413 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010414 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010415 }
10416
10417 // Prohibit variably-modified types; they're difficult to deal with.
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010418 if (Var->getType()->isVariablyModifiedType()) {
10419 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010420 if (IsBlock)
10421 Diag(Loc, diag::err_ref_vm_type);
10422 else
10423 Diag(Loc, diag::err_lambda_capture_vm_type) << Var->getDeclName();
10424 Diag(Var->getLocation(), diag::note_previous_decl)
10425 << Var->getDeclName();
10426 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010427 return true;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010428 }
10429
Eli Friedman24af8502012-02-03 22:47:37 +000010430 // Lambdas are not allowed to capture __block variables; they don't
10431 // support the expected semantics.
Douglas Gregor81495f32012-02-12 18:42:33 +000010432 if (IsLambda && HasBlocksAttr) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010433 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010434 Diag(Loc, diag::err_lambda_capture_block)
10435 << Var->getDeclName();
10436 Diag(Var->getLocation(), diag::note_previous_decl)
10437 << Var->getDeclName();
10438 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010439 return true;
Eli Friedman24af8502012-02-03 22:47:37 +000010440 }
10441
Douglas Gregor81495f32012-02-12 18:42:33 +000010442 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_None && !Explicit) {
10443 // No capture-default
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010444 if (BuildAndDiagnose) {
Douglas Gregor81495f32012-02-12 18:42:33 +000010445 Diag(Loc, diag::err_lambda_impcap) << Var->getDeclName();
10446 Diag(Var->getLocation(), diag::note_previous_decl)
10447 << Var->getDeclName();
10448 Diag(cast<LambdaScopeInfo>(CSI)->Lambda->getLocStart(),
10449 diag::note_lambda_decl);
10450 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010451 return true;
Douglas Gregor81495f32012-02-12 18:42:33 +000010452 }
10453
10454 FunctionScopesIndex--;
10455 DC = ParentDC;
10456 Explicit = false;
10457 } while (!Var->getDeclContext()->Equals(DC));
10458
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010459 // Walk back down the scope stack, computing the type of the capture at
10460 // each step, checking type-specific requirements, and adding captures if
10461 // requested.
10462 for (unsigned I = ++FunctionScopesIndex, N = FunctionScopes.size(); I != N;
10463 ++I) {
10464 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[I]);
Douglas Gregor812d8f62012-02-18 05:51:20 +000010465
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010466 // Compute the type of the capture and of a reference to the capture within
10467 // this scope.
10468 if (isa<BlockScopeInfo>(CSI)) {
10469 Expr *CopyExpr = 0;
10470 bool ByRef = false;
10471
10472 // Blocks are not allowed to capture arrays.
10473 if (CaptureType->isArrayType()) {
10474 if (BuildAndDiagnose) {
10475 Diag(Loc, diag::err_ref_array_type);
10476 Diag(Var->getLocation(), diag::note_previous_decl)
10477 << Var->getDeclName();
10478 }
10479 return true;
10480 }
10481
John McCall67cd5e02012-03-30 05:23:48 +000010482 // Forbid the block-capture of autoreleasing variables.
10483 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10484 if (BuildAndDiagnose) {
10485 Diag(Loc, diag::err_arc_autoreleasing_capture)
10486 << /*block*/ 0;
10487 Diag(Var->getLocation(), diag::note_previous_decl)
10488 << Var->getDeclName();
10489 }
10490 return true;
10491 }
10492
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010493 if (HasBlocksAttr || CaptureType->isReferenceType()) {
10494 // Block capture by reference does not change the capture or
10495 // declaration reference types.
10496 ByRef = true;
10497 } else {
10498 // Block capture by copy introduces 'const'.
10499 CaptureType = CaptureType.getNonReferenceType().withConst();
10500 DeclRefType = CaptureType;
10501
David Blaikiebbafb8a2012-03-11 07:00:24 +000010502 if (getLangOpts().CPlusPlus && BuildAndDiagnose) {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010503 if (const RecordType *Record = DeclRefType->getAs<RecordType>()) {
10504 // The capture logic needs the destructor, so make sure we mark it.
10505 // Usually this is unnecessary because most local variables have
10506 // their destructors marked at declaration time, but parameters are
10507 // an exception because it's technically only the call site that
10508 // actually requires the destructor.
10509 if (isa<ParmVarDecl>(Var))
10510 FinalizeVarWithDestructor(Var, Record);
10511
10512 // According to the blocks spec, the capture of a variable from
10513 // the stack requires a const copy constructor. This is not true
10514 // of the copy/move done to move a __block variable to the heap.
John McCall113bee02012-03-10 09:33:50 +000010515 Expr *DeclRef = new (Context) DeclRefExpr(Var, false,
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010516 DeclRefType.withConst(),
10517 VK_LValue, Loc);
10518 ExprResult Result
10519 = PerformCopyInitialization(
10520 InitializedEntity::InitializeBlock(Var->getLocation(),
10521 CaptureType, false),
10522 Loc, Owned(DeclRef));
10523
10524 // Build a full-expression copy expression if initialization
10525 // succeeded and used a non-trivial constructor. Recover from
10526 // errors by pretending that the copy isn't necessary.
10527 if (!Result.isInvalid() &&
10528 !cast<CXXConstructExpr>(Result.get())->getConstructor()
10529 ->isTrivial()) {
10530 Result = MaybeCreateExprWithCleanups(Result);
10531 CopyExpr = Result.take();
10532 }
10533 }
10534 }
10535 }
10536
10537 // Actually capture the variable.
10538 if (BuildAndDiagnose)
10539 CSI->addCapture(Var, HasBlocksAttr, ByRef, Nested, Loc,
10540 SourceLocation(), CaptureType, CopyExpr);
10541 Nested = true;
10542 continue;
10543 }
Douglas Gregor812d8f62012-02-18 05:51:20 +000010544
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010545 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(CSI);
10546
10547 // Determine whether we are capturing by reference or by value.
10548 bool ByRef = false;
10549 if (I == N - 1 && Kind != TryCapture_Implicit) {
10550 ByRef = (Kind == TryCapture_ExplicitByRef);
Eli Friedman24af8502012-02-03 22:47:37 +000010551 } else {
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010552 ByRef = (LSI->ImpCaptureStyle == LambdaScopeInfo::ImpCap_LambdaByref);
Eli Friedman24af8502012-02-03 22:47:37 +000010553 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010554
10555 // Compute the type of the field that will capture this variable.
10556 if (ByRef) {
10557 // C++11 [expr.prim.lambda]p15:
10558 // An entity is captured by reference if it is implicitly or
10559 // explicitly captured but not captured by copy. It is
10560 // unspecified whether additional unnamed non-static data
10561 // members are declared in the closure type for entities
10562 // captured by reference.
10563 //
10564 // FIXME: It is not clear whether we want to build an lvalue reference
10565 // to the DeclRefType or to CaptureType.getNonReferenceType(). GCC appears
10566 // to do the former, while EDG does the latter. Core issue 1249 will
10567 // clarify, but for now we follow GCC because it's a more permissive and
10568 // easily defensible position.
10569 CaptureType = Context.getLValueReferenceType(DeclRefType);
10570 } else {
10571 // C++11 [expr.prim.lambda]p14:
10572 // For each entity captured by copy, an unnamed non-static
10573 // data member is declared in the closure type. The
10574 // declaration order of these members is unspecified. The type
10575 // of such a data member is the type of the corresponding
10576 // captured entity if the entity is not a reference to an
10577 // object, or the referenced type otherwise. [Note: If the
10578 // captured entity is a reference to a function, the
10579 // corresponding data member is also a reference to a
10580 // function. - end note ]
10581 if (const ReferenceType *RefType = CaptureType->getAs<ReferenceType>()){
10582 if (!RefType->getPointeeType()->isFunctionType())
10583 CaptureType = RefType->getPointeeType();
Eli Friedman9bb33f52012-02-03 02:04:35 +000010584 }
John McCall67cd5e02012-03-30 05:23:48 +000010585
10586 // Forbid the lambda copy-capture of autoreleasing variables.
10587 if (CaptureType.getObjCLifetime() == Qualifiers::OCL_Autoreleasing) {
10588 if (BuildAndDiagnose) {
10589 Diag(Loc, diag::err_arc_autoreleasing_capture) << /*lambda*/ 1;
10590 Diag(Var->getLocation(), diag::note_previous_decl)
10591 << Var->getDeclName();
10592 }
10593 return true;
10594 }
Eli Friedman9bb33f52012-02-03 02:04:35 +000010595 }
10596
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010597 // Capture this variable in the lambda.
10598 Expr *CopyExpr = 0;
10599 if (BuildAndDiagnose) {
10600 ExprResult Result = captureInLambda(*this, LSI, Var, CaptureType,
Douglas Gregora8182f92012-05-16 17:01:33 +000010601 DeclRefType, Loc,
10602 I == N-1);
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010603 if (!Result.isInvalid())
10604 CopyExpr = Result.take();
10605 }
10606
10607 // Compute the type of a reference to this captured variable.
10608 if (ByRef)
10609 DeclRefType = CaptureType.getNonReferenceType();
10610 else {
10611 // C++ [expr.prim.lambda]p5:
10612 // The closure type for a lambda-expression has a public inline
10613 // function call operator [...]. This function call operator is
10614 // declared const (9.3.1) if and only if the lambda-expression’s
10615 // parameter-declaration-clause is not followed by mutable.
10616 DeclRefType = CaptureType.getNonReferenceType();
10617 if (!LSI->Mutable && !CaptureType->isReferenceType())
10618 DeclRefType.addConst();
10619 }
10620
10621 // Add the capture.
10622 if (BuildAndDiagnose)
10623 CSI->addCapture(Var, /*IsBlock=*/false, ByRef, Nested, Loc,
10624 EllipsisLoc, CaptureType, CopyExpr);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010625 Nested = true;
10626 }
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010627
10628 return false;
10629}
10630
10631bool Sema::tryCaptureVariable(VarDecl *Var, SourceLocation Loc,
10632 TryCaptureKind Kind, SourceLocation EllipsisLoc) {
10633 QualType CaptureType;
10634 QualType DeclRefType;
10635 return tryCaptureVariable(Var, Loc, Kind, EllipsisLoc,
10636 /*BuildAndDiagnose=*/true, CaptureType,
10637 DeclRefType);
10638}
10639
10640QualType Sema::getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc) {
10641 QualType CaptureType;
10642 QualType DeclRefType;
10643
10644 // Determine whether we can capture this variable.
10645 if (tryCaptureVariable(Var, Loc, TryCapture_Implicit, SourceLocation(),
10646 /*BuildAndDiagnose=*/false, CaptureType, DeclRefType))
10647 return QualType();
10648
10649 return DeclRefType;
Eli Friedman9bb33f52012-02-03 02:04:35 +000010650}
10651
Eli Friedman3bda6b12012-02-02 23:15:15 +000010652static void MarkVarDeclODRUsed(Sema &SemaRef, VarDecl *Var,
10653 SourceLocation Loc) {
10654 // Keep track of used but undefined variables.
Eli Friedman130bbd02012-02-04 00:54:05 +000010655 // FIXME: We shouldn't suppress this warning for static data members.
Daniel Dunbar9d355812012-03-09 01:51:51 +000010656 if (Var->hasDefinition(SemaRef.Context) == VarDecl::DeclarationOnly &&
Eli Friedman130bbd02012-02-04 00:54:05 +000010657 Var->getLinkage() != ExternalLinkage &&
10658 !(Var->isStaticDataMember() && Var->hasInit())) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010659 SourceLocation &old = SemaRef.UndefinedInternals[Var->getCanonicalDecl()];
10660 if (old.isInvalid()) old = Loc;
10661 }
10662
Douglas Gregorfdf598e2012-02-18 09:37:24 +000010663 SemaRef.tryCaptureVariable(Var, Loc);
Eli Friedman9bb33f52012-02-03 02:04:35 +000010664
Eli Friedman3bda6b12012-02-02 23:15:15 +000010665 Var->setUsed(true);
10666}
10667
10668void Sema::UpdateMarkingForLValueToRValue(Expr *E) {
10669 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10670 // an object that satisfies the requirements for appearing in a
10671 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10672 // is immediately applied." This function handles the lvalue-to-rvalue
10673 // conversion part.
10674 MaybeODRUseExprs.erase(E->IgnoreParens());
10675}
10676
Eli Friedmanc6237c62012-02-29 03:16:56 +000010677ExprResult Sema::ActOnConstantExpression(ExprResult Res) {
10678 if (!Res.isUsable())
10679 return Res;
10680
10681 // If a constant-expression is a reference to a variable where we delay
10682 // deciding whether it is an odr-use, just assume we will apply the
10683 // lvalue-to-rvalue conversion. In the one case where this doesn't happen
10684 // (a non-type template argument), we have special handling anyway.
10685 UpdateMarkingForLValueToRValue(Res.get());
10686 return Res;
10687}
10688
Eli Friedman3bda6b12012-02-02 23:15:15 +000010689void Sema::CleanupVarDeclMarking() {
10690 for (llvm::SmallPtrSetIterator<Expr*> i = MaybeODRUseExprs.begin(),
10691 e = MaybeODRUseExprs.end();
10692 i != e; ++i) {
10693 VarDecl *Var;
10694 SourceLocation Loc;
John McCall113bee02012-03-10 09:33:50 +000010695 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(*i)) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010696 Var = cast<VarDecl>(DRE->getDecl());
10697 Loc = DRE->getLocation();
10698 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(*i)) {
10699 Var = cast<VarDecl>(ME->getMemberDecl());
10700 Loc = ME->getMemberLoc();
10701 } else {
10702 llvm_unreachable("Unexpcted expression");
10703 }
10704
10705 MarkVarDeclODRUsed(*this, Var, Loc);
10706 }
10707
10708 MaybeODRUseExprs.clear();
10709}
10710
10711// Mark a VarDecl referenced, and perform the necessary handling to compute
10712// odr-uses.
10713static void DoMarkVarDeclReferenced(Sema &SemaRef, SourceLocation Loc,
10714 VarDecl *Var, Expr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010715 Var->setReferenced();
10716
Eli Friedman3bda6b12012-02-02 23:15:15 +000010717 if (!IsPotentiallyEvaluatedContext(SemaRef))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010718 return;
10719
10720 // Implicit instantiation of static data members of class templates.
Richard Smithd3cf2382012-02-15 02:42:50 +000010721 if (Var->isStaticDataMember() && Var->getInstantiatedFromStaticDataMember()) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010722 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
10723 assert(MSInfo && "Missing member specialization information?");
Richard Smithd3cf2382012-02-15 02:42:50 +000010724 bool AlreadyInstantiated = !MSInfo->getPointOfInstantiation().isInvalid();
10725 if (MSInfo->getTemplateSpecializationKind() == TSK_ImplicitInstantiation &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010726 (!AlreadyInstantiated ||
10727 Var->isUsableInConstantExpressions(SemaRef.Context))) {
Richard Smithd3cf2382012-02-15 02:42:50 +000010728 if (!AlreadyInstantiated) {
10729 // This is a modification of an existing AST node. Notify listeners.
10730 if (ASTMutationListener *L = SemaRef.getASTMutationListener())
10731 L->StaticDataMemberInstantiated(Var);
10732 MSInfo->setPointOfInstantiation(Loc);
10733 }
10734 SourceLocation PointOfInstantiation = MSInfo->getPointOfInstantiation();
Daniel Dunbar9d355812012-03-09 01:51:51 +000010735 if (Var->isUsableInConstantExpressions(SemaRef.Context))
Eli Friedmanfa0df832012-02-02 03:46:19 +000010736 // Do not defer instantiations of variables which could be used in a
10737 // constant expression.
Richard Smithd3cf2382012-02-15 02:42:50 +000010738 SemaRef.InstantiateStaticDataMemberDefinition(PointOfInstantiation,Var);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010739 else
Richard Smithd3cf2382012-02-15 02:42:50 +000010740 SemaRef.PendingInstantiations.push_back(
10741 std::make_pair(Var, PointOfInstantiation));
Eli Friedmanfa0df832012-02-02 03:46:19 +000010742 }
10743 }
10744
Eli Friedman3bda6b12012-02-02 23:15:15 +000010745 // Per C++11 [basic.def.odr], a variable is odr-used "unless it is
10746 // an object that satisfies the requirements for appearing in a
10747 // constant expression (5.19) and the lvalue-to-rvalue conversion (4.1)
10748 // is immediately applied." We check the first part here, and
10749 // Sema::UpdateMarkingForLValueToRValue deals with the second part.
10750 // Note that we use the C++11 definition everywhere because nothing in
Richard Smith35ecb362012-03-02 04:14:40 +000010751 // C++03 depends on whether we get the C++03 version correct. This does not
10752 // apply to references, since they are not objects.
Eli Friedman3bda6b12012-02-02 23:15:15 +000010753 const VarDecl *DefVD;
Richard Smith35ecb362012-03-02 04:14:40 +000010754 if (E && !isa<ParmVarDecl>(Var) && !Var->getType()->isReferenceType() &&
Daniel Dunbar9d355812012-03-09 01:51:51 +000010755 Var->isUsableInConstantExpressions(SemaRef.Context) &&
Eli Friedman3bda6b12012-02-02 23:15:15 +000010756 Var->getAnyInitializer(DefVD) && DefVD->checkInitIsICE())
10757 SemaRef.MaybeODRUseExprs.insert(E);
10758 else
10759 MarkVarDeclODRUsed(SemaRef, Var, Loc);
10760}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010761
Eli Friedman3bda6b12012-02-02 23:15:15 +000010762/// \brief Mark a variable referenced, and check whether it is odr-used
10763/// (C++ [basic.def.odr]p2, C99 6.9p3). Note that this should not be
10764/// used directly for normal expressions referring to VarDecl.
10765void Sema::MarkVariableReferenced(SourceLocation Loc, VarDecl *Var) {
10766 DoMarkVarDeclReferenced(*this, Loc, Var, 0);
Eli Friedmanfa0df832012-02-02 03:46:19 +000010767}
10768
10769static void MarkExprReferenced(Sema &SemaRef, SourceLocation Loc,
10770 Decl *D, Expr *E) {
Eli Friedman3bda6b12012-02-02 23:15:15 +000010771 if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
10772 DoMarkVarDeclReferenced(SemaRef, Loc, Var, E);
10773 return;
10774 }
10775
Eli Friedmanfa0df832012-02-02 03:46:19 +000010776 SemaRef.MarkAnyDeclReferenced(Loc, D);
Douglas Gregord3b672c2012-02-16 01:06:16 +000010777}
Eli Friedmanfa0df832012-02-02 03:46:19 +000010778
Eli Friedmanfa0df832012-02-02 03:46:19 +000010779/// \brief Perform reference-marking and odr-use handling for a DeclRefExpr.
10780void Sema::MarkDeclRefReferenced(DeclRefExpr *E) {
10781 MarkExprReferenced(*this, E->getLocation(), E->getDecl(), E);
10782}
10783
10784/// \brief Perform reference-marking and odr-use handling for a MemberExpr.
10785void Sema::MarkMemberReferenced(MemberExpr *E) {
10786 MarkExprReferenced(*this, E->getMemberLoc(), E->getMemberDecl(), E);
10787}
10788
Douglas Gregorf02455e2012-02-10 09:26:04 +000010789/// \brief Perform marking for a reference to an arbitrary declaration. It
Eli Friedmanfa0df832012-02-02 03:46:19 +000010790/// marks the declaration referenced, and performs odr-use checking for functions
10791/// and variables. This method should not be used when building an normal
10792/// expression which refers to a variable.
10793void Sema::MarkAnyDeclReferenced(SourceLocation Loc, Decl *D) {
10794 if (VarDecl *VD = dyn_cast<VarDecl>(D))
10795 MarkVariableReferenced(Loc, VD);
10796 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
10797 MarkFunctionReferenced(Loc, FD);
10798 else
10799 D->setReferenced();
Douglas Gregorc9c02ed2009-06-19 23:52:42 +000010800}
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010801
Douglas Gregor5597ab42010-05-07 23:12:07 +000010802namespace {
Chandler Carruthaf80f662010-06-09 08:17:30 +000010803 // Mark all of the declarations referenced
Douglas Gregor5597ab42010-05-07 23:12:07 +000010804 // FIXME: Not fully implemented yet! We need to have a better understanding
Chandler Carruthaf80f662010-06-09 08:17:30 +000010805 // of when we're entering
Douglas Gregor5597ab42010-05-07 23:12:07 +000010806 class MarkReferencedDecls : public RecursiveASTVisitor<MarkReferencedDecls> {
10807 Sema &S;
10808 SourceLocation Loc;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010809
Douglas Gregor5597ab42010-05-07 23:12:07 +000010810 public:
10811 typedef RecursiveASTVisitor<MarkReferencedDecls> Inherited;
Chandler Carruthaf80f662010-06-09 08:17:30 +000010812
Douglas Gregor5597ab42010-05-07 23:12:07 +000010813 MarkReferencedDecls(Sema &S, SourceLocation Loc) : S(S), Loc(Loc) { }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010814
10815 bool TraverseTemplateArgument(const TemplateArgument &Arg);
10816 bool TraverseRecordType(RecordType *T);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010817 };
10818}
10819
Chandler Carruthaf80f662010-06-09 08:17:30 +000010820bool MarkReferencedDecls::TraverseTemplateArgument(
10821 const TemplateArgument &Arg) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010822 if (Arg.getKind() == TemplateArgument::Declaration) {
Douglas Gregor31f55dc2012-04-06 22:40:38 +000010823 if (Decl *D = Arg.getAsDecl())
10824 S.MarkAnyDeclReferenced(Loc, D);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010825 }
Chandler Carruthaf80f662010-06-09 08:17:30 +000010826
10827 return Inherited::TraverseTemplateArgument(Arg);
Douglas Gregor5597ab42010-05-07 23:12:07 +000010828}
10829
Chandler Carruthaf80f662010-06-09 08:17:30 +000010830bool MarkReferencedDecls::TraverseRecordType(RecordType *T) {
Douglas Gregor5597ab42010-05-07 23:12:07 +000010831 if (ClassTemplateSpecializationDecl *Spec
10832 = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl())) {
10833 const TemplateArgumentList &Args = Spec->getTemplateArgs();
Douglas Gregor1ccc8412010-11-07 23:05:16 +000010834 return TraverseTemplateArguments(Args.data(), Args.size());
Douglas Gregor5597ab42010-05-07 23:12:07 +000010835 }
10836
Chandler Carruthc65667c2010-06-10 10:31:57 +000010837 return true;
Douglas Gregor5597ab42010-05-07 23:12:07 +000010838}
10839
10840void Sema::MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T) {
10841 MarkReferencedDecls Marker(*this, Loc);
Chandler Carruthaf80f662010-06-09 08:17:30 +000010842 Marker.TraverseType(Context.getCanonicalType(T));
Douglas Gregor5597ab42010-05-07 23:12:07 +000010843}
10844
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010845namespace {
10846 /// \brief Helper class that marks all of the declarations referenced by
10847 /// potentially-evaluated subexpressions as "referenced".
10848 class EvaluatedExprMarker : public EvaluatedExprVisitor<EvaluatedExprMarker> {
10849 Sema &S;
Douglas Gregor680e9e02012-02-21 19:11:17 +000010850 bool SkipLocalVariables;
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010851
10852 public:
10853 typedef EvaluatedExprVisitor<EvaluatedExprMarker> Inherited;
10854
Douglas Gregor680e9e02012-02-21 19:11:17 +000010855 EvaluatedExprMarker(Sema &S, bool SkipLocalVariables)
10856 : Inherited(S.Context), S(S), SkipLocalVariables(SkipLocalVariables) { }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010857
10858 void VisitDeclRefExpr(DeclRefExpr *E) {
Douglas Gregor680e9e02012-02-21 19:11:17 +000010859 // If we were asked not to visit local variables, don't.
10860 if (SkipLocalVariables) {
10861 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
10862 if (VD->hasLocalStorage())
10863 return;
10864 }
10865
Eli Friedmanfa0df832012-02-02 03:46:19 +000010866 S.MarkDeclRefReferenced(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010867 }
10868
10869 void VisitMemberExpr(MemberExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010870 S.MarkMemberReferenced(E);
Douglas Gregor32b3de52010-09-11 23:32:50 +000010871 Inherited::VisitMemberExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010872 }
10873
John McCall28fc7092011-11-10 05:35:25 +000010874 void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010875 S.MarkFunctionReferenced(E->getLocStart(),
John McCall28fc7092011-11-10 05:35:25 +000010876 const_cast<CXXDestructorDecl*>(E->getTemporary()->getDestructor()));
10877 Visit(E->getSubExpr());
10878 }
10879
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010880 void VisitCXXNewExpr(CXXNewExpr *E) {
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010881 if (E->getOperatorNew())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010882 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorNew());
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010883 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010884 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010885 Inherited::VisitCXXNewExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010886 }
Sebastian Redl6047f072012-02-16 12:22:20 +000010887
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010888 void VisitCXXDeleteExpr(CXXDeleteExpr *E) {
10889 if (E->getOperatorDelete())
Eli Friedmanfa0df832012-02-02 03:46:19 +000010890 S.MarkFunctionReferenced(E->getLocStart(), E->getOperatorDelete());
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010891 QualType Destroyed = S.Context.getBaseElementType(E->getDestroyedType());
10892 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
10893 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
Eli Friedmanfa0df832012-02-02 03:46:19 +000010894 S.MarkFunctionReferenced(E->getLocStart(),
Douglas Gregor6ed2fee2010-09-14 22:55:20 +000010895 S.LookupDestructor(Record));
10896 }
10897
Douglas Gregor32b3de52010-09-11 23:32:50 +000010898 Inherited::VisitCXXDeleteExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010899 }
10900
10901 void VisitCXXConstructExpr(CXXConstructExpr *E) {
Eli Friedmanfa0df832012-02-02 03:46:19 +000010902 S.MarkFunctionReferenced(E->getLocStart(), E->getConstructor());
Douglas Gregor32b3de52010-09-11 23:32:50 +000010903 Inherited::VisitCXXConstructExpr(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010904 }
10905
Douglas Gregorf0873f42010-10-19 17:17:35 +000010906 void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
10907 Visit(E->getExpr());
10908 }
Eli Friedman3bda6b12012-02-02 23:15:15 +000010909
10910 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10911 Inherited::VisitImplicitCastExpr(E);
10912
10913 if (E->getCastKind() == CK_LValueToRValue)
10914 S.UpdateMarkingForLValueToRValue(E->getSubExpr());
10915 }
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010916 };
10917}
10918
10919/// \brief Mark any declarations that appear within this expression or any
10920/// potentially-evaluated subexpressions as "referenced".
Douglas Gregor680e9e02012-02-21 19:11:17 +000010921///
10922/// \param SkipLocalVariables If true, don't mark local variables as
10923/// 'referenced'.
10924void Sema::MarkDeclarationsReferencedInExpr(Expr *E,
10925 bool SkipLocalVariables) {
10926 EvaluatedExprMarker(*this, SkipLocalVariables).Visit(E);
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010927}
10928
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010929/// \brief Emit a diagnostic that describes an effect on the run-time behavior
10930/// of the program being compiled.
10931///
10932/// This routine emits the given diagnostic when the code currently being
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010933/// type-checked is "potentially evaluated", meaning that there is a
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010934/// possibility that the code will actually be executable. Code in sizeof()
10935/// expressions, code used only during overload resolution, etc., are not
10936/// potentially evaluated. This routine will suppress such diagnostics or,
10937/// in the absolutely nutty case of potentially potentially evaluated
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010938/// expressions (C++ typeid), queue the diagnostic to potentially emit it
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010939/// later.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010940///
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010941/// This routine should be used for all diagnostics that describe the run-time
10942/// behavior of a program, such as passing a non-POD value through an ellipsis.
10943/// Failure to do so will likely result in spurious diagnostics or failures
10944/// during overload resolution or within sizeof/alignof/typeof/typeid.
Richard Trieuba63ce62011-09-09 01:45:06 +000010945bool Sema::DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement,
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010946 const PartialDiagnostic &PD) {
John McCall31168b02011-06-15 23:02:42 +000010947 switch (ExprEvalContexts.back().Context) {
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010948 case Unevaluated:
10949 // The argument will never be evaluated, so don't complain.
10950 break;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000010951
Richard Smith764d2fe2011-12-20 02:08:33 +000010952 case ConstantEvaluated:
10953 // Relevant diagnostics should be produced by constant evaluation.
10954 break;
10955
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010956 case PotentiallyEvaluated:
Douglas Gregor8a01b2a2010-09-11 20:24:53 +000010957 case PotentiallyEvaluatedIfUsed:
Richard Trieuba63ce62011-09-09 01:45:06 +000010958 if (Statement && getCurFunctionOrMethodDecl()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +000010959 FunctionScopes.back()->PossiblyUnreachableDiags.
Richard Trieuba63ce62011-09-09 01:45:06 +000010960 push_back(sema::PossiblyUnreachableDiag(PD, Loc, Statement));
Ted Kremenek3427fac2011-02-23 01:52:04 +000010961 }
10962 else
10963 Diag(Loc, PD);
10964
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010965 return true;
Douglas Gregorda8cdbc2009-12-22 01:01:55 +000010966 }
10967
10968 return false;
10969}
10970
Anders Carlsson7f84ed92009-10-09 23:51:55 +000010971bool Sema::CheckCallReturnType(QualType ReturnType, SourceLocation Loc,
10972 CallExpr *CE, FunctionDecl *FD) {
10973 if (ReturnType->isVoidType() || !ReturnType->isIncompleteType())
10974 return false;
10975
Richard Smithfd555f62012-02-22 02:04:18 +000010976 // If we're inside a decltype's expression, don't check for a valid return
10977 // type or construct temporaries until we know whether this is the last call.
10978 if (ExprEvalContexts.back().IsDecltype) {
10979 ExprEvalContexts.back().DelayedDecltypeCalls.push_back(CE);
10980 return false;
10981 }
10982
Douglas Gregora6c5abb2012-05-04 16:48:41 +000010983 class CallReturnIncompleteDiagnoser : public TypeDiagnoser {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000010984 FunctionDecl *FD;
10985 CallExpr *CE;
10986
10987 public:
10988 CallReturnIncompleteDiagnoser(FunctionDecl *FD, CallExpr *CE)
10989 : FD(FD), CE(CE) { }
10990
10991 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
10992 if (!FD) {
10993 S.Diag(Loc, diag::err_call_incomplete_return)
10994 << T << CE->getSourceRange();
10995 return;
10996 }
10997
10998 S.Diag(Loc, diag::err_call_function_incomplete_return)
10999 << CE->getSourceRange() << FD->getDeclName() << T;
11000 S.Diag(FD->getLocation(),
11001 diag::note_function_with_incomplete_return_type_declared_here)
11002 << FD->getDeclName();
11003 }
11004 } Diagnoser(FD, CE);
11005
11006 if (RequireCompleteType(Loc, ReturnType, Diagnoser))
Anders Carlsson7f84ed92009-10-09 23:51:55 +000011007 return true;
11008
11009 return false;
11010}
11011
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011012// Diagnose the s/=/==/ and s/\|=/!=/ typos. Note that adding parentheses
John McCalld5707ab2009-10-12 21:59:07 +000011013// will prevent this condition from triggering, which is what we want.
11014void Sema::DiagnoseAssignmentAsCondition(Expr *E) {
11015 SourceLocation Loc;
11016
John McCall0506e4a2009-11-11 02:41:58 +000011017 unsigned diagnostic = diag::warn_condition_is_assignment;
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011018 bool IsOrAssign = false;
John McCall0506e4a2009-11-11 02:41:58 +000011019
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011020 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011021 if (Op->getOpcode() != BO_Assign && Op->getOpcode() != BO_OrAssign)
John McCalld5707ab2009-10-12 21:59:07 +000011022 return;
11023
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011024 IsOrAssign = Op->getOpcode() == BO_OrAssign;
11025
John McCallb0e419e2009-11-12 00:06:05 +000011026 // Greylist some idioms by putting them into a warning subcategory.
11027 if (ObjCMessageExpr *ME
11028 = dyn_cast<ObjCMessageExpr>(Op->getRHS()->IgnoreParenCasts())) {
11029 Selector Sel = ME->getSelector();
11030
John McCallb0e419e2009-11-12 00:06:05 +000011031 // self = [<foo> init...]
Douglas Gregor486b74e2011-09-27 16:10:05 +000011032 if (isSelfExpr(Op->getLHS()) && Sel.getNameForSlot(0).startswith("init"))
John McCallb0e419e2009-11-12 00:06:05 +000011033 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11034
11035 // <foo> = [<bar> nextObject]
Douglas Gregoraf2a6ae2011-02-18 22:29:55 +000011036 else if (Sel.isUnarySelector() && Sel.getNameForSlot(0) == "nextObject")
John McCallb0e419e2009-11-12 00:06:05 +000011037 diagnostic = diag::warn_condition_is_idiomatic_assignment;
11038 }
John McCall0506e4a2009-11-11 02:41:58 +000011039
John McCalld5707ab2009-10-12 21:59:07 +000011040 Loc = Op->getOperatorLoc();
Chandler Carruthf87d6c02011-08-16 22:30:10 +000011041 } else if (CXXOperatorCallExpr *Op = dyn_cast<CXXOperatorCallExpr>(E)) {
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011042 if (Op->getOperator() != OO_Equal && Op->getOperator() != OO_PipeEqual)
John McCalld5707ab2009-10-12 21:59:07 +000011043 return;
11044
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011045 IsOrAssign = Op->getOperator() == OO_PipeEqual;
John McCalld5707ab2009-10-12 21:59:07 +000011046 Loc = Op->getOperatorLoc();
11047 } else {
11048 // Not an assignment.
11049 return;
11050 }
11051
Douglas Gregor2bf2d3d2010-04-14 16:09:52 +000011052 Diag(Loc, diagnostic) << E->getSourceRange();
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011053
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011054 SourceLocation Open = E->getLocStart();
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011055 SourceLocation Close = PP.getLocForEndOfToken(E->getSourceRange().getEnd());
11056 Diag(Loc, diag::note_condition_assign_silence)
11057 << FixItHint::CreateInsertion(Open, "(")
11058 << FixItHint::CreateInsertion(Close, ")");
11059
Douglas Gregor2d4f64f2011-01-19 16:50:08 +000011060 if (IsOrAssign)
11061 Diag(Loc, diag::note_condition_or_assign_to_comparison)
11062 << FixItHint::CreateReplacement(Loc, "!=");
11063 else
11064 Diag(Loc, diag::note_condition_assign_to_comparison)
11065 << FixItHint::CreateReplacement(Loc, "==");
John McCalld5707ab2009-10-12 21:59:07 +000011066}
11067
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011068/// \brief Redundant parentheses over an equality comparison can indicate
11069/// that the user intended an assignment used as condition.
Richard Trieuba63ce62011-09-09 01:45:06 +000011070void Sema::DiagnoseEqualityWithExtraParens(ParenExpr *ParenE) {
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011071 // Don't warn if the parens came from a macro.
Richard Trieuba63ce62011-09-09 01:45:06 +000011072 SourceLocation parenLoc = ParenE->getLocStart();
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011073 if (parenLoc.isInvalid() || parenLoc.isMacroID())
11074 return;
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011075 // Don't warn for dependent expressions.
Richard Trieuba63ce62011-09-09 01:45:06 +000011076 if (ParenE->isTypeDependent())
Argyrios Kyrtzidisba699d62011-03-28 23:52:04 +000011077 return;
Argyrios Kyrtzidisf4f82782011-02-01 22:23:56 +000011078
Richard Trieuba63ce62011-09-09 01:45:06 +000011079 Expr *E = ParenE->IgnoreParens();
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011080
11081 if (BinaryOperator *opE = dyn_cast<BinaryOperator>(E))
Argyrios Kyrtzidis582dd682011-02-01 19:32:59 +000011082 if (opE->getOpcode() == BO_EQ &&
11083 opE->getLHS()->IgnoreParenImpCasts()->isModifiableLvalue(Context)
11084 == Expr::MLV_Valid) {
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011085 SourceLocation Loc = opE->getOperatorLoc();
Ted Kremenekc358d9f2011-02-01 22:36:09 +000011086
Ted Kremenekae022092011-02-02 02:20:30 +000011087 Diag(Loc, diag::warn_equality_with_extra_parens) << E->getSourceRange();
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011088 SourceRange ParenERange = ParenE->getSourceRange();
Ted Kremenekae022092011-02-02 02:20:30 +000011089 Diag(Loc, diag::note_equality_comparison_silence)
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011090 << FixItHint::CreateRemoval(ParenERange.getBegin())
11091 << FixItHint::CreateRemoval(ParenERange.getEnd());
Argyrios Kyrtzidise1b97c42011-04-25 23:01:29 +000011092 Diag(Loc, diag::note_equality_comparison_to_assign)
11093 << FixItHint::CreateReplacement(Loc, "=");
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011094 }
11095}
11096
John Wiegley01296292011-04-08 18:41:53 +000011097ExprResult Sema::CheckBooleanCondition(Expr *E, SourceLocation Loc) {
John McCalld5707ab2009-10-12 21:59:07 +000011098 DiagnoseAssignmentAsCondition(E);
Argyrios Kyrtzidis8b6ec682011-02-01 18:24:22 +000011099 if (ParenExpr *parenE = dyn_cast<ParenExpr>(E))
11100 DiagnoseEqualityWithExtraParens(parenE);
John McCalld5707ab2009-10-12 21:59:07 +000011101
John McCall0009fcc2011-04-26 20:42:42 +000011102 ExprResult result = CheckPlaceholderExpr(E);
11103 if (result.isInvalid()) return ExprError();
11104 E = result.take();
Argyrios Kyrtzidisca766292010-11-01 18:49:26 +000011105
John McCall0009fcc2011-04-26 20:42:42 +000011106 if (!E->isTypeDependent()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000011107 if (getLangOpts().CPlusPlus)
John McCall34376a62010-12-04 03:47:34 +000011108 return CheckCXXBooleanCondition(E); // C++ 6.4p4
11109
John Wiegley01296292011-04-08 18:41:53 +000011110 ExprResult ERes = DefaultFunctionArrayLvalueConversion(E);
11111 if (ERes.isInvalid())
11112 return ExprError();
11113 E = ERes.take();
John McCall29cb2fd2010-12-04 06:09:13 +000011114
11115 QualType T = E->getType();
John Wiegley01296292011-04-08 18:41:53 +000011116 if (!T->isScalarType()) { // C99 6.8.4.1p1
11117 Diag(Loc, diag::err_typecheck_statement_requires_scalar)
11118 << T << E->getSourceRange();
11119 return ExprError();
11120 }
John McCalld5707ab2009-10-12 21:59:07 +000011121 }
11122
John Wiegley01296292011-04-08 18:41:53 +000011123 return Owned(E);
John McCalld5707ab2009-10-12 21:59:07 +000011124}
Douglas Gregore60e41a2010-05-06 17:25:47 +000011125
John McCalldadc5752010-08-24 06:29:42 +000011126ExprResult Sema::ActOnBooleanCondition(Scope *S, SourceLocation Loc,
Richard Trieuba63ce62011-09-09 01:45:06 +000011127 Expr *SubExpr) {
11128 if (!SubExpr)
Douglas Gregore60e41a2010-05-06 17:25:47 +000011129 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011130
Richard Trieuba63ce62011-09-09 01:45:06 +000011131 return CheckBooleanCondition(SubExpr, Loc);
Douglas Gregore60e41a2010-05-06 17:25:47 +000011132}
John McCall36e7fe32010-10-12 00:20:44 +000011133
John McCall31996342011-04-07 08:22:57 +000011134namespace {
John McCall2979fe02011-04-12 00:42:48 +000011135 /// A visitor for rebuilding a call to an __unknown_any expression
11136 /// to have an appropriate type.
11137 struct RebuildUnknownAnyFunction
11138 : StmtVisitor<RebuildUnknownAnyFunction, ExprResult> {
11139
11140 Sema &S;
11141
11142 RebuildUnknownAnyFunction(Sema &S) : S(S) {}
11143
11144 ExprResult VisitStmt(Stmt *S) {
11145 llvm_unreachable("unexpected statement!");
John McCall2979fe02011-04-12 00:42:48 +000011146 }
11147
Richard Trieu10162ab2011-09-09 03:59:41 +000011148 ExprResult VisitExpr(Expr *E) {
11149 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_call)
11150 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011151 return ExprError();
11152 }
11153
11154 /// Rebuild an expression which simply semantically wraps another
11155 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011156 template <class T> ExprResult rebuildSugarExpr(T *E) {
11157 ExprResult SubResult = Visit(E->getSubExpr());
11158 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011159
Richard Trieu10162ab2011-09-09 03:59:41 +000011160 Expr *SubExpr = SubResult.take();
11161 E->setSubExpr(SubExpr);
11162 E->setType(SubExpr->getType());
11163 E->setValueKind(SubExpr->getValueKind());
11164 assert(E->getObjectKind() == OK_Ordinary);
11165 return E;
John McCall2979fe02011-04-12 00:42:48 +000011166 }
11167
Richard Trieu10162ab2011-09-09 03:59:41 +000011168 ExprResult VisitParenExpr(ParenExpr *E) {
11169 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011170 }
11171
Richard Trieu10162ab2011-09-09 03:59:41 +000011172 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11173 return rebuildSugarExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011174 }
11175
Richard Trieu10162ab2011-09-09 03:59:41 +000011176 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11177 ExprResult SubResult = Visit(E->getSubExpr());
11178 if (SubResult.isInvalid()) return ExprError();
John McCall2979fe02011-04-12 00:42:48 +000011179
Richard Trieu10162ab2011-09-09 03:59:41 +000011180 Expr *SubExpr = SubResult.take();
11181 E->setSubExpr(SubExpr);
11182 E->setType(S.Context.getPointerType(SubExpr->getType()));
11183 assert(E->getValueKind() == VK_RValue);
11184 assert(E->getObjectKind() == OK_Ordinary);
11185 return E;
John McCall2979fe02011-04-12 00:42:48 +000011186 }
11187
Richard Trieu10162ab2011-09-09 03:59:41 +000011188 ExprResult resolveDecl(Expr *E, ValueDecl *VD) {
11189 if (!isa<FunctionDecl>(VD)) return VisitExpr(E);
John McCall2979fe02011-04-12 00:42:48 +000011190
Richard Trieu10162ab2011-09-09 03:59:41 +000011191 E->setType(VD->getType());
John McCall2979fe02011-04-12 00:42:48 +000011192
Richard Trieu10162ab2011-09-09 03:59:41 +000011193 assert(E->getValueKind() == VK_RValue);
David Blaikiebbafb8a2012-03-11 07:00:24 +000011194 if (S.getLangOpts().CPlusPlus &&
Richard Trieu10162ab2011-09-09 03:59:41 +000011195 !(isa<CXXMethodDecl>(VD) &&
11196 cast<CXXMethodDecl>(VD)->isInstance()))
11197 E->setValueKind(VK_LValue);
John McCall2979fe02011-04-12 00:42:48 +000011198
Richard Trieu10162ab2011-09-09 03:59:41 +000011199 return E;
John McCall2979fe02011-04-12 00:42:48 +000011200 }
11201
Richard Trieu10162ab2011-09-09 03:59:41 +000011202 ExprResult VisitMemberExpr(MemberExpr *E) {
11203 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011204 }
11205
Richard Trieu10162ab2011-09-09 03:59:41 +000011206 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11207 return resolveDecl(E, E->getDecl());
John McCall2979fe02011-04-12 00:42:48 +000011208 }
11209 };
11210}
11211
11212/// Given a function expression of unknown-any type, try to rebuild it
11213/// to have a function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011214static ExprResult rebuildUnknownAnyFunction(Sema &S, Expr *FunctionExpr) {
11215 ExprResult Result = RebuildUnknownAnyFunction(S).Visit(FunctionExpr);
11216 if (Result.isInvalid()) return ExprError();
11217 return S.DefaultFunctionArrayConversion(Result.take());
John McCall2979fe02011-04-12 00:42:48 +000011218}
11219
11220namespace {
John McCall2d2e8702011-04-11 07:02:50 +000011221 /// A visitor for rebuilding an expression of type __unknown_anytype
11222 /// into one which resolves the type directly on the referring
11223 /// expression. Strict preservation of the original source
11224 /// structure is not a goal.
John McCall31996342011-04-07 08:22:57 +000011225 struct RebuildUnknownAnyExpr
John McCall39439732011-04-09 22:50:59 +000011226 : StmtVisitor<RebuildUnknownAnyExpr, ExprResult> {
John McCall31996342011-04-07 08:22:57 +000011227
11228 Sema &S;
11229
11230 /// The current destination type.
11231 QualType DestType;
11232
Richard Trieu10162ab2011-09-09 03:59:41 +000011233 RebuildUnknownAnyExpr(Sema &S, QualType CastType)
11234 : S(S), DestType(CastType) {}
John McCall31996342011-04-07 08:22:57 +000011235
John McCall39439732011-04-09 22:50:59 +000011236 ExprResult VisitStmt(Stmt *S) {
John McCall2d2e8702011-04-11 07:02:50 +000011237 llvm_unreachable("unexpected statement!");
John McCall31996342011-04-07 08:22:57 +000011238 }
11239
Richard Trieu10162ab2011-09-09 03:59:41 +000011240 ExprResult VisitExpr(Expr *E) {
11241 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11242 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011243 return ExprError();
John McCall31996342011-04-07 08:22:57 +000011244 }
11245
Richard Trieu10162ab2011-09-09 03:59:41 +000011246 ExprResult VisitCallExpr(CallExpr *E);
11247 ExprResult VisitObjCMessageExpr(ObjCMessageExpr *E);
John McCall2d2e8702011-04-11 07:02:50 +000011248
John McCall39439732011-04-09 22:50:59 +000011249 /// Rebuild an expression which simply semantically wraps another
11250 /// expression which it shares the type and value kind of.
Richard Trieu10162ab2011-09-09 03:59:41 +000011251 template <class T> ExprResult rebuildSugarExpr(T *E) {
11252 ExprResult SubResult = Visit(E->getSubExpr());
11253 if (SubResult.isInvalid()) return ExprError();
11254 Expr *SubExpr = SubResult.take();
11255 E->setSubExpr(SubExpr);
11256 E->setType(SubExpr->getType());
11257 E->setValueKind(SubExpr->getValueKind());
11258 assert(E->getObjectKind() == OK_Ordinary);
11259 return E;
John McCall39439732011-04-09 22:50:59 +000011260 }
John McCall31996342011-04-07 08:22:57 +000011261
Richard Trieu10162ab2011-09-09 03:59:41 +000011262 ExprResult VisitParenExpr(ParenExpr *E) {
11263 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011264 }
11265
Richard Trieu10162ab2011-09-09 03:59:41 +000011266 ExprResult VisitUnaryExtension(UnaryOperator *E) {
11267 return rebuildSugarExpr(E);
John McCall39439732011-04-09 22:50:59 +000011268 }
11269
Richard Trieu10162ab2011-09-09 03:59:41 +000011270 ExprResult VisitUnaryAddrOf(UnaryOperator *E) {
11271 const PointerType *Ptr = DestType->getAs<PointerType>();
11272 if (!Ptr) {
11273 S.Diag(E->getOperatorLoc(), diag::err_unknown_any_addrof)
11274 << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011275 return ExprError();
11276 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011277 assert(E->getValueKind() == VK_RValue);
11278 assert(E->getObjectKind() == OK_Ordinary);
11279 E->setType(DestType);
John McCall2979fe02011-04-12 00:42:48 +000011280
11281 // Build the sub-expression as if it were an object of the pointee type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011282 DestType = Ptr->getPointeeType();
11283 ExprResult SubResult = Visit(E->getSubExpr());
11284 if (SubResult.isInvalid()) return ExprError();
11285 E->setSubExpr(SubResult.take());
11286 return E;
John McCall2979fe02011-04-12 00:42:48 +000011287 }
11288
Richard Trieu10162ab2011-09-09 03:59:41 +000011289 ExprResult VisitImplicitCastExpr(ImplicitCastExpr *E);
John McCall39439732011-04-09 22:50:59 +000011290
Richard Trieu10162ab2011-09-09 03:59:41 +000011291 ExprResult resolveDecl(Expr *E, ValueDecl *VD);
John McCall39439732011-04-09 22:50:59 +000011292
Richard Trieu10162ab2011-09-09 03:59:41 +000011293 ExprResult VisitMemberExpr(MemberExpr *E) {
11294 return resolveDecl(E, E->getMemberDecl());
John McCall2979fe02011-04-12 00:42:48 +000011295 }
John McCall39439732011-04-09 22:50:59 +000011296
Richard Trieu10162ab2011-09-09 03:59:41 +000011297 ExprResult VisitDeclRefExpr(DeclRefExpr *E) {
11298 return resolveDecl(E, E->getDecl());
John McCall31996342011-04-07 08:22:57 +000011299 }
11300 };
11301}
11302
John McCall2d2e8702011-04-11 07:02:50 +000011303/// Rebuilds a call expression which yielded __unknown_anytype.
Richard Trieu10162ab2011-09-09 03:59:41 +000011304ExprResult RebuildUnknownAnyExpr::VisitCallExpr(CallExpr *E) {
11305 Expr *CalleeExpr = E->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011306
11307 enum FnKind {
John McCall4adb38c2011-04-27 00:36:17 +000011308 FK_MemberFunction,
John McCall2d2e8702011-04-11 07:02:50 +000011309 FK_FunctionPointer,
11310 FK_BlockPointer
11311 };
11312
Richard Trieu10162ab2011-09-09 03:59:41 +000011313 FnKind Kind;
11314 QualType CalleeType = CalleeExpr->getType();
11315 if (CalleeType == S.Context.BoundMemberTy) {
11316 assert(isa<CXXMemberCallExpr>(E) || isa<CXXOperatorCallExpr>(E));
11317 Kind = FK_MemberFunction;
11318 CalleeType = Expr::findBoundMemberType(CalleeExpr);
11319 } else if (const PointerType *Ptr = CalleeType->getAs<PointerType>()) {
11320 CalleeType = Ptr->getPointeeType();
11321 Kind = FK_FunctionPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011322 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011323 CalleeType = CalleeType->castAs<BlockPointerType>()->getPointeeType();
11324 Kind = FK_BlockPointer;
John McCall2d2e8702011-04-11 07:02:50 +000011325 }
Richard Trieu10162ab2011-09-09 03:59:41 +000011326 const FunctionType *FnType = CalleeType->castAs<FunctionType>();
John McCall2d2e8702011-04-11 07:02:50 +000011327
11328 // Verify that this is a legal result type of a function.
11329 if (DestType->isArrayType() || DestType->isFunctionType()) {
11330 unsigned diagID = diag::err_func_returning_array_function;
Richard Trieu10162ab2011-09-09 03:59:41 +000011331 if (Kind == FK_BlockPointer)
John McCall2d2e8702011-04-11 07:02:50 +000011332 diagID = diag::err_block_returning_array_function;
11333
Richard Trieu10162ab2011-09-09 03:59:41 +000011334 S.Diag(E->getExprLoc(), diagID)
John McCall2d2e8702011-04-11 07:02:50 +000011335 << DestType->isFunctionType() << DestType;
11336 return ExprError();
11337 }
11338
11339 // Otherwise, go ahead and set DestType as the call's result.
Richard Trieu10162ab2011-09-09 03:59:41 +000011340 E->setType(DestType.getNonLValueExprType(S.Context));
11341 E->setValueKind(Expr::getValueKindForType(DestType));
11342 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011343
11344 // Rebuild the function type, replacing the result type with DestType.
Richard Trieu10162ab2011-09-09 03:59:41 +000011345 if (const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FnType))
John McCall2d2e8702011-04-11 07:02:50 +000011346 DestType = S.Context.getFunctionType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011347 Proto->arg_type_begin(),
11348 Proto->getNumArgs(),
11349 Proto->getExtProtoInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011350 else
11351 DestType = S.Context.getFunctionNoProtoType(DestType,
Richard Trieu10162ab2011-09-09 03:59:41 +000011352 FnType->getExtInfo());
John McCall2d2e8702011-04-11 07:02:50 +000011353
11354 // Rebuild the appropriate pointer-to-function type.
Richard Trieu10162ab2011-09-09 03:59:41 +000011355 switch (Kind) {
John McCall4adb38c2011-04-27 00:36:17 +000011356 case FK_MemberFunction:
John McCall2d2e8702011-04-11 07:02:50 +000011357 // Nothing to do.
11358 break;
11359
11360 case FK_FunctionPointer:
11361 DestType = S.Context.getPointerType(DestType);
11362 break;
11363
11364 case FK_BlockPointer:
11365 DestType = S.Context.getBlockPointerType(DestType);
11366 break;
11367 }
11368
11369 // Finally, we can recurse.
Richard Trieu10162ab2011-09-09 03:59:41 +000011370 ExprResult CalleeResult = Visit(CalleeExpr);
11371 if (!CalleeResult.isUsable()) return ExprError();
11372 E->setCallee(CalleeResult.take());
John McCall2d2e8702011-04-11 07:02:50 +000011373
11374 // Bind a temporary if necessary.
Richard Trieu10162ab2011-09-09 03:59:41 +000011375 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011376}
11377
Richard Trieu10162ab2011-09-09 03:59:41 +000011378ExprResult RebuildUnknownAnyExpr::VisitObjCMessageExpr(ObjCMessageExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011379 // Verify that this is a legal result type of a call.
11380 if (DestType->isArrayType() || DestType->isFunctionType()) {
Richard Trieu10162ab2011-09-09 03:59:41 +000011381 S.Diag(E->getExprLoc(), diag::err_func_returning_array_function)
John McCall2979fe02011-04-12 00:42:48 +000011382 << DestType->isFunctionType() << DestType;
11383 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011384 }
11385
John McCall3f4138c2011-07-13 17:56:40 +000011386 // Rewrite the method result type if available.
Richard Trieu10162ab2011-09-09 03:59:41 +000011387 if (ObjCMethodDecl *Method = E->getMethodDecl()) {
11388 assert(Method->getResultType() == S.Context.UnknownAnyTy);
11389 Method->setResultType(DestType);
John McCall3f4138c2011-07-13 17:56:40 +000011390 }
John McCall2979fe02011-04-12 00:42:48 +000011391
John McCall2d2e8702011-04-11 07:02:50 +000011392 // Change the type of the message.
Richard Trieu10162ab2011-09-09 03:59:41 +000011393 E->setType(DestType.getNonReferenceType());
11394 E->setValueKind(Expr::getValueKindForType(DestType));
John McCall2d2e8702011-04-11 07:02:50 +000011395
Richard Trieu10162ab2011-09-09 03:59:41 +000011396 return S.MaybeBindToTemporary(E);
John McCall2d2e8702011-04-11 07:02:50 +000011397}
11398
Richard Trieu10162ab2011-09-09 03:59:41 +000011399ExprResult RebuildUnknownAnyExpr::VisitImplicitCastExpr(ImplicitCastExpr *E) {
John McCall2979fe02011-04-12 00:42:48 +000011400 // The only case we should ever see here is a function-to-pointer decay.
Sean Callanan2db103c2012-03-06 23:12:57 +000011401 if (E->getCastKind() == CK_FunctionToPointerDecay) {
Sean Callanan12495112012-03-06 21:34:12 +000011402 assert(E->getValueKind() == VK_RValue);
11403 assert(E->getObjectKind() == OK_Ordinary);
11404
11405 E->setType(DestType);
11406
11407 // Rebuild the sub-expression as the pointee (function) type.
11408 DestType = DestType->castAs<PointerType>()->getPointeeType();
11409
11410 ExprResult Result = Visit(E->getSubExpr());
11411 if (!Result.isUsable()) return ExprError();
11412
11413 E->setSubExpr(Result.take());
11414 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011415 } else if (E->getCastKind() == CK_LValueToRValue) {
Sean Callanan12495112012-03-06 21:34:12 +000011416 assert(E->getValueKind() == VK_RValue);
11417 assert(E->getObjectKind() == OK_Ordinary);
John McCall2d2e8702011-04-11 07:02:50 +000011418
Sean Callanan12495112012-03-06 21:34:12 +000011419 assert(isa<BlockPointerType>(E->getType()));
John McCall2979fe02011-04-12 00:42:48 +000011420
Sean Callanan12495112012-03-06 21:34:12 +000011421 E->setType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011422
Sean Callanan12495112012-03-06 21:34:12 +000011423 // The sub-expression has to be a lvalue reference, so rebuild it as such.
11424 DestType = S.Context.getLValueReferenceType(DestType);
John McCall2d2e8702011-04-11 07:02:50 +000011425
Sean Callanan12495112012-03-06 21:34:12 +000011426 ExprResult Result = Visit(E->getSubExpr());
11427 if (!Result.isUsable()) return ExprError();
11428
11429 E->setSubExpr(Result.take());
11430 return S.Owned(E);
Sean Callanan2db103c2012-03-06 23:12:57 +000011431 } else {
Sean Callanan12495112012-03-06 21:34:12 +000011432 llvm_unreachable("Unhandled cast type!");
11433 }
John McCall2d2e8702011-04-11 07:02:50 +000011434}
11435
Richard Trieu10162ab2011-09-09 03:59:41 +000011436ExprResult RebuildUnknownAnyExpr::resolveDecl(Expr *E, ValueDecl *VD) {
11437 ExprValueKind ValueKind = VK_LValue;
11438 QualType Type = DestType;
John McCall2d2e8702011-04-11 07:02:50 +000011439
11440 // We know how to make this work for certain kinds of decls:
11441
11442 // - functions
Richard Trieu10162ab2011-09-09 03:59:41 +000011443 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(VD)) {
11444 if (const PointerType *Ptr = Type->getAs<PointerType>()) {
11445 DestType = Ptr->getPointeeType();
11446 ExprResult Result = resolveDecl(E, VD);
11447 if (Result.isInvalid()) return ExprError();
11448 return S.ImpCastExprToType(Result.take(), Type,
John McCall9a877fe2011-08-10 04:12:23 +000011449 CK_FunctionToPointerDecay, VK_RValue);
11450 }
11451
Richard Trieu10162ab2011-09-09 03:59:41 +000011452 if (!Type->isFunctionType()) {
11453 S.Diag(E->getExprLoc(), diag::err_unknown_any_function)
11454 << VD << E->getSourceRange();
John McCall9a877fe2011-08-10 04:12:23 +000011455 return ExprError();
11456 }
John McCall2d2e8702011-04-11 07:02:50 +000011457
Richard Trieu10162ab2011-09-09 03:59:41 +000011458 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
11459 if (MD->isInstance()) {
11460 ValueKind = VK_RValue;
11461 Type = S.Context.BoundMemberTy;
John McCall4adb38c2011-04-27 00:36:17 +000011462 }
11463
John McCall2d2e8702011-04-11 07:02:50 +000011464 // Function references aren't l-values in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011465 if (!S.getLangOpts().CPlusPlus)
Richard Trieu10162ab2011-09-09 03:59:41 +000011466 ValueKind = VK_RValue;
John McCall2d2e8702011-04-11 07:02:50 +000011467
11468 // - variables
Richard Trieu10162ab2011-09-09 03:59:41 +000011469 } else if (isa<VarDecl>(VD)) {
11470 if (const ReferenceType *RefTy = Type->getAs<ReferenceType>()) {
11471 Type = RefTy->getPointeeType();
11472 } else if (Type->isFunctionType()) {
11473 S.Diag(E->getExprLoc(), diag::err_unknown_any_var_function_type)
11474 << VD << E->getSourceRange();
John McCall2979fe02011-04-12 00:42:48 +000011475 return ExprError();
John McCall2d2e8702011-04-11 07:02:50 +000011476 }
11477
11478 // - nothing else
11479 } else {
Richard Trieu10162ab2011-09-09 03:59:41 +000011480 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_decl)
11481 << VD << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011482 return ExprError();
11483 }
11484
Richard Trieu10162ab2011-09-09 03:59:41 +000011485 VD->setType(DestType);
11486 E->setType(Type);
11487 E->setValueKind(ValueKind);
11488 return S.Owned(E);
John McCall2d2e8702011-04-11 07:02:50 +000011489}
11490
John McCall31996342011-04-07 08:22:57 +000011491/// Check a cast of an unknown-any type. We intentionally only
11492/// trigger this for C-style casts.
Richard Trieuba63ce62011-09-09 01:45:06 +000011493ExprResult Sema::checkUnknownAnyCast(SourceRange TypeRange, QualType CastType,
11494 Expr *CastExpr, CastKind &CastKind,
11495 ExprValueKind &VK, CXXCastPath &Path) {
John McCall31996342011-04-07 08:22:57 +000011496 // Rewrite the casted expression from scratch.
Richard Trieuba63ce62011-09-09 01:45:06 +000011497 ExprResult result = RebuildUnknownAnyExpr(*this, CastType).Visit(CastExpr);
John McCall39439732011-04-09 22:50:59 +000011498 if (!result.isUsable()) return ExprError();
John McCall31996342011-04-07 08:22:57 +000011499
Richard Trieuba63ce62011-09-09 01:45:06 +000011500 CastExpr = result.take();
11501 VK = CastExpr->getValueKind();
11502 CastKind = CK_NoOp;
John McCall39439732011-04-09 22:50:59 +000011503
Richard Trieuba63ce62011-09-09 01:45:06 +000011504 return CastExpr;
John McCall31996342011-04-07 08:22:57 +000011505}
11506
Douglas Gregord8fb1e32011-12-01 01:37:36 +000011507ExprResult Sema::forceUnknownAnyToType(Expr *E, QualType ToType) {
11508 return RebuildUnknownAnyExpr(*this, ToType).Visit(E);
11509}
11510
Richard Trieuba63ce62011-09-09 01:45:06 +000011511static ExprResult diagnoseUnknownAnyExpr(Sema &S, Expr *E) {
11512 Expr *orig = E;
John McCall2d2e8702011-04-11 07:02:50 +000011513 unsigned diagID = diag::err_uncasted_use_of_unknown_any;
John McCall31996342011-04-07 08:22:57 +000011514 while (true) {
Richard Trieuba63ce62011-09-09 01:45:06 +000011515 E = E->IgnoreParenImpCasts();
11516 if (CallExpr *call = dyn_cast<CallExpr>(E)) {
11517 E = call->getCallee();
John McCall2d2e8702011-04-11 07:02:50 +000011518 diagID = diag::err_uncasted_call_of_unknown_any;
11519 } else {
John McCall31996342011-04-07 08:22:57 +000011520 break;
John McCall2d2e8702011-04-11 07:02:50 +000011521 }
John McCall31996342011-04-07 08:22:57 +000011522 }
11523
John McCall2d2e8702011-04-11 07:02:50 +000011524 SourceLocation loc;
11525 NamedDecl *d;
Richard Trieuba63ce62011-09-09 01:45:06 +000011526 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011527 loc = ref->getLocation();
11528 d = ref->getDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011529 } else if (MemberExpr *mem = dyn_cast<MemberExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011530 loc = mem->getMemberLoc();
11531 d = mem->getMemberDecl();
Richard Trieuba63ce62011-09-09 01:45:06 +000011532 } else if (ObjCMessageExpr *msg = dyn_cast<ObjCMessageExpr>(E)) {
John McCall2d2e8702011-04-11 07:02:50 +000011533 diagID = diag::err_uncasted_call_of_unknown_any;
Argyrios Kyrtzidisa6011e22011-10-03 06:36:51 +000011534 loc = msg->getSelectorStartLoc();
John McCall2d2e8702011-04-11 07:02:50 +000011535 d = msg->getMethodDecl();
John McCallfa6f5d62011-08-31 20:57:36 +000011536 if (!d) {
11537 S.Diag(loc, diag::err_uncasted_send_to_unknown_any_method)
11538 << static_cast<unsigned>(msg->isClassMessage()) << msg->getSelector()
11539 << orig->getSourceRange();
11540 return ExprError();
11541 }
John McCall2d2e8702011-04-11 07:02:50 +000011542 } else {
Richard Trieuba63ce62011-09-09 01:45:06 +000011543 S.Diag(E->getExprLoc(), diag::err_unsupported_unknown_any_expr)
11544 << E->getSourceRange();
John McCall2d2e8702011-04-11 07:02:50 +000011545 return ExprError();
11546 }
11547
11548 S.Diag(loc, diagID) << d << orig->getSourceRange();
John McCall31996342011-04-07 08:22:57 +000011549
11550 // Never recoverable.
11551 return ExprError();
11552}
11553
John McCall36e7fe32010-10-12 00:20:44 +000011554/// Check for operands with placeholder types and complain if found.
11555/// Returns true if there was an error and no recovery was possible.
John McCall3aef3d82011-04-10 19:13:55 +000011556ExprResult Sema::CheckPlaceholderExpr(Expr *E) {
John McCall4124c492011-10-17 18:40:02 +000011557 const BuiltinType *placeholderType = E->getType()->getAsPlaceholderType();
11558 if (!placeholderType) return Owned(E);
11559
11560 switch (placeholderType->getKind()) {
John McCall36e7fe32010-10-12 00:20:44 +000011561
John McCall31996342011-04-07 08:22:57 +000011562 // Overloaded expressions.
John McCall4124c492011-10-17 18:40:02 +000011563 case BuiltinType::Overload: {
John McCall50a2c2c2011-10-11 23:14:30 +000011564 // Try to resolve a single function template specialization.
11565 // This is obligatory.
11566 ExprResult result = Owned(E);
11567 if (ResolveAndFixSingleFunctionTemplateSpecialization(result, false)) {
11568 return result;
11569
11570 // If that failed, try to recover with a call.
11571 } else {
11572 tryToRecoverWithCall(result, PDiag(diag::err_ovl_unresolvable),
11573 /*complain*/ true);
11574 return result;
11575 }
11576 }
John McCall31996342011-04-07 08:22:57 +000011577
John McCall0009fcc2011-04-26 20:42:42 +000011578 // Bound member functions.
John McCall4124c492011-10-17 18:40:02 +000011579 case BuiltinType::BoundMember: {
John McCall50a2c2c2011-10-11 23:14:30 +000011580 ExprResult result = Owned(E);
11581 tryToRecoverWithCall(result, PDiag(diag::err_bound_member_function),
11582 /*complain*/ true);
11583 return result;
John McCall4124c492011-10-17 18:40:02 +000011584 }
11585
11586 // ARC unbridged casts.
11587 case BuiltinType::ARCUnbridgedCast: {
11588 Expr *realCast = stripARCUnbridgedCast(E);
11589 diagnoseARCUnbridgedCast(realCast);
11590 return Owned(realCast);
11591 }
John McCall0009fcc2011-04-26 20:42:42 +000011592
John McCall31996342011-04-07 08:22:57 +000011593 // Expressions of unknown type.
John McCall4124c492011-10-17 18:40:02 +000011594 case BuiltinType::UnknownAny:
John McCall31996342011-04-07 08:22:57 +000011595 return diagnoseUnknownAnyExpr(*this, E);
11596
John McCall526ab472011-10-25 17:37:35 +000011597 // Pseudo-objects.
11598 case BuiltinType::PseudoObject:
11599 return checkPseudoObjectRValue(E);
11600
John McCalle314e272011-10-18 21:02:43 +000011601 // Everything else should be impossible.
11602#define BUILTIN_TYPE(Id, SingletonId) \
11603 case BuiltinType::Id:
11604#define PLACEHOLDER_TYPE(Id, SingletonId)
11605#include "clang/AST/BuiltinTypes.def"
John McCall4124c492011-10-17 18:40:02 +000011606 break;
11607 }
11608
11609 llvm_unreachable("invalid placeholder type!");
John McCall36e7fe32010-10-12 00:20:44 +000011610}
Richard Trieu2c850c02011-04-21 21:44:26 +000011611
Richard Trieuba63ce62011-09-09 01:45:06 +000011612bool Sema::CheckCaseExpression(Expr *E) {
11613 if (E->isTypeDependent())
Richard Trieu2c850c02011-04-21 21:44:26 +000011614 return true;
Richard Trieuba63ce62011-09-09 01:45:06 +000011615 if (E->isValueDependent() || E->isIntegerConstantExpr(Context))
11616 return E->getType()->isIntegralOrEnumerationType();
Richard Trieu2c850c02011-04-21 21:44:26 +000011617 return false;
11618}
Ted Kremeneke65b0862012-03-06 20:05:56 +000011619
11620/// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals.
11621ExprResult
11622Sema::ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
11623 assert((Kind == tok::kw___objc_yes || Kind == tok::kw___objc_no) &&
11624 "Unknown Objective-C Boolean value!");
11625 return Owned(new (Context) ObjCBoolLiteralExpr(Kind == tok::kw___objc_yes,
Fariborz Jahanian29898f42012-04-16 21:03:30 +000011626 Context.ObjCBuiltinBoolTy, OpLoc));
Ted Kremeneke65b0862012-03-06 20:05:56 +000011627}