blob: 88c2bf408dacce08592f59330e863c4b6ee3c1f7 [file] [log] [blame]
Chris Lattner29375652006-12-04 18:06:35 +00001//===--- SemaExprCXX.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 Lattner29375652006-12-04 18:06:35 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for C++ expressions.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall19c1bfd2010-08-25 05:32:35 +000015#include "clang/Sema/DeclSpec.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/ParsedTemplate.h"
John McCallc63de662011-02-02 13:00:07 +000019#include "clang/Sema/ScopeInfo.h"
Richard Smith938f40b2011-06-11 17:19:42 +000020#include "clang/Sema/Scope.h"
John McCall19c1bfd2010-08-25 05:32:35 +000021#include "clang/Sema/TemplateDeduction.h"
Steve Naroffaac94152007-08-25 14:02:58 +000022#include "clang/AST/ASTContext.h"
Nick Lewycky411fc652012-01-24 21:15:41 +000023#include "clang/AST/CharUnits.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000024#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000025#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000026#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000027#include "clang/AST/ExprObjC.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000028#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000030#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000031#include "clang/Lex/Preprocessor.h"
David Blaikie1d578782011-12-16 16:03:09 +000032#include "TypeLocBuilder.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000033#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000034#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000035#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000036using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000037using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000038
John McCallba7bf592010-08-24 05:47:05 +000039ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000040 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000041 SourceLocation NameLoc,
42 Scope *S, CXXScopeSpec &SS,
43 ParsedType ObjectTypePtr,
44 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000045 // Determine where to perform name lookup.
46
47 // FIXME: This area of the standard is very messy, and the current
48 // wording is rather unclear about which scopes we search for the
49 // destructor name; see core issues 399 and 555. Issue 399 in
50 // particular shows where the current description of destructor name
51 // lookup is completely out of line with existing practice, e.g.,
52 // this appears to be ill-formed:
53 //
54 // namespace N {
55 // template <typename T> struct S {
56 // ~S();
57 // };
58 // }
59 //
60 // void f(N::S<int>* s) {
61 // s->N::S<int>::~S();
62 // }
63 //
Douglas Gregor46841e12010-02-23 00:15:22 +000064 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +000065 // For this reason, we're currently only doing the C++03 version of this
66 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +000067 QualType SearchType;
68 DeclContext *LookupCtx = 0;
69 bool isDependent = false;
70 bool LookInScope = false;
71
72 // If we have an object type, it's because we are in a
73 // pseudo-destructor-expression or a member access expression, and
74 // we know what type we're looking for.
75 if (ObjectTypePtr)
76 SearchType = GetTypeFromParser(ObjectTypePtr);
77
78 if (SS.isSet()) {
Douglas Gregor46841e12010-02-23 00:15:22 +000079 NestedNameSpecifier *NNS = (NestedNameSpecifier *)SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000080
Douglas Gregor46841e12010-02-23 00:15:22 +000081 bool AlreadySearched = false;
82 bool LookAtPrefix = true;
Sebastian Redla771d222010-07-07 23:17:38 +000083 // C++ [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000084 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +000085 // the type-names are looked up as types in the scope designated by the
86 // nested-name-specifier. In a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000087 //
88 // ::[opt] nested-name-specifier ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +000089 //
90 // where the nested-name-specifier designates a namespace scope, and in
Chandler Carruth8f254812010-02-21 10:19:54 +000091 // a qualified-id of the form:
Douglas Gregorfe17d252010-02-16 19:09:40 +000092 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +000093 // ::opt nested-name-specifier class-name :: ~ class-name
Douglas Gregorfe17d252010-02-16 19:09:40 +000094 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000095 // the class-names are looked up as types in the scope designated by
Sebastian Redla771d222010-07-07 23:17:38 +000096 // the nested-name-specifier.
Douglas Gregorfe17d252010-02-16 19:09:40 +000097 //
Sebastian Redla771d222010-07-07 23:17:38 +000098 // Here, we check the first case (completely) and determine whether the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000099 // code below is permitted to look at the prefix of the
Sebastian Redla771d222010-07-07 23:17:38 +0000100 // nested-name-specifier.
101 DeclContext *DC = computeDeclContext(SS, EnteringContext);
102 if (DC && DC->isFileContext()) {
103 AlreadySearched = true;
104 LookupCtx = DC;
105 isDependent = false;
106 } else if (DC && isa<CXXRecordDecl>(DC))
107 LookAtPrefix = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000108
Sebastian Redla771d222010-07-07 23:17:38 +0000109 // The second case from the C++03 rules quoted further above.
Douglas Gregor46841e12010-02-23 00:15:22 +0000110 NestedNameSpecifier *Prefix = 0;
111 if (AlreadySearched) {
112 // Nothing left to do.
113 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
114 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000115 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000116 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
117 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000118 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000119 LookupCtx = computeDeclContext(SearchType);
120 isDependent = SearchType->isDependentType();
121 } else {
122 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000123 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000125
Douglas Gregorcd3f49f2010-02-25 04:46:04 +0000126 LookInScope = false;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000127 } else if (ObjectTypePtr) {
128 // C++ [basic.lookup.classref]p3:
129 // If the unqualified-id is ~type-name, the type-name is looked up
130 // in the context of the entire postfix-expression. If the type T
131 // of the object expression is of a class type C, the type-name is
132 // also looked up in the scope of class C. At least one of the
133 // lookups shall find a name that refers to (possibly
134 // cv-qualified) T.
135 LookupCtx = computeDeclContext(SearchType);
136 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000137 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000138 "Caller should have completed object type");
139
140 LookInScope = true;
141 } else {
142 // Perform lookup into the current scope (only).
143 LookInScope = true;
144 }
145
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000146 TypeDecl *NonMatchingTypeDecl = 0;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000147 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
148 for (unsigned Step = 0; Step != 2; ++Step) {
149 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000150 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000151 // we're allowed to look there).
152 Found.clear();
153 if (Step == 0 && LookupCtx)
154 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000155 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000156 LookupName(Found, S);
157 else
158 continue;
159
160 // FIXME: Should we be suppressing ambiguities here?
161 if (Found.isAmbiguous())
John McCallba7bf592010-08-24 05:47:05 +0000162 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000163
164 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
165 QualType T = Context.getTypeDeclType(Type);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166
167 if (SearchType.isNull() || SearchType->isDependentType() ||
168 Context.hasSameUnqualifiedType(T, SearchType)) {
169 // We found our type!
170
John McCallba7bf592010-08-24 05:47:05 +0000171 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000172 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000173
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000174 if (!SearchType.isNull())
175 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000176 }
177
178 // If the name that we found is a class template name, and it is
179 // the same name as the template name in the last part of the
180 // nested-name-specifier (if present) or the object type, then
181 // this is the destructor for that class.
182 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000183 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000184 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
185 QualType MemberOfType;
186 if (SS.isSet()) {
187 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
188 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000189 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
190 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000191 }
192 }
193 if (MemberOfType.isNull())
194 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000195
Douglas Gregorfe17d252010-02-16 19:09:40 +0000196 if (MemberOfType.isNull())
197 continue;
198
199 // We're referring into a class template specialization. If the
200 // class template we found is the same as the template being
201 // specialized, we found what we are looking for.
202 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
203 if (ClassTemplateSpecializationDecl *Spec
204 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
205 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
206 Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000207 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000208 }
209
210 continue;
211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000212
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 // We're referring to an unresolved class template
214 // specialization. Determine whether we class template we found
215 // is the same as the template being specialized or, if we don't
216 // know which template is being specialized, that it at least
217 // has the same name.
218 if (const TemplateSpecializationType *SpecType
219 = MemberOfType->getAs<TemplateSpecializationType>()) {
220 TemplateName SpecName = SpecType->getTemplateName();
221
222 // The class template we found is the same template being
223 // specialized.
224 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
225 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
John McCallba7bf592010-08-24 05:47:05 +0000226 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000227
228 continue;
229 }
230
231 // The class template we found has the same name as the
232 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000233 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000234 = SpecName.getAsDependentTemplateName()) {
235 if (DepTemplate->isIdentifier() &&
236 DepTemplate->getIdentifier() == Template->getIdentifier())
John McCallba7bf592010-08-24 05:47:05 +0000237 return ParsedType::make(MemberOfType);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000238
239 continue;
240 }
241 }
242 }
243 }
244
245 if (isDependent) {
246 // We didn't find our type, but that's okay: it's dependent
247 // anyway.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000248
249 // FIXME: What if we have no nested-name-specifier?
250 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
251 SS.getWithLocInContext(Context),
252 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000253 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000254 }
255
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000256 if (NonMatchingTypeDecl) {
257 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
258 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
259 << T << SearchType;
260 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
261 << T;
262 } else if (ObjectTypePtr)
263 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000264 << &II;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000265 else
266 Diag(NameLoc, diag::err_destructor_class_name);
267
John McCallba7bf592010-08-24 05:47:05 +0000268 return ParsedType();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000269}
270
David Blaikieecd8a942011-12-08 16:13:53 +0000271ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000272 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieecd8a942011-12-08 16:13:53 +0000273 return ParsedType();
274 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
275 && "only get destructor types from declspecs");
276 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
277 QualType SearchType = GetTypeFromParser(ObjectType);
278 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
279 return ParsedType::make(T);
280 }
281
282 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
283 << T << SearchType;
284 return ParsedType();
285}
286
Douglas Gregor9da64192010-04-26 22:37:10 +0000287/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000288ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000289 SourceLocation TypeidLoc,
290 TypeSourceInfo *Operand,
291 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000292 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000293 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000294 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000295 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000296 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000297 Qualifiers Quals;
298 QualType T
299 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
300 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000301 if (T->getAs<RecordType>() &&
302 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
303 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000304
Douglas Gregor9da64192010-04-26 22:37:10 +0000305 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
306 Operand,
307 SourceRange(TypeidLoc, RParenLoc)));
308}
309
310/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000311ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000312 SourceLocation TypeidLoc,
313 Expr *E,
314 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000315 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000316 if (E->getType()->isPlaceholderType()) {
317 ExprResult result = CheckPlaceholderExpr(E);
318 if (result.isInvalid()) return ExprError();
319 E = result.take();
320 }
321
Douglas Gregor9da64192010-04-26 22:37:10 +0000322 QualType T = E->getType();
323 if (const RecordType *RecordT = T->getAs<RecordType>()) {
324 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
325 // C++ [expr.typeid]p3:
326 // [...] If the type of the expression is a class type, the class
327 // shall be completely-defined.
328 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
329 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000330
Douglas Gregor9da64192010-04-26 22:37:10 +0000331 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000332 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000333 // polymorphic class type [...] [the] expression is an unevaluated
334 // operand. [...]
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000335 if (RecordD->isPolymorphic() && E->Classify(Context).isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000336 // The subexpression is potentially evaluated; switch the context
337 // and recheck the subexpression.
338 ExprResult Result = TranformToPotentiallyEvaluated(E);
339 if (Result.isInvalid()) return ExprError();
340 E = Result.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000341
342 // We require a vtable to query the type at run time.
343 MarkVTableUsed(TypeidLoc, RecordD);
344 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000346
Douglas Gregor9da64192010-04-26 22:37:10 +0000347 // C++ [expr.typeid]p4:
348 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000349 // cv-qualified type, the result of the typeid expression refers to a
350 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000351 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000352 Qualifiers Quals;
353 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
354 if (!Context.hasSameType(T, UnqualT)) {
355 T = UnqualT;
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000356 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).take();
Douglas Gregor9da64192010-04-26 22:37:10 +0000357 }
358 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
Douglas Gregor9da64192010-04-26 22:37:10 +0000360 return Owned(new (Context) CXXTypeidExpr(TypeInfoType.withConst(),
John McCallb268a282010-08-23 23:25:46 +0000361 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000362 SourceRange(TypeidLoc, RParenLoc)));
Douglas Gregor9da64192010-04-26 22:37:10 +0000363}
364
365/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000366ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000367Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
368 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000369 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000370 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000371 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000372
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000373 if (!CXXTypeInfoDecl) {
374 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
375 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
376 LookupQualifiedName(R, getStdNamespace());
377 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
378 if (!CXXTypeInfoDecl)
379 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000381
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000382 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000383
Douglas Gregor9da64192010-04-26 22:37:10 +0000384 if (isType) {
385 // The operand is a type; handle it as such.
386 TypeSourceInfo *TInfo = 0;
John McCallba7bf592010-08-24 05:47:05 +0000387 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
388 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000389 if (T.isNull())
390 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
Douglas Gregor9da64192010-04-26 22:37:10 +0000392 if (!TInfo)
393 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000394
Douglas Gregor9da64192010-04-26 22:37:10 +0000395 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000396 }
Mike Stump11289f42009-09-09 15:08:12 +0000397
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000399 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000400}
401
Francois Pichetb7577652010-12-27 01:32:00 +0000402/// Retrieve the UuidAttr associated with QT.
403static UuidAttr *GetUuidAttrOfType(QualType QT) {
404 // Optionally remove one level of pointer, reference or array indirection.
John McCall424cec92011-01-19 06:33:43 +0000405 const Type *Ty = QT.getTypePtr();;
Francois Pichet9dddd402010-12-20 03:51:03 +0000406 if (QT->isPointerType() || QT->isReferenceType())
407 Ty = QT->getPointeeType().getTypePtr();
408 else if (QT->isArrayType())
409 Ty = cast<ArrayType>(QT)->getElementType().getTypePtr();
410
Francois Pichet59d2b012011-05-08 10:02:20 +0000411 // Loop all record redeclaration looking for an uuid attribute.
Francois Pichetb7577652010-12-27 01:32:00 +0000412 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
Francois Pichet59d2b012011-05-08 10:02:20 +0000413 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
414 E = RD->redecls_end(); I != E; ++I) {
415 if (UuidAttr *Uuid = I->getAttr<UuidAttr>())
Francois Pichetb7577652010-12-27 01:32:00 +0000416 return Uuid;
Francois Pichetb7577652010-12-27 01:32:00 +0000417 }
Francois Pichet59d2b012011-05-08 10:02:20 +0000418
Francois Pichetb7577652010-12-27 01:32:00 +0000419 return 0;
Francois Pichet9dddd402010-12-20 03:51:03 +0000420}
421
Francois Pichet9f4f2072010-09-08 12:20:18 +0000422/// \brief Build a Microsoft __uuidof expression with a type operand.
423ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
424 SourceLocation TypeidLoc,
425 TypeSourceInfo *Operand,
426 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000427 if (!Operand->getType()->isDependentType()) {
428 if (!GetUuidAttrOfType(Operand->getType()))
429 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000431
Francois Pichet9f4f2072010-09-08 12:20:18 +0000432 // FIXME: add __uuidof semantic analysis for type operand.
433 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
434 Operand,
435 SourceRange(TypeidLoc, RParenLoc)));
436}
437
438/// \brief Build a Microsoft __uuidof expression with an expression operand.
439ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
440 SourceLocation TypeidLoc,
441 Expr *E,
442 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000443 if (!E->getType()->isDependentType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000444 if (!GetUuidAttrOfType(E->getType()) &&
Francois Pichetb7577652010-12-27 01:32:00 +0000445 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
446 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
447 }
448 // FIXME: add __uuidof semantic analysis for type operand.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000449 return Owned(new (Context) CXXUuidofExpr(TypeInfoType.withConst(),
450 E,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451 SourceRange(TypeidLoc, RParenLoc)));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000452}
453
454/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
455ExprResult
456Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
457 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000459 if (!MSVCGuidDecl) {
460 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
461 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
462 LookupQualifiedName(R, Context.getTranslationUnitDecl());
463 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
464 if (!MSVCGuidDecl)
465 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000466 }
467
Francois Pichet9f4f2072010-09-08 12:20:18 +0000468 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000469
Francois Pichet9f4f2072010-09-08 12:20:18 +0000470 if (isType) {
471 // The operand is a type; handle it as such.
472 TypeSourceInfo *TInfo = 0;
473 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
474 &TInfo);
475 if (T.isNull())
476 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000477
Francois Pichet9f4f2072010-09-08 12:20:18 +0000478 if (!TInfo)
479 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
480
481 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
482 }
483
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000484 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000485 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
486}
487
Steve Naroff66356bd2007-09-16 14:56:35 +0000488/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000489ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000490Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000491 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000492 "Unknown C++ Boolean value!");
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000493 return Owned(new (Context) CXXBoolLiteralExpr(Kind == tok::kw_true,
494 Context.BoolTy, OpLoc));
Bill Wendling4073ed52007-02-13 01:51:42 +0000495}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000496
Sebastian Redl576fd422009-05-10 18:38:11 +0000497/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000498ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000499Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
500 return Owned(new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc));
501}
502
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000503/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000504ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000505Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
506 bool IsThrownVarInScope = false;
507 if (Ex) {
508 // C++0x [class.copymove]p31:
509 // When certain criteria are met, an implementation is allowed to omit the
510 // copy/move construction of a class object [...]
511 //
512 // - in a throw-expression, when the operand is the name of a
513 // non-volatile automatic object (other than a function or catch-
514 // clause parameter) whose scope does not extend beyond the end of the
515 // innermost enclosing try-block (if there is one), the copy/move
516 // operation from the operand to the exception object (15.1) can be
517 // omitted by constructing the automatic object directly into the
518 // exception object
519 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
520 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
521 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
522 for( ; S; S = S->getParent()) {
523 if (S->isDeclScope(Var)) {
524 IsThrownVarInScope = true;
525 break;
526 }
527
528 if (S->getFlags() &
529 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
530 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
531 Scope::TryScope))
532 break;
533 }
534 }
535 }
536 }
537
538 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
539}
540
541ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
542 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000543 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000544 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000545 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000546 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000547
John Wiegley01296292011-04-08 18:41:53 +0000548 if (Ex && !Ex->isTypeDependent()) {
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000549 ExprResult ExRes = CheckCXXThrowOperand(OpLoc, Ex, IsThrownVarInScope);
John Wiegley01296292011-04-08 18:41:53 +0000550 if (ExRes.isInvalid())
551 return ExprError();
552 Ex = ExRes.take();
553 }
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000554
555 return Owned(new (Context) CXXThrowExpr(Ex, Context.VoidTy, OpLoc,
556 IsThrownVarInScope));
Sebastian Redl4de47b42009-04-27 20:27:31 +0000557}
558
559/// CheckCXXThrowOperand - Validate the operand of a throw.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000560ExprResult Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, Expr *E,
561 bool IsThrownVarInScope) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000562 // C++ [except.throw]p3:
Douglas Gregor247894b2009-12-23 22:04:40 +0000563 // A throw-expression initializes a temporary object, called the exception
564 // object, the type of which is determined by removing any top-level
565 // cv-qualifiers from the static type of the operand of throw and adjusting
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566 // the type from "array of T" or "function returning T" to "pointer to T"
Douglas Gregor247894b2009-12-23 22:04:40 +0000567 // or "pointer to function returning T", [...]
568 if (E->getType().hasQualifiers())
John Wiegley01296292011-04-08 18:41:53 +0000569 E = ImpCastExprToType(E, E->getType().getUnqualifiedType(), CK_NoOp,
Eli Friedmanbe4b3632011-09-27 21:58:52 +0000570 E->getValueKind()).take();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000571
John Wiegley01296292011-04-08 18:41:53 +0000572 ExprResult Res = DefaultFunctionArrayConversion(E);
573 if (Res.isInvalid())
574 return ExprError();
575 E = Res.take();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000576
577 // If the type of the exception would be an incomplete type or a pointer
578 // to an incomplete type other than (cv) void the program is ill-formed.
579 QualType Ty = E->getType();
John McCall2e6567a2010-04-22 01:10:34 +0000580 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000581 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000582 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000583 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000584 }
585 if (!isPointer || !Ty->isVoidType()) {
586 if (RequireCompleteType(ThrowLoc, Ty,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000587 isPointer? diag::err_throw_incomplete_ptr
588 : diag::err_throw_incomplete,
589 E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000590 return ExprError();
Rafael Espindola70e040d2010-03-02 21:28:26 +0000591
Douglas Gregore8154332010-04-15 18:05:39 +0000592 if (RequireNonAbstractType(ThrowLoc, E->getType(),
593 PDiag(diag::err_throw_abstract_type)
594 << E->getSourceRange()))
John Wiegley01296292011-04-08 18:41:53 +0000595 return ExprError();
Sebastian Redl4de47b42009-04-27 20:27:31 +0000596 }
597
John McCall2e6567a2010-04-22 01:10:34 +0000598 // Initialize the exception result. This implicitly weeds out
599 // abstract types or types with inaccessible copy constructors.
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000600
601 // C++0x [class.copymove]p31:
602 // When certain criteria are met, an implementation is allowed to omit the
603 // copy/move construction of a class object [...]
604 //
605 // - in a throw-expression, when the operand is the name of a
606 // non-volatile automatic object (other than a function or catch-clause
607 // parameter) whose scope does not extend beyond the end of the
608 // innermost enclosing try-block (if there is one), the copy/move
609 // operation from the operand to the exception object (15.1) can be
610 // omitted by constructing the automatic object directly into the
611 // exception object
612 const VarDecl *NRVOVariable = 0;
613 if (IsThrownVarInScope)
614 NRVOVariable = getCopyElisionCandidate(QualType(), E, false);
615
John McCall2e6567a2010-04-22 01:10:34 +0000616 InitializedEntity Entity =
Douglas Gregorc74edc22011-01-21 22:46:35 +0000617 InitializedEntity::InitializeException(ThrowLoc, E->getType(),
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000618 /*NRVO=*/NRVOVariable != 0);
John Wiegley01296292011-04-08 18:41:53 +0000619 Res = PerformMoveOrCopyInitialization(Entity, NRVOVariable,
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000620 QualType(), E,
621 IsThrownVarInScope);
John McCall2e6567a2010-04-22 01:10:34 +0000622 if (Res.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +0000623 return ExprError();
624 E = Res.take();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000625
Eli Friedman91a3d272010-06-03 20:39:03 +0000626 // If the exception has class type, we need additional handling.
627 const RecordType *RecordTy = Ty->getAs<RecordType>();
628 if (!RecordTy)
John Wiegley01296292011-04-08 18:41:53 +0000629 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000630 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
631
Douglas Gregor88d292c2010-05-13 16:44:06 +0000632 // If we are throwing a polymorphic class type or pointer thereof,
633 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000634 MarkVTableUsed(ThrowLoc, RD);
635
Eli Friedman36ebbec2010-10-12 20:32:36 +0000636 // If a pointer is thrown, the referenced object will not be destroyed.
637 if (isPointer)
John Wiegley01296292011-04-08 18:41:53 +0000638 return Owned(E);
Eli Friedman36ebbec2010-10-12 20:32:36 +0000639
Richard Smitheec915d62012-02-18 04:13:32 +0000640 // If the class has a destructor, we must be able to call it.
641 if (RD->hasIrrelevantDestructor())
John Wiegley01296292011-04-08 18:41:53 +0000642 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000643
Sebastian Redl249dee52012-03-05 19:35:43 +0000644 CXXDestructorDecl *Destructor = LookupDestructor(RD);
Eli Friedman91a3d272010-06-03 20:39:03 +0000645 if (!Destructor)
John Wiegley01296292011-04-08 18:41:53 +0000646 return Owned(E);
Eli Friedman91a3d272010-06-03 20:39:03 +0000647
Eli Friedmanfa0df832012-02-02 03:46:19 +0000648 MarkFunctionReferenced(E->getExprLoc(), Destructor);
Eli Friedman91a3d272010-06-03 20:39:03 +0000649 CheckDestructorAccess(E->getExprLoc(), Destructor,
Douglas Gregor747eb782010-07-08 06:14:04 +0000650 PDiag(diag::err_access_dtor_exception) << Ty);
Richard Smitheec915d62012-02-18 04:13:32 +0000651 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John Wiegley01296292011-04-08 18:41:53 +0000652 return Owned(E);
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000653}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000654
Eli Friedman73a04092012-01-07 04:59:52 +0000655QualType Sema::getCurrentThisType() {
656 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000657 QualType ThisTy = CXXThisTypeOverride;
Richard Smith938f40b2011-06-11 17:19:42 +0000658 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
659 if (method && method->isInstance())
660 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000661 }
Douglas Gregor3024f072012-04-16 07:05:22 +0000662
Richard Smith938f40b2011-06-11 17:19:42 +0000663 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000664}
665
Douglas Gregor3024f072012-04-16 07:05:22 +0000666Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
667 Decl *ContextDecl,
668 unsigned CXXThisTypeQuals,
669 bool Enabled)
670 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
671{
672 if (!Enabled || !ContextDecl)
673 return;
674
675 CXXRecordDecl *Record = 0;
676 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
677 Record = Template->getTemplatedDecl();
678 else
679 Record = cast<CXXRecordDecl>(ContextDecl);
680
681 S.CXXThisTypeOverride
682 = S.Context.getPointerType(
683 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
684
685 this->Enabled = true;
686}
687
688
689Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
690 if (Enabled) {
691 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
692 }
693}
694
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000695void Sema::CheckCXXThisCapture(SourceLocation Loc, bool Explicit) {
Eli Friedman73a04092012-01-07 04:59:52 +0000696 // We don't need to capture this in an unevaluated context.
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000697 if (ExprEvalContexts.back().Context == Unevaluated && !Explicit)
Eli Friedman73a04092012-01-07 04:59:52 +0000698 return;
699
700 // Otherwise, check that we can capture 'this'.
701 unsigned NumClosures = 0;
702 for (unsigned idx = FunctionScopes.size() - 1; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +0000703 if (CapturingScopeInfo *CSI =
704 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
705 if (CSI->CXXThisCaptureIndex != 0) {
706 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +0000707 break;
708 }
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000709
Eli Friedman20139d32012-01-11 02:36:31 +0000710 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +0000711 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000712 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
713 Explicit) {
714 // This closure can capture 'this'; continue looking upwards.
Eli Friedman73a04092012-01-07 04:59:52 +0000715 NumClosures++;
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000716 Explicit = false;
Eli Friedman73a04092012-01-07 04:59:52 +0000717 continue;
718 }
Eli Friedman20139d32012-01-11 02:36:31 +0000719 // This context can't implicitly capture 'this'; fail out.
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000720 Diag(Loc, diag::err_this_capture) << Explicit;
Eli Friedman73a04092012-01-07 04:59:52 +0000721 return;
722 }
Eli Friedman73a04092012-01-07 04:59:52 +0000723 break;
724 }
725
726 // Mark that we're implicitly capturing 'this' in all the scopes we skipped.
727 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
728 // contexts.
729 for (unsigned idx = FunctionScopes.size() - 1;
730 NumClosures; --idx, --NumClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +0000731 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Eli Friedmanc9751062012-02-11 02:51:16 +0000732 Expr *ThisExpr = 0;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000733 QualType ThisTy = getCurrentThisType();
Eli Friedmanc9751062012-02-11 02:51:16 +0000734 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
735 // For lambda expressions, build a field and an initializing expression.
Eli Friedmanc9751062012-02-11 02:51:16 +0000736 CXXRecordDecl *Lambda = LSI->Lambda;
737 FieldDecl *Field
738 = FieldDecl::Create(Context, Lambda, Loc, Loc, 0, ThisTy,
739 Context.getTrivialTypeSourceInfo(ThisTy, Loc),
740 0, false, false);
741 Field->setImplicit(true);
742 Field->setAccess(AS_private);
743 Lambda->addDecl(Field);
744 ThisExpr = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/true);
745 }
Eli Friedman20139d32012-01-11 02:36:31 +0000746 bool isNested = NumClosures > 1;
Douglas Gregorfdf598e2012-02-18 09:37:24 +0000747 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr);
Eli Friedman73a04092012-01-07 04:59:52 +0000748 }
749}
750
Richard Smith938f40b2011-06-11 17:19:42 +0000751ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +0000752 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
753 /// is a non-lvalue expression whose value is the address of the object for
754 /// which the function is called.
755
Douglas Gregor09deffa2011-10-18 16:47:30 +0000756 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +0000757 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +0000758
Eli Friedman73a04092012-01-07 04:59:52 +0000759 CheckCXXThisCapture(Loc);
Richard Smith938f40b2011-06-11 17:19:42 +0000760 return Owned(new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000761}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000762
Douglas Gregor3024f072012-04-16 07:05:22 +0000763bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
764 // If we're outside the body of a member function, then we'll have a specified
765 // type for 'this'.
766 if (CXXThisTypeOverride.isNull())
767 return false;
768
769 // Determine whether we're looking into a class that's currently being
770 // defined.
771 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
772 return Class && Class->isBeingDefined();
773}
774
John McCalldadc5752010-08-24 06:29:42 +0000775ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +0000776Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000777 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000778 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000779 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +0000780 if (!TypeRep)
781 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000782
John McCall97513962010-01-15 18:39:57 +0000783 TypeSourceInfo *TInfo;
784 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
785 if (!TInfo)
786 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +0000787
788 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
789}
790
791/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
792/// Can be interpreted either as function-style casting ("int(x)")
793/// or class type construction ("ClassType(x,y,z)")
794/// or creation of a value-initialized type ("int()").
795ExprResult
796Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
797 SourceLocation LParenLoc,
798 MultiExprArg exprs,
799 SourceLocation RParenLoc) {
800 QualType Ty = TInfo->getType();
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000801 unsigned NumExprs = exprs.size();
802 Expr **Exprs = (Expr**)exprs.get();
Douglas Gregor2b88c112010-09-08 00:15:04 +0000803 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000804
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000805 if (Ty->isDependentType() ||
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +0000806 CallExpr::hasAnyTypeDependentArguments(
807 llvm::makeArrayRef(Exprs, NumExprs))) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000808 exprs.release();
Mike Stump11289f42009-09-09 15:08:12 +0000809
Douglas Gregor2b88c112010-09-08 00:15:04 +0000810 return Owned(CXXUnresolvedConstructExpr::Create(Context, TInfo,
Douglas Gregorce934142009-05-20 18:46:25 +0000811 LParenLoc,
812 Exprs, NumExprs,
813 RParenLoc));
Douglas Gregor0950e412009-03-13 21:01:28 +0000814 }
815
Sebastian Redld74dd492012-02-12 18:41:05 +0000816 bool ListInitialization = LParenLoc.isInvalid();
817 assert((!ListInitialization || (NumExprs == 1 && isa<InitListExpr>(Exprs[0])))
818 && "List initialization must have initializer list as expression.");
819 SourceRange FullRange = SourceRange(TyBeginLoc,
820 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
821
Douglas Gregordd04d332009-01-16 18:33:17 +0000822 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000823 // If the expression list is a single expression, the type conversion
824 // expression is equivalent (in definedness, and if defined in meaning) to the
825 // corresponding cast expression.
Sebastian Redl2b80af42012-02-13 19:55:43 +0000826 if (NumExprs == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +0000827 Expr *Arg = Exprs[0];
Anders Carlssone9766d52009-09-09 21:33:21 +0000828 exprs.release();
John McCallb50451a2011-10-05 07:41:44 +0000829 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000830 }
831
Eli Friedman576cbd02012-02-29 00:00:28 +0000832 QualType ElemTy = Ty;
833 if (Ty->isArrayType()) {
834 if (!ListInitialization)
835 return ExprError(Diag(TyBeginLoc,
836 diag::err_value_init_for_array_type) << FullRange);
837 ElemTy = Context.getBaseElementType(Ty);
838 }
839
840 if (!Ty->isVoidType() &&
841 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000842 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +0000843 return ExprError();
844
845 if (RequireNonAbstractType(TyBeginLoc, Ty,
846 diag::err_allocation_of_abstract_type))
847 return ExprError();
848
Douglas Gregor8ec51732010-09-08 21:40:08 +0000849 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
850 InitializationKind Kind
Sebastian Redl2b80af42012-02-13 19:55:43 +0000851 = NumExprs ? ListInitialization
852 ? InitializationKind::CreateDirectList(TyBeginLoc)
853 : InitializationKind::CreateDirect(TyBeginLoc,
854 LParenLoc, RParenLoc)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000855 : InitializationKind::CreateValue(TyBeginLoc,
Douglas Gregor8ec51732010-09-08 21:40:08 +0000856 LParenLoc, RParenLoc);
857 InitializationSequence InitSeq(*this, Entity, Kind, Exprs, NumExprs);
858 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, move(exprs));
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000859
Sebastian Redl2b80af42012-02-13 19:55:43 +0000860 if (!Result.isInvalid() && ListInitialization &&
861 isa<InitListExpr>(Result.get())) {
862 // If the list-initialization doesn't involve a constructor call, we'll get
863 // the initializer-list (with corrected type) back, but that's not what we
864 // want, since it will be treated as an initializer list in further
865 // processing. Explicitly insert a cast here.
866 InitListExpr *List = cast<InitListExpr>(Result.take());
867 Result = Owned(CXXFunctionalCastExpr::Create(Context, List->getType(),
868 Expr::getValueKindForType(TInfo->getType()),
869 TInfo, TyBeginLoc, CK_NoOp,
870 List, /*Path=*/0, RParenLoc));
871 }
872
Douglas Gregor8ec51732010-09-08 21:40:08 +0000873 // FIXME: Improve AST representation?
874 return move(Result);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +0000875}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000876
John McCall284c48f2011-01-27 09:37:56 +0000877/// doesUsualArrayDeleteWantSize - Answers whether the usual
878/// operator delete[] for the given type has a size_t parameter.
879static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
880 QualType allocType) {
881 const RecordType *record =
882 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
883 if (!record) return false;
884
885 // Try to find an operator delete[] in class scope.
886
887 DeclarationName deleteName =
888 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
889 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
890 S.LookupQualifiedName(ops, record->getDecl());
891
892 // We're just doing this for information.
893 ops.suppressDiagnostics();
894
895 // Very likely: there's no operator delete[].
896 if (ops.empty()) return false;
897
898 // If it's ambiguous, it should be illegal to call operator delete[]
899 // on this thing, so it doesn't matter if we allocate extra space or not.
900 if (ops.isAmbiguous()) return false;
901
902 LookupResult::Filter filter = ops.makeFilter();
903 while (filter.hasNext()) {
904 NamedDecl *del = filter.next()->getUnderlyingDecl();
905
906 // C++0x [basic.stc.dynamic.deallocation]p2:
907 // A template instance is never a usual deallocation function,
908 // regardless of its signature.
909 if (isa<FunctionTemplateDecl>(del)) {
910 filter.erase();
911 continue;
912 }
913
914 // C++0x [basic.stc.dynamic.deallocation]p2:
915 // If class T does not declare [an operator delete[] with one
916 // parameter] but does declare a member deallocation function
917 // named operator delete[] with exactly two parameters, the
918 // second of which has type std::size_t, then this function
919 // is a usual deallocation function.
920 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
921 filter.erase();
922 continue;
923 }
924 }
925 filter.done();
926
927 if (!ops.isSingleResult()) return false;
928
929 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
930 return (del->getNumParams() == 2);
931}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +0000932
Sebastian Redld74dd492012-02-12 18:41:05 +0000933/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
934
935/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +0000936/// @code new (memory) int[size][4] @endcode
937/// or
938/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +0000939///
940/// \param StartLoc The first location of the expression.
941/// \param UseGlobal True if 'new' was prefixed with '::'.
942/// \param PlacementLParen Opening paren of the placement arguments.
943/// \param PlacementArgs Placement new arguments.
944/// \param PlacementRParen Closing paren of the placement arguments.
945/// \param TypeIdParens If the type is in parens, the source range.
946/// \param D The type to be allocated, as well as array dimensions.
947/// \param ConstructorLParen Opening paren of the constructor args, empty if
948/// initializer-list syntax is used.
949/// \param ConstructorArgs Constructor/initialization arguments.
950/// \param ConstructorRParen Closing paren of the constructor args.
John McCalldadc5752010-08-24 06:29:42 +0000951ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +0000952Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000953 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000954 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +0000955 Declarator &D, Expr *Initializer) {
Richard Smith30482bc2011-02-20 03:19:35 +0000956 bool TypeContainsAuto = D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto;
957
Sebastian Redl351bb782008-12-02 14:43:59 +0000958 Expr *ArraySize = 0;
Sebastian Redl351bb782008-12-02 14:43:59 +0000959 // If the specified type is an array, unwrap it and save the expression.
960 if (D.getNumTypeObjects() > 0 &&
961 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
962 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +0000963 if (TypeContainsAuto)
964 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
965 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000966 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000967 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
968 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +0000969 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000970 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
971 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000972
Sebastian Redl351bb782008-12-02 14:43:59 +0000973 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000974 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +0000975 }
976
Douglas Gregor73341c42009-09-11 00:18:58 +0000977 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000978 if (ArraySize) {
979 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +0000980 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
981 break;
982
983 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
984 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +0000985 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
986 Array.NumElts = VerifyIntegerConstantExpression(NumElts, 0,
987 PDiag(diag::err_new_array_nonconst)).take();
988 if (!Array.NumElts)
989 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +0000990 }
991 }
992 }
993 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +0000994
Argyrios Kyrtzidis3ff13572011-06-28 03:01:23 +0000995 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/0);
John McCall8cb7bdf2010-06-04 23:28:52 +0000996 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +0000997 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000998 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000999
Sebastian Redl6047f072012-02-16 12:22:20 +00001000 SourceRange DirectInitRange;
1001 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1002 DirectInitRange = List->getSourceRange();
1003
Mike Stump11289f42009-09-09 15:08:12 +00001004 return BuildCXXNew(StartLoc, UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001005 PlacementLParen,
Mike Stump11289f42009-09-09 15:08:12 +00001006 move(PlacementArgs),
Douglas Gregord0fefba2009-05-21 00:00:09 +00001007 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001008 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001009 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001010 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001011 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001012 DirectInitRange,
1013 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001014 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001015}
1016
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001017static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1018 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001019 if (!Init)
1020 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001021 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1022 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001023 if (isa<ImplicitValueInitExpr>(Init))
1024 return true;
1025 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1026 return !CCE->isListInitialization() &&
1027 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001028 else if (Style == CXXNewExpr::ListInit) {
1029 assert(isa<InitListExpr>(Init) &&
1030 "Shouldn't create list CXXConstructExprs for arrays.");
1031 return true;
1032 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001033 return false;
1034}
1035
John McCalldadc5752010-08-24 06:29:42 +00001036ExprResult
Douglas Gregord0fefba2009-05-21 00:00:09 +00001037Sema::BuildCXXNew(SourceLocation StartLoc, bool UseGlobal,
1038 SourceLocation PlacementLParen,
1039 MultiExprArg PlacementArgs,
1040 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001041 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001042 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001043 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001044 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001045 SourceRange DirectInitRange,
1046 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001047 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001048 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
Sebastian Redl351bb782008-12-02 14:43:59 +00001049
Sebastian Redl6047f072012-02-16 12:22:20 +00001050 CXXNewExpr::InitializationStyle initStyle;
1051 if (DirectInitRange.isValid()) {
1052 assert(Initializer && "Have parens but no initializer.");
1053 initStyle = CXXNewExpr::CallInit;
1054 } else if (Initializer && isa<InitListExpr>(Initializer))
1055 initStyle = CXXNewExpr::ListInit;
1056 else {
Sebastian Redle7c31a92012-02-22 09:07:21 +00001057 // In template instantiation, the initializer could be a CXXDefaultArgExpr
1058 // unwrapped from a CXXConstructExpr that was implicitly built. There is no
1059 // particularly sane way we can handle this (especially since it can even
1060 // occur for array new), so we throw the initializer away and have it be
1061 // rebuilt.
1062 if (Initializer && isa<CXXDefaultArgExpr>(Initializer))
1063 Initializer = 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001064 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1065 isa<CXXConstructExpr>(Initializer)) &&
1066 "Initializer expression that cannot have been implicitly created.");
1067 initStyle = CXXNewExpr::NoInit;
1068 }
1069
1070 Expr **Inits = &Initializer;
1071 unsigned NumInits = Initializer ? 1 : 0;
1072 if (initStyle == CXXNewExpr::CallInit) {
1073 if (ParenListExpr *List = dyn_cast<ParenListExpr>(Initializer)) {
1074 Inits = List->getExprs();
1075 NumInits = List->getNumExprs();
1076 } else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Initializer)){
1077 if (!isa<CXXTemporaryObjectExpr>(CCE)) {
1078 // Can happen in template instantiation. Since this is just an implicit
1079 // construction, we just take it apart and rebuild it.
1080 Inits = CCE->getArgs();
1081 NumInits = CCE->getNumArgs();
1082 }
1083 }
1084 }
1085
Richard Smith30482bc2011-02-20 03:19:35 +00001086 // C++0x [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1087 if (TypeMayContainAuto && AllocType->getContainedAutoType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001088 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001089 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1090 << AllocType << TypeRange);
Sebastian Redl6047f072012-02-16 12:22:20 +00001091 if (initStyle == CXXNewExpr::ListInit)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001092 return ExprError(Diag(Inits[0]->getLocStart(),
Sebastian Redl6047f072012-02-16 12:22:20 +00001093 diag::err_auto_new_requires_parens)
1094 << AllocType << TypeRange);
1095 if (NumInits > 1) {
1096 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001097 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001098 diag::err_auto_new_ctor_multiple_expressions)
1099 << AllocType << TypeRange);
1100 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001101 Expr *Deduce = Inits[0];
Richard Smith9647d3c2011-03-17 16:11:59 +00001102 TypeSourceInfo *DeducedType = 0;
Sebastian Redld74dd492012-02-12 18:41:05 +00001103 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) ==
Sebastian Redl09edce02012-01-23 22:09:39 +00001104 DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001105 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001106 << AllocType << Deduce->getType()
1107 << TypeRange << Deduce->getSourceRange());
Richard Smith9647d3c2011-03-17 16:11:59 +00001108 if (!DeducedType)
1109 return ExprError();
Richard Smith30482bc2011-02-20 03:19:35 +00001110
Richard Smith9647d3c2011-03-17 16:11:59 +00001111 AllocTypeInfo = DeducedType;
1112 AllocType = AllocTypeInfo->getType();
Richard Smith30482bc2011-02-20 03:19:35 +00001113 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001114
Douglas Gregorcda95f42010-05-16 16:01:03 +00001115 // Per C++0x [expr.new]p5, the type being constructed may be a
1116 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001117 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001118 if (const ConstantArrayType *Array
1119 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001120 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1121 Context.getSizeType(),
1122 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001123 AllocType = Array->getElementType();
1124 }
1125 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001126
Douglas Gregor3999e152010-10-06 16:00:31 +00001127 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1128 return ExprError();
1129
Sebastian Redl6047f072012-02-16 12:22:20 +00001130 if (initStyle == CXXNewExpr::ListInit && isStdInitializerList(AllocType, 0)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001131 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1132 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001133 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001134 }
1135
John McCall31168b02011-06-15 23:02:42 +00001136 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001137 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001138 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1139 AllocType->isObjCLifetimeType()) {
1140 AllocType = Context.getLifetimeQualifiedType(AllocType,
1141 AllocType->getObjCARCImplicitLifetime());
1142 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001143
John McCall31168b02011-06-15 23:02:42 +00001144 QualType ResultType = Context.getPointerType(AllocType);
1145
Richard Smith8dd34252012-02-04 07:07:42 +00001146 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1147 // integral or enumeration type with a non-negative value."
1148 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1149 // enumeration type, or a class type for which a single non-explicit
1150 // conversion function to integral or unscoped enumeration type exists.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001151 if (ArraySize && !ArraySize->isTypeDependent()) {
Eli Friedman1da70392012-01-26 00:26:18 +00001152 ExprResult ConvertedSize = ConvertToIntegralOrEnumerationType(
Richard Smith0bf8a4922011-10-18 20:49:44 +00001153 StartLoc, ArraySize,
David Blaikiebbafb8a2012-03-11 07:00:24 +00001154 PDiag(diag::err_array_size_not_integral) << getLangOpts().CPlusPlus0x,
Richard Smith0bf8a4922011-10-18 20:49:44 +00001155 PDiag(diag::err_array_size_incomplete_type)
1156 << ArraySize->getSourceRange(),
1157 PDiag(diag::err_array_size_explicit_conversion),
1158 PDiag(diag::note_array_size_conversion),
1159 PDiag(diag::err_array_size_ambiguous_conversion),
1160 PDiag(diag::note_array_size_conversion),
David Blaikiebbafb8a2012-03-11 07:00:24 +00001161 PDiag(getLangOpts().CPlusPlus0x ?
Richard Smith0bf8a4922011-10-18 20:49:44 +00001162 diag::warn_cxx98_compat_array_size_conversion :
Richard Smith8dd34252012-02-04 07:07:42 +00001163 diag::ext_array_size_conversion),
1164 /*AllowScopedEnumerations*/ false);
Douglas Gregor4799d032010-06-30 00:20:43 +00001165 if (ConvertedSize.isInvalid())
1166 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001167
John McCallb268a282010-08-23 23:25:46 +00001168 ArraySize = ConvertedSize.take();
John McCall9b80c212012-01-11 00:14:46 +00001169 QualType SizeType = ArraySize->getType();
Douglas Gregor0bf31402010-10-08 23:50:27 +00001170 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001171 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001172
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001173 // C++98 [expr.new]p7:
1174 // The expression in a direct-new-declarator shall have integral type
1175 // with a non-negative value.
1176 //
1177 // Let's see if this is a constant < 0. If so, we reject it out of
1178 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1179 // array type.
1180 //
1181 // Note: such a construct has well-defined semantics in C++11: it throws
1182 // std::bad_array_new_length.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001183 if (!ArraySize->isValueDependent()) {
1184 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001185 // We've already performed any required implicit conversion to integer or
1186 // unscoped enumeration type.
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001187 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001188 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001189 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001190 Value.isUnsigned())) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001191 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001192 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001193 diag::warn_typecheck_negative_array_new_size)
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001194 << ArraySize->getSourceRange();
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001195 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001196 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001197 diag::err_typecheck_negative_array_size)
1198 << ArraySize->getSourceRange());
1199 } else if (!AllocType->isDependentType()) {
1200 unsigned ActiveSizeBits =
1201 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1202 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001203 if (getLangOpts().CPlusPlus0x)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001204 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001205 diag::warn_array_new_too_large)
1206 << Value.toString(10)
1207 << ArraySize->getSourceRange();
1208 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001209 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001210 diag::err_array_too_large)
1211 << Value.toString(10)
1212 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001213 }
1214 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001215 } else if (TypeIdParens.isValid()) {
1216 // Can't have dynamic array size when the type-id is in parentheses.
1217 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1218 << ArraySize->getSourceRange()
1219 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1220 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001221
Douglas Gregorf2753b32010-07-13 15:54:32 +00001222 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001223 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001224 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001225
John McCall31168b02011-06-15 23:02:42 +00001226 // ARC: warn about ABI issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001227 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001228 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1229 if (BaseAllocType.hasStrongOrWeakObjCLifetime())
1230 Diag(StartLoc, diag::warn_err_new_delete_object_array)
1231 << 0 << BaseAllocType;
1232 }
1233
John McCall036f2f62011-05-15 07:14:44 +00001234 // Note that we do *not* convert the argument in any way. It can
1235 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001236 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001237
Sebastian Redlbd150f42008-11-21 19:14:01 +00001238 FunctionDecl *OperatorNew = 0;
1239 FunctionDecl *OperatorDelete = 0;
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001240 Expr **PlaceArgs = (Expr**)PlacementArgs.get();
1241 unsigned NumPlaceArgs = PlacementArgs.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001242
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001243 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001244 !Expr::hasAnyTypeDependentArguments(
1245 llvm::makeArrayRef(PlaceArgs, NumPlaceArgs)) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001246 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001247 SourceRange(PlacementLParen, PlacementRParen),
1248 UseGlobal, AllocType, ArraySize, PlaceArgs,
1249 NumPlaceArgs, OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001250 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001251
1252 // If this is an array allocation, compute whether the usual array
1253 // deallocation function for the type has a size_t parameter.
1254 bool UsualArrayDeleteWantsSize = false;
1255 if (ArraySize && !AllocType->isDependentType())
1256 UsualArrayDeleteWantsSize
1257 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1258
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001259 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001260 if (OperatorNew) {
1261 // Add default arguments, if any.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262 const FunctionProtoType *Proto =
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001263 OperatorNew->getType()->getAs<FunctionProtoType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264 VariadicCallType CallType =
Fariborz Jahanian6f2d25e2009-11-24 19:27:49 +00001265 Proto->isVariadic() ? VariadicFunction : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
Anders Carlssonc144bc22010-05-03 02:07:56 +00001267 if (GatherArgumentsForCall(PlacementLParen, OperatorNew,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268 Proto, 1, PlaceArgs, NumPlaceArgs,
Anders Carlssonc144bc22010-05-03 02:07:56 +00001269 AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001270 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001271
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001272 NumPlaceArgs = AllPlaceArgs.size();
1273 if (NumPlaceArgs > 0)
1274 PlaceArgs = &AllPlaceArgs[0];
Eli Friedmanff4b4072012-02-18 04:48:30 +00001275
1276 DiagnoseSentinelCalls(OperatorNew, PlacementLParen,
1277 PlaceArgs, NumPlaceArgs);
1278
1279 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001281
Nick Lewycky411fc652012-01-24 21:15:41 +00001282 // Warn if the type is over-aligned and is being allocated by global operator
1283 // new.
Nick Lewycky96ed7b62012-02-04 03:30:14 +00001284 if (NumPlaceArgs == 0 && OperatorNew &&
Nick Lewycky411fc652012-01-24 21:15:41 +00001285 (OperatorNew->isImplicit() ||
1286 getSourceManager().isInSystemHeader(OperatorNew->getLocStart()))) {
1287 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1288 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1289 if (Align > SuitableAlign)
1290 Diag(StartLoc, diag::warn_overaligned_type)
1291 << AllocType
1292 << unsigned(Align / Context.getCharWidth())
1293 << unsigned(SuitableAlign / Context.getCharWidth());
1294 }
1295 }
1296
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001297 QualType InitType = AllocType;
Sebastian Redl6047f072012-02-16 12:22:20 +00001298 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001299 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1300 // dialect distinction.
1301 if (ResultType->isArrayType() || ArraySize) {
1302 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1303 SourceRange InitRange(Inits[0]->getLocStart(),
1304 Inits[NumInits - 1]->getLocEnd());
1305 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1306 return ExprError();
1307 }
1308 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1309 // We do the initialization typechecking against the array type
1310 // corresponding to the number of initializers + 1 (to also check
1311 // default-initialization).
1312 unsigned NumElements = ILE->getNumInits() + 1;
1313 InitType = Context.getConstantArrayType(AllocType,
1314 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1315 ArrayType::Normal, 0);
1316 }
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001317 }
1318
Douglas Gregor85dabae2009-12-16 01:38:02 +00001319 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001320 !Expr::hasAnyTypeDependentArguments(
1321 llvm::makeArrayRef(Inits, NumInits))) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001322 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001323 // A new-expression that creates an object of type T initializes that
1324 // object as follows:
1325 InitializationKind Kind
1326 // - If the new-initializer is omitted, the object is default-
1327 // initialized (8.5); if no initialization is performed,
1328 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001329 = initStyle == CXXNewExpr::NoInit
1330 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001332 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001333 : initStyle == CXXNewExpr::ListInit
1334 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1335 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1336 DirectInitRange.getBegin(),
1337 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001338
Douglas Gregor85dabae2009-12-16 01:38:02 +00001339 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001340 = InitializedEntity::InitializeNew(StartLoc, InitType);
Sebastian Redl6047f072012-02-16 12:22:20 +00001341 InitializationSequence InitSeq(*this, Entity, Kind, Inits, NumInits);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001342 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001343 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001344 if (FullInit.isInvalid())
1345 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001346
Sebastian Redl6047f072012-02-16 12:22:20 +00001347 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1348 // we don't want the initialized object to be destructed.
1349 if (CXXBindTemporaryExpr *Binder =
1350 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1351 FullInit = Owned(Binder->getSubExpr());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001352
Sebastian Redl6047f072012-02-16 12:22:20 +00001353 Initializer = FullInit.take();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001355
Douglas Gregor6642ca22010-02-26 05:06:18 +00001356 // Mark the new and delete operators as referenced.
1357 if (OperatorNew)
Eli Friedmanfa0df832012-02-02 03:46:19 +00001358 MarkFunctionReferenced(StartLoc, OperatorNew);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001359 if (OperatorDelete)
Eli Friedmanfa0df832012-02-02 03:46:19 +00001360 MarkFunctionReferenced(StartLoc, OperatorDelete);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001361
John McCall928a2572011-07-13 20:12:57 +00001362 // C++0x [expr.new]p17:
1363 // If the new expression creates an array of objects of class type,
1364 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001365 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1366 if (ArraySize && !BaseAllocType->isDependentType()) {
1367 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1368 if (CXXDestructorDecl *dtor = LookupDestructor(
1369 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1370 MarkFunctionReferenced(StartLoc, dtor);
1371 CheckDestructorAccess(StartLoc, dtor,
1372 PDiag(diag::err_access_dtor)
1373 << BaseAllocType);
1374 DiagnoseUseOfDecl(dtor, StartLoc);
1375 }
John McCall928a2572011-07-13 20:12:57 +00001376 }
1377 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001378
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001379 PlacementArgs.release();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380
Ted Kremenek9d6eb402010-02-11 22:51:03 +00001381 return Owned(new (Context) CXXNewExpr(Context, UseGlobal, OperatorNew,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00001382 OperatorDelete,
John McCall284c48f2011-01-27 09:37:56 +00001383 UsualArrayDeleteWantsSize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001384 PlaceArgs, NumPlaceArgs, TypeIdParens,
1385 ArraySize, initStyle, Initializer,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001386 ResultType, AllocTypeInfo,
Sebastian Redl6047f072012-02-16 12:22:20 +00001387 StartLoc, DirectInitRange));
Sebastian Redlbd150f42008-11-21 19:14:01 +00001388}
1389
Sebastian Redl6047f072012-02-16 12:22:20 +00001390/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001391/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001392bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001393 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001394 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1395 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001396 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001397 return Diag(Loc, diag::err_bad_new_type)
1398 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001399 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001400 return Diag(Loc, diag::err_bad_new_type)
1401 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001402 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001403 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001404 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001405 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001406 diag::err_allocation_of_abstract_type))
1407 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001408 else if (AllocType->isVariablyModifiedType())
1409 return Diag(Loc, diag::err_variably_modified_new_type)
1410 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001411 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1412 return Diag(Loc, diag::err_address_space_qualified_new)
1413 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001414 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001415 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1416 QualType BaseAllocType = Context.getBaseElementType(AT);
1417 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1418 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001419 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001420 << BaseAllocType;
1421 }
1422 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001423
Sebastian Redlbd150f42008-11-21 19:14:01 +00001424 return false;
1425}
1426
Douglas Gregor6642ca22010-02-26 05:06:18 +00001427/// \brief Determine whether the given function is a non-placement
1428/// deallocation function.
1429static bool isNonPlacementDeallocationFunction(FunctionDecl *FD) {
1430 if (FD->isInvalidDecl())
1431 return false;
1432
1433 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1434 return Method->isUsualDeallocationFunction();
1435
1436 return ((FD->getOverloadedOperator() == OO_Delete ||
1437 FD->getOverloadedOperator() == OO_Array_Delete) &&
1438 FD->getNumParams() == 1);
1439}
1440
Sebastian Redlfaf68082008-12-03 20:26:15 +00001441/// FindAllocationFunctions - Finds the overloads of operator new and delete
1442/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001443bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1444 bool UseGlobal, QualType AllocType,
1445 bool IsArray, Expr **PlaceArgs,
1446 unsigned NumPlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001447 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001448 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001449 // --- Choosing an allocation function ---
1450 // C++ 5.3.4p8 - 14 & 18
1451 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1452 // in the scope of the allocated class.
1453 // 2) If an array size is given, look for operator new[], else look for
1454 // operator new.
1455 // 3) The first argument is always size_t. Append the arguments from the
1456 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001457
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001458 SmallVector<Expr*, 8> AllocArgs(1 + NumPlaceArgs);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001459 // We don't care about the actual value of this argument.
1460 // FIXME: Should the Sema create the expression and embed it in the syntax
1461 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001462 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001463 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001464 Context.getSizeType(),
1465 SourceLocation());
1466 AllocArgs[0] = &Size;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001467 std::copy(PlaceArgs, PlaceArgs + NumPlaceArgs, AllocArgs.begin() + 1);
1468
Douglas Gregor6642ca22010-02-26 05:06:18 +00001469 // C++ [expr.new]p8:
1470 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001471 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001472 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001473 // type, the allocation function's name is operator new[] and the
1474 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001475 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1476 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001477 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1478 IsArray ? OO_Array_Delete : OO_Delete);
1479
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001480 QualType AllocElemType = Context.getBaseElementType(AllocType);
1481
1482 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001483 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001484 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001485 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001486 AllocArgs.size(), Record, /*AllowMissing=*/true,
1487 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001488 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001489 }
1490 if (!OperatorNew) {
1491 // Didn't find a member overload. Look for a global one.
1492 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001493 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001494 if (FindAllocationOverload(StartLoc, Range, NewName, &AllocArgs[0],
Sebastian Redl33a31012008-12-04 22:20:51 +00001495 AllocArgs.size(), TUDecl, /*AllowMissing=*/false,
1496 OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001497 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001498 }
1499
John McCall0f55a032010-04-20 02:18:25 +00001500 // We don't need an operator delete if we're running under
1501 // -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001502 if (!getLangOpts().Exceptions) {
John McCall0f55a032010-04-20 02:18:25 +00001503 OperatorDelete = 0;
1504 return false;
1505 }
1506
Anders Carlsson6f9dabf2009-05-31 20:26:12 +00001507 // FindAllocationOverload can change the passed in arguments, so we need to
1508 // copy them back.
1509 if (NumPlaceArgs > 0)
1510 std::copy(&AllocArgs[1], AllocArgs.end(), PlaceArgs);
Mike Stump11289f42009-09-09 15:08:12 +00001511
Douglas Gregor6642ca22010-02-26 05:06:18 +00001512 // C++ [expr.new]p19:
1513 //
1514 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001515 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001516 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001517 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001518 // the scope of T. If this lookup fails to find the name, or if
1519 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001520 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001521 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001522 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001523 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001524 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001525 LookupQualifiedName(FoundDelete, RD);
1526 }
John McCallfb6f5262010-03-18 08:19:33 +00001527 if (FoundDelete.isAmbiguous())
1528 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001529
1530 if (FoundDelete.empty()) {
1531 DeclareGlobalNewDelete();
1532 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1533 }
1534
1535 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001536
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001537 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001538
John McCalld3be2c82010-09-14 21:34:24 +00001539 // Whether we're looking for a placement operator delete is dictated
1540 // by whether we selected a placement operator new, not by whether
1541 // we had explicit placement arguments. This matters for things like
1542 // struct A { void *operator new(size_t, int = 0); ... };
1543 // A *a = new A()
1544 bool isPlacementNew = (NumPlaceArgs > 0 || OperatorNew->param_size() != 1);
1545
1546 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001547 // C++ [expr.new]p20:
1548 // A declaration of a placement deallocation function matches the
1549 // declaration of a placement allocation function if it has the
1550 // same number of parameters and, after parameter transformations
1551 // (8.3.5), all parameter types except the first are
1552 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001554 // To perform this comparison, we compute the function type that
1555 // the deallocation function should have, and use that type both
1556 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001557 //
1558 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001559 QualType ExpectedFunctionType;
1560 {
1561 const FunctionProtoType *Proto
1562 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001563
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001564 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001565 ArgTypes.push_back(Context.VoidPtrTy);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001566 for (unsigned I = 1, N = Proto->getNumArgs(); I < N; ++I)
1567 ArgTypes.push_back(Proto->getArgType(I));
1568
John McCalldb40c7f2010-12-14 08:05:40 +00001569 FunctionProtoType::ExtProtoInfo EPI;
1570 EPI.Variadic = Proto->isVariadic();
1571
Douglas Gregor6642ca22010-02-26 05:06:18 +00001572 ExpectedFunctionType
1573 = Context.getFunctionType(Context.VoidTy, ArgTypes.data(),
John McCalldb40c7f2010-12-14 08:05:40 +00001574 ArgTypes.size(), EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001575 }
1576
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001577 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001578 DEnd = FoundDelete.end();
1579 D != DEnd; ++D) {
1580 FunctionDecl *Fn = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001581 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001582 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1583 // Perform template argument deduction to try to match the
1584 // expected function type.
1585 TemplateDeductionInfo Info(Context, StartLoc);
1586 if (DeduceTemplateArguments(FnTmpl, 0, ExpectedFunctionType, Fn, Info))
1587 continue;
1588 } else
1589 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1590
1591 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001592 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001593 }
1594 } else {
1595 // C++ [expr.new]p20:
1596 // [...] Any non-placement deallocation function matches a
1597 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001598 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001599 DEnd = FoundDelete.end();
1600 D != DEnd; ++D) {
1601 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
1602 if (isNonPlacementDeallocationFunction(Fn))
John McCalla0296f72010-03-19 07:35:19 +00001603 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001604 }
1605 }
1606
1607 // C++ [expr.new]p20:
1608 // [...] If the lookup finds a single matching deallocation
1609 // function, that function will be called; otherwise, no
1610 // deallocation function will be called.
1611 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00001612 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00001613
1614 // C++0x [expr.new]p20:
1615 // If the lookup finds the two-parameter form of a usual
1616 // deallocation function (3.7.4.2) and that function, considered
1617 // as a placement deallocation function, would have been
1618 // selected as a match for the allocation function, the program
1619 // is ill-formed.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001620 if (NumPlaceArgs && getLangOpts().CPlusPlus0x &&
Douglas Gregor6642ca22010-02-26 05:06:18 +00001621 isNonPlacementDeallocationFunction(OperatorDelete)) {
1622 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623 << SourceRange(PlaceArgs[0]->getLocStart(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001624 PlaceArgs[NumPlaceArgs - 1]->getLocEnd());
1625 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
1626 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00001627 } else {
1628 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00001629 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001630 }
1631 }
1632
Sebastian Redlfaf68082008-12-03 20:26:15 +00001633 return false;
1634}
1635
Sebastian Redl33a31012008-12-04 22:20:51 +00001636/// FindAllocationOverload - Find an fitting overload for the allocation
1637/// function in the specified scope.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001638bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
1639 DeclarationName Name, Expr** Args,
1640 unsigned NumArgs, DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001641 bool AllowMissing, FunctionDecl *&Operator,
1642 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001643 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
1644 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00001645 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001646 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00001647 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00001648 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00001649 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00001650 }
1651
John McCallfb6f5262010-03-18 08:19:33 +00001652 if (R.isAmbiguous())
1653 return true;
1654
1655 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00001656
John McCallbc077cf2010-02-08 23:07:23 +00001657 OverloadCandidateSet Candidates(StartLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001658 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00001659 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00001660 // Even member operator new/delete are implicitly treated as
1661 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00001662 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00001663
John McCalla0296f72010-03-19 07:35:19 +00001664 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
1665 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001666 /*ExplicitTemplateArgs=*/0,
1667 llvm::makeArrayRef(Args, NumArgs),
Chandler Carruth93538422010-02-03 11:02:14 +00001668 Candidates,
1669 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00001670 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00001671 }
1672
John McCalla0296f72010-03-19 07:35:19 +00001673 FunctionDecl *Fn = cast<FunctionDecl>(D);
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001674 AddOverloadCandidate(Fn, Alloc.getPair(),
1675 llvm::makeArrayRef(Args, NumArgs), Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00001676 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00001677 }
1678
1679 // Do the resolution.
1680 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00001681 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00001682 case OR_Success: {
1683 // Got one!
1684 FunctionDecl *FnDecl = Best->Function;
Eli Friedmanfa0df832012-02-02 03:46:19 +00001685 MarkFunctionReferenced(StartLoc, FnDecl);
Sebastian Redl33a31012008-12-04 22:20:51 +00001686 // The first argument is size_t, and the first parameter must be size_t,
1687 // too. This is checked on declaration and can be assumed. (It can't be
1688 // asserted on, though, since invalid decls are left in there.)
John McCallfb6f5262010-03-18 08:19:33 +00001689 // Watch out for variadic allocator function.
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001690 unsigned NumArgsInFnDecl = FnDecl->getNumParams();
1691 for (unsigned i = 0; (i < NumArgs && i < NumArgsInFnDecl); ++i) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001692 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
1693 FnDecl->getParamDecl(i));
1694
1695 if (!Diagnose && !CanPerformCopyInitialization(Entity, Owned(Args[i])))
1696 return true;
1697
John McCalldadc5752010-08-24 06:29:42 +00001698 ExprResult Result
Alexis Hunt1f69a022011-05-12 22:46:29 +00001699 = PerformCopyInitialization(Entity, SourceLocation(), Owned(Args[i]));
Douglas Gregor34147272010-03-26 20:35:59 +00001700 if (Result.isInvalid())
Sebastian Redl33a31012008-12-04 22:20:51 +00001701 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001702
Douglas Gregor34147272010-03-26 20:35:59 +00001703 Args[i] = Result.takeAs<Expr>();
Sebastian Redl33a31012008-12-04 22:20:51 +00001704 }
Richard Smith921bd202012-02-26 09:11:52 +00001705
Sebastian Redl33a31012008-12-04 22:20:51 +00001706 Operator = FnDecl;
Richard Smith921bd202012-02-26 09:11:52 +00001707
1708 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
1709 Best->FoundDecl, Diagnose) == AR_inaccessible)
1710 return true;
1711
Sebastian Redl33a31012008-12-04 22:20:51 +00001712 return false;
1713 }
1714
1715 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001716 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001717 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
1718 << Name << Range;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001719 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1720 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruthe6c88182011-06-08 10:26:03 +00001721 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001722 return true;
1723
1724 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00001725 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001726 Diag(StartLoc, diag::err_ovl_ambiguous_call)
1727 << Name << Range;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001728 Candidates.NoteCandidates(*this, OCD_ViableCandidates,
1729 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruthe6c88182011-06-08 10:26:03 +00001730 }
Sebastian Redl33a31012008-12-04 22:20:51 +00001731 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001732
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001733 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00001734 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001735 Diag(StartLoc, diag::err_ovl_deleted_call)
1736 << Best->Function->isDeleted()
1737 << Name
1738 << getDeletedOrUnavailableSuffix(Best->Function)
1739 << Range;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001740 Candidates.NoteCandidates(*this, OCD_AllCandidates,
1741 llvm::makeArrayRef(Args, NumArgs));
Chandler Carruthe6c88182011-06-08 10:26:03 +00001742 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00001743 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00001744 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00001745 }
David Blaikie83d382b2011-09-23 05:06:16 +00001746 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00001747}
1748
1749
Sebastian Redlfaf68082008-12-03 20:26:15 +00001750/// DeclareGlobalNewDelete - Declare the global forms of operator new and
1751/// delete. These are:
1752/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00001753/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00001754/// void* operator new(std::size_t) throw(std::bad_alloc);
1755/// void* operator new[](std::size_t) throw(std::bad_alloc);
1756/// void operator delete(void *) throw();
1757/// void operator delete[](void *) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001758/// // C++0x:
1759/// void* operator new(std::size_t);
1760/// void* operator new[](std::size_t);
1761/// void operator delete(void *);
1762/// void operator delete[](void *);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001763/// @endcode
Sebastian Redl37588092011-03-14 18:08:30 +00001764/// C++0x operator delete is implicitly noexcept.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001765/// Note that the placement and nothrow forms of new are *not* implicitly
1766/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00001767void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001768 if (GlobalNewDeleteDeclared)
1769 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770
Douglas Gregor87f54062009-09-15 22:30:29 +00001771 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001772 // [...] The following allocation and deallocation functions (18.4) are
1773 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00001774 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001775 //
Sebastian Redl37588092011-03-14 18:08:30 +00001776 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00001777 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778 // void* operator new[](std::size_t) throw(std::bad_alloc);
1779 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00001780 // void operator delete[](void*) throw();
Sebastian Redl37588092011-03-14 18:08:30 +00001781 // C++0x:
1782 // void* operator new(std::size_t);
1783 // void* operator new[](std::size_t);
1784 // void operator delete(void*);
1785 // void operator delete[](void*);
Douglas Gregor87f54062009-09-15 22:30:29 +00001786 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001787 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00001788 // new, operator new[], operator delete, operator delete[].
1789 //
1790 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
1791 // "std" or "bad_alloc" as necessary to form the exception specification.
1792 // However, we do not make these implicit declarations visible to name
1793 // lookup.
Sebastian Redl37588092011-03-14 18:08:30 +00001794 // Note that the C++0x versions of operator delete are deallocation functions,
1795 // and thus are implicitly noexcept.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001796 if (!StdBadAlloc && !getLangOpts().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001797 // The "std::bad_alloc" class has not yet been declared, so build it
1798 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001799 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
1800 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001801 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001802 &PP.getIdentifierTable().get("bad_alloc"),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00001803 0);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001804 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00001805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001806
Sebastian Redlfaf68082008-12-03 20:26:15 +00001807 GlobalNewDeleteDeclared = true;
1808
1809 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
1810 QualType SizeT = Context.getSizeType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001811 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001812
Sebastian Redlfaf68082008-12-03 20:26:15 +00001813 DeclareGlobalAllocationFunction(
1814 Context.DeclarationNames.getCXXOperatorName(OO_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001815 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001816 DeclareGlobalAllocationFunction(
1817 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Nuno Lopes13c88c72009-12-16 16:59:22 +00001818 VoidPtr, SizeT, AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001819 DeclareGlobalAllocationFunction(
1820 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
1821 Context.VoidTy, VoidPtr);
1822 DeclareGlobalAllocationFunction(
1823 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
1824 Context.VoidTy, VoidPtr);
1825}
1826
1827/// DeclareGlobalAllocationFunction - Declares a single implicit global
1828/// allocation function if it doesn't already exist.
1829void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Nuno Lopes13c88c72009-12-16 16:59:22 +00001830 QualType Return, QualType Argument,
1831 bool AddMallocAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001832 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
1833
1834 // Check if this function is already declared.
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001835 {
Douglas Gregor17eb26b2008-12-23 22:05:29 +00001836 DeclContext::lookup_iterator Alloc, AllocEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001837 for (llvm::tie(Alloc, AllocEnd) = GlobalCtx->lookup(Name);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001838 Alloc != AllocEnd; ++Alloc) {
Chandler Carruth93538422010-02-03 11:02:14 +00001839 // Only look at non-template functions, as it is the predefined,
1840 // non-templated allocation function we are trying to declare here.
1841 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
1842 QualType InitialParamType =
Douglas Gregor684d7bd2009-12-22 23:42:49 +00001843 Context.getCanonicalType(
Chandler Carruth93538422010-02-03 11:02:14 +00001844 Func->getParamDecl(0)->getType().getUnqualifiedType());
1845 // FIXME: Do we need to check for default arguments here?
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001846 if (Func->getNumParams() == 1 && InitialParamType == Argument) {
1847 if(AddMallocAttr && !Func->hasAttr<MallocAttr>())
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001848 Func->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
Chandler Carruth93538422010-02-03 11:02:14 +00001849 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00001850 }
Chandler Carruth93538422010-02-03 11:02:14 +00001851 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001852 }
1853 }
1854
Douglas Gregor87f54062009-09-15 22:30:29 +00001855 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001856 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00001857 = (Name.getCXXOverloadedOperator() == OO_New ||
1858 Name.getCXXOverloadedOperator() == OO_Array_New);
David Blaikiebbafb8a2012-03-11 07:00:24 +00001859 if (HasBadAllocExceptionSpec && !getLangOpts().CPlusPlus0x) {
Douglas Gregor87f54062009-09-15 22:30:29 +00001860 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00001861 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Douglas Gregor87f54062009-09-15 22:30:29 +00001862 }
John McCalldb40c7f2010-12-14 08:05:40 +00001863
1864 FunctionProtoType::ExtProtoInfo EPI;
John McCalldb40c7f2010-12-14 08:05:40 +00001865 if (HasBadAllocExceptionSpec) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001866 if (!getLangOpts().CPlusPlus0x) {
Sebastian Redl37588092011-03-14 18:08:30 +00001867 EPI.ExceptionSpecType = EST_Dynamic;
1868 EPI.NumExceptions = 1;
1869 EPI.Exceptions = &BadAllocType;
1870 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00001871 } else {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001872 EPI.ExceptionSpecType = getLangOpts().CPlusPlus0x ?
Sebastian Redl37588092011-03-14 18:08:30 +00001873 EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00001874 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001875
John McCalldb40c7f2010-12-14 08:05:40 +00001876 QualType FnType = Context.getFunctionType(Return, &Argument, 1, EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001877 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00001878 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
1879 SourceLocation(), Name,
John McCall8e7d6562010-08-26 03:08:43 +00001880 FnType, /*TInfo=*/0, SC_None,
1881 SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001882 Alloc->setImplicit();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001883
Nuno Lopes13c88c72009-12-16 16:59:22 +00001884 if (AddMallocAttr)
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001885 Alloc->addAttr(::new (Context) MallocAttr(SourceLocation(), Context));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001886
Sebastian Redlfaf68082008-12-03 20:26:15 +00001887 ParmVarDecl *Param = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Abramo Bagnaradff19302011-03-08 08:55:46 +00001888 SourceLocation(), 0,
1889 Argument, /*TInfo=*/0,
1890 SC_None, SC_None, 0);
David Blaikie9c70e042011-09-21 18:16:56 +00001891 Alloc->setParams(Param);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001892
Douglas Gregor8b9ccca2008-12-23 21:05:05 +00001893 // FIXME: Also add this declaration to the IdentifierResolver, but
1894 // make sure it is at the end of the chain to coincide with the
1895 // global scope.
John McCallcc14d1f2010-08-24 08:50:51 +00001896 Context.getTranslationUnitDecl()->addDecl(Alloc);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001897}
1898
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001899bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
1900 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001901 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00001902 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001903 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00001904 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001905
John McCall27b18f82009-11-17 02:14:36 +00001906 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001907 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001908
Chandler Carruthb6f99172010-06-28 00:30:51 +00001909 Found.suppressDiagnostics();
1910
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001911 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001912 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1913 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00001914 NamedDecl *ND = (*F)->getUnderlyingDecl();
1915
1916 // Ignore template operator delete members from the check for a usual
1917 // deallocation function.
1918 if (isa<FunctionTemplateDecl>(ND))
1919 continue;
1920
1921 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00001922 Matches.push_back(F.getPair());
1923 }
1924
1925 // There's exactly one suitable operator; pick it.
1926 if (Matches.size() == 1) {
1927 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00001928
1929 if (Operator->isDeleted()) {
1930 if (Diagnose) {
1931 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00001932 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00001933 }
1934 return true;
1935 }
1936
Richard Smith921bd202012-02-26 09:11:52 +00001937 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
1938 Matches[0], Diagnose) == AR_inaccessible)
1939 return true;
1940
John McCall66a87592010-08-04 00:31:26 +00001941 return false;
1942
1943 // We found multiple suitable operators; complain about the ambiguity.
1944 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001945 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001946 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
1947 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00001948
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001949 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00001950 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
1951 Diag((*F)->getUnderlyingDecl()->getLocation(),
1952 diag::note_member_declared_here) << Name;
1953 }
John McCall66a87592010-08-04 00:31:26 +00001954 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001955 }
1956
1957 // We did find operator delete/operator delete[] declarations, but
1958 // none of them were suitable.
1959 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00001960 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00001961 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
1962 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001963
Alexis Huntf91729462011-05-12 22:46:25 +00001964 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
1965 F != FEnd; ++F)
1966 Diag((*F)->getUnderlyingDecl()->getLocation(),
1967 diag::note_member_declared_here) << Name;
1968 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001969 return true;
1970 }
1971
1972 // Look for a global declaration.
1973 DeclareGlobalNewDelete();
1974 DeclContext *TUDecl = Context.getTranslationUnitDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001976 CXXNullPtrLiteralExpr Null(Context.VoidPtrTy, SourceLocation());
1977 Expr* DeallocArgs[1];
1978 DeallocArgs[0] = &Null;
1979 if (FindAllocationOverload(StartLoc, SourceRange(), Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00001980 DeallocArgs, 1, TUDecl, !Diagnose,
1981 Operator, Diagnose))
Anders Carlssone1d34ba02009-11-15 18:45:20 +00001982 return true;
1983
1984 assert(Operator && "Did not find a deallocation function!");
1985 return false;
1986}
1987
Sebastian Redlbd150f42008-11-21 19:14:01 +00001988/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
1989/// @code ::delete ptr; @endcode
1990/// or
1991/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00001992ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001993Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00001994 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00001995 // C++ [expr.delete]p1:
1996 // The operand shall have a pointer type, or a class type having a single
1997 // conversion function to a pointer type. The result has type void.
1998 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00001999 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2000
John Wiegley01296292011-04-08 18:41:53 +00002001 ExprResult Ex = Owned(ExE);
Anders Carlssona471db02009-08-16 20:29:29 +00002002 FunctionDecl *OperatorDelete = 0;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002003 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00002004 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00002005
John Wiegley01296292011-04-08 18:41:53 +00002006 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00002007 // Perform lvalue-to-rvalue cast, if needed.
2008 Ex = DefaultLvalueConversion(Ex.take());
2009
John Wiegley01296292011-04-08 18:41:53 +00002010 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002011
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002012 if (const RecordType *Record = Type->getAs<RecordType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002013 if (RequireCompleteType(StartLoc, Type,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002014 diag::err_delete_incomplete_class_type))
Douglas Gregorf65f4902010-07-29 14:44:35 +00002015 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002016
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002017 SmallVector<CXXConversionDecl*, 4> ObjectPtrConversions;
John McCallda4458e2010-03-31 01:36:47 +00002018
Fariborz Jahanianb54ccb22009-09-11 21:44:33 +00002019 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002020 const UnresolvedSetImpl *Conversions = RD->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002021 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002022 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00002023 NamedDecl *D = I.getDecl();
2024 if (isa<UsingShadowDecl>(D))
2025 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2026
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002027 // Skip over templated conversion functions; they aren't considered.
John McCallda4458e2010-03-31 01:36:47 +00002028 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002029 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002030
John McCallda4458e2010-03-31 01:36:47 +00002031 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002032
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002033 QualType ConvType = Conv->getConversionType().getNonReferenceType();
2034 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00002035 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002036 ObjectPtrConversions.push_back(Conv);
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002037 }
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002038 if (ObjectPtrConversions.size() == 1) {
2039 // We have a single conversion to a pointer-to-object type. Perform
2040 // that conversion.
John McCallda4458e2010-03-31 01:36:47 +00002041 // TODO: don't redo the conversion calculation.
John Wiegley01296292011-04-08 18:41:53 +00002042 ExprResult Res =
2043 PerformImplicitConversion(Ex.get(),
John McCallda4458e2010-03-31 01:36:47 +00002044 ObjectPtrConversions.front()->getConversionType(),
John Wiegley01296292011-04-08 18:41:53 +00002045 AA_Converting);
2046 if (Res.isUsable()) {
2047 Ex = move(Res);
2048 Type = Ex.get()->getType();
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002049 }
2050 }
2051 else if (ObjectPtrConversions.size() > 1) {
2052 Diag(StartLoc, diag::err_ambiguous_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002053 << Type << Ex.get()->getSourceRange();
John McCallda4458e2010-03-31 01:36:47 +00002054 for (unsigned i= 0; i < ObjectPtrConversions.size(); i++)
2055 NoteOverloadCandidate(ObjectPtrConversions[i]);
Fariborz Jahanianadcea102009-09-15 22:15:23 +00002056 return ExprError();
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002057 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002058 }
2059
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002060 if (!Type->isPointerType())
2061 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002062 << Type << Ex.get()->getSourceRange());
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002063
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002064 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002065 QualType PointeeElem = Context.getBaseElementType(Pointee);
2066
2067 if (unsigned AddressSpace = Pointee.getAddressSpace())
2068 return Diag(Ex.get()->getLocStart(),
2069 diag::err_address_space_qualified_delete)
2070 << Pointee.getUnqualifiedType() << AddressSpace;
2071
2072 CXXRecordDecl *PointeeRD = 0;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002073 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002074 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002075 // effectively bans deletion of "void*". However, most compilers support
2076 // this, so we treat it as a warning unless we're in a SFINAE context.
2077 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00002078 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002079 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002080 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002081 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00002082 } else if (!Pointee->isDependentType()) {
2083 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002084 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002085 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2086 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2087 }
2088 }
2089
Douglas Gregor98496dc2009-09-29 21:38:53 +00002090 // C++ [expr.delete]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002091 // [Note: a pointer to a const type can be the operand of a
2092 // delete-expression; it is not necessary to cast away the constness
2093 // (5.2.11) of the pointer expression before it is used as the operand
Douglas Gregor98496dc2009-09-29 21:38:53 +00002094 // of the delete-expression. ]
John McCall31168b02011-06-15 23:02:42 +00002095 if (!Context.hasSameType(Ex.get()->getType(), Context.VoidPtrTy))
Abramo Bagnarad4756b92011-11-16 15:42:13 +00002096 Ex = Owned(ImplicitCastExpr::Create(Context, Context.VoidPtrTy,
2097 CK_BitCast, Ex.take(), 0, VK_RValue));
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002098
2099 if (Pointee->isArrayType() && !ArrayForm) {
2100 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00002101 << Type << Ex.get()->getSourceRange()
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002102 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(StartLoc), "[]");
2103 ArrayForm = true;
2104 }
2105
Anders Carlssona471db02009-08-16 20:29:29 +00002106 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2107 ArrayForm ? OO_Array_Delete : OO_Delete);
2108
Eli Friedmanae4280f2011-07-26 22:25:31 +00002109 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002110 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00002111 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2112 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00002113 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002114
John McCall284c48f2011-01-27 09:37:56 +00002115 // If we're allocating an array of records, check whether the
2116 // usual operator delete[] has a size_t parameter.
2117 if (ArrayForm) {
2118 // If the user specifically asked to use the global allocator,
2119 // we'll need to do the lookup into the class.
2120 if (UseGlobal)
2121 UsualArrayDeleteWantsSize =
2122 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2123
2124 // Otherwise, the usual operator delete[] should be the
2125 // function we just found.
2126 else if (isa<CXXMethodDecl>(OperatorDelete))
2127 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2128 }
2129
Richard Smitheec915d62012-02-18 04:13:32 +00002130 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00002131 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002132 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002133 const_cast<CXXDestructorDecl*>(Dtor));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002134 DiagnoseUseOfDecl(Dtor, StartLoc);
2135 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002136
2137 // C++ [expr.delete]p3:
2138 // In the first alternative (delete object), if the static type of the
2139 // object to be deleted is different from its dynamic type, the static
2140 // type shall be a base class of the dynamic type of the object to be
2141 // deleted and the static type shall have a virtual destructor or the
2142 // behavior is undefined.
2143 //
2144 // Note: a final class cannot be derived from, no issue there
Eli Friedman1b71a222011-07-26 23:27:24 +00002145 if (PointeeRD->isPolymorphic() && !PointeeRD->hasAttr<FinalAttr>()) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002146 CXXDestructorDecl *dtor = PointeeRD->getDestructor();
Eli Friedman1b71a222011-07-26 23:27:24 +00002147 if (dtor && !dtor->isVirtual()) {
2148 if (PointeeRD->isAbstract()) {
2149 // If the class is abstract, we warn by default, because we're
2150 // sure the code has undefined behavior.
2151 Diag(StartLoc, diag::warn_delete_abstract_non_virtual_dtor)
2152 << PointeeElem;
2153 } else if (!ArrayForm) {
2154 // Otherwise, if this is not an array delete, it's a bit suspect,
2155 // but not necessarily wrong.
2156 Diag(StartLoc, diag::warn_delete_non_virtual_dtor) << PointeeElem;
2157 }
2158 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002159 }
John McCall31168b02011-06-15 23:02:42 +00002160
David Blaikiebbafb8a2012-03-11 07:00:24 +00002161 } else if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002162 PointeeElem->isObjCLifetimeType() &&
2163 (PointeeElem.getObjCLifetime() == Qualifiers::OCL_Strong ||
2164 PointeeElem.getObjCLifetime() == Qualifiers::OCL_Weak) &&
2165 ArrayForm) {
2166 Diag(StartLoc, diag::warn_err_new_delete_object_array)
2167 << 1 << PointeeElem;
Anders Carlssona471db02009-08-16 20:29:29 +00002168 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169
Anders Carlssona471db02009-08-16 20:29:29 +00002170 if (!OperatorDelete) {
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002171 // Look for a global declaration.
Anders Carlssona471db02009-08-16 20:29:29 +00002172 DeclareGlobalNewDelete();
2173 DeclContext *TUDecl = Context.getTranslationUnitDecl();
John Wiegley01296292011-04-08 18:41:53 +00002174 Expr *Arg = Ex.get();
Mike Stump11289f42009-09-09 15:08:12 +00002175 if (FindAllocationOverload(StartLoc, SourceRange(), DeleteName,
John Wiegley01296292011-04-08 18:41:53 +00002176 &Arg, 1, TUDecl, /*AllowMissing=*/false,
Anders Carlssona471db02009-08-16 20:29:29 +00002177 OperatorDelete))
2178 return ExprError();
2179 }
Mike Stump11289f42009-09-09 15:08:12 +00002180
Eli Friedmanfa0df832012-02-02 03:46:19 +00002181 MarkFunctionReferenced(StartLoc, OperatorDelete);
John McCall284c48f2011-01-27 09:37:56 +00002182
Douglas Gregorfa778132011-02-01 15:50:11 +00002183 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00002184 if (PointeeRD) {
2185 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00002186 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00002187 PDiag(diag::err_access_dtor) << PointeeElem);
2188 }
2189 }
2190
Sebastian Redlbd150f42008-11-21 19:14:01 +00002191 }
2192
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002193 return Owned(new (Context) CXXDeleteExpr(Context.VoidTy, UseGlobal, ArrayForm,
John McCall284c48f2011-01-27 09:37:56 +00002194 ArrayFormAsWritten,
2195 UsualArrayDeleteWantsSize,
John Wiegley01296292011-04-08 18:41:53 +00002196 OperatorDelete, Ex.take(), StartLoc));
Sebastian Redlbd150f42008-11-21 19:14:01 +00002197}
2198
Douglas Gregor633caca2009-11-23 23:44:04 +00002199/// \brief Check the use of the given variable as a C++ condition in an if,
2200/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00002201ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00002202 SourceLocation StmtLoc,
2203 bool ConvertToBoolean) {
Douglas Gregor633caca2009-11-23 23:44:04 +00002204 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002205
Douglas Gregor633caca2009-11-23 23:44:04 +00002206 // C++ [stmt.select]p2:
2207 // The declarator shall not specify a function or an array.
2208 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002209 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002210 diag::err_invalid_use_of_function_type)
2211 << ConditionVar->getSourceRange());
2212 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002213 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002214 diag::err_invalid_use_of_array_type)
2215 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00002216
John Wiegley01296292011-04-08 18:41:53 +00002217 ExprResult Condition =
Abramo Bagnara7945c982012-01-27 09:46:47 +00002218 Owned(DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2219 SourceLocation(),
2220 ConditionVar,
John McCall113bee02012-03-10 09:33:50 +00002221 /*enclosing*/ false,
Abramo Bagnara7945c982012-01-27 09:46:47 +00002222 ConditionVar->getLocation(),
2223 ConditionVar->getType().getNonReferenceType(),
John Wiegley01296292011-04-08 18:41:53 +00002224 VK_LValue));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002225
Eli Friedmanfa0df832012-02-02 03:46:19 +00002226 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002227
John Wiegley01296292011-04-08 18:41:53 +00002228 if (ConvertToBoolean) {
2229 Condition = CheckBooleanCondition(Condition.take(), StmtLoc);
2230 if (Condition.isInvalid())
2231 return ExprError();
2232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002233
John Wiegley01296292011-04-08 18:41:53 +00002234 return move(Condition);
Douglas Gregor633caca2009-11-23 23:44:04 +00002235}
2236
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002237/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002238ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002239 // C++ 6.4p4:
2240 // The value of a condition that is an initialized declaration in a statement
2241 // other than a switch statement is the value of the declared variable
2242 // implicitly converted to type bool. If that conversion is ill-formed, the
2243 // program is ill-formed.
2244 // The value of a condition that is an expression is the value of the
2245 // expression, implicitly converted to bool.
2246 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002247 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002248}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002249
2250/// Helper function to determine whether this is the (deprecated) C++
2251/// conversion from a string literal to a pointer to non-const char or
2252/// non-const wchar_t (for narrow and wide string literals,
2253/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002254bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002255Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2256 // Look inside the implicit cast, if it exists.
2257 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2258 From = Cast->getSubExpr();
2259
2260 // A string literal (2.13.4) that is not a wide string literal can
2261 // be converted to an rvalue of type "pointer to char"; a wide
2262 // string literal can be converted to an rvalue of type "pointer
2263 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002264 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002265 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002266 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002267 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002268 // This conversion is considered only when there is an
2269 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00002270 if (!ToPtrType->getPointeeType().hasQualifiers()) {
2271 switch (StrLit->getKind()) {
2272 case StringLiteral::UTF8:
2273 case StringLiteral::UTF16:
2274 case StringLiteral::UTF32:
2275 // We don't allow UTF literals to be implicitly converted
2276 break;
2277 case StringLiteral::Ascii:
2278 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
2279 ToPointeeType->getKind() == BuiltinType::Char_S);
2280 case StringLiteral::Wide:
2281 return ToPointeeType->isWideCharType();
2282 }
2283 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002284 }
2285
2286 return false;
2287}
Douglas Gregor39c16d42008-10-24 04:54:22 +00002288
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00002290 SourceLocation CastLoc,
2291 QualType Ty,
2292 CastKind Kind,
2293 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00002294 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002295 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00002296 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00002297 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002298 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00002299 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00002300 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
John McCall37ad5512010-08-23 06:44:23 +00002301 ASTOwningVector<Expr*> ConstructorArgs(S);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302
Douglas Gregorc7a31072011-10-10 22:41:00 +00002303 if (S.CompleteConstructorCall(Constructor,
John McCallfaf5fb42010-08-26 23:41:50 +00002304 MultiExprArg(&From, 1),
Douglas Gregora4253922010-04-16 22:17:36 +00002305 CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00002306 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
John McCall5dadb652012-04-07 03:04:20 +00002308 S.CheckConstructorAccess(CastLoc, Constructor,
2309 InitializedEntity::InitializeTemporary(Ty),
2310 Constructor->getAccess());
Douglas Gregorc7a31072011-10-10 22:41:00 +00002311
2312 ExprResult Result
2313 = S.BuildCXXConstructExpr(CastLoc, Ty, cast<CXXConstructorDecl>(Method),
2314 move_arg(ConstructorArgs),
2315 HadMultipleCandidates, /*ZeroInit*/ false,
2316 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00002317 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00002318 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002319
Douglas Gregora4253922010-04-16 22:17:36 +00002320 return S.MaybeBindToTemporary(Result.takeAs<Expr>());
2321 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002322
John McCalle3027922010-08-25 11:45:40 +00002323 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00002324 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325
Douglas Gregora4253922010-04-16 22:17:36 +00002326 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00002327 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
2328 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002329 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00002330 if (Result.isInvalid())
2331 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00002332 // Record usage of conversion in an implicit cast.
2333 Result = S.Owned(ImplicitCastExpr::Create(S.Context,
2334 Result.get()->getType(),
2335 CK_UserDefinedConversion,
2336 Result.get(), 0,
2337 Result.get()->getValueKind()));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002338
John McCall30909032011-09-21 08:36:56 +00002339 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ 0, FoundDecl);
2340
Douglas Gregor668443e2011-01-20 00:18:04 +00002341 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00002342 }
2343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002344}
Douglas Gregora4253922010-04-16 22:17:36 +00002345
Douglas Gregor5fb53972009-01-14 15:45:31 +00002346/// PerformImplicitConversion - Perform an implicit conversion of the
2347/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00002348/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00002349/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002350/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00002351ExprResult
2352Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002353 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00002354 AssignmentAction Action,
2355 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00002356 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00002357 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002358 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
2359 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00002360 if (Res.isInvalid())
2361 return ExprError();
2362 From = Res.take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002363 break;
John Wiegley01296292011-04-08 18:41:53 +00002364 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00002365
Anders Carlsson110b07b2009-09-15 06:28:28 +00002366 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002367
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00002368 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00002369 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00002370 QualType BeforeToType;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002371 assert(FD && "FIXME: aggregate initialization from init list");
Anders Carlsson110b07b2009-09-15 06:28:28 +00002372 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00002373 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002374
Anders Carlsson110b07b2009-09-15 06:28:28 +00002375 // If the user-defined conversion is specified by a conversion function,
2376 // the initial standard conversion sequence converts the source type to
2377 // the implicit object parameter of the conversion function.
2378 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00002379 } else {
2380 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00002381 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002382 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00002383 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002384 // If the user-defined conversion is specified by a constructor, the
Fariborz Jahanian55824512009-11-06 00:23:08 +00002385 // initial standard conversion sequence converts the source type to the
2386 // type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00002387 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
2388 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002389 }
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002390 // Watch out for elipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00002391 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00002392 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00002393 PerformImplicitConversion(From, BeforeToType,
2394 ICS.UserDefined.Before, AA_Converting,
2395 CCK);
John Wiegley01296292011-04-08 18:41:53 +00002396 if (Res.isInvalid())
2397 return ExprError();
2398 From = Res.take();
Fariborz Jahanian55824512009-11-06 00:23:08 +00002399 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002400
2401 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00002402 = BuildCXXCastArgument(*this,
2403 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00002404 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002405 CastKind, cast<CXXMethodDecl>(FD),
2406 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002407 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00002408 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00002409
2410 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00002411 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002412
John Wiegley01296292011-04-08 18:41:53 +00002413 From = CastArg.take();
Eli Friedmane96f1d32009-11-27 04:41:50 +00002414
Richard Smith507840d2011-11-29 22:48:16 +00002415 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
2416 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00002417 }
John McCall0d1da222010-01-12 00:44:57 +00002418
2419 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00002420 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00002421 PDiag(diag::err_typecheck_ambiguous_condition)
2422 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00002423 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002424
Douglas Gregor39c16d42008-10-24 04:54:22 +00002425 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00002426 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002427
2428 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00002429 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002430 }
2431
2432 // Everything went well.
John Wiegley01296292011-04-08 18:41:53 +00002433 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002434}
2435
Richard Smith507840d2011-11-29 22:48:16 +00002436/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00002437/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00002438/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00002439/// expression. Flavor is the context in which we're performing this
2440/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00002441ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00002442Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002443 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00002444 AssignmentAction Action,
2445 CheckedConversionKind CCK) {
2446 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
2447
Mike Stump87c57ac2009-05-16 07:39:55 +00002448 // Overall FIXME: we are recomputing too many types here and doing far too
2449 // much extra work. What this means is that we need to keep track of more
2450 // information that is computed when we try the implicit conversion initially,
2451 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002452 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00002453
Douglas Gregor2fe98832008-11-03 19:09:14 +00002454 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00002455 // FIXME: When can ToType be a reference type?
2456 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002457 if (SCS.Second == ICK_Derived_To_Base) {
John McCall37ad5512010-08-23 06:44:23 +00002458 ASTOwningVector<Expr*> ConstructorArgs(*this);
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002459 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
John McCall37ad5512010-08-23 06:44:23 +00002460 MultiExprArg(*this, &From, 1),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002461 /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002462 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00002463 return ExprError();
2464 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2465 ToType, SCS.CopyConstructor,
2466 move_arg(ConstructorArgs),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002467 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002468 /*ZeroInit*/ false,
2469 CXXConstructExpr::CK_Complete,
2470 SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00002471 }
John Wiegley01296292011-04-08 18:41:53 +00002472 return BuildCXXConstructExpr(/*FIXME:ConstructLoc*/SourceLocation(),
2473 ToType, SCS.CopyConstructor,
2474 MultiExprArg(*this, &From, 1),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002475 /*HadMultipleCandidates*/ false,
John Wiegley01296292011-04-08 18:41:53 +00002476 /*ZeroInit*/ false,
2477 CXXConstructExpr::CK_Complete,
2478 SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00002479 }
2480
Douglas Gregor980fb162010-04-29 18:24:40 +00002481 // Resolve overloaded function references.
2482 if (Context.hasSameType(FromType, Context.OverloadTy)) {
2483 DeclAccessPair Found;
2484 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
2485 true, Found);
2486 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00002487 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00002488
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002489 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00002490 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002491
Douglas Gregor980fb162010-04-29 18:24:40 +00002492 From = FixOverloadedFunctionReference(From, Found, Fn);
2493 FromType = From->getType();
2494 }
2495
Richard Smith507840d2011-11-29 22:48:16 +00002496 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002497 switch (SCS.First) {
2498 case ICK_Identity:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002499 // Nothing to do.
2500 break;
2501
Eli Friedman946b7b52012-01-24 22:51:26 +00002502 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00002503 assert(From->getObjectKind() != OK_ObjCProperty);
John McCall34376a62010-12-04 03:47:34 +00002504 FromType = FromType.getUnqualifiedType();
Eli Friedman946b7b52012-01-24 22:51:26 +00002505 ExprResult FromRes = DefaultLvalueConversion(From);
2506 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
2507 From = FromRes.take();
John McCall34376a62010-12-04 03:47:34 +00002508 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00002509 }
John McCall34376a62010-12-04 03:47:34 +00002510
Douglas Gregor39c16d42008-10-24 04:54:22 +00002511 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00002512 FromType = Context.getArrayDecayedType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002513 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
2514 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor171c45a2009-02-18 21:56:37 +00002515 break;
2516
2517 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002518 FromType = Context.getPointerType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00002519 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
2520 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002521 break;
2522
2523 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002524 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002525 }
2526
Richard Smith507840d2011-11-29 22:48:16 +00002527 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00002528 switch (SCS.Second) {
2529 case ICK_Identity:
Sebastian Redl5d431642009-10-10 12:04:10 +00002530 // If both sides are functions (or pointers/references to them), there could
2531 // be incompatible exception declarations.
2532 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002533 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002534 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00002535 break;
2536
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002537 case ICK_NoReturn_Adjustment:
2538 // If both sides are functions (or pointers/references to them), there could
2539 // be incompatible exception declarations.
2540 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002541 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002542
Richard Smith507840d2011-11-29 22:48:16 +00002543 From = ImpCastExprToType(From, ToType, CK_NoOp,
2544 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00002545 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002546
Douglas Gregor39c16d42008-10-24 04:54:22 +00002547 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002548 case ICK_Integral_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002549 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
2550 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002551 break;
2552
2553 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00002554 case ICK_Floating_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002555 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
2556 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002557 break;
2558
2559 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00002560 case ICK_Complex_Conversion: {
2561 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
2562 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
2563 CastKind CK;
2564 if (FromEl->isRealFloatingType()) {
2565 if (ToEl->isRealFloatingType())
2566 CK = CK_FloatingComplexCast;
2567 else
2568 CK = CK_FloatingComplexToIntegralComplex;
2569 } else if (ToEl->isRealFloatingType()) {
2570 CK = CK_IntegralComplexToFloatingComplex;
2571 } else {
2572 CK = CK_IntegralComplexCast;
2573 }
Richard Smith507840d2011-11-29 22:48:16 +00002574 From = ImpCastExprToType(From, ToType, CK,
2575 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002576 break;
John McCall8cb679e2010-11-15 09:13:47 +00002577 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00002578
Douglas Gregor39c16d42008-10-24 04:54:22 +00002579 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00002580 if (ToType->isRealFloatingType())
Richard Smith507840d2011-11-29 22:48:16 +00002581 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
2582 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002583 else
Richard Smith507840d2011-11-29 22:48:16 +00002584 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
2585 VK_RValue, /*BasePath=*/0, CCK).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00002586 break;
2587
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002588 case ICK_Compatible_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002589 From = ImpCastExprToType(From, ToType, CK_NoOp,
2590 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002591 break;
2592
John McCall31168b02011-06-15 23:02:42 +00002593 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002594 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00002595 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002596 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00002597 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002598 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002599 diag::ext_typecheck_convert_incompatible_pointer)
2600 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002601 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002602 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002603 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00002604 diag::ext_typecheck_convert_incompatible_pointer)
2605 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00002606 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00002607
Douglas Gregor33823722011-06-11 01:09:30 +00002608 if (From->getType()->isObjCObjectPointerType() &&
2609 ToType->isObjCObjectPointerType())
2610 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002611 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00002612 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002613 !CheckObjCARCUnavailableWeakConversion(ToType,
2614 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00002615 if (Action == AA_Initializing)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002616 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002617 diag::err_arc_weak_unavailable_assign);
2618 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00002619 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00002620 diag::err_arc_convesion_of_weak_unavailable)
2621 << (Action == AA_Casting) << From->getType() << ToType
2622 << From->getSourceRange();
2623 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00002624
John McCall8cb679e2010-11-15 09:13:47 +00002625 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002626 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002627 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002628 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00002629
2630 // Make sure we extend blocks if necessary.
2631 // FIXME: doing this here is really ugly.
2632 if (Kind == CK_BlockPointerToObjCPointerCast) {
2633 ExprResult E = From;
2634 (void) PrepareCastToObjCObjectPointer(E);
2635 From = E.take();
2636 }
2637
Richard Smith507840d2011-11-29 22:48:16 +00002638 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2639 .take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002640 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002642
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002643 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00002644 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00002645 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00002646 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002647 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00002648 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00002649 return ExprError();
Richard Smith507840d2011-11-29 22:48:16 +00002650 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
2651 .take();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002652 break;
2653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002654
Abramo Bagnara7ccce982011-04-07 09:26:19 +00002655 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002656 // Perform half-to-boolean conversion via float.
2657 if (From->getType()->isHalfType()) {
2658 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).take();
2659 FromType = Context.FloatTy;
2660 }
2661
Richard Smith507840d2011-11-29 22:48:16 +00002662 From = ImpCastExprToType(From, Context.BoolTy,
2663 ScalarTypeToBooleanCastKind(FromType),
2664 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor39c16d42008-10-24 04:54:22 +00002665 break;
2666
Douglas Gregor88d292c2010-05-13 16:44:06 +00002667 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00002668 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002669 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002670 ToType.getNonReferenceType(),
2671 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00002673 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00002674 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00002675 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00002676
Richard Smith507840d2011-11-29 22:48:16 +00002677 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
2678 CK_DerivedToBase, From->getValueKind(),
2679 &BasePath, CCK).take();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00002680 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00002681 }
2682
Douglas Gregor46188682010-05-18 22:42:18 +00002683 case ICK_Vector_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00002684 From = ImpCastExprToType(From, ToType, CK_BitCast,
2685 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002686 break;
2687
2688 case ICK_Vector_Splat:
Richard Smith507840d2011-11-29 22:48:16 +00002689 From = ImpCastExprToType(From, ToType, CK_VectorSplat,
2690 VK_RValue, /*BasePath=*/0, CCK).take();
Douglas Gregor46188682010-05-18 22:42:18 +00002691 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002692
Douglas Gregor46188682010-05-18 22:42:18 +00002693 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00002694 // Case 1. x -> _Complex y
2695 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
2696 QualType ElType = ToComplex->getElementType();
2697 bool isFloatingComplex = ElType->isRealFloatingType();
2698
2699 // x -> y
2700 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
2701 // do nothing
2702 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002703 From = ImpCastExprToType(From, ElType,
2704 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).take();
John McCall8cb679e2010-11-15 09:13:47 +00002705 } else {
2706 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002707 From = ImpCastExprToType(From, ElType,
2708 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).take();
John McCall8cb679e2010-11-15 09:13:47 +00002709 }
2710 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00002711 From = ImpCastExprToType(From, ToType,
2712 isFloatingComplex ? CK_FloatingRealToComplex
2713 : CK_IntegralRealToComplex).take();
John McCall8cb679e2010-11-15 09:13:47 +00002714
2715 // Case 2. _Complex x -> y
2716 } else {
2717 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
2718 assert(FromComplex);
2719
2720 QualType ElType = FromComplex->getElementType();
2721 bool isFloatingComplex = ElType->isRealFloatingType();
2722
2723 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00002724 From = ImpCastExprToType(From, ElType,
2725 isFloatingComplex ? CK_FloatingComplexToReal
2726 : CK_IntegralComplexToReal,
2727 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002728
2729 // x -> y
2730 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
2731 // do nothing
2732 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00002733 From = ImpCastExprToType(From, ToType,
2734 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
2735 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002736 } else {
2737 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00002738 From = ImpCastExprToType(From, ToType,
2739 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
2740 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall8cb679e2010-11-15 09:13:47 +00002741 }
2742 }
Douglas Gregor46188682010-05-18 22:42:18 +00002743 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002744
2745 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00002746 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
2747 VK_RValue, /*BasePath=*/0, CCK).take();
John McCall31168b02011-06-15 23:02:42 +00002748 break;
2749 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002750
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002751 case ICK_TransparentUnionConversion: {
John Wiegley01296292011-04-08 18:41:53 +00002752 ExprResult FromRes = Owned(From);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002753 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00002754 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
2755 if (FromRes.isInvalid())
2756 return ExprError();
2757 From = FromRes.take();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00002758 assert ((ConvTy == Sema::Compatible) &&
2759 "Improper transparent union conversion");
2760 (void)ConvTy;
2761 break;
2762 }
2763
Douglas Gregor46188682010-05-18 22:42:18 +00002764 case ICK_Lvalue_To_Rvalue:
2765 case ICK_Array_To_Pointer:
2766 case ICK_Function_To_Pointer:
2767 case ICK_Qualification:
2768 case ICK_Num_Conversion_Kinds:
David Blaikie83d382b2011-09-23 05:06:16 +00002769 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002770 }
2771
2772 switch (SCS.Third) {
2773 case ICK_Identity:
2774 // Nothing to do.
2775 break;
2776
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002777 case ICK_Qualification: {
2778 // The qualification keeps the category of the inner expression, unless the
2779 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00002780 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00002781 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00002782 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
2783 CK_NoOp, VK, /*BasePath=*/0, CCK).take();
Douglas Gregore489a7d2010-02-28 18:30:25 +00002784
Douglas Gregore981bb02011-03-14 16:13:32 +00002785 if (SCS.DeprecatedStringLiteralToCharPtr &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002786 !getLangOpts().WritableStrings)
Douglas Gregore489a7d2010-02-28 18:30:25 +00002787 Diag(From->getLocStart(), diag::warn_deprecated_string_literal_conversion)
2788 << ToType.getNonReferenceType();
2789
Douglas Gregor39c16d42008-10-24 04:54:22 +00002790 break;
Sebastian Redlc57d34b2010-07-20 04:20:21 +00002791 }
2792
Douglas Gregor39c16d42008-10-24 04:54:22 +00002793 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002794 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00002795 }
2796
Douglas Gregor298f43d2012-04-12 20:42:30 +00002797 // If this conversion sequence involved a scalar -> atomic conversion, perform
2798 // that conversion now.
2799 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>())
2800 if (Context.hasSameType(ToAtomic->getValueType(), From->getType()))
2801 From = ImpCastExprToType(From, ToType, CK_NonAtomicToAtomic, VK_RValue, 0,
2802 CCK).take();
2803
John Wiegley01296292011-04-08 18:41:53 +00002804 return Owned(From);
Douglas Gregor39c16d42008-10-24 04:54:22 +00002805}
2806
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002807ExprResult Sema::ActOnUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00002808 SourceLocation KWLoc,
2809 ParsedType Ty,
2810 SourceLocation RParen) {
2811 TypeSourceInfo *TSInfo;
2812 QualType T = GetTypeFromParser(Ty, &TSInfo);
Mike Stump11289f42009-09-09 15:08:12 +00002813
Douglas Gregor54e5b132010-09-09 16:14:44 +00002814 if (!TSInfo)
2815 TSInfo = Context.getTrivialTypeSourceInfo(T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002816 return BuildUnaryTypeTrait(UTT, KWLoc, TSInfo, RParen);
Douglas Gregor54e5b132010-09-09 16:14:44 +00002817}
2818
Chandler Carruth8e172c62011-05-01 06:51:22 +00002819/// \brief Check the completeness of a type in a unary type trait.
2820///
2821/// If the particular type trait requires a complete type, tries to complete
2822/// it. If completing the type fails, a diagnostic is emitted and false
2823/// returned. If completing the type succeeds or no completion was required,
2824/// returns true.
2825static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S,
2826 UnaryTypeTrait UTT,
2827 SourceLocation Loc,
2828 QualType ArgTy) {
2829 // C++0x [meta.unary.prop]p3:
2830 // For all of the class templates X declared in this Clause, instantiating
2831 // that template with a template argument that is a class template
2832 // specialization may result in the implicit instantiation of the template
2833 // argument if and only if the semantics of X require that the argument
2834 // must be a complete type.
2835 // We apply this rule to all the type trait expressions used to implement
2836 // these class templates. We also try to follow any GCC documented behavior
2837 // in these expressions to ensure portability of standard libraries.
2838 switch (UTT) {
Chandler Carruth8e172c62011-05-01 06:51:22 +00002839 // is_complete_type somewhat obviously cannot require a complete type.
2840 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002841 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002842
2843 // These traits are modeled on the type predicates in C++0x
2844 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
2845 // requiring a complete type, as whether or not they return true cannot be
2846 // impacted by the completeness of the type.
2847 case UTT_IsVoid:
2848 case UTT_IsIntegral:
2849 case UTT_IsFloatingPoint:
2850 case UTT_IsArray:
2851 case UTT_IsPointer:
2852 case UTT_IsLvalueReference:
2853 case UTT_IsRvalueReference:
2854 case UTT_IsMemberFunctionPointer:
2855 case UTT_IsMemberObjectPointer:
2856 case UTT_IsEnum:
2857 case UTT_IsUnion:
2858 case UTT_IsClass:
2859 case UTT_IsFunction:
2860 case UTT_IsReference:
2861 case UTT_IsArithmetic:
2862 case UTT_IsFundamental:
2863 case UTT_IsObject:
2864 case UTT_IsScalar:
2865 case UTT_IsCompound:
2866 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002867 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002868
2869 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
2870 // which requires some of its traits to have the complete type. However,
2871 // the completeness of the type cannot impact these traits' semantics, and
2872 // so they don't require it. This matches the comments on these traits in
2873 // Table 49.
2874 case UTT_IsConst:
2875 case UTT_IsVolatile:
2876 case UTT_IsSigned:
2877 case UTT_IsUnsigned:
2878 return true;
2879
2880 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002881 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00002882 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00002883 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002884 case UTT_IsStandardLayout:
2885 case UTT_IsPOD:
2886 case UTT_IsLiteral:
2887 case UTT_IsEmpty:
2888 case UTT_IsPolymorphic:
2889 case UTT_IsAbstract:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002890 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00002891
Douglas Gregordca70af2011-12-03 18:14:24 +00002892 // These traits require a complete type.
2893 case UTT_IsFinal:
2894
Chandler Carrutha62d8a52011-05-01 19:18:02 +00002895 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00002896 // [meta.unary.prop] despite not being named the same. They are specified
2897 // by both GCC and the Embarcadero C++ compiler, and require the complete
2898 // type due to the overarching C++0x type predicates being implemented
2899 // requiring the complete type.
2900 case UTT_HasNothrowAssign:
2901 case UTT_HasNothrowConstructor:
2902 case UTT_HasNothrowCopy:
2903 case UTT_HasTrivialAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00002904 case UTT_HasTrivialDefaultConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00002905 case UTT_HasTrivialCopy:
2906 case UTT_HasTrivialDestructor:
2907 case UTT_HasVirtualDestructor:
2908 // Arrays of unknown bound are expressly allowed.
2909 QualType ElTy = ArgTy;
2910 if (ArgTy->isIncompleteArrayType())
2911 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
2912
2913 // The void type is expressly allowed.
2914 if (ElTy->isVoidType())
2915 return true;
2916
2917 return !S.RequireCompleteType(
2918 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00002919 }
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +00002920 llvm_unreachable("Type trait not handled by switch");
Chandler Carruth8e172c62011-05-01 06:51:22 +00002921}
2922
2923static bool EvaluateUnaryTypeTrait(Sema &Self, UnaryTypeTrait UTT,
2924 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00002925 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00002926
Sebastian Redl8eb06f12010-09-13 20:56:31 +00002927 ASTContext &C = Self.Context;
2928 switch(UTT) {
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002929 // Type trait expressions corresponding to the primary type category
2930 // predicates in C++0x [meta.unary.cat].
2931 case UTT_IsVoid:
2932 return T->isVoidType();
2933 case UTT_IsIntegral:
2934 return T->isIntegralType(C);
2935 case UTT_IsFloatingPoint:
2936 return T->isFloatingType();
2937 case UTT_IsArray:
2938 return T->isArrayType();
2939 case UTT_IsPointer:
2940 return T->isPointerType();
2941 case UTT_IsLvalueReference:
2942 return T->isLValueReferenceType();
2943 case UTT_IsRvalueReference:
2944 return T->isRValueReferenceType();
2945 case UTT_IsMemberFunctionPointer:
2946 return T->isMemberFunctionPointerType();
2947 case UTT_IsMemberObjectPointer:
2948 return T->isMemberDataPointerType();
2949 case UTT_IsEnum:
2950 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00002951 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00002952 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002953 case UTT_IsClass:
Chandler Carruthaf858862011-05-01 09:29:58 +00002954 return T->isClassType() || T->isStructureType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002955 case UTT_IsFunction:
2956 return T->isFunctionType();
2957
2958 // Type trait expressions which correspond to the convenient composition
2959 // predicates in C++0x [meta.unary.comp].
2960 case UTT_IsReference:
2961 return T->isReferenceType();
2962 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00002963 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002964 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00002965 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002966 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00002967 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002968 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00002969 // Note: semantic analysis depends on Objective-C lifetime types to be
2970 // considered scalar types. However, such types do not actually behave
2971 // like scalar types at run time (since they may require retain/release
2972 // operations), so we report them as non-scalar.
2973 if (T->isObjCLifetimeType()) {
2974 switch (T.getObjCLifetime()) {
2975 case Qualifiers::OCL_None:
2976 case Qualifiers::OCL_ExplicitNone:
2977 return true;
2978
2979 case Qualifiers::OCL_Strong:
2980 case Qualifiers::OCL_Weak:
2981 case Qualifiers::OCL_Autoreleasing:
2982 return false;
2983 }
2984 }
2985
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00002986 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002987 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00002988 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00002989 case UTT_IsMemberPointer:
2990 return T->isMemberPointerType();
2991
2992 // Type trait expressions which correspond to the type property predicates
2993 // in C++0x [meta.unary.prop].
2994 case UTT_IsConst:
2995 return T.isConstQualified();
2996 case UTT_IsVolatile:
2997 return T.isVolatileQualified();
2998 case UTT_IsTrivial:
John McCall31168b02011-06-15 23:02:42 +00002999 return T.isTrivialType(Self.Context);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003000 case UTT_IsTriviallyCopyable:
John McCall31168b02011-06-15 23:02:42 +00003001 return T.isTriviallyCopyableType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003002 case UTT_IsStandardLayout:
3003 return T->isStandardLayoutType();
3004 case UTT_IsPOD:
Benjamin Kramera3c0dad2012-04-28 10:00:33 +00003005 return T.isPODType(Self.Context);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003006 case UTT_IsLiteral:
3007 return T->isLiteralType();
3008 case UTT_IsEmpty:
3009 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3010 return !RD->isUnion() && RD->isEmpty();
3011 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003012 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003013 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3014 return RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003015 return false;
3016 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003017 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3018 return RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003019 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00003020 case UTT_IsFinal:
3021 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3022 return RD->hasAttr<FinalAttr>();
3023 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00003024 case UTT_IsSigned:
3025 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00003026 case UTT_IsUnsigned:
3027 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003028
3029 // Type trait expressions which query classes regarding their construction,
3030 // destruction, and copying. Rather than being based directly on the
3031 // related type predicates in the standard, they are specified by both
3032 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3033 // specifications.
3034 //
3035 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3036 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Alexis Huntf479f1b2011-05-09 18:22:59 +00003037 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003038 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3039 // If __is_pod (type) is true then the trait is true, else if type is
3040 // a cv class or union type (or array thereof) with a trivial default
3041 // constructor ([class.ctor]) then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003042 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003043 return true;
3044 if (const RecordType *RT =
3045 C.getBaseElementType(T)->getAs<RecordType>())
Alexis Huntf479f1b2011-05-09 18:22:59 +00003046 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003047 return false;
3048 case UTT_HasTrivialCopy:
3049 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3050 // If __is_pod (type) is true or type is a reference type then
3051 // the trait is true, else if type is a cv class or union type
3052 // with a trivial copy constructor ([class.copy]) then the trait
3053 // is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003054 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003055 return true;
3056 if (const RecordType *RT = T->getAs<RecordType>())
3057 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyConstructor();
3058 return false;
3059 case UTT_HasTrivialAssign:
3060 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3061 // If type is const qualified or is a reference type then the
3062 // trait is false. Otherwise if __is_pod (type) is true then the
3063 // trait is true, else if type is a cv class or union type with
3064 // a trivial copy assignment ([class.copy]) then the trait is
3065 // true, else it is false.
3066 // Note: the const and reference restrictions are interesting,
3067 // given that const and reference members don't prevent a class
3068 // from having a trivial copy assignment operator (but do cause
3069 // errors if the copy assignment operator is actually used, q.v.
3070 // [class.copy]p12).
3071
3072 if (C.getBaseElementType(T).isConstQualified())
3073 return false;
John McCall31168b02011-06-15 23:02:42 +00003074 if (T.isPODType(Self.Context))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003075 return true;
3076 if (const RecordType *RT = T->getAs<RecordType>())
3077 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialCopyAssignment();
3078 return false;
3079 case UTT_HasTrivialDestructor:
3080 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3081 // If __is_pod (type) is true or type is a reference type
3082 // then the trait is true, else if type is a cv class or union
3083 // type (or array thereof) with a trivial destructor
3084 // ([class.dtor]) then the trait is true, else it is
3085 // false.
John McCall31168b02011-06-15 23:02:42 +00003086 if (T.isPODType(Self.Context) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003087 return true;
John McCall31168b02011-06-15 23:02:42 +00003088
3089 // Objective-C++ ARC: autorelease types don't require destruction.
3090 if (T->isObjCLifetimeType() &&
3091 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3092 return true;
3093
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003094 if (const RecordType *RT =
3095 C.getBaseElementType(T)->getAs<RecordType>())
3096 return cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor();
3097 return false;
3098 // TODO: Propagate nothrowness for implicitly declared special members.
3099 case UTT_HasNothrowAssign:
3100 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3101 // If type is const qualified or is a reference type then the
3102 // trait is false. Otherwise if __has_trivial_assign (type)
3103 // is true then the trait is true, else if type is a cv class
3104 // or union type with copy assignment operators that are known
3105 // not to throw an exception then the trait is true, else it is
3106 // false.
3107 if (C.getBaseElementType(T).isConstQualified())
3108 return false;
3109 if (T->isReferenceType())
3110 return false;
John McCall31168b02011-06-15 23:02:42 +00003111 if (T.isPODType(Self.Context) || T->isObjCLifetimeType())
3112 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003113 if (const RecordType *RT = T->getAs<RecordType>()) {
3114 CXXRecordDecl* RD = cast<CXXRecordDecl>(RT->getDecl());
3115 if (RD->hasTrivialCopyAssignment())
3116 return true;
3117
3118 bool FoundAssign = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003119 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(OO_Equal);
Sebastian Redl058fc822010-09-14 23:40:14 +00003120 LookupResult Res(Self, DeclarationNameInfo(Name, KeyLoc),
3121 Sema::LookupOrdinaryName);
3122 if (Self.LookupQualifiedName(Res, RD)) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00003123 Res.suppressDiagnostics();
Sebastian Redl058fc822010-09-14 23:40:14 +00003124 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3125 Op != OpEnd; ++Op) {
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00003126 if (isa<FunctionTemplateDecl>(*Op))
3127 continue;
3128
Sebastian Redl058fc822010-09-14 23:40:14 +00003129 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3130 if (Operator->isCopyAssignmentOperator()) {
3131 FoundAssign = true;
3132 const FunctionProtoType *CPT
3133 = Operator->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003134 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3135 if (!CPT)
3136 return false;
Richard Smith938f40b2011-06-11 17:19:42 +00003137 if (CPT->getExceptionSpecType() == EST_Delayed)
3138 return false;
3139 if (!CPT->isNothrow(Self.Context))
3140 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003141 }
3142 }
3143 }
Douglas Gregor6a0e23f2011-10-12 15:40:49 +00003144
Richard Smith938f40b2011-06-11 17:19:42 +00003145 return FoundAssign;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003146 }
3147 return false;
3148 case UTT_HasNothrowCopy:
3149 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3150 // If __has_trivial_copy (type) is true then the trait is true, else
3151 // if type is a cv class or union type with copy constructors that are
3152 // known not to throw an exception then the trait is true, else it is
3153 // false.
John McCall31168b02011-06-15 23:02:42 +00003154 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003155 return true;
3156 if (const RecordType *RT = T->getAs<RecordType>()) {
3157 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3158 if (RD->hasTrivialCopyConstructor())
3159 return true;
3160
3161 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003162 unsigned FoundTQs;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003163 DeclContext::lookup_const_iterator Con, ConEnd;
Sebastian Redl951006f2010-09-13 21:10:20 +00003164 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003165 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003166 // A template constructor is never a copy constructor.
3167 // FIXME: However, it may actually be selected at the actual overload
3168 // resolution point.
3169 if (isa<FunctionTemplateDecl>(*Con))
3170 continue;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003171 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3172 if (Constructor->isCopyConstructor(FoundTQs)) {
3173 FoundConstructor = true;
3174 const FunctionProtoType *CPT
3175 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003176 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3177 if (!CPT)
3178 return false;
Richard Smith938f40b2011-06-11 17:19:42 +00003179 if (CPT->getExceptionSpecType() == EST_Delayed)
3180 return false;
Sebastian Redlfa453cf2011-03-12 11:50:43 +00003181 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00003182 // For now, we'll be conservative and assume that they can throw.
Richard Smith938f40b2011-06-11 17:19:42 +00003183 if (!CPT->isNothrow(Self.Context) || CPT->getNumArgs() > 1)
3184 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003185 }
3186 }
3187
Richard Smith938f40b2011-06-11 17:19:42 +00003188 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003189 }
3190 return false;
3191 case UTT_HasNothrowConstructor:
3192 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3193 // If __has_trivial_constructor (type) is true then the trait is
3194 // true, else if type is a cv class or union type (or array
3195 // thereof) with a default constructor that is known not to
3196 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00003197 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003198 return true;
3199 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>()) {
3200 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Alexis Huntf479f1b2011-05-09 18:22:59 +00003201 if (RD->hasTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003202 return true;
3203
Sebastian Redlc15c3262010-09-13 22:02:47 +00003204 DeclContext::lookup_const_iterator Con, ConEnd;
3205 for (llvm::tie(Con, ConEnd) = Self.LookupConstructors(RD);
3206 Con != ConEnd; ++Con) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00003207 // FIXME: In C++0x, a constructor template can be a default constructor.
3208 if (isa<FunctionTemplateDecl>(*Con))
3209 continue;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003210 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*Con);
3211 if (Constructor->isDefaultConstructor()) {
3212 const FunctionProtoType *CPT
3213 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00003214 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3215 if (!CPT)
3216 return false;
Richard Smith938f40b2011-06-11 17:19:42 +00003217 if (CPT->getExceptionSpecType() == EST_Delayed)
3218 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003219 // TODO: check whether evaluating default arguments can throw.
3220 // For now, we'll be conservative and assume that they can throw.
Sebastian Redl31ad7542011-03-13 17:09:40 +00003221 return CPT->isNothrow(Self.Context) && CPT->getNumArgs() == 0;
Sebastian Redlc15c3262010-09-13 22:02:47 +00003222 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003223 }
3224 }
3225 return false;
3226 case UTT_HasVirtualDestructor:
3227 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3228 // If type is a class type with a virtual destructor ([class.dtor])
3229 // then the trait is true, else it is false.
3230 if (const RecordType *Record = T->getAs<RecordType>()) {
3231 CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
Sebastian Redl058fc822010-09-14 23:40:14 +00003232 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003233 return Destructor->isVirtual();
3234 }
3235 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003236
3237 // These type trait expressions are modeled on the specifications for the
3238 // Embarcadero C++0x type trait functions:
3239 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
3240 case UTT_IsCompleteType:
3241 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
3242 // Returns True if and only if T is a complete type at the point of the
3243 // function call.
3244 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003245 }
Chandler Carruthb42fb192011-05-01 07:44:17 +00003246 llvm_unreachable("Type trait not covered by switch");
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003247}
3248
3249ExprResult Sema::BuildUnaryTypeTrait(UnaryTypeTrait UTT,
Douglas Gregor54e5b132010-09-09 16:14:44 +00003250 SourceLocation KWLoc,
3251 TypeSourceInfo *TSInfo,
3252 SourceLocation RParen) {
3253 QualType T = TSInfo->getType();
Chandler Carruthb0776202011-04-30 10:07:32 +00003254 if (!CheckUnaryTypeTraitTypeCompleteness(*this, UTT, KWLoc, T))
3255 return ExprError();
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003256
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003257 bool Value = false;
3258 if (!T->isDependentType())
Chandler Carruth8e172c62011-05-01 06:51:22 +00003259 Value = EvaluateUnaryTypeTrait(*this, UTT, KWLoc, T);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003260
3261 return Owned(new (Context) UnaryTypeTraitExpr(KWLoc, UTT, TSInfo, Value,
Anders Carlsson1f9648d2009-07-07 19:06:02 +00003262 RParen, Context.BoolTy));
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003263}
Sebastian Redl5822f082009-02-07 20:10:22 +00003264
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003265ExprResult Sema::ActOnBinaryTypeTrait(BinaryTypeTrait BTT,
3266 SourceLocation KWLoc,
3267 ParsedType LhsTy,
3268 ParsedType RhsTy,
3269 SourceLocation RParen) {
3270 TypeSourceInfo *LhsTSInfo;
3271 QualType LhsT = GetTypeFromParser(LhsTy, &LhsTSInfo);
3272 if (!LhsTSInfo)
3273 LhsTSInfo = Context.getTrivialTypeSourceInfo(LhsT);
3274
3275 TypeSourceInfo *RhsTSInfo;
3276 QualType RhsT = GetTypeFromParser(RhsTy, &RhsTSInfo);
3277 if (!RhsTSInfo)
3278 RhsTSInfo = Context.getTrivialTypeSourceInfo(RhsT);
3279
3280 return BuildBinaryTypeTrait(BTT, KWLoc, LhsTSInfo, RhsTSInfo, RParen);
3281}
3282
Douglas Gregor29c42f22012-02-24 07:38:34 +00003283static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
3284 ArrayRef<TypeSourceInfo *> Args,
3285 SourceLocation RParenLoc) {
3286 switch (Kind) {
3287 case clang::TT_IsTriviallyConstructible: {
3288 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003289 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00003290 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00003291 // is_constructible<T, Args...>::value is true and the variable
3292 // definition for is_constructible, as defined below, is known to call no
3293 // operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00003294 //
3295 // The predicate condition for a template specialization
3296 // is_constructible<T, Args...> shall be satisfied if and only if the
3297 // following variable definition would be well-formed for some invented
3298 // variable t:
3299 //
3300 // T t(create<Args>()...);
3301 if (Args.empty()) {
3302 S.Diag(KWLoc, diag::err_type_trait_arity)
3303 << 1 << 1 << 1 << (int)Args.size();
3304 return false;
3305 }
3306
3307 bool SawVoid = false;
3308 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3309 if (Args[I]->getType()->isVoidType()) {
3310 SawVoid = true;
3311 continue;
3312 }
3313
3314 if (!Args[I]->getType()->isIncompleteType() &&
3315 S.RequireCompleteType(KWLoc, Args[I]->getType(),
3316 diag::err_incomplete_type_used_in_type_trait_expr))
3317 return false;
3318 }
3319
3320 // If any argument was 'void', of course it won't type-check.
3321 if (SawVoid)
3322 return false;
3323
3324 llvm::SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
3325 llvm::SmallVector<Expr *, 2> ArgExprs;
3326 ArgExprs.reserve(Args.size() - 1);
3327 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
3328 QualType T = Args[I]->getType();
3329 if (T->isObjectType() || T->isFunctionType())
3330 T = S.Context.getRValueReferenceType(T);
3331 OpaqueArgExprs.push_back(
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003332 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
Douglas Gregor29c42f22012-02-24 07:38:34 +00003333 T.getNonLValueExprType(S.Context),
3334 Expr::getValueKindForType(T)));
3335 ArgExprs.push_back(&OpaqueArgExprs.back());
3336 }
3337
3338 // Perform the initialization in an unevaluated context within a SFINAE
3339 // trap at translation unit scope.
3340 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
3341 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
3342 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
3343 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
3344 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
3345 RParenLoc));
3346 InitializationSequence Init(S, To, InitKind,
3347 ArgExprs.begin(), ArgExprs.size());
3348 if (Init.Failed())
3349 return false;
3350
3351 ExprResult Result = Init.Perform(S, To, InitKind,
3352 MultiExprArg(ArgExprs.data(),
3353 ArgExprs.size()));
3354 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3355 return false;
3356
3357 // The initialization succeeded; not make sure there are no non-trivial
3358 // calls.
3359 return !Result.get()->hasNonTrivialCall(S.Context);
3360 }
3361 }
3362
3363 return false;
3364}
3365
3366ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3367 ArrayRef<TypeSourceInfo *> Args,
3368 SourceLocation RParenLoc) {
3369 bool Dependent = false;
3370 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3371 if (Args[I]->getType()->isDependentType()) {
3372 Dependent = true;
3373 break;
3374 }
3375 }
3376
3377 bool Value = false;
3378 if (!Dependent)
3379 Value = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
3380
3381 return TypeTraitExpr::Create(Context, Context.BoolTy, KWLoc, Kind,
3382 Args, RParenLoc, Value);
3383}
3384
3385ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
3386 ArrayRef<ParsedType> Args,
3387 SourceLocation RParenLoc) {
3388 llvm::SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
3389 ConvertedArgs.reserve(Args.size());
3390
3391 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
3392 TypeSourceInfo *TInfo;
3393 QualType T = GetTypeFromParser(Args[I], &TInfo);
3394 if (!TInfo)
3395 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
3396
3397 ConvertedArgs.push_back(TInfo);
3398 }
3399
3400 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
3401}
3402
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003403static bool EvaluateBinaryTypeTrait(Sema &Self, BinaryTypeTrait BTT,
3404 QualType LhsT, QualType RhsT,
3405 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003406 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
3407 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003408
3409 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00003410 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003411 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00003412 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003413 // Base and Derived are not unions and name the same class type without
3414 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003415
John McCall388ef532011-01-28 22:02:36 +00003416 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
3417 if (!lhsRecord) return false;
3418
3419 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
3420 if (!rhsRecord) return false;
3421
3422 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
3423 == (lhsRecord == rhsRecord));
3424
3425 if (lhsRecord == rhsRecord)
3426 return !lhsRecord->getDecl()->isUnion();
3427
3428 // C++0x [meta.rel]p2:
3429 // If Base and Derived are class types and are different types
3430 // (ignoring possible cv-qualifiers) then Derived shall be a
3431 // complete type.
3432 if (Self.RequireCompleteType(KeyLoc, RhsT,
3433 diag::err_incomplete_type_used_in_type_trait_expr))
3434 return false;
3435
3436 return cast<CXXRecordDecl>(rhsRecord->getDecl())
3437 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
3438 }
John Wiegley65497cc2011-04-27 23:09:49 +00003439 case BTT_IsSame:
3440 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00003441 case BTT_TypeCompatible:
3442 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
3443 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00003444 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00003445 case BTT_IsConvertibleTo: {
3446 // C++0x [meta.rel]p4:
3447 // Given the following function prototype:
3448 //
3449 // template <class T>
3450 // typename add_rvalue_reference<T>::type create();
3451 //
3452 // the predicate condition for a template specialization
3453 // is_convertible<From, To> shall be satisfied if and only if
3454 // the return expression in the following code would be
3455 // well-formed, including any implicit conversions to the return
3456 // type of the function:
3457 //
3458 // To test() {
3459 // return create<From>();
3460 // }
3461 //
3462 // Access checking is performed as if in a context unrelated to To and
3463 // From. Only the validity of the immediate context of the expression
3464 // of the return-statement (including conversions to the return type)
3465 // is considered.
3466 //
3467 // We model the initialization as a copy-initialization of a temporary
3468 // of the appropriate type, which for this expression is identical to the
3469 // return statement (since NRVO doesn't apply).
3470 if (LhsT->isObjectType() || LhsT->isFunctionType())
3471 LhsT = Self.Context.getRValueReferenceType(LhsT);
3472
3473 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00003474 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00003475 Expr::getValueKindForType(LhsT));
3476 Expr *FromPtr = &From;
3477 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
3478 SourceLocation()));
3479
Eli Friedmana59b1902012-01-25 01:05:57 +00003480 // Perform the initialization in an unevaluated context within a SFINAE
3481 // trap at translation unit scope.
3482 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00003483 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3484 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Douglas Gregor8006e762011-01-27 20:28:01 +00003485 InitializationSequence Init(Self, To, Kind, &FromPtr, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003486 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00003487 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00003488
Douglas Gregor8006e762011-01-27 20:28:01 +00003489 ExprResult Result = Init.Perform(Self, To, Kind, MultiExprArg(&FromPtr, 1));
3490 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
3491 }
Douglas Gregor1be329d2012-02-23 07:33:15 +00003492
3493 case BTT_IsTriviallyAssignable: {
3494 // C++11 [meta.unary.prop]p3:
3495 // is_trivially_assignable is defined as:
3496 // is_assignable<T, U>::value is true and the assignment, as defined by
3497 // is_assignable, is known to call no operation that is not trivial
3498 //
3499 // is_assignable is defined as:
3500 // The expression declval<T>() = declval<U>() is well-formed when
3501 // treated as an unevaluated operand (Clause 5).
3502 //
3503 // For both, T and U shall be complete types, (possibly cv-qualified)
3504 // void, or arrays of unknown bound.
3505 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
3506 Self.RequireCompleteType(KeyLoc, LhsT,
3507 diag::err_incomplete_type_used_in_type_trait_expr))
3508 return false;
3509 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
3510 Self.RequireCompleteType(KeyLoc, RhsT,
3511 diag::err_incomplete_type_used_in_type_trait_expr))
3512 return false;
3513
3514 // cv void is never assignable.
3515 if (LhsT->isVoidType() || RhsT->isVoidType())
3516 return false;
3517
3518 // Build expressions that emulate the effect of declval<T>() and
3519 // declval<U>().
3520 if (LhsT->isObjectType() || LhsT->isFunctionType())
3521 LhsT = Self.Context.getRValueReferenceType(LhsT);
3522 if (RhsT->isObjectType() || RhsT->isFunctionType())
3523 RhsT = Self.Context.getRValueReferenceType(RhsT);
3524 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
3525 Expr::getValueKindForType(LhsT));
3526 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
3527 Expr::getValueKindForType(RhsT));
3528
3529 // Attempt the assignment in an unevaluated context within a SFINAE
3530 // trap at translation unit scope.
3531 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
3532 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
3533 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
3534 ExprResult Result = Self.BuildBinOp(/*S=*/0, KeyLoc, BO_Assign, &Lhs, &Rhs);
3535 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
3536 return false;
3537
3538 return !Result.get()->hasNonTrivialCall(Self.Context);
3539 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003540 }
3541 llvm_unreachable("Unknown type trait or not implemented");
3542}
3543
3544ExprResult Sema::BuildBinaryTypeTrait(BinaryTypeTrait BTT,
3545 SourceLocation KWLoc,
3546 TypeSourceInfo *LhsTSInfo,
3547 TypeSourceInfo *RhsTSInfo,
3548 SourceLocation RParen) {
3549 QualType LhsT = LhsTSInfo->getType();
3550 QualType RhsT = RhsTSInfo->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
John McCall388ef532011-01-28 22:02:36 +00003552 if (BTT == BTT_TypeCompatible) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00003553 if (getLangOpts().CPlusPlus) {
Francois Pichet34b21132010-12-08 22:35:30 +00003554 Diag(KWLoc, diag::err_types_compatible_p_in_cplusplus)
3555 << SourceRange(KWLoc, RParen);
3556 return ExprError();
3557 }
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003558 }
3559
3560 bool Value = false;
3561 if (!LhsT->isDependentType() && !RhsT->isDependentType())
3562 Value = EvaluateBinaryTypeTrait(*this, BTT, LhsT, RhsT, KWLoc);
3563
Francois Pichet34b21132010-12-08 22:35:30 +00003564 // Select trait result type.
3565 QualType ResultType;
3566 switch (BTT) {
Francois Pichet34b21132010-12-08 22:35:30 +00003567 case BTT_IsBaseOf: ResultType = Context.BoolTy; break;
John Wiegley65497cc2011-04-27 23:09:49 +00003568 case BTT_IsConvertible: ResultType = Context.BoolTy; break;
3569 case BTT_IsSame: ResultType = Context.BoolTy; break;
Francois Pichet34b21132010-12-08 22:35:30 +00003570 case BTT_TypeCompatible: ResultType = Context.IntTy; break;
Douglas Gregor8006e762011-01-27 20:28:01 +00003571 case BTT_IsConvertibleTo: ResultType = Context.BoolTy; break;
Douglas Gregor1be329d2012-02-23 07:33:15 +00003572 case BTT_IsTriviallyAssignable: ResultType = Context.BoolTy;
Francois Pichet34b21132010-12-08 22:35:30 +00003573 }
3574
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003575 return Owned(new (Context) BinaryTypeTraitExpr(KWLoc, BTT, LhsTSInfo,
3576 RhsTSInfo, Value, RParen,
Francois Pichet34b21132010-12-08 22:35:30 +00003577 ResultType));
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003578}
3579
John Wiegley6242b6a2011-04-28 00:16:57 +00003580ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
3581 SourceLocation KWLoc,
3582 ParsedType Ty,
3583 Expr* DimExpr,
3584 SourceLocation RParen) {
3585 TypeSourceInfo *TSInfo;
3586 QualType T = GetTypeFromParser(Ty, &TSInfo);
3587 if (!TSInfo)
3588 TSInfo = Context.getTrivialTypeSourceInfo(T);
3589
3590 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
3591}
3592
3593static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
3594 QualType T, Expr *DimExpr,
3595 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003596 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00003597
3598 switch(ATT) {
3599 case ATT_ArrayRank:
3600 if (T->isArrayType()) {
3601 unsigned Dim = 0;
3602 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3603 ++Dim;
3604 T = AT->getElementType();
3605 }
3606 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00003607 }
John Wiegleyd3522222011-04-28 02:06:46 +00003608 return 0;
3609
John Wiegley6242b6a2011-04-28 00:16:57 +00003610 case ATT_ArrayExtent: {
3611 llvm::APSInt Value;
3612 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00003613 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
3614 Self.PDiag(diag::err_dimension_expr_not_constant_integer),
3615 false).isInvalid())
3616 return 0;
3617 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00003618 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
3619 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00003620 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00003621 }
Richard Smithf4c51d92012-02-04 09:53:13 +00003622 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00003623
3624 if (T->isArrayType()) {
3625 unsigned D = 0;
3626 bool Matched = false;
3627 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
3628 if (Dim == D) {
3629 Matched = true;
3630 break;
3631 }
3632 ++D;
3633 T = AT->getElementType();
3634 }
3635
John Wiegleyd3522222011-04-28 02:06:46 +00003636 if (Matched && T->isArrayType()) {
3637 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
3638 return CAT->getSize().getLimitedValue();
3639 }
John Wiegley6242b6a2011-04-28 00:16:57 +00003640 }
John Wiegleyd3522222011-04-28 02:06:46 +00003641 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00003642 }
3643 }
3644 llvm_unreachable("Unknown type trait or not implemented");
3645}
3646
3647ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
3648 SourceLocation KWLoc,
3649 TypeSourceInfo *TSInfo,
3650 Expr* DimExpr,
3651 SourceLocation RParen) {
3652 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00003653
Chandler Carruthc5276e52011-05-01 08:48:21 +00003654 // FIXME: This should likely be tracked as an APInt to remove any host
3655 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003656 uint64_t Value = 0;
3657 if (!T->isDependentType())
3658 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
3659
Chandler Carruthc5276e52011-05-01 08:48:21 +00003660 // While the specification for these traits from the Embarcadero C++
3661 // compiler's documentation says the return type is 'unsigned int', Clang
3662 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
3663 // compiler, there is no difference. On several other platforms this is an
3664 // important distinction.
John Wiegley6242b6a2011-04-28 00:16:57 +00003665 return Owned(new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value,
Chandler Carruth9cf632c2011-05-01 07:49:26 +00003666 DimExpr, RParen,
Chandler Carruthc5276e52011-05-01 08:48:21 +00003667 Context.getSizeType()));
John Wiegley6242b6a2011-04-28 00:16:57 +00003668}
3669
John Wiegleyf9f65842011-04-25 06:54:41 +00003670ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003671 SourceLocation KWLoc,
3672 Expr *Queried,
3673 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003674 // If error parsing the expression, ignore.
3675 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003676 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00003677
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003678 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00003679
3680 return move(Result);
3681}
3682
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003683static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
3684 switch (ET) {
3685 case ET_IsLValueExpr: return E->isLValue();
3686 case ET_IsRValueExpr: return E->isRValue();
3687 }
3688 llvm_unreachable("Expression trait not covered by switch");
3689}
3690
John Wiegleyf9f65842011-04-25 06:54:41 +00003691ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003692 SourceLocation KWLoc,
3693 Expr *Queried,
3694 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00003695 if (Queried->isTypeDependent()) {
3696 // Delay type-checking for type-dependent expressions.
3697 } else if (Queried->getType()->isPlaceholderType()) {
3698 ExprResult PE = CheckPlaceholderExpr(Queried);
3699 if (PE.isInvalid()) return ExprError();
3700 return BuildExpressionTrait(ET, KWLoc, PE.take(), RParen);
3701 }
3702
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003703 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00003704
Chandler Carruth20b9bc82011-05-01 07:44:20 +00003705 return Owned(new (Context) ExpressionTraitExpr(KWLoc, ET, Queried, Value,
3706 RParen, Context.BoolTy));
John Wiegleyf9f65842011-04-25 06:54:41 +00003707}
3708
Richard Trieu82402a02011-09-15 21:56:47 +00003709QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00003710 ExprValueKind &VK,
3711 SourceLocation Loc,
3712 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003713 assert(!LHS.get()->getType()->isPlaceholderType() &&
3714 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00003715 "placeholders should have been weeded out by now");
3716
3717 // The LHS undergoes lvalue conversions if this is ->*.
3718 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003719 LHS = DefaultLvalueConversion(LHS.take());
3720 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003721 }
3722
3723 // The RHS always undergoes lvalue conversions.
Richard Trieu82402a02011-09-15 21:56:47 +00003724 RHS = DefaultLvalueConversion(RHS.take());
3725 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00003726
Sebastian Redl5822f082009-02-07 20:10:22 +00003727 const char *OpSpelling = isIndirect ? "->*" : ".*";
3728 // C++ 5.5p2
3729 // The binary operator .* [p3: ->*] binds its second operand, which shall
3730 // be of type "pointer to member of T" (where T is a completely-defined
3731 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00003732 QualType RHSType = RHS.get()->getType();
3733 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00003734 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00003735 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003736 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00003737 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00003738 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00003739
Sebastian Redl5822f082009-02-07 20:10:22 +00003740 QualType Class(MemPtr->getClass(), 0);
3741
Douglas Gregord07ba342010-10-13 20:41:14 +00003742 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
3743 // member pointer points must be completely-defined. However, there is no
3744 // reason for this semantic distinction, and the rule is not enforced by
3745 // other compilers. Therefore, we do not check this property, as it is
3746 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00003747
Sebastian Redl5822f082009-02-07 20:10:22 +00003748 // C++ 5.5p2
3749 // [...] to its first operand, which shall be of class T or of a class of
3750 // which T is an unambiguous and accessible base class. [p3: a pointer to
3751 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00003752 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003753 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00003754 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
3755 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003756 else {
3757 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00003758 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00003759 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00003760 return QualType();
3761 }
3762 }
3763
Richard Trieu82402a02011-09-15 21:56:47 +00003764 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003765 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003766 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
3767 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00003768 return QualType();
3769 }
Anders Carlssona70cff62010-04-24 19:06:50 +00003770 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00003771 /*DetectVirtual=*/false);
Mike Stump87c57ac2009-05-16 07:39:55 +00003772 // FIXME: Would it be useful to print full ambiguity paths, or is that
3773 // overkill?
Richard Trieu82402a02011-09-15 21:56:47 +00003774 if (!IsDerivedFrom(LHSType, Class, Paths) ||
Sebastian Redl5822f082009-02-07 20:10:22 +00003775 Paths.isAmbiguous(Context.getCanonicalType(Class))) {
3776 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00003777 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00003778 return QualType();
3779 }
Eli Friedman1fcf66b2010-01-16 00:00:48 +00003780 // Cast LHS to type of use.
3781 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003782 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003783
John McCallcf142162010-08-07 06:22:56 +00003784 CXXCastPath BasePath;
Anders Carlssona70cff62010-04-24 19:06:50 +00003785 BuildBasePathArray(Paths, BasePath);
Richard Trieu82402a02011-09-15 21:56:47 +00003786 LHS = ImpCastExprToType(LHS.take(), UseType, CK_DerivedToBase, VK,
3787 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00003788 }
3789
Richard Trieu82402a02011-09-15 21:56:47 +00003790 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00003791 // Diagnose use of pointer-to-member type which when used as
3792 // the functional cast in a pointer-to-member expression.
3793 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
3794 return QualType();
3795 }
John McCall7decc9e2010-11-18 06:31:45 +00003796
Sebastian Redl5822f082009-02-07 20:10:22 +00003797 // C++ 5.5p2
3798 // The result is an object or a function of the type specified by the
3799 // second operand.
3800 // The cv qualifiers are the union of those in the pointer and the left side,
3801 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00003802 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00003803 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00003804
Douglas Gregor1d042092011-01-26 16:40:18 +00003805 // C++0x [expr.mptr.oper]p6:
3806 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003807 // ill-formed if the second operand is a pointer to member function with
3808 // ref-qualifier &. In a ->* expression or in a .* expression whose object
3809 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00003810 // is a pointer to member function with ref-qualifier &&.
3811 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
3812 switch (Proto->getRefQualifier()) {
3813 case RQ_None:
3814 // Do nothing
3815 break;
3816
3817 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003818 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003819 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003820 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003821 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003822
Douglas Gregor1d042092011-01-26 16:40:18 +00003823 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00003824 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00003825 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00003826 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00003827 break;
3828 }
3829 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003830
John McCall7decc9e2010-11-18 06:31:45 +00003831 // C++ [expr.mptr.oper]p6:
3832 // The result of a .* expression whose second operand is a pointer
3833 // to a data member is of the same value category as its
3834 // first operand. The result of a .* expression whose second
3835 // operand is a pointer to a member function is a prvalue. The
3836 // result of an ->* expression is an lvalue if its second operand
3837 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00003838 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00003839 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00003840 return Context.BoundMemberTy;
3841 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00003842 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00003843 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00003844 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00003845 }
John McCall7decc9e2010-11-18 06:31:45 +00003846
Sebastian Redl5822f082009-02-07 20:10:22 +00003847 return Result;
3848}
Sebastian Redl1a99f442009-04-16 17:51:27 +00003849
Sebastian Redl1a99f442009-04-16 17:51:27 +00003850/// \brief Try to convert a type to another according to C++0x 5.16p3.
3851///
3852/// This is part of the parameter validation for the ? operator. If either
3853/// value operand is a class type, the two operands are attempted to be
3854/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003855/// It returns true if the program is ill-formed and has already been diagnosed
3856/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003857static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
3858 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00003859 bool &HaveConversion,
3860 QualType &ToType) {
3861 HaveConversion = false;
3862 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863
3864 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00003865 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00003866 // C++0x 5.16p3
3867 // The process for determining whether an operand expression E1 of type T1
3868 // can be converted to match an operand expression E2 of type T2 is defined
3869 // as follows:
3870 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00003871 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00003872 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003873 // E1 can be converted to match E2 if E1 can be implicitly converted to
3874 // type "lvalue reference to T2", subject to the constraint that in the
3875 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00003876 QualType T = Self.Context.getLValueReferenceType(ToType);
3877 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003878
Douglas Gregor838fcc32010-03-26 20:14:36 +00003879 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
3880 if (InitSeq.isDirectReferenceBinding()) {
3881 ToType = T;
3882 HaveConversion = true;
3883 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003884 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003885
Douglas Gregor838fcc32010-03-26 20:14:36 +00003886 if (InitSeq.isAmbiguous())
3887 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003888 }
John McCall65eb8792010-02-25 01:37:24 +00003889
Sebastian Redl1a99f442009-04-16 17:51:27 +00003890 // -- If E2 is an rvalue, or if the conversion above cannot be done:
3891 // -- if E1 and E2 have class type, and the underlying class types are
3892 // the same or one is a base class of the other:
3893 QualType FTy = From->getType();
3894 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003895 const RecordType *FRec = FTy->getAs<RecordType>();
3896 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003898 Self.IsDerivedFrom(FTy, TTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003899 if (FRec && TRec &&
Douglas Gregor838fcc32010-03-26 20:14:36 +00003900 (FRec == TRec || FDerivedFromT || Self.IsDerivedFrom(TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003901 // E1 can be converted to match E2 if the class of T2 is the
3902 // same type as, or a base class of, the class of T1, and
3903 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00003904 if (FRec == TRec || FDerivedFromT) {
3905 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003906 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3907 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003908 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00003909 HaveConversion = true;
3910 return false;
3911 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003912
Douglas Gregor838fcc32010-03-26 20:14:36 +00003913 if (InitSeq.isAmbiguous())
3914 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003916 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917
Douglas Gregor838fcc32010-03-26 20:14:36 +00003918 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003920
Douglas Gregor838fcc32010-03-26 20:14:36 +00003921 // -- Otherwise: E1 can be converted to match E2 if E1 can be
3922 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00003924 // an rvalue).
3925 //
3926 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
3927 // to the array-to-pointer or function-to-pointer conversions.
3928 if (!TTy->getAs<TagType>())
3929 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930
Douglas Gregor838fcc32010-03-26 20:14:36 +00003931 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
3932 InitializationSequence InitSeq(Self, Entity, Kind, &From, 1);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00003933 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00003934 ToType = TTy;
3935 if (InitSeq.isAmbiguous())
3936 return InitSeq.Diagnose(Self, Entity, Kind, &From, 1);
3937
Sebastian Redl1a99f442009-04-16 17:51:27 +00003938 return false;
3939}
3940
3941/// \brief Try to find a common type for two according to C++0x 5.16p5.
3942///
3943/// This is part of the parameter validation for the ? operator. If either
3944/// value operand is a class type, overload resolution is used to find a
3945/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00003946static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003947 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00003948 Expr *Args[2] = { LHS.get(), RHS.get() };
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003949 OverloadCandidateSet CandidateSet(QuestionLoc);
3950 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, 2,
3951 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003952
3953 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003954 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00003955 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003956 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00003957 ExprResult LHSRes =
3958 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
3959 Best->Conversions[0], Sema::AA_Converting);
3960 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00003961 break;
John Wiegley01296292011-04-08 18:41:53 +00003962 LHS = move(LHSRes);
3963
3964 ExprResult RHSRes =
3965 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
3966 Best->Conversions[1], Sema::AA_Converting);
3967 if (RHSRes.isInvalid())
3968 break;
3969 RHS = move(RHSRes);
Chandler Carruth30141632011-02-25 19:41:05 +00003970 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00003971 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003972 return false;
John Wiegley01296292011-04-08 18:41:53 +00003973 }
3974
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003975 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003976
3977 // Emit a better diagnostic if one of the expressions is a null pointer
3978 // constant and the other is a pointer type. In this case, the user most
3979 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00003980 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003981 return true;
3982
3983 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00003984 << LHS.get()->getType() << RHS.get()->getType()
3985 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00003986 return true;
3987
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003988 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00003989 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00003990 << LHS.get()->getType() << RHS.get()->getType()
3991 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00003992 // FIXME: Print the possible common types by printing the return types of
3993 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003994 break;
3995
Douglas Gregor3e1e5272009-12-09 23:02:17 +00003996 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00003997 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003998 }
3999 return true;
4000}
4001
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004002/// \brief Perform an "extended" implicit conversion as returned by
4003/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00004004static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004005 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00004006 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004007 SourceLocation());
John Wiegley01296292011-04-08 18:41:53 +00004008 Expr *Arg = E.take();
4009 InitializationSequence InitSeq(Self, Entity, Kind, &Arg, 1);
4010 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, MultiExprArg(&Arg, 1));
Douglas Gregor838fcc32010-03-26 20:14:36 +00004011 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004012 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004013
John Wiegley01296292011-04-08 18:41:53 +00004014 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004015 return false;
4016}
4017
Sebastian Redl1a99f442009-04-16 17:51:27 +00004018/// \brief Check the operands of ?: under C++ semantics.
4019///
4020/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4021/// extension. In this case, LHS == Cond. (But they're not aliases.)
John Wiegley01296292011-04-08 18:41:53 +00004022QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS,
John McCallc07a0c72011-02-17 10:25:35 +00004023 ExprValueKind &VK, ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00004024 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00004025 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4026 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004027
4028 // C++0x 5.16p1
4029 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00004030 if (!Cond.get()->isTypeDependent()) {
4031 ExprResult CondRes = CheckCXXBooleanCondition(Cond.take());
4032 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004033 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004034 Cond = move(CondRes);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004035 }
4036
John McCall7decc9e2010-11-18 06:31:45 +00004037 // Assume r-value.
4038 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004039 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00004040
Sebastian Redl1a99f442009-04-16 17:51:27 +00004041 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00004042 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004043 return Context.DependentTy;
4044
4045 // C++0x 5.16p2
4046 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00004047 QualType LTy = LHS.get()->getType();
4048 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004049 bool LVoid = LTy->isVoidType();
4050 bool RVoid = RTy->isVoidType();
4051 if (LVoid || RVoid) {
4052 // ... then the [l2r] conversions are performed on the second and third
4053 // operands ...
John Wiegley01296292011-04-08 18:41:53 +00004054 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4055 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4056 if (LHS.isInvalid() || RHS.isInvalid())
4057 return QualType();
4058 LTy = LHS.get()->getType();
4059 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004060
4061 // ... and one of the following shall hold:
4062 // -- The second or the third operand (but not both) is a throw-
4063 // expression; the result is of the type of the other and is an rvalue.
John Wiegley01296292011-04-08 18:41:53 +00004064 bool LThrow = isa<CXXThrowExpr>(LHS.get());
4065 bool RThrow = isa<CXXThrowExpr>(RHS.get());
Sebastian Redl1a99f442009-04-16 17:51:27 +00004066 if (LThrow && !RThrow)
4067 return RTy;
4068 if (RThrow && !LThrow)
4069 return LTy;
4070
4071 // -- Both the second and third operands have type void; the result is of
4072 // type void and is an rvalue.
4073 if (LVoid && RVoid)
4074 return Context.VoidTy;
4075
4076 // Neither holds, error.
4077 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4078 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00004079 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004080 return QualType();
4081 }
4082
4083 // Neither is void.
4084
4085 // C++0x 5.16p3
4086 // Otherwise, if the second and third operand have different types, and
4087 // either has (cv) class type, and attempt is made to convert each of those
4088 // operands to the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004089 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00004090 (LTy->isRecordType() || RTy->isRecordType())) {
4091 ImplicitConversionSequence ICSLeftToRight, ICSRightToLeft;
4092 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004093 QualType L2RType, R2LType;
4094 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00004095 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004096 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004097 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00004098 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099
Sebastian Redl1a99f442009-04-16 17:51:27 +00004100 // If both can be converted, [...] the program is ill-formed.
4101 if (HaveL2R && HaveR2L) {
4102 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00004103 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004104 return QualType();
4105 }
4106
4107 // If exactly one conversion is possible, that conversion is applied to
4108 // the chosen operand and the converted operands are used in place of the
4109 // original operands for the remainder of this section.
4110 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00004111 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004112 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004113 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004114 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00004115 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004116 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00004117 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004118 }
4119 }
4120
4121 // C++0x 5.16p4
John McCall7decc9e2010-11-18 06:31:45 +00004122 // If the second and third operands are glvalues of the same value
4123 // category and have the same type, the result is of that type and
4124 // value category and it is a bit-field if the second or the third
4125 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00004126 // We only extend this to bitfields, not to the crazy other kinds of
4127 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00004128 bool Same = Context.hasSameType(LTy, RTy);
John McCall7decc9e2010-11-18 06:31:45 +00004129 if (Same &&
John Wiegley01296292011-04-08 18:41:53 +00004130 LHS.get()->isGLValue() &&
4131 LHS.get()->getValueKind() == RHS.get()->getValueKind() &&
4132 LHS.get()->isOrdinaryOrBitFieldObject() &&
4133 RHS.get()->isOrdinaryOrBitFieldObject()) {
4134 VK = LHS.get()->getValueKind();
4135 if (LHS.get()->getObjectKind() == OK_BitField ||
4136 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00004137 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00004138 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00004139 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004140
4141 // C++0x 5.16p5
4142 // Otherwise, the result is an rvalue. If the second and third operands
4143 // do not have the same type, and either has (cv) class type, ...
4144 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
4145 // ... overload resolution is used to determine the conversions (if any)
4146 // to be applied to the operands. If the overload resolution fails, the
4147 // program is ill-formed.
4148 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
4149 return QualType();
4150 }
4151
4152 // C++0x 5.16p6
4153 // LValue-to-rvalue, array-to-pointer, and function-to-pointer standard
4154 // conversions are performed on the second and third operands.
John Wiegley01296292011-04-08 18:41:53 +00004155 LHS = DefaultFunctionArrayLvalueConversion(LHS.take());
4156 RHS = DefaultFunctionArrayLvalueConversion(RHS.take());
4157 if (LHS.isInvalid() || RHS.isInvalid())
4158 return QualType();
4159 LTy = LHS.get()->getType();
4160 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004161
4162 // After those conversions, one of the following shall hold:
4163 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004164 // is of that type. If the operands have class type, the result
4165 // is a prvalue temporary of the result type, which is
4166 // copy-initialized from either the second operand or the third
4167 // operand depending on the value of the first operand.
4168 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
4169 if (LTy->isRecordType()) {
4170 // The operands have class type. Make a temporary copy.
4171 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172 ExprResult LHSCopy = PerformCopyInitialization(Entity,
4173 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004174 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004175 if (LHSCopy.isInvalid())
4176 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004177
4178 ExprResult RHSCopy = PerformCopyInitialization(Entity,
4179 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00004180 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004181 if (RHSCopy.isInvalid())
4182 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004183
John Wiegley01296292011-04-08 18:41:53 +00004184 LHS = LHSCopy;
4185 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004186 }
4187
Sebastian Redl1a99f442009-04-16 17:51:27 +00004188 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00004189 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004190
Douglas Gregor46188682010-05-18 22:42:18 +00004191 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192 if (LTy->isVectorType() || RTy->isVectorType())
Eli Friedman1408bc92011-06-23 18:10:35 +00004193 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00004194
Sebastian Redl1a99f442009-04-16 17:51:27 +00004195 // -- The second and third operands have arithmetic or enumeration type;
4196 // the usual arithmetic conversions are performed to bring them to a
4197 // common type, and the result is of that type.
4198 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
4199 UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00004200 if (LHS.isInvalid() || RHS.isInvalid())
4201 return QualType();
4202 return LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004203 }
4204
4205 // -- The second and third operands have pointer type, or one has pointer
4206 // type and the other is a null pointer constant; pointer conversions
4207 // and qualification conversions are performed to bring them to their
4208 // composite pointer type. The result is of the composite pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00004209 // -- The second and third operands have pointer to member type, or one has
4210 // pointer to member type and the other is a null pointer constant;
4211 // pointer to member conversions and qualification conversions are
4212 // performed to bring them to a common type, whose cv-qualification
4213 // shall match the cv-qualification of either the second or the third
4214 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004215 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00004216 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004217 isSFINAEContext()? 0 : &NonStandardCompositeType);
4218 if (!Composite.isNull()) {
4219 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004221 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
4222 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00004223 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004225 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004226 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227
Douglas Gregor697a3912010-04-01 22:47:07 +00004228 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00004229 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
4230 if (!Composite.isNull())
4231 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004232
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004233 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00004234 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00004235 return QualType();
4236
Sebastian Redl1a99f442009-04-16 17:51:27 +00004237 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004238 << LHS.get()->getType() << RHS.get()->getType()
4239 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004240 return QualType();
4241}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004242
4243/// \brief Find a merged pointer type and convert the two expressions to it.
4244///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004245/// This finds the composite pointer type (or member pointer type) for @p E1
4246/// and @p E2 according to C++0x 5.9p2. It converts both expressions to this
4247/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004248/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004249///
Douglas Gregor19175ff2010-04-16 23:20:25 +00004250/// \param Loc The location of the operator requiring these two expressions to
4251/// be converted to the composite pointer type.
4252///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004253/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
4254/// a non-standard (but still sane) composite type to which both expressions
4255/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
4256/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004257QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00004258 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004259 bool *NonStandardCompositeType) {
4260 if (NonStandardCompositeType)
4261 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
David Blaikiebbafb8a2012-03-11 07:00:24 +00004263 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004264 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004265
Fariborz Jahanian33e148f2009-12-08 20:04:24 +00004266 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
4267 !T2->isAnyPointerType() && !T2->isMemberPointerType())
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004268 return QualType();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004269
4270 // C++0x 5.9p2
4271 // Pointer conversions and qualification conversions are performed on
4272 // pointer operands to bring them to their composite pointer type. If
4273 // one operand is a null pointer constant, the composite pointer type is
4274 // the type of the other operand.
Douglas Gregor56751b52009-09-25 04:25:58 +00004275 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004276 if (T2->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00004277 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004278 else
John Wiegley01296292011-04-08 18:41:53 +00004279 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004280 return T2;
4281 }
Douglas Gregor56751b52009-09-25 04:25:58 +00004282 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00004283 if (T1->isMemberPointerType())
John Wiegley01296292011-04-08 18:41:53 +00004284 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).take();
Eli Friedman06ed2a52009-10-20 08:27:19 +00004285 else
John Wiegley01296292011-04-08 18:41:53 +00004286 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).take();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004287 return T1;
4288 }
Mike Stump11289f42009-09-09 15:08:12 +00004289
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004290 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00004291 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
4292 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004293 return QualType();
4294
4295 // Otherwise, of one of the operands has type "pointer to cv1 void," then
4296 // the other has type "pointer to cv2 T" and the composite pointer type is
4297 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
4298 // Otherwise, the composite pointer type is a pointer type similar to the
4299 // type of one of the operands, with a cv-qualification signature that is
4300 // the union of the cv-qualification signatures of the operand types.
4301 // In practice, the first part here is redundant; it's subsumed by the second.
4302 // What we do here is, we build the two possible composite types, and try the
4303 // conversions in both directions. If only one works, or if the two composite
4304 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00004305 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004306 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00004307 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004308 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00004309 ContainingClassVector;
4310 ContainingClassVector MemberOfClass;
4311 QualType Composite1 = Context.getCanonicalType(T1),
4312 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004314 do {
4315 const PointerType *Ptr1, *Ptr2;
4316 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
4317 (Ptr2 = Composite2->getAs<PointerType>())) {
4318 Composite1 = Ptr1->getPointeeType();
4319 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004321 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004323 if (NonStandardCompositeType &&
4324 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4325 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004327 QualifierUnion.push_back(
4328 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4329 MemberOfClass.push_back(std::make_pair((const Type *)0, (const Type *)0));
4330 continue;
4331 }
Mike Stump11289f42009-09-09 15:08:12 +00004332
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004333 const MemberPointerType *MemPtr1, *MemPtr2;
4334 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
4335 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
4336 Composite1 = MemPtr1->getPointeeType();
4337 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004339 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004341 if (NonStandardCompositeType &&
4342 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
4343 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004345 QualifierUnion.push_back(
4346 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
4347 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
4348 MemPtr2->getClass()));
4349 continue;
4350 }
Mike Stump11289f42009-09-09 15:08:12 +00004351
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004352 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00004353
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004354 // Cannot unwrap any more types.
4355 break;
4356 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00004357
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004358 if (NeedConstBefore && NonStandardCompositeType) {
4359 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00004361 // requirements of C++ [conv.qual]p4 bullet 3.
4362 for (unsigned I = 0; I != NeedConstBefore; ++I) {
4363 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
4364 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
4365 *NonStandardCompositeType = true;
4366 }
4367 }
4368 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004369
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004370 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00004371 ContainingClassVector::reverse_iterator MOC
4372 = MemberOfClass.rbegin();
4373 for (QualifierVector::reverse_iterator
4374 I = QualifierUnion.rbegin(),
4375 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004376 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00004377 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004378 if (MOC->first && MOC->second) {
4379 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004380 Composite1 = Context.getMemberPointerType(
4381 Context.getQualifiedType(Composite1, Quals),
4382 MOC->first);
4383 Composite2 = Context.getMemberPointerType(
4384 Context.getQualifiedType(Composite2, Quals),
4385 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004386 } else {
4387 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00004388 Composite1
4389 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
4390 Composite2
4391 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00004392 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004393 }
4394
Douglas Gregor19175ff2010-04-16 23:20:25 +00004395 // Try to convert to the first composite pointer type.
4396 InitializedEntity Entity1
4397 = InitializedEntity::InitializeTemporary(Composite1);
4398 InitializationKind Kind
4399 = InitializationKind::CreateCopy(Loc, SourceLocation());
4400 InitializationSequence E1ToC1(*this, Entity1, Kind, &E1, 1);
4401 InitializationSequence E2ToC1(*this, Entity1, Kind, &E2, 1);
Mike Stump11289f42009-09-09 15:08:12 +00004402
Douglas Gregor19175ff2010-04-16 23:20:25 +00004403 if (E1ToC1 && E2ToC1) {
4404 // Conversion to Composite1 is viable.
4405 if (!Context.hasSameType(Composite1, Composite2)) {
4406 // Composite2 is a different type from Composite1. Check whether
4407 // Composite2 is also viable.
4408 InitializedEntity Entity2
4409 = InitializedEntity::InitializeTemporary(Composite2);
4410 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4411 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4412 if (E1ToC2 && E2ToC2) {
4413 // Both Composite1 and Composite2 are viable and are different;
4414 // this is an ambiguity.
4415 return QualType();
4416 }
4417 }
4418
4419 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004420 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004421 = E1ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E1,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004422 if (E1Result.isInvalid())
4423 return QualType();
4424 E1 = E1Result.takeAs<Expr>();
4425
4426 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00004427 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004428 = E2ToC1.Perform(*this, Entity1, Kind, MultiExprArg(*this,&E2,1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004429 if (E2Result.isInvalid())
4430 return QualType();
4431 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432
Douglas Gregor19175ff2010-04-16 23:20:25 +00004433 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004434 }
4435
Douglas Gregor19175ff2010-04-16 23:20:25 +00004436 // Check whether Composite2 is viable.
4437 InitializedEntity Entity2
4438 = InitializedEntity::InitializeTemporary(Composite2);
4439 InitializationSequence E1ToC2(*this, Entity2, Kind, &E1, 1);
4440 InitializationSequence E2ToC2(*this, Entity2, Kind, &E2, 1);
4441 if (!E1ToC2 || !E2ToC2)
4442 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Douglas Gregor19175ff2010-04-16 23:20:25 +00004444 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004445 ExprResult E1Result
John McCall37ad5512010-08-23 06:44:23 +00004446 = E1ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E1, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004447 if (E1Result.isInvalid())
4448 return QualType();
4449 E1 = E1Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004450
Douglas Gregor19175ff2010-04-16 23:20:25 +00004451 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00004452 ExprResult E2Result
John McCall37ad5512010-08-23 06:44:23 +00004453 = E2ToC2.Perform(*this, Entity2, Kind, MultiExprArg(*this, &E2, 1));
Douglas Gregor19175ff2010-04-16 23:20:25 +00004454 if (E2Result.isInvalid())
4455 return QualType();
4456 E2 = E2Result.takeAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004457
Douglas Gregor19175ff2010-04-16 23:20:25 +00004458 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00004459}
Anders Carlsson85a307d2009-05-17 18:41:29 +00004460
John McCalldadc5752010-08-24 06:29:42 +00004461ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00004462 if (!E)
4463 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004464
John McCall31168b02011-06-15 23:02:42 +00004465 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
4466
4467 // If the result is a glvalue, we shouldn't bind it.
4468 if (!E->isRValue())
Anders Carlssonf86a8d12009-08-15 23:41:35 +00004469 return Owned(E);
Mike Stump11289f42009-09-09 15:08:12 +00004470
John McCall31168b02011-06-15 23:02:42 +00004471 // In ARC, calls that return a retainable type can return retained,
4472 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004473 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00004474 E->getType()->isObjCRetainableType()) {
4475
4476 bool ReturnsRetained;
4477
4478 // For actual calls, we compute this by examining the type of the
4479 // called value.
4480 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
4481 Expr *Callee = Call->getCallee()->IgnoreParens();
4482 QualType T = Callee->getType();
4483
4484 if (T == Context.BoundMemberTy) {
4485 // Handle pointer-to-members.
4486 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
4487 T = BinOp->getRHS()->getType();
4488 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
4489 T = Mem->getMemberDecl()->getType();
4490 }
4491
4492 if (const PointerType *Ptr = T->getAs<PointerType>())
4493 T = Ptr->getPointeeType();
4494 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
4495 T = Ptr->getPointeeType();
4496 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
4497 T = MemPtr->getPointeeType();
4498
4499 const FunctionType *FTy = T->getAs<FunctionType>();
4500 assert(FTy && "call to value not of function type?");
4501 ReturnsRetained = FTy->getExtInfo().getProducesResult();
4502
4503 // ActOnStmtExpr arranges things so that StmtExprs of retainable
4504 // type always produce a +1 object.
4505 } else if (isa<StmtExpr>(E)) {
4506 ReturnsRetained = true;
4507
Ted Kremeneke65b0862012-03-06 20:05:56 +00004508 // We hit this case with the lambda conversion-to-block optimization;
4509 // we don't want any extra casts here.
4510 } else if (isa<CastExpr>(E) &&
4511 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
4512 return Owned(E);
4513
John McCall31168b02011-06-15 23:02:42 +00004514 // For message sends and property references, we try to find an
4515 // actual method. FIXME: we should infer retention by selector in
4516 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00004517 } else {
4518 ObjCMethodDecl *D = 0;
4519 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
4520 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00004521 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
4522 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00004523 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
4524 D = ArrayLit->getArrayWithObjectsMethod();
4525 } else if (ObjCDictionaryLiteral *DictLit
4526 = dyn_cast<ObjCDictionaryLiteral>(E)) {
4527 D = DictLit->getDictWithObjectsMethod();
4528 }
John McCall31168b02011-06-15 23:02:42 +00004529
4530 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00004531
4532 // Don't do reclaims on performSelector calls; despite their
4533 // return type, the invoked method doesn't necessarily actually
4534 // return an object.
4535 if (!ReturnsRetained &&
4536 D && D->getMethodFamily() == OMF_performSelector)
4537 return Owned(E);
John McCall31168b02011-06-15 23:02:42 +00004538 }
4539
John McCall16de4d22011-11-14 19:53:16 +00004540 // Don't reclaim an object of Class type.
4541 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
4542 return Owned(E);
4543
John McCall4db5c3c2011-07-07 06:58:02 +00004544 ExprNeedsCleanups = true;
4545
John McCall2d637d22011-09-10 06:18:15 +00004546 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
4547 : CK_ARCReclaimReturnedObject);
John McCall4db5c3c2011-07-07 06:58:02 +00004548 return Owned(ImplicitCastExpr::Create(Context, E->getType(), ck, E, 0,
4549 VK_RValue));
John McCall31168b02011-06-15 23:02:42 +00004550 }
4551
David Blaikiebbafb8a2012-03-11 07:00:24 +00004552 if (!getLangOpts().CPlusPlus)
John McCall31168b02011-06-15 23:02:42 +00004553 return Owned(E);
Douglas Gregor363b1512009-12-24 18:51:59 +00004554
Peter Collingbournec331a1e2012-01-26 03:33:51 +00004555 // Search for the base element type (cf. ASTContext::getBaseElementType) with
4556 // a fast path for the common case that the type is directly a RecordType.
4557 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
4558 const RecordType *RT = 0;
4559 while (!RT) {
4560 switch (T->getTypeClass()) {
4561 case Type::Record:
4562 RT = cast<RecordType>(T);
4563 break;
4564 case Type::ConstantArray:
4565 case Type::IncompleteArray:
4566 case Type::VariableArray:
4567 case Type::DependentSizedArray:
4568 T = cast<ArrayType>(T)->getElementType().getTypePtr();
4569 break;
4570 default:
4571 return Owned(E);
4572 }
4573 }
Mike Stump11289f42009-09-09 15:08:12 +00004574
Richard Smithfd555f62012-02-22 02:04:18 +00004575 // That should be enough to guarantee that this type is complete, if we're
4576 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00004577 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00004578 if (RD->isInvalidDecl() || RD->isDependentContext())
John McCall67da35c2010-02-04 22:26:26 +00004579 return Owned(E);
Richard Smithfd555f62012-02-22 02:04:18 +00004580
4581 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
4582 CXXDestructorDecl *Destructor = IsDecltype ? 0 : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00004583
John McCall31168b02011-06-15 23:02:42 +00004584 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00004585 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00004586 CheckDestructorAccess(E->getExprLoc(), Destructor,
4587 PDiag(diag::err_access_dtor_temp)
4588 << E->getType());
Richard Smitheec915d62012-02-18 04:13:32 +00004589 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
John McCall31168b02011-06-15 23:02:42 +00004590
Richard Smithfd555f62012-02-22 02:04:18 +00004591 // If destructor is trivial, we can avoid the extra copy.
4592 if (Destructor->isTrivial())
4593 return Owned(E);
Richard Smitheec915d62012-02-18 04:13:32 +00004594
John McCall28fc7092011-11-10 05:35:25 +00004595 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00004596 ExprNeedsCleanups = true;
Richard Smithfd555f62012-02-22 02:04:18 +00004597 }
Richard Smitheec915d62012-02-18 04:13:32 +00004598
4599 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00004600 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
4601
4602 if (IsDecltype)
4603 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
4604
4605 return Owned(Bind);
Anders Carlsson2d4cada2009-05-30 20:36:53 +00004606}
4607
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004608ExprResult
John McCall5d413782010-12-06 08:20:24 +00004609Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004610 if (SubExpr.isInvalid())
4611 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612
John McCall5d413782010-12-06 08:20:24 +00004613 return Owned(MaybeCreateExprWithCleanups(SubExpr.take()));
Douglas Gregorb6ea6082009-12-22 22:17:25 +00004614}
4615
John McCall28fc7092011-11-10 05:35:25 +00004616Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
4617 assert(SubExpr && "sub expression can't be null!");
4618
Eli Friedman3bda6b12012-02-02 23:15:15 +00004619 CleanupVarDeclMarking();
4620
John McCall28fc7092011-11-10 05:35:25 +00004621 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
4622 assert(ExprCleanupObjects.size() >= FirstCleanup);
4623 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
4624 if (!ExprNeedsCleanups)
4625 return SubExpr;
4626
4627 ArrayRef<ExprWithCleanups::CleanupObject> Cleanups
4628 = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
4629 ExprCleanupObjects.size() - FirstCleanup);
4630
4631 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
4632 DiscardCleanupsInEvaluationContext();
4633
4634 return E;
4635}
4636
John McCall5d413782010-12-06 08:20:24 +00004637Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004638 assert(SubStmt && "sub statement can't be null!");
4639
Eli Friedman3bda6b12012-02-02 23:15:15 +00004640 CleanupVarDeclMarking();
4641
John McCall31168b02011-06-15 23:02:42 +00004642 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004643 return SubStmt;
4644
4645 // FIXME: In order to attach the temporaries, wrap the statement into
4646 // a StmtExpr; currently this is only used for asm statements.
4647 // This is hacky, either create a new CXXStmtWithTemporaries statement or
4648 // a new AsmStmtWithTemporaries.
4649 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, &SubStmt, 1,
4650 SourceLocation(),
4651 SourceLocation());
4652 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
4653 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00004654 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00004655}
4656
Richard Smithfd555f62012-02-22 02:04:18 +00004657/// Process the expression contained within a decltype. For such expressions,
4658/// certain semantic checks on temporaries are delayed until this point, and
4659/// are omitted for the 'topmost' call in the decltype expression. If the
4660/// topmost call bound a temporary, strip that temporary off the expression.
4661ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
4662 ExpressionEvaluationContextRecord &Rec = ExprEvalContexts.back();
4663 assert(Rec.IsDecltype && "not in a decltype expression");
4664
4665 // C++11 [expr.call]p11:
4666 // If a function call is a prvalue of object type,
4667 // -- if the function call is either
4668 // -- the operand of a decltype-specifier, or
4669 // -- the right operand of a comma operator that is the operand of a
4670 // decltype-specifier,
4671 // a temporary object is not introduced for the prvalue.
4672
4673 // Recursively rebuild ParenExprs and comma expressions to strip out the
4674 // outermost CXXBindTemporaryExpr, if any.
4675 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
4676 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
4677 if (SubExpr.isInvalid())
4678 return ExprError();
4679 if (SubExpr.get() == PE->getSubExpr())
4680 return Owned(E);
4681 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.take());
4682 }
4683 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
4684 if (BO->getOpcode() == BO_Comma) {
4685 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
4686 if (RHS.isInvalid())
4687 return ExprError();
4688 if (RHS.get() == BO->getRHS())
4689 return Owned(E);
4690 return Owned(new (Context) BinaryOperator(BO->getLHS(), RHS.take(),
4691 BO_Comma, BO->getType(),
4692 BO->getValueKind(),
4693 BO->getObjectKind(),
4694 BO->getOperatorLoc()));
4695 }
4696 }
4697
4698 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
4699 if (TopBind)
4700 E = TopBind->getSubExpr();
4701
4702 // Disable the special decltype handling now.
4703 Rec.IsDecltype = false;
4704
4705 // Perform the semantic checks we delayed until this point.
4706 CallExpr *TopCall = dyn_cast<CallExpr>(E);
4707 for (unsigned I = 0, N = Rec.DelayedDecltypeCalls.size(); I != N; ++I) {
4708 CallExpr *Call = Rec.DelayedDecltypeCalls[I];
4709 if (Call == TopCall)
4710 continue;
4711
4712 if (CheckCallReturnType(Call->getCallReturnType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004713 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00004714 Call, Call->getDirectCallee()))
4715 return ExprError();
4716 }
4717
4718 // Now all relevant types are complete, check the destructors are accessible
4719 // and non-deleted, and annotate them on the temporaries.
4720 for (unsigned I = 0, N = Rec.DelayedDecltypeBinds.size(); I != N; ++I) {
4721 CXXBindTemporaryExpr *Bind = Rec.DelayedDecltypeBinds[I];
4722 if (Bind == TopBind)
4723 continue;
4724
4725 CXXTemporary *Temp = Bind->getTemporary();
4726
4727 CXXRecordDecl *RD =
4728 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
4729 CXXDestructorDecl *Destructor = LookupDestructor(RD);
4730 Temp->setDestructor(Destructor);
4731
4732 MarkFunctionReferenced(E->getExprLoc(), Destructor);
4733 CheckDestructorAccess(E->getExprLoc(), Destructor,
4734 PDiag(diag::err_access_dtor_temp)
4735 << E->getType());
4736 DiagnoseUseOfDecl(Destructor, E->getExprLoc());
4737
4738 // We need a cleanup, but we don't need to remember the temporary.
4739 ExprNeedsCleanups = true;
4740 }
4741
4742 // Possibly strip off the top CXXBindTemporaryExpr.
4743 return Owned(E);
4744}
4745
John McCalldadc5752010-08-24 06:29:42 +00004746ExprResult
John McCallb268a282010-08-23 23:25:46 +00004747Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc,
John McCallba7bf592010-08-24 05:47:05 +00004748 tok::TokenKind OpKind, ParsedType &ObjectType,
Douglas Gregore610ada2010-02-24 18:44:31 +00004749 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004750 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00004751 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00004752 if (Result.isInvalid()) return ExprError();
4753 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00004754
John McCall526ab472011-10-25 17:37:35 +00004755 Result = CheckPlaceholderExpr(Base);
4756 if (Result.isInvalid()) return ExprError();
4757 Base = Result.take();
4758
John McCallb268a282010-08-23 23:25:46 +00004759 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004760 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004761 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00004762 // If we have a pointer to a dependent type and are using the -> operator,
4763 // the object type is the type that the pointer points to. We might still
4764 // have enough information about that type to do something useful.
4765 if (OpKind == tok::arrow)
4766 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
4767 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768
John McCallba7bf592010-08-24 05:47:05 +00004769 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00004770 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004771 return Owned(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004772 }
Mike Stump11289f42009-09-09 15:08:12 +00004773
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004774 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00004775 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004776 // returned, with the original second operand.
4777 if (OpKind == tok::arrow) {
John McCallc1538c02009-09-30 01:01:30 +00004778 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00004779 llvm::SmallPtrSet<CanQualType,8> CTypes;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004780 SmallVector<SourceLocation, 8> Locations;
John McCallbd0465b2009-09-30 01:30:54 +00004781 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004783 while (BaseType->isRecordType()) {
John McCallb268a282010-08-23 23:25:46 +00004784 Result = BuildOverloadedArrowExpr(S, Base, OpLoc);
4785 if (Result.isInvalid())
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004786 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00004787 Base = Result.get();
4788 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Anders Carlssonfbd2d492009-10-13 22:55:59 +00004789 Locations.push_back(OpCall->getDirectCallee()->getLocation());
John McCallb268a282010-08-23 23:25:46 +00004790 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00004791 CanQualType CBaseType = Context.getCanonicalType(BaseType);
John McCallbd0465b2009-09-30 01:30:54 +00004792 if (!CTypes.insert(CBaseType)) {
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004793 Diag(OpLoc, diag::err_operator_arrow_circular);
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00004794 for (unsigned i = 0; i < Locations.size(); i++)
4795 Diag(Locations[i], diag::note_declared_at);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00004796 return ExprError();
4797 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004798 }
Mike Stump11289f42009-09-09 15:08:12 +00004799
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004800 if (BaseType->isPointerType() || BaseType->isObjCObjectPointerType())
Douglas Gregore4f764f2009-11-20 19:58:21 +00004801 BaseType = BaseType->getPointeeType();
4802 }
Mike Stump11289f42009-09-09 15:08:12 +00004803
Douglas Gregorbf3a8262012-01-12 16:11:24 +00004804 // Objective-C properties allow "." access on Objective-C pointer types,
4805 // so adjust the base type to the object type itself.
4806 if (BaseType->isObjCObjectPointerType())
4807 BaseType = BaseType->getPointeeType();
4808
4809 // C++ [basic.lookup.classref]p2:
4810 // [...] If the type of the object expression is of pointer to scalar
4811 // type, the unqualified-id is looked up in the context of the complete
4812 // postfix-expression.
4813 //
4814 // This also indicates that we could be parsing a pseudo-destructor-name.
4815 // Note that Objective-C class and object types can be pseudo-destructor
4816 // expressions or normal member (ivar or property) access expressions.
4817 if (BaseType->isObjCObjectOrInterfaceType()) {
4818 MayBePseudoDestructor = true;
4819 } else if (!BaseType->isRecordType()) {
John McCallba7bf592010-08-24 05:47:05 +00004820 ObjectType = ParsedType();
Douglas Gregore610ada2010-02-24 18:44:31 +00004821 MayBePseudoDestructor = true;
John McCallb268a282010-08-23 23:25:46 +00004822 return Owned(Base);
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004823 }
Mike Stump11289f42009-09-09 15:08:12 +00004824
Douglas Gregor3024f072012-04-16 07:05:22 +00004825 // The object type must be complete (or dependent), or
4826 // C++11 [expr.prim.general]p3:
4827 // Unlike the object expression in other contexts, *this is not required to
4828 // be of complete type for purposes of class member access (5.2.5) outside
4829 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00004830 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00004831 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004832 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00004833 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004834
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004835 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004836 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00004837 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00004838 // type C (or of pointer to a class type C), the unqualified-id is looked
4839 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00004840 ObjectType = ParsedType::make(BaseType);
Mike Stump11289f42009-09-09 15:08:12 +00004841 return move(Base);
Douglas Gregorb7bfe792009-09-02 22:59:36 +00004842}
4843
John McCalldadc5752010-08-24 06:29:42 +00004844ExprResult Sema::DiagnoseDtorReference(SourceLocation NameLoc,
John McCallb268a282010-08-23 23:25:46 +00004845 Expr *MemExpr) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004846 SourceLocation ExpectedLParenLoc = PP.getLocForEndOfToken(NameLoc);
John McCallb268a282010-08-23 23:25:46 +00004847 Diag(MemExpr->getLocStart(), diag::err_dtor_expr_without_call)
4848 << isa<CXXPseudoDestructorExpr>(MemExpr)
Douglas Gregora771f462010-03-31 17:46:05 +00004849 << FixItHint::CreateInsertion(ExpectedLParenLoc, "()");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004850
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004851 return ActOnCallExpr(/*Scope*/ 0,
John McCallb268a282010-08-23 23:25:46 +00004852 MemExpr,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004853 /*LPLoc*/ ExpectedLParenLoc,
John McCallfaf5fb42010-08-26 23:41:50 +00004854 MultiExprArg(),
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004855 /*RPLoc*/ ExpectedLParenLoc);
4856}
Douglas Gregore610ada2010-02-24 18:44:31 +00004857
Eli Friedman6601b552012-01-25 04:29:24 +00004858static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00004859 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00004860 if (Base->hasPlaceholderType()) {
4861 ExprResult result = S.CheckPlaceholderExpr(Base);
4862 if (result.isInvalid()) return true;
4863 Base = result.take();
4864 }
4865 ObjectType = Base->getType();
4866
David Blaikie1d578782011-12-16 16:03:09 +00004867 // C++ [expr.pseudo]p2:
4868 // The left-hand side of the dot operator shall be of scalar type. The
4869 // left-hand side of the arrow operator shall be of pointer to scalar type.
4870 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00004871 // Note that this is rather different from the normal handling for the
4872 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00004873 if (OpKind == tok::arrow) {
4874 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
4875 ObjectType = Ptr->getPointeeType();
4876 } else if (!Base->isTypeDependent()) {
4877 // The user wrote "p->" when she probably meant "p."; fix it.
4878 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
4879 << ObjectType << true
4880 << FixItHint::CreateReplacement(OpLoc, ".");
4881 if (S.isSFINAEContext())
4882 return true;
4883
4884 OpKind = tok::period;
4885 }
4886 }
4887
4888 return false;
4889}
4890
John McCalldadc5752010-08-24 06:29:42 +00004891ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004892 SourceLocation OpLoc,
4893 tok::TokenKind OpKind,
4894 const CXXScopeSpec &SS,
4895 TypeSourceInfo *ScopeTypeInfo,
4896 SourceLocation CCLoc,
4897 SourceLocation TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004898 PseudoDestructorTypeStorage Destructed,
John McCalla2c4e722011-02-25 05:21:17 +00004899 bool HasTrailingLParen) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00004900 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004901
Eli Friedman0ce4de42012-01-25 04:35:06 +00004902 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00004903 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
4904 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004905
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004906 if (!ObjectType->isDependentType() && !ObjectType->isScalarType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00004907 if (getLangOpts().MicrosoftMode && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00004908 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Nico Weber58829272012-01-23 05:50:57 +00004909 else
4910 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
4911 << ObjectType << Base->getSourceRange();
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004912 return ExprError();
4913 }
4914
4915 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004916 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004917 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00004918 if (DestructedTypeInfo) {
4919 QualType DestructedType = DestructedTypeInfo->getType();
4920 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004921 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00004922 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
4923 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
4924 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
4925 << ObjectType << DestructedType << Base->getSourceRange()
4926 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004927
John McCall31168b02011-06-15 23:02:42 +00004928 // Recover by setting the destructed type to the object type.
4929 DestructedType = ObjectType;
4930 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00004931 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00004932 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4933 } else if (DestructedType.getObjCLifetime() !=
4934 ObjectType.getObjCLifetime()) {
4935
4936 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
4937 // Okay: just pretend that the user provided the correctly-qualified
4938 // type.
4939 } else {
4940 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
4941 << ObjectType << DestructedType << Base->getSourceRange()
4942 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
4943 }
4944
4945 // Recover by setting the destructed type to the object type.
4946 DestructedType = ObjectType;
4947 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
4948 DestructedTypeStart);
4949 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
4950 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00004951 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004953
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004954 // C++ [expr.pseudo]p2:
4955 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
4956 // form
4957 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004958 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004959 //
4960 // shall designate the same scalar type.
4961 if (ScopeTypeInfo) {
4962 QualType ScopeType = ScopeTypeInfo->getType();
4963 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00004964 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004965
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004966 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004967 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00004968 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00004969 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004970
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004971 ScopeType = QualType();
4972 ScopeTypeInfo = 0;
4973 }
4974 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004975
John McCallb268a282010-08-23 23:25:46 +00004976 Expr *Result
4977 = new (Context) CXXPseudoDestructorExpr(Context, Base,
4978 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00004979 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00004980 ScopeTypeInfo,
4981 CCLoc,
4982 TildeLoc,
4983 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004984
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00004985 if (HasTrailingLParen)
John McCallb268a282010-08-23 23:25:46 +00004986 return Owned(Result);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004987
John McCallb268a282010-08-23 23:25:46 +00004988 return DiagnoseDtorReference(Destructed.getLocation(), Result);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00004989}
4990
John McCalldadc5752010-08-24 06:29:42 +00004991ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00004992 SourceLocation OpLoc,
4993 tok::TokenKind OpKind,
4994 CXXScopeSpec &SS,
4995 UnqualifiedId &FirstTypeName,
4996 SourceLocation CCLoc,
4997 SourceLocation TildeLoc,
4998 UnqualifiedId &SecondTypeName,
4999 bool HasTrailingLParen) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005000 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5001 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5002 "Invalid first type name in pseudo-destructor");
5003 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
5004 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
5005 "Invalid second type name in pseudo-destructor");
5006
Eli Friedman0ce4de42012-01-25 04:35:06 +00005007 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005008 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5009 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00005010
5011 // Compute the object type that we should use for name lookup purposes. Only
5012 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00005013 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005014 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00005015 if (ObjectType->isRecordType())
5016 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00005017 else if (ObjectType->isDependentType())
5018 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005020
5021 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005022 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005023 QualType DestructedType;
5024 TypeSourceInfo *DestructedTypeInfo = 0;
Douglas Gregor678f90d2010-02-25 01:56:36 +00005025 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005026 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005027 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005028 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00005029 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005030 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00005031 ((SS.isSet() && !computeDeclContext(SS, false)) ||
5032 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005033 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00005034 // couldn't find anything useful in scope. Just store the identifier and
5035 // it's location, and we'll perform (qualified) name lookup again at
5036 // template instantiation time.
5037 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
5038 SecondTypeName.StartLocation);
5039 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005040 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005041 diag::err_pseudo_dtor_destructor_non_type)
5042 << SecondTypeName.Identifier << ObjectType;
5043 if (isSFINAEContext())
5044 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005045
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005046 // Recover by assuming we had the right type all along.
5047 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005048 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005049 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005050 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005051 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005052 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005053 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5054 TemplateId->getTemplateArgs(),
5055 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005056 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005057 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005058 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005059 TemplateId->TemplateNameLoc,
5060 TemplateId->LAngleLoc,
5061 TemplateArgsPtr,
5062 TemplateId->RAngleLoc);
5063 if (T.isInvalid() || !T.get()) {
5064 // Recover by assuming we had the right type all along.
5065 DestructedType = ObjectType;
5066 } else
5067 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005068 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005069
5070 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005071 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00005072 if (!DestructedType.isNull()) {
5073 if (!DestructedTypeInfo)
5074 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005075 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00005076 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005079 // Convert the name of the scope type (the type prior to '::') into a type.
5080 TypeSourceInfo *ScopeTypeInfo = 0;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005081 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005082 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005083 FirstTypeName.Identifier) {
5084 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005085 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00005086 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00005087 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005088 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005089 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005090 diag::err_pseudo_dtor_destructor_non_type)
5091 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005092
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005093 if (isSFINAEContext())
5094 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005095
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005096 // Just drop this type. It's unnecessary anyway.
5097 ScopeType = QualType();
5098 } else
5099 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005100 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005101 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005102 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005103 ASTTemplateArgsPtr TemplateArgsPtr(*this,
5104 TemplateId->getTemplateArgs(),
5105 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00005106 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00005107 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00005108 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005109 TemplateId->TemplateNameLoc,
5110 TemplateId->LAngleLoc,
5111 TemplateArgsPtr,
5112 TemplateId->RAngleLoc);
5113 if (T.isInvalid() || !T.get()) {
5114 // Recover by dropping this type.
5115 ScopeType = QualType();
5116 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005117 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00005118 }
5119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005120
Douglas Gregor90ad9222010-02-24 23:02:30 +00005121 if (!ScopeType.isNull() && !ScopeTypeInfo)
5122 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
5123 FirstTypeName.StartLocation);
5124
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125
John McCallb268a282010-08-23 23:25:46 +00005126 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00005127 ScopeTypeInfo, CCLoc, TildeLoc,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005128 Destructed, HasTrailingLParen);
Douglas Gregore610ada2010-02-24 18:44:31 +00005129}
5130
David Blaikie1d578782011-12-16 16:03:09 +00005131ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
5132 SourceLocation OpLoc,
5133 tok::TokenKind OpKind,
5134 SourceLocation TildeLoc,
5135 const DeclSpec& DS,
5136 bool HasTrailingLParen) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00005137 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005138 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5139 return ExprError();
5140
5141 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
5142
5143 TypeLocBuilder TLB;
5144 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
5145 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
5146 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
5147 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
5148
5149 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
5150 0, SourceLocation(), TildeLoc,
5151 Destructed, HasTrailingLParen);
5152}
5153
John Wiegley01296292011-04-08 18:41:53 +00005154ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00005155 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005156 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00005157 if (Method->getParent()->isLambda() &&
5158 Method->getConversionType()->isBlockPointerType()) {
5159 // This is a lambda coversion to block pointer; check if the argument
5160 // is a LambdaExpr.
5161 Expr *SubE = E;
5162 CastExpr *CE = dyn_cast<CastExpr>(SubE);
5163 if (CE && CE->getCastKind() == CK_NoOp)
5164 SubE = CE->getSubExpr();
5165 SubE = SubE->IgnoreParens();
5166 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
5167 SubE = BE->getSubExpr();
5168 if (isa<LambdaExpr>(SubE)) {
5169 // For the conversion to block pointer on a lambda expression, we
5170 // construct a special BlockLiteral instead; this doesn't really make
5171 // a difference in ARC, but outside of ARC the resulting block literal
5172 // follows the normal lifetime rules for block literals instead of being
5173 // autoreleased.
5174 DiagnosticErrorTrap Trap(Diags);
5175 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
5176 E->getExprLoc(),
5177 Method, E);
5178 if (Exp.isInvalid())
5179 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
5180 return Exp;
5181 }
5182 }
5183
5184
John Wiegley01296292011-04-08 18:41:53 +00005185 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/0,
5186 FoundDecl, Method);
5187 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00005188 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00005189
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005190 MemberExpr *ME =
John Wiegley01296292011-04-08 18:41:53 +00005191 new (Context) MemberExpr(Exp.take(), /*IsArrow=*/false, Method,
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00005192 SourceLocation(), Context.BoundMemberTy,
John McCall7decc9e2010-11-18 06:31:45 +00005193 VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005194 if (HadMultipleCandidates)
5195 ME->setHadMultipleCandidates(true);
5196
John McCall7decc9e2010-11-18 06:31:45 +00005197 QualType ResultType = Method->getResultType();
5198 ExprValueKind VK = Expr::getValueKindForType(ResultType);
5199 ResultType = ResultType.getNonLValueExprType(Context);
5200
Eli Friedmanfa0df832012-02-02 03:46:19 +00005201 MarkFunctionReferenced(Exp.get()->getLocStart(), Method);
Douglas Gregor27381f32009-11-23 12:27:39 +00005202 CXXMemberCallExpr *CE =
John McCall7decc9e2010-11-18 06:31:45 +00005203 new (Context) CXXMemberCallExpr(Context, ME, 0, 0, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00005204 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005205 return CE;
5206}
5207
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005208ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
5209 SourceLocation RParen) {
Richard Smithf623c962012-04-17 00:58:00 +00005210 CanThrowResult CanThrow = canThrow(Operand);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005211 return Owned(new (Context) CXXNoexceptExpr(Context.BoolTy, Operand,
Richard Smithf623c962012-04-17 00:58:00 +00005212 CanThrow, KeyLoc, RParen));
Sebastian Redl4202c0f2010-09-10 20:55:43 +00005213}
5214
5215ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
5216 Expr *Operand, SourceLocation RParen) {
5217 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00005218}
5219
John McCall34376a62010-12-04 03:47:34 +00005220/// Perform the conversions required for an expression used in a
5221/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00005222ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00005223 if (E->hasPlaceholderType()) {
5224 ExprResult result = CheckPlaceholderExpr(E);
5225 if (result.isInvalid()) return Owned(E);
5226 E = result.take();
5227 }
5228
John McCallfee942d2010-12-02 02:07:15 +00005229 // C99 6.3.2.1:
5230 // [Except in specific positions,] an lvalue that does not have
5231 // array type is converted to the value stored in the
5232 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00005233 if (E->isRValue()) {
5234 // In C, function designators (i.e. expressions of function type)
5235 // are r-values, but we still want to do function-to-pointer decay
5236 // on them. This is both technically correct and convenient for
5237 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005238 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00005239 return DefaultFunctionArrayConversion(E);
5240
5241 return Owned(E);
5242 }
John McCallfee942d2010-12-02 02:07:15 +00005243
John McCall34376a62010-12-04 03:47:34 +00005244 // Otherwise, this rule does not apply in C++, at least not for the moment.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005245 if (getLangOpts().CPlusPlus) return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00005246
5247 // GCC seems to also exclude expressions of incomplete enum type.
5248 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
5249 if (!T->getDecl()->isComplete()) {
5250 // FIXME: stupid workaround for a codegen bug!
John Wiegley01296292011-04-08 18:41:53 +00005251 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).take();
5252 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00005253 }
5254 }
5255
John Wiegley01296292011-04-08 18:41:53 +00005256 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
5257 if (Res.isInvalid())
5258 return Owned(E);
5259 E = Res.take();
5260
John McCallca61b652010-12-04 12:29:11 +00005261 if (!E->getType()->isVoidType())
5262 RequireCompleteType(E->getExprLoc(), E->getType(),
5263 diag::err_incomplete_type);
John Wiegley01296292011-04-08 18:41:53 +00005264 return Owned(E);
John McCall34376a62010-12-04 03:47:34 +00005265}
5266
John Wiegley01296292011-04-08 18:41:53 +00005267ExprResult Sema::ActOnFinishFullExpr(Expr *FE) {
5268 ExprResult FullExpr = Owned(FE);
5269
5270 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00005271 return ExprError();
John McCall34376a62010-12-04 03:47:34 +00005272
John Wiegley01296292011-04-08 18:41:53 +00005273 if (DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00005274 return ExprError();
5275
Douglas Gregor95715f92011-12-15 00:53:32 +00005276 // Top-level message sends default to 'id' when we're in a debugger.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005277 if (getLangOpts().DebuggerCastResultToId &&
Douglas Gregor95715f92011-12-15 00:53:32 +00005278 FullExpr.get()->getType() == Context.UnknownAnyTy &&
5279 isa<ObjCMessageExpr>(FullExpr.get())) {
5280 FullExpr = forceUnknownAnyToType(FullExpr.take(), Context.getObjCIdType());
5281 if (FullExpr.isInvalid())
5282 return ExprError();
5283 }
5284
John McCall3aef3d82011-04-10 19:13:55 +00005285 FullExpr = CheckPlaceholderExpr(FullExpr.take());
5286 if (FullExpr.isInvalid())
5287 return ExprError();
Douglas Gregor0ec210b2011-03-07 02:05:23 +00005288
John Wiegley01296292011-04-08 18:41:53 +00005289 FullExpr = IgnoredValueConversions(FullExpr.take());
5290 if (FullExpr.isInvalid())
5291 return ExprError();
5292
Richard Trieu021baa32011-09-23 20:10:00 +00005293 CheckImplicitConversions(FullExpr.get(), FullExpr.get()->getExprLoc());
John McCall5d413782010-12-06 08:20:24 +00005294 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00005295}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005296
5297StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
5298 if (!FullStmt) return StmtError();
5299
John McCall5d413782010-12-06 08:20:24 +00005300 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005301}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005302
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005303Sema::IfExistsResult
5304Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
5305 CXXScopeSpec &SS,
5306 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005307 DeclarationName TargetName = TargetNameInfo.getName();
5308 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00005309 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005310
Douglas Gregor43edb322011-10-24 22:31:10 +00005311 // If the name itself is dependent, then the result is dependent.
5312 if (TargetName.isDependentName())
5313 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005314
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005315 // Do the redeclaration lookup in the current scope.
5316 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
5317 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00005318 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005319 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00005320
5321 switch (R.getResultKind()) {
5322 case LookupResult::Found:
5323 case LookupResult::FoundOverloaded:
5324 case LookupResult::FoundUnresolvedValue:
5325 case LookupResult::Ambiguous:
5326 return IER_Exists;
5327
5328 case LookupResult::NotFound:
5329 return IER_DoesNotExist;
5330
5331 case LookupResult::NotFoundInCurrentInstantiation:
5332 return IER_Dependent;
5333 }
David Blaikie8a40f702012-01-17 06:56:22 +00005334
5335 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00005336}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005337
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00005338Sema::IfExistsResult
5339Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
5340 bool IsIfExists, CXXScopeSpec &SS,
5341 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005342 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00005343
5344 // Check for unexpanded parameter packs.
5345 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5346 collectUnexpandedParameterPacks(SS, Unexpanded);
5347 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
5348 if (!Unexpanded.empty()) {
5349 DiagnoseUnexpandedParameterPacks(KeywordLoc,
5350 IsIfExists? UPPC_IfExists
5351 : UPPC_IfNotExists,
5352 Unexpanded);
5353 return IER_Error;
5354 }
5355
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00005356 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
5357}