blob: 129969469abe8882dfd3c99743dd942e92a11e64 [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//===----------------------------------------------------------------------===//
James Dennett84053fb2012-06-22 05:14:59 +00009///
10/// \file
11/// \brief Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
Chris Lattner29375652006-12-04 18:06:35 +000014
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Kaelyn Takata6c759512014-10-27 18:07:37 +000016#include "TreeTransform.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "TypeLocBuilder.h"
Steve Naroffaac94152007-08-25 14:02:58 +000018#include "clang/AST/ASTContext.h"
Faisal Vali47d9ed42014-05-30 04:39:37 +000019#include "clang/AST/ASTLambda.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/AST/CharUnits.h"
John McCallde6836a2010-08-24 07:21:54 +000022#include "clang/AST/DeclObjC.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000023#include "clang/AST/ExprCXX.h"
Fariborz Jahanian1d446082010-06-16 18:56:04 +000024#include "clang/AST/ExprObjC.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000025#include "clang/AST/RecursiveASTVisitor.h"
Douglas Gregorb1dd23f2010-02-24 22:38:50 +000026#include "clang/AST/TypeLoc.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000027#include "clang/Basic/PartialDiagnostic.h"
Sebastian Redlfaf68082008-12-03 20:26:15 +000028#include "clang/Basic/TargetInfo.h"
Anders Carlsson029fc692009-08-26 22:59:12 +000029#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Sema/DeclSpec.h"
31#include "clang/Sema/Initialization.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/ParsedTemplate.h"
34#include "clang/Sema/Scope.h"
35#include "clang/Sema/ScopeInfo.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000036#include "clang/Sema/SemaLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/TemplateDeduction.h"
Sebastian Redlb8fc4772012-02-16 12:59:47 +000038#include "llvm/ADT/APInt.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000039#include "llvm/ADT/STLExtras.h"
Chandler Carruth8b0cf1d2011-05-01 07:23:17 +000040#include "llvm/Support/ErrorHandling.h"
Chris Lattner29375652006-12-04 18:06:35 +000041using namespace clang;
John McCall19c1bfd2010-08-25 05:32:35 +000042using namespace sema;
Chris Lattner29375652006-12-04 18:06:35 +000043
Richard Smith7447af42013-03-26 01:15:19 +000044/// \brief Handle the result of the special case name lookup for inheriting
45/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46/// constructor names in member using declarations, even if 'X' is not the
47/// name of the corresponding type.
48ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +000070 case NestedNameSpecifier::Super:
Richard Smith7447af42013-03-26 01:15:19 +000071 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80}
81
John McCallba7bf592010-08-24 05:47:05 +000082ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000083 IdentifierInfo &II,
John McCallba7bf592010-08-24 05:47:05 +000084 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
Douglas Gregorfe17d252010-02-16 19:09:40 +000088 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
Douglas Gregor46841e12010-02-23 00:15:22 +0000107 // See also PR6358 and PR6359.
Sebastian Redla771d222010-07-07 23:17:38 +0000108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000110 QualType SearchType;
Craig Topperc3ec1492014-05-26 06:22:03 +0000111 DeclContext *LookupCtx = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000112 bool isDependent = false;
113 bool LookInScope = false;
114
Richard Smith64e033f2015-01-15 00:48:52 +0000115 if (SS.isInvalid())
David Blaikieefdccaa2016-01-15 23:43:34 +0000116 return nullptr;
Richard Smith64e033f2015-01-15 00:48:52 +0000117
Douglas Gregorfe17d252010-02-16 19:09:40 +0000118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
Aaron Ballman4a979672014-01-03 13:56:08 +0000125 NestedNameSpecifier *NNS = SS.getScopeRep();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000126
Douglas Gregor46841e12010-02-23 00:15:22 +0000127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
David Majnemere37a6ce2014-05-21 20:19:59 +0000129 // C++11 [basic.lookup.qual]p6:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
Sebastian Redla771d222010-07-07 23:17:38 +0000131 // the type-names are looked up as types in the scope designated by the
David Majnemere37a6ce2014-05-21 20:19:59 +0000132 // nested-name-specifier. Similarly, in a qualified-id of the form:
NAKAMURA Takumi7c288862011-01-27 07:09:49 +0000133 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000134 // nested-name-specifier[opt] class-name :: ~ class-name
Sebastian Redla771d222010-07-07 23:17:38 +0000135 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000136 // the second class-name is looked up in the same scope as the first.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000137 //
David Majnemere37a6ce2014-05-21 20:19:59 +0000138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
Sebastian Redla771d222010-07-07 23:17:38 +0000140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000145 } else if (DC && isa<CXXRecordDecl>(DC)) {
Sebastian Redla771d222010-07-07 23:17:38 +0000146 LookAtPrefix = false;
David Majnemere37a6ce2014-05-21 20:19:59 +0000147 LookInScope = true;
148 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000149
Sebastian Redla771d222010-07-07 23:17:38 +0000150 // The second case from the C++03 rules quoted further above.
Craig Topperc3ec1492014-05-26 06:22:03 +0000151 NestedNameSpecifier *Prefix = nullptr;
Douglas Gregor46841e12010-02-23 00:15:22 +0000152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
Douglas Gregor10176412011-02-25 16:07:42 +0000156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
Douglas Gregor46841e12010-02-23 00:15:22 +0000157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
Douglas Gregor46841e12010-02-23 00:15:22 +0000159 } else if (ObjectTypePtr) {
Douglas Gregorfe17d252010-02-16 19:09:40 +0000160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
Douglas Gregor46841e12010-02-23 00:15:22 +0000164 isDependent = LookupCtx && LookupCtx->isDependentContext();
Douglas Gregorfe17d252010-02-16 19:09:40 +0000165 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000176 assert((isDependent || !SearchType->isIncompleteType()) &&
Douglas Gregorfe17d252010-02-16 19:09:40 +0000177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
Craig Topperc3ec1492014-05-26 06:22:03 +0000185 TypeDecl *NonMatchingTypeDecl = nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000189 // have one) and, if that fails to find a match, in the scope (if
Douglas Gregorfe17d252010-02-16 19:09:40 +0000190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
Douglas Gregor678f90d2010-02-25 01:56:36 +0000194 else if (Step == 1 && LookInScope && S)
Douglas Gregorfe17d252010-02-16 19:09:40 +0000195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
David Blaikieefdccaa2016-01-15 23:43:34 +0000201 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
Nico Weber83a63872014-11-12 04:33:52 +0000205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
Richard Smithc278c002014-01-22 00:30:17 +0000211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000213 }
John Wiegleyb4a9e512011-03-08 08:13:22 +0000214
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000224 // issue 399, for which there isn't even an obvious direction.
Douglas Gregorfe17d252010-02-16 19:09:40 +0000225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
John McCalle78aac42010-03-10 03:28:59 +0000230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000236
Douglas Gregorfe17d252010-02-16 19:09:40 +0000237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000251 }
252
253 continue;
254 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000255
Douglas Gregorfe17d252010-02-16 19:09:40 +0000256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
Richard Smithc278c002014-01-22 00:30:17 +0000269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000278 if (DependentTemplateName *DepTemplate
Douglas Gregorfe17d252010-02-16 19:09:40 +0000279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
Richard Smithc278c002014-01-22 00:30:17 +0000282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
Douglas Gregorfe17d252010-02-16 19:09:40 +0000285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
Douglas Gregor9cbc22b2011-02-28 22:42:13 +0000295
296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
John McCallba7bf592010-08-24 05:47:05 +0000300 return ParsedType::make(T);
Douglas Gregorfe17d252010-02-16 19:09:40 +0000301 }
302
Douglas Gregor4cf85a72011-03-04 22:32:08 +0000303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000311 << &II;
David Blaikie5e026f52013-03-20 17:42:13 +0000312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
Ted Kremenekc37877d2013-10-08 17:08:03 +0000316 const DeclContext *Ctx = S->getEntity();
David Blaikie5e026f52013-03-20 17:42:13 +0000317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
Douglas Gregorfe17d252010-02-16 19:09:40 +0000322
David Blaikieefdccaa2016-01-15 23:43:34 +0000323 return nullptr;
Douglas Gregorfe17d252010-02-16 19:09:40 +0000324}
325
David Blaikieecd8a942011-12-08 16:13:53 +0000326ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
David Blaikie08608f62011-12-12 04:13:55 +0000327 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
David Blaikieefdccaa2016-01-15 23:43:34 +0000328 return nullptr;
David Blaikieecd8a942011-12-08 16:13:53 +0000329 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
330 && "only get destructor types from declspecs");
331 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
332 QualType SearchType = GetTypeFromParser(ObjectType);
333 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
334 return ParsedType::make(T);
335 }
336
337 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
338 << T << SearchType;
David Blaikieefdccaa2016-01-15 23:43:34 +0000339 return nullptr;
David Blaikieecd8a942011-12-08 16:13:53 +0000340}
341
Richard Smithd091dc12013-12-05 00:58:33 +0000342bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
343 const UnqualifiedId &Name) {
344 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
345
346 if (!SS.isValid())
347 return false;
348
349 switch (SS.getScopeRep()->getKind()) {
350 case NestedNameSpecifier::Identifier:
351 case NestedNameSpecifier::TypeSpec:
352 case NestedNameSpecifier::TypeSpecWithTemplate:
353 // Per C++11 [over.literal]p2, literal operators can only be declared at
354 // namespace scope. Therefore, this unqualified-id cannot name anything.
355 // Reject it early, because we have no AST representation for this in the
356 // case where the scope is dependent.
357 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
358 << SS.getScopeRep();
359 return true;
360
361 case NestedNameSpecifier::Global:
Nikola Smiljanic67860242014-09-26 00:28:20 +0000362 case NestedNameSpecifier::Super:
Richard Smithd091dc12013-12-05 00:58:33 +0000363 case NestedNameSpecifier::Namespace:
364 case NestedNameSpecifier::NamespaceAlias:
365 return false;
366 }
367
368 llvm_unreachable("unknown nested name specifier kind");
369}
370
Douglas Gregor9da64192010-04-26 22:37:10 +0000371/// \brief Build a C++ typeid expression with a type operand.
John McCalldadc5752010-08-24 06:29:42 +0000372ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000373 SourceLocation TypeidLoc,
374 TypeSourceInfo *Operand,
375 SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000376 // C++ [expr.typeid]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000377 // The top-level cv-qualifiers of the lvalue expression or the type-id
Douglas Gregor9da64192010-04-26 22:37:10 +0000378 // that is the operand of typeid are always ignored.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379 // If the type of the type-id is a class type or a reference to a class
Douglas Gregor9da64192010-04-26 22:37:10 +0000380 // type, the class shall be completely-defined.
Douglas Gregor876cec22010-06-02 06:16:02 +0000381 Qualifiers Quals;
382 QualType T
383 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
384 Quals);
Douglas Gregor9da64192010-04-26 22:37:10 +0000385 if (T->getAs<RecordType>() &&
386 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
387 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000388
David Majnemer6f3150a2014-11-21 21:09:12 +0000389 if (T->isVariablyModifiedType())
390 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
391
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000392 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
393 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000394}
395
396/// \brief Build a C++ typeid expression with an expression operand.
John McCalldadc5752010-08-24 06:29:42 +0000397ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000398 SourceLocation TypeidLoc,
399 Expr *E,
400 SourceLocation RParenLoc) {
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000401 bool WasEvaluated = false;
Douglas Gregor9da64192010-04-26 22:37:10 +0000402 if (E && !E->isTypeDependent()) {
John McCall50a2c2c2011-10-11 23:14:30 +0000403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000406 E = result.get();
John McCall50a2c2c2011-10-11 23:14:30 +0000407 }
408
Douglas Gregor9da64192010-04-26 22:37:10 +0000409 QualType T = E->getType();
410 if (const RecordType *RecordT = T->getAs<RecordType>()) {
411 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
412 // C++ [expr.typeid]p3:
413 // [...] If the type of the expression is a class type, the class
414 // shall be completely-defined.
415 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
416 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor9da64192010-04-26 22:37:10 +0000418 // C++ [expr.typeid]p3:
Sebastian Redlc57d34b2010-07-20 04:20:21 +0000419 // When typeid is applied to an expression other than an glvalue of a
Douglas Gregor9da64192010-04-26 22:37:10 +0000420 // polymorphic class type [...] [the] expression is an unevaluated
421 // operand. [...]
Richard Smithef8bf432012-08-13 20:08:14 +0000422 if (RecordD->isPolymorphic() && E->isGLValue()) {
Eli Friedman456f0182012-01-20 01:26:23 +0000423 // The subexpression is potentially evaluated; switch the context
424 // and recheck the subexpression.
Benjamin Kramerd81108f2012-11-14 15:08:31 +0000425 ExprResult Result = TransformToPotentiallyEvaluated(E);
Eli Friedman456f0182012-01-20 01:26:23 +0000426 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000427 E = Result.get();
Douglas Gregor88d292c2010-05-13 16:44:06 +0000428
429 // We require a vtable to query the type at run time.
430 MarkVTableUsed(TypeidLoc, RecordD);
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000431 WasEvaluated = true;
Douglas Gregor88d292c2010-05-13 16:44:06 +0000432 }
Douglas Gregor9da64192010-04-26 22:37:10 +0000433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor9da64192010-04-26 22:37:10 +0000435 // C++ [expr.typeid]p4:
436 // [...] If the type of the type-id is a reference to a possibly
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437 // cv-qualified type, the result of the typeid expression refers to a
438 // std::type_info object representing the cv-unqualified referenced
Douglas Gregor9da64192010-04-26 22:37:10 +0000439 // type.
Douglas Gregor876cec22010-06-02 06:16:02 +0000440 Qualifiers Quals;
441 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
442 if (!Context.hasSameType(T, UnqualT)) {
443 T = UnqualT;
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000444 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
Douglas Gregor9da64192010-04-26 22:37:10 +0000445 }
446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000447
David Majnemer6f3150a2014-11-21 21:09:12 +0000448 if (E->getType()->isVariablyModifiedType())
449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
450 << E->getType());
Aaron Ballman6c93b3e2014-12-17 21:57:17 +0000451 else if (ActiveTemplateInstantiations.empty() &&
452 E->HasSideEffects(Context, WasEvaluated)) {
453 // The expression operand for typeid is in an unevaluated expression
454 // context, so side effects could result in unintended consequences.
455 Diag(E->getExprLoc(), WasEvaluated
456 ? diag::warn_side_effects_typeid
457 : diag::warn_side_effects_unevaluated_context);
458 }
David Majnemer6f3150a2014-11-21 21:09:12 +0000459
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
461 SourceRange(TypeidLoc, RParenLoc));
Douglas Gregor9da64192010-04-26 22:37:10 +0000462}
463
464/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
John McCalldadc5752010-08-24 06:29:42 +0000465ExprResult
Sebastian Redlc4704762008-11-11 11:37:55 +0000466Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
467 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
Douglas Gregor9da64192010-04-26 22:37:10 +0000468 // Find the std::type_info type.
Sebastian Redl7ac97412011-03-31 19:29:24 +0000469 if (!getStdNamespace())
Sebastian Redl6d4256c2009-03-15 17:47:39 +0000470 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
Argyrios Kyrtzidisc7148c92009-08-19 01:28:28 +0000471
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000472 if (!CXXTypeInfoDecl) {
473 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
474 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
475 LookupQualifiedName(R, getStdNamespace());
476 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
Nico Weber5f968832012-06-19 23:58:27 +0000477 // Microsoft's typeinfo doesn't have type_info in std but in the global
478 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
Alp Tokerbfa39342014-01-14 12:51:41 +0000479 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
Nico Weber5f968832012-06-19 23:58:27 +0000480 LookupQualifiedName(R, Context.getTranslationUnitDecl());
481 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
482 }
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000483 if (!CXXTypeInfoDecl)
484 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000486
Nico Weber1b7f39d2012-05-20 01:27:21 +0000487 if (!getLangOpts().RTTI) {
488 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
489 }
490
Douglas Gregor4c7c1092010-09-08 23:14:30 +0000491 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000492
Douglas Gregor9da64192010-04-26 22:37:10 +0000493 if (isType) {
494 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000495 TypeSourceInfo *TInfo = nullptr;
John McCallba7bf592010-08-24 05:47:05 +0000496 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
497 &TInfo);
Douglas Gregor9da64192010-04-26 22:37:10 +0000498 if (T.isNull())
499 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor9da64192010-04-26 22:37:10 +0000501 if (!TInfo)
502 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000503
Douglas Gregor9da64192010-04-26 22:37:10 +0000504 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
Douglas Gregor0b6a6242009-06-22 20:57:11 +0000505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 // The operand is an expression.
John McCallb268a282010-08-23 23:25:46 +0000508 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
Sebastian Redlc4704762008-11-11 11:37:55 +0000509}
510
Francois Pichet9f4f2072010-09-08 12:20:18 +0000511/// \brief Build a Microsoft __uuidof expression with a type operand.
512ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
513 SourceLocation TypeidLoc,
514 TypeSourceInfo *Operand,
515 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000516 if (!Operand->getType()->isDependentType()) {
David Majnemer59c0ec22013-09-07 06:59:46 +0000517 bool HasMultipleGUIDs = false;
518 if (!CXXUuidofExpr::GetUuidAttrOfType(Operand->getType(),
519 &HasMultipleGUIDs)) {
520 if (HasMultipleGUIDs)
521 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
522 else
523 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
524 }
Francois Pichetb7577652010-12-27 01:32:00 +0000525 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000526
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000527 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand,
528 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000529}
530
531/// \brief Build a Microsoft __uuidof expression with an expression operand.
532ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
533 SourceLocation TypeidLoc,
534 Expr *E,
535 SourceLocation RParenLoc) {
Francois Pichetb7577652010-12-27 01:32:00 +0000536 if (!E->getType()->isDependentType()) {
David Majnemer59c0ec22013-09-07 06:59:46 +0000537 bool HasMultipleGUIDs = false;
538 if (!CXXUuidofExpr::GetUuidAttrOfType(E->getType(), &HasMultipleGUIDs) &&
539 !E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
540 if (HasMultipleGUIDs)
541 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
542 else
543 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
544 }
Francois Pichetb7577652010-12-27 01:32:00 +0000545 }
David Majnemer59c0ec22013-09-07 06:59:46 +0000546
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000547 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E,
548 SourceRange(TypeidLoc, RParenLoc));
Francois Pichet9f4f2072010-09-08 12:20:18 +0000549}
550
551/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
552ExprResult
553Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
554 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000555 // If MSVCGuidDecl has not been cached, do the lookup.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000556 if (!MSVCGuidDecl) {
557 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
558 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
559 LookupQualifiedName(R, Context.getTranslationUnitDecl());
560 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
561 if (!MSVCGuidDecl)
562 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000563 }
564
Francois Pichet9f4f2072010-09-08 12:20:18 +0000565 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000566
Francois Pichet9f4f2072010-09-08 12:20:18 +0000567 if (isType) {
568 // The operand is a type; handle it as such.
Craig Topperc3ec1492014-05-26 06:22:03 +0000569 TypeSourceInfo *TInfo = nullptr;
Francois Pichet9f4f2072010-09-08 12:20:18 +0000570 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
571 &TInfo);
572 if (T.isNull())
573 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000574
Francois Pichet9f4f2072010-09-08 12:20:18 +0000575 if (!TInfo)
576 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
577
578 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
579 }
580
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000581 // The operand is an expression.
Francois Pichet9f4f2072010-09-08 12:20:18 +0000582 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
583}
584
Steve Naroff66356bd2007-09-16 14:56:35 +0000585/// ActOnCXXBoolLiteral - Parse {true,false} literals.
John McCalldadc5752010-08-24 06:29:42 +0000586ExprResult
Steve Naroff66356bd2007-09-16 14:56:35 +0000587Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
Douglas Gregor08d918a2008-10-24 15:36:09 +0000588 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
Bill Wendlingbf313b02007-02-13 20:09:46 +0000589 "Unknown C++ Boolean value!");
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000590 return new (Context)
591 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
Bill Wendling4073ed52007-02-13 01:51:42 +0000592}
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000593
Sebastian Redl576fd422009-05-10 18:38:11 +0000594/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
John McCalldadc5752010-08-24 06:29:42 +0000595ExprResult
Sebastian Redl576fd422009-05-10 18:38:11 +0000596Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000597 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
Sebastian Redl576fd422009-05-10 18:38:11 +0000598}
599
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000600/// ActOnCXXThrow - Parse throw expressions.
John McCalldadc5752010-08-24 06:29:42 +0000601ExprResult
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000602Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
603 bool IsThrownVarInScope = false;
604 if (Ex) {
605 // C++0x [class.copymove]p31:
Nico Weberb58e51c2014-11-19 05:21:39 +0000606 // When certain criteria are met, an implementation is allowed to omit the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000607 // copy/move construction of a class object [...]
608 //
David Blaikie3c8c46e2014-11-19 05:48:40 +0000609 // - in a throw-expression, when the operand is the name of a
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000610 // non-volatile automatic object (other than a function or catch-
Nico Weberb58e51c2014-11-19 05:21:39 +0000611 // clause parameter) whose scope does not extend beyond the end of the
David Blaikie3c8c46e2014-11-19 05:48:40 +0000612 // innermost enclosing try-block (if there is one), the copy/move
613 // operation from the operand to the exception object (15.1) can be
614 // omitted by constructing the automatic object directly into the
Douglas Gregor53e191ed2011-07-06 22:04:06 +0000615 // exception object
616 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
617 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
618 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
619 for( ; S; S = S->getParent()) {
620 if (S->isDeclScope(Var)) {
621 IsThrownVarInScope = true;
622 break;
623 }
624
625 if (S->getFlags() &
626 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
627 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
628 Scope::TryScope))
629 break;
630 }
631 }
632 }
633 }
634
635 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
636}
637
638ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
639 bool IsThrownVarInScope) {
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000640 // Don't report an error if 'throw' is used in system headers.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000641 if (!getLangOpts().CXXExceptions &&
Anders Carlssond99dbcc2011-02-23 03:46:46 +0000642 !getSourceManager().isInSystemHeader(OpLoc))
Anders Carlssonb94ad3e2011-02-19 21:53:09 +0000643 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
Alexander Musmana8e9d2e2014-06-03 10:16:47 +0000644
645 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
646 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
647
John Wiegley01296292011-04-08 18:41:53 +0000648 if (Ex && !Ex->isTypeDependent()) {
David Majnemerba3e5ec2015-03-13 18:26:17 +0000649 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
650 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
John Wiegley01296292011-04-08 18:41:53 +0000651 return ExprError();
David Majnemerba3e5ec2015-03-13 18:26:17 +0000652
653 // Initialize the exception result. This implicitly weeds out
654 // abstract types or types with inaccessible copy constructors.
655
656 // C++0x [class.copymove]p31:
657 // When certain criteria are met, an implementation is allowed to omit the
658 // copy/move construction of a class object [...]
659 //
660 // - in a throw-expression, when the operand is the name of a
661 // non-volatile automatic object (other than a function or
662 // catch-clause
663 // parameter) whose scope does not extend beyond the end of the
664 // innermost enclosing try-block (if there is one), the copy/move
665 // operation from the operand to the exception object (15.1) can be
666 // omitted by constructing the automatic object directly into the
667 // exception object
668 const VarDecl *NRVOVariable = nullptr;
669 if (IsThrownVarInScope)
670 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
671
672 InitializedEntity Entity = InitializedEntity::InitializeException(
673 OpLoc, ExceptionObjectTy,
674 /*NRVO=*/NRVOVariable != nullptr);
675 ExprResult Res = PerformMoveOrCopyInitialization(
676 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
677 if (Res.isInvalid())
678 return ExprError();
679 Ex = Res.get();
John Wiegley01296292011-04-08 18:41:53 +0000680 }
David Majnemerba3e5ec2015-03-13 18:26:17 +0000681
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000682 return new (Context)
683 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
Sebastian Redl4de47b42009-04-27 20:27:31 +0000684}
685
David Majnemere7a818f2015-03-06 18:53:55 +0000686static void
687collectPublicBases(CXXRecordDecl *RD,
688 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
689 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
690 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
691 bool ParentIsPublic) {
692 for (const CXXBaseSpecifier &BS : RD->bases()) {
693 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
694 bool NewSubobject;
695 // Virtual bases constitute the same subobject. Non-virtual bases are
696 // always distinct subobjects.
697 if (BS.isVirtual())
698 NewSubobject = VBases.insert(BaseDecl).second;
699 else
700 NewSubobject = true;
701
702 if (NewSubobject)
703 ++SubobjectsSeen[BaseDecl];
704
705 // Only add subobjects which have public access throughout the entire chain.
706 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
707 if (PublicPath)
708 PublicSubobjectsSeen.insert(BaseDecl);
709
710 // Recurse on to each base subobject.
711 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
712 PublicPath);
713 }
714}
715
716static void getUnambiguousPublicSubobjects(
717 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
718 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
719 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
720 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
721 SubobjectsSeen[RD] = 1;
722 PublicSubobjectsSeen.insert(RD);
723 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
724 /*ParentIsPublic=*/true);
725
726 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
727 // Skip ambiguous objects.
728 if (SubobjectsSeen[PublicSubobject] > 1)
729 continue;
730
731 Objects.push_back(PublicSubobject);
732 }
733}
734
Sebastian Redl4de47b42009-04-27 20:27:31 +0000735/// CheckCXXThrowOperand - Validate the operand of a throw.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000736bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
737 QualType ExceptionObjectTy, Expr *E) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000738 // If the type of the exception would be an incomplete type or a pointer
739 // to an incomplete type other than (cv) void the program is ill-formed.
David Majnemerd09a51c2015-03-03 01:50:05 +0000740 QualType Ty = ExceptionObjectTy;
John McCall2e6567a2010-04-22 01:10:34 +0000741 bool isPointer = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000742 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
Sebastian Redl4de47b42009-04-27 20:27:31 +0000743 Ty = Ptr->getPointeeType();
John McCall2e6567a2010-04-22 01:10:34 +0000744 isPointer = true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000745 }
746 if (!isPointer || !Ty->isVoidType()) {
747 if (RequireCompleteType(ThrowLoc, Ty,
David Majnemerba3e5ec2015-03-13 18:26:17 +0000748 isPointer ? diag::err_throw_incomplete_ptr
749 : diag::err_throw_incomplete,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000750 E->getSourceRange()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000751 return true;
Rafael Espindola70e040d2010-03-02 21:28:26 +0000752
David Majnemerd09a51c2015-03-03 01:50:05 +0000753 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
Douglas Gregorae298422012-05-04 17:09:59 +0000754 diag::err_throw_abstract_type, E))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000755 return true;
Sebastian Redl4de47b42009-04-27 20:27:31 +0000756 }
757
Eli Friedman91a3d272010-06-03 20:39:03 +0000758 // If the exception has class type, we need additional handling.
David Majnemerba3e5ec2015-03-13 18:26:17 +0000759 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
760 if (!RD)
761 return false;
Eli Friedman91a3d272010-06-03 20:39:03 +0000762
Douglas Gregor88d292c2010-05-13 16:44:06 +0000763 // If we are throwing a polymorphic class type or pointer thereof,
764 // exception handling will make use of the vtable.
Eli Friedman91a3d272010-06-03 20:39:03 +0000765 MarkVTableUsed(ThrowLoc, RD);
766
Eli Friedman36ebbec2010-10-12 20:32:36 +0000767 // If a pointer is thrown, the referenced object will not be destroyed.
768 if (isPointer)
David Majnemerba3e5ec2015-03-13 18:26:17 +0000769 return false;
Eli Friedman36ebbec2010-10-12 20:32:36 +0000770
Richard Smitheec915d62012-02-18 04:13:32 +0000771 // If the class has a destructor, we must be able to call it.
David Majnemere7a818f2015-03-06 18:53:55 +0000772 if (!RD->hasIrrelevantDestructor()) {
773 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
774 MarkFunctionReferenced(E->getExprLoc(), Destructor);
775 CheckDestructorAccess(E->getExprLoc(), Destructor,
776 PDiag(diag::err_access_dtor_exception) << Ty);
777 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
David Majnemerba3e5ec2015-03-13 18:26:17 +0000778 return true;
David Majnemere7a818f2015-03-06 18:53:55 +0000779 }
780 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000781
David Majnemerdfa6d202015-03-11 18:36:39 +0000782 // The MSVC ABI creates a list of all types which can catch the exception
783 // object. This list also references the appropriate copy constructor to call
784 // if the object is caught by value and has a non-trivial copy constructor.
David Majnemere7a818f2015-03-06 18:53:55 +0000785 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000786 // We are only interested in the public, unambiguous bases contained within
787 // the exception object. Bases which are ambiguous or otherwise
788 // inaccessible are not catchable types.
David Majnemere7a818f2015-03-06 18:53:55 +0000789 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
790 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
David Majnemerdfa6d202015-03-11 18:36:39 +0000791
David Majnemere7a818f2015-03-06 18:53:55 +0000792 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
David Majnemerdfa6d202015-03-11 18:36:39 +0000793 // Attempt to lookup the copy constructor. Various pieces of machinery
794 // will spring into action, like template instantiation, which means this
795 // cannot be a simple walk of the class's decls. Instead, we must perform
796 // lookup and overload resolution.
797 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
798 if (!CD)
799 continue;
800
801 // Mark the constructor referenced as it is used by this throw expression.
802 MarkFunctionReferenced(E->getExprLoc(), CD);
803
804 // Skip this copy constructor if it is trivial, we don't need to record it
805 // in the catchable type data.
806 if (CD->isTrivial())
807 continue;
808
809 // The copy constructor is non-trivial, create a mapping from this class
810 // type to this constructor.
811 // N.B. The selection of copy constructor is not sensitive to this
812 // particular throw-site. Lookup will be performed at the catch-site to
813 // ensure that the copy constructor is, in fact, accessible (via
814 // friendship or any other means).
815 Context.addCopyConstructorForExceptionObject(Subobject, CD);
816
817 // We don't keep the instantiated default argument expressions around so
818 // we must rebuild them here.
819 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
820 // Skip any default arguments that we've already instantiated.
821 if (Context.getDefaultArgExprForConstructor(CD, I))
822 continue;
823
824 Expr *DefaultArg =
825 BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
826 Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
David Majnemere7a818f2015-03-06 18:53:55 +0000827 }
828 }
829 }
Eli Friedman91a3d272010-06-03 20:39:03 +0000830
David Majnemerba3e5ec2015-03-13 18:26:17 +0000831 return false;
Chris Lattnerb7e656b2008-02-26 00:51:44 +0000832}
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000833
Eli Friedman73a04092012-01-07 04:59:52 +0000834QualType Sema::getCurrentThisType() {
835 DeclContext *DC = getFunctionLevelDeclContext();
Douglas Gregor3024f072012-04-16 07:05:22 +0000836 QualType ThisTy = CXXThisTypeOverride;
Richard Smith938f40b2011-06-11 17:19:42 +0000837 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
838 if (method && method->isInstance())
839 ThisTy = method->getThisType(Context);
Richard Smith938f40b2011-06-11 17:19:42 +0000840 }
Faisal Vali47d9ed42014-05-30 04:39:37 +0000841 if (ThisTy.isNull()) {
842 if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
843 CurContext->getParent()->getParent()->isRecord()) {
844 // This is a generic lambda call operator that is being instantiated
845 // within a default initializer - so use the enclosing class as 'this'.
846 // There is no enclosing member function to retrieve the 'this' pointer
847 // from.
Faisal Validc6b5962016-03-21 09:25:37 +0000848
849 // FIXME: This looks wrong. If we're in a lambda within a lambda within a
850 // default member initializer, we need to recurse up more parents to find
851 // the right context. Looks like we should be walking up to the parent of
852 // the closure type, checking whether that is itself a lambda, and if so,
853 // recursing, until we reach a class or a function that isn't a lambda
854 // call operator. And we should accumulate the constness of *this on the
855 // way.
856
Faisal Vali47d9ed42014-05-30 04:39:37 +0000857 QualType ClassTy = Context.getTypeDeclType(
858 cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
859 // There are no cv-qualifiers for 'this' within default initializers,
860 // per [expr.prim.general]p4.
Faisal Validc6b5962016-03-21 09:25:37 +0000861 ThisTy = Context.getPointerType(ClassTy);
862 }
863 }
864 // Add const for '* this' capture if not mutable.
865 if (isLambdaCallOperator(CurContext)) {
866 LambdaScopeInfo *LSI = getCurLambda();
867 assert(LSI);
868 if (LSI->isCXXThisCaptured()) {
869 auto C = LSI->getCXXThisCapture();
870 QualType BaseType = ThisTy->getPointeeType();
871 if ((C.isThisCapture() && C.isCopyCapture()) &&
872 LSI->CallOperator->isConst() && !BaseType.isConstQualified()) {
873 BaseType.addConst();
874 ThisTy = Context.getPointerType(BaseType);
875 }
Faisal Vali47d9ed42014-05-30 04:39:37 +0000876 }
877 }
Richard Smith938f40b2011-06-11 17:19:42 +0000878 return ThisTy;
John McCallf3a88602011-02-03 08:15:49 +0000879}
880
Douglas Gregor3024f072012-04-16 07:05:22 +0000881Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
882 Decl *ContextDecl,
883 unsigned CXXThisTypeQuals,
884 bool Enabled)
885 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
886{
887 if (!Enabled || !ContextDecl)
888 return;
Craig Topperc3ec1492014-05-26 06:22:03 +0000889
890 CXXRecordDecl *Record = nullptr;
Douglas Gregor3024f072012-04-16 07:05:22 +0000891 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
892 Record = Template->getTemplatedDecl();
893 else
894 Record = cast<CXXRecordDecl>(ContextDecl);
895
896 S.CXXThisTypeOverride
897 = S.Context.getPointerType(
898 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
899
900 this->Enabled = true;
901}
902
903
904Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
905 if (Enabled) {
906 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
907 }
908}
909
Faisal Validc6b5962016-03-21 09:25:37 +0000910static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
911 QualType ThisTy, SourceLocation Loc,
912 const bool ByCopy) {
913 QualType CaptureThisTy = ByCopy ? ThisTy->getPointeeType() : ThisTy;
914
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000915 FieldDecl *Field
Faisal Validc6b5962016-03-21 09:25:37 +0000916 = FieldDecl::Create(Context, RD, Loc, Loc, nullptr, CaptureThisTy,
917 Context.getTrivialTypeSourceInfo(CaptureThisTy, Loc),
Craig Topperc3ec1492014-05-26 06:22:03 +0000918 nullptr, false, ICIS_NoInit);
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000919 Field->setImplicit(true);
920 Field->setAccess(AS_private);
921 RD->addDecl(Field);
Faisal Validc6b5962016-03-21 09:25:37 +0000922 Expr *This = new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/true);
923 if (ByCopy) {
924 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
925 UO_Deref,
926 This).get();
927 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
928 nullptr, CaptureThisTy, Loc);
929 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
930 InitializationSequence Init(S, Entity, InitKind, StarThis);
931 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
932 if (ER.isInvalid()) return nullptr;
933 return ER.get();
934 }
935 return This;
Ben Langmuire7d7c4c2013-04-29 13:32:41 +0000936}
937
Faisal Validc6b5962016-03-21 09:25:37 +0000938bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
939 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
940 const bool ByCopy) {
Eli Friedman73a04092012-01-07 04:59:52 +0000941 // We don't need to capture this in an unevaluated context.
John McCallf413f5e2013-05-03 00:10:13 +0000942 if (isUnevaluatedContext() && !Explicit)
Faisal Valia17d19f2013-11-07 05:17:06 +0000943 return true;
Faisal Validc6b5962016-03-21 09:25:37 +0000944
945 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
Eli Friedman73a04092012-01-07 04:59:52 +0000946
Faisal Valia17d19f2013-11-07 05:17:06 +0000947 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
Faisal Validc6b5962016-03-21 09:25:37 +0000948 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
949
950 // Check that we can capture the *enclosing object* (referred to by '*this')
951 // by the capturing-entity/closure (lambda/block/etc) at
952 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
953
954 // Note: The *enclosing object* can only be captured by-value by a
955 // closure that is a lambda, using the explicit notation:
956 // [*this] { ... }.
957 // Every other capture of the *enclosing object* results in its by-reference
958 // capture.
959
960 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
961 // stack), we can capture the *enclosing object* only if:
962 // - 'L' has an explicit byref or byval capture of the *enclosing object*
963 // - or, 'L' has an implicit capture.
964 // AND
965 // -- there is no enclosing closure
966 // -- or, there is some enclosing closure 'E' that has already captured the
967 // *enclosing object*, and every intervening closure (if any) between 'E'
968 // and 'L' can implicitly capture the *enclosing object*.
969 // -- or, every enclosing closure can implicitly capture the
970 // *enclosing object*
971
972
973 unsigned NumCapturingClosures = 0;
Faisal Valia17d19f2013-11-07 05:17:06 +0000974 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
Eli Friedman20139d32012-01-11 02:36:31 +0000975 if (CapturingScopeInfo *CSI =
976 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
977 if (CSI->CXXThisCaptureIndex != 0) {
978 // 'this' is already being captured; there isn't anything more to do.
Eli Friedman73a04092012-01-07 04:59:52 +0000979 break;
980 }
Faisal Valia17d19f2013-11-07 05:17:06 +0000981 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
982 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
983 // This context can't implicitly capture 'this'; fail out.
984 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +0000985 Diag(Loc, diag::err_this_capture)
986 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +0000987 return true;
988 }
Eli Friedman20139d32012-01-11 02:36:31 +0000989 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
Douglas Gregora1bffa22012-02-10 17:46:20 +0000990 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000991 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +0000992 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
Faisal Validc6b5962016-03-21 09:25:37 +0000993 (Explicit && idx == MaxFunctionScopesIndex)) {
994 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
995 // iteration through can be an explicit capture, all enclosing closures,
996 // if any, must perform implicit captures.
997
Douglas Gregorcdd11d42012-02-01 17:04:21 +0000998 // This closure can capture 'this'; continue looking upwards.
Faisal Validc6b5962016-03-21 09:25:37 +0000999 NumCapturingClosures++;
Eli Friedman73a04092012-01-07 04:59:52 +00001000 continue;
1001 }
Eli Friedman20139d32012-01-11 02:36:31 +00001002 // This context can't implicitly capture 'this'; fail out.
Faisal Valia17d19f2013-11-07 05:17:06 +00001003 if (BuildAndDiagnose)
Faisal Validc6b5962016-03-21 09:25:37 +00001004 Diag(Loc, diag::err_this_capture)
1005 << (Explicit && idx == MaxFunctionScopesIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +00001006 return true;
Eli Friedman73a04092012-01-07 04:59:52 +00001007 }
Eli Friedman73a04092012-01-07 04:59:52 +00001008 break;
1009 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001010 if (!BuildAndDiagnose) return false;
Faisal Validc6b5962016-03-21 09:25:37 +00001011
1012 // If we got here, then the closure at MaxFunctionScopesIndex on the
1013 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1014 // (including implicit by-reference captures in any enclosing closures).
1015
1016 // In the loop below, respect the ByCopy flag only for the closure requesting
1017 // the capture (i.e. first iteration through the loop below). Ignore it for
1018 // all enclosing closure's upto NumCapturingClosures (since they must be
1019 // implicitly capturing the *enclosing object* by reference (see loop
1020 // above)).
1021 assert((!ByCopy ||
1022 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1023 "Only a lambda can capture the enclosing object (referred to by "
1024 "*this) by copy");
Eli Friedman73a04092012-01-07 04:59:52 +00001025 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1026 // contexts.
Faisal Validc6b5962016-03-21 09:25:37 +00001027
1028 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1029 --idx, --NumCapturingClosures) {
Eli Friedman20139d32012-01-11 02:36:31 +00001030 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
Craig Topperc3ec1492014-05-26 06:22:03 +00001031 Expr *ThisExpr = nullptr;
Douglas Gregorfdf598e2012-02-18 09:37:24 +00001032 QualType ThisTy = getCurrentThisType();
Faisal Validc6b5962016-03-21 09:25:37 +00001033 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1034 // For lambda expressions, build a field and an initializing expression,
1035 // and capture the *enclosing object* by copy only if this is the first
1036 // iteration.
1037 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1038 ByCopy && idx == MaxFunctionScopesIndex);
1039
1040 } else if (CapturedRegionScopeInfo *RSI
Ben Langmuire7d7c4c2013-04-29 13:32:41 +00001041 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
Faisal Validc6b5962016-03-21 09:25:37 +00001042 ThisExpr =
1043 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1044 false/*ByCopy*/);
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001045
Faisal Validc6b5962016-03-21 09:25:37 +00001046 bool isNested = NumCapturingClosures > 1;
1047 CSI->addThisCapture(isNested, Loc, ThisTy, ThisExpr, ByCopy);
Eli Friedman73a04092012-01-07 04:59:52 +00001048 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001049 return false;
Eli Friedman73a04092012-01-07 04:59:52 +00001050}
1051
Richard Smith938f40b2011-06-11 17:19:42 +00001052ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
John McCallf3a88602011-02-03 08:15:49 +00001053 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1054 /// is a non-lvalue expression whose value is the address of the object for
1055 /// which the function is called.
1056
Douglas Gregor09deffa2011-10-18 16:47:30 +00001057 QualType ThisTy = getCurrentThisType();
Richard Smith938f40b2011-06-11 17:19:42 +00001058 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
John McCallf3a88602011-02-03 08:15:49 +00001059
Eli Friedman73a04092012-01-07 04:59:52 +00001060 CheckCXXThisCapture(Loc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001061 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00001062}
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001063
Douglas Gregor3024f072012-04-16 07:05:22 +00001064bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1065 // If we're outside the body of a member function, then we'll have a specified
1066 // type for 'this'.
1067 if (CXXThisTypeOverride.isNull())
1068 return false;
1069
1070 // Determine whether we're looking into a class that's currently being
1071 // defined.
1072 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1073 return Class && Class->isBeingDefined();
1074}
1075
John McCalldadc5752010-08-24 06:29:42 +00001076ExprResult
Douglas Gregor2b88c112010-09-08 00:15:04 +00001077Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001078 SourceLocation LParenLoc,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001079 MultiExprArg exprs,
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001080 SourceLocation RParenLoc) {
Douglas Gregor7df89f52010-02-05 19:11:37 +00001081 if (!TypeRep)
1082 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001083
John McCall97513962010-01-15 18:39:57 +00001084 TypeSourceInfo *TInfo;
1085 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1086 if (!TInfo)
1087 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
Douglas Gregor2b88c112010-09-08 00:15:04 +00001088
1089 return BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1090}
1091
1092/// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1093/// Can be interpreted either as function-style casting ("int(x)")
1094/// or class type construction ("ClassType(x,y,z)")
1095/// or creation of a value-initialized type ("int()").
1096ExprResult
1097Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1098 SourceLocation LParenLoc,
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001099 MultiExprArg Exprs,
Douglas Gregor2b88c112010-09-08 00:15:04 +00001100 SourceLocation RParenLoc) {
1101 QualType Ty = TInfo->getType();
Douglas Gregor2b88c112010-09-08 00:15:04 +00001102 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001103
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001104 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001105 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1106 RParenLoc);
Douglas Gregor0950e412009-03-13 21:01:28 +00001107 }
1108
Sebastian Redld74dd492012-02-12 18:41:05 +00001109 bool ListInitialization = LParenLoc.isInvalid();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001110 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
Sebastian Redld74dd492012-02-12 18:41:05 +00001111 && "List initialization must have initializer list as expression.");
1112 SourceRange FullRange = SourceRange(TyBeginLoc,
1113 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1114
Douglas Gregordd04d332009-01-16 18:33:17 +00001115 // C++ [expr.type.conv]p1:
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001116 // If the expression list is a single expression, the type conversion
1117 // expression is equivalent (in definedness, and if defined in meaning) to the
1118 // corresponding cast expression.
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001119 if (Exprs.size() == 1 && !ListInitialization) {
John McCallb50451a2011-10-05 07:41:44 +00001120 Expr *Arg = Exprs[0];
John McCallb50451a2011-10-05 07:41:44 +00001121 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001122 }
1123
David Majnemer7eddcff2015-09-14 07:05:00 +00001124 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1125 // simple-type-specifier or typename-specifier for a non-array complete
1126 // object type or the (possibly cv-qualified) void type, creates a prvalue
1127 // of the specified type, whose value is that produced by value-initializing
1128 // an object of type T.
Eli Friedman576cbd02012-02-29 00:00:28 +00001129 QualType ElemTy = Ty;
1130 if (Ty->isArrayType()) {
1131 if (!ListInitialization)
1132 return ExprError(Diag(TyBeginLoc,
1133 diag::err_value_init_for_array_type) << FullRange);
1134 ElemTy = Context.getBaseElementType(Ty);
1135 }
1136
David Majnemer7eddcff2015-09-14 07:05:00 +00001137 if (!ListInitialization && Ty->isFunctionType())
1138 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1139 << FullRange);
1140
Eli Friedman576cbd02012-02-29 00:00:28 +00001141 if (!Ty->isVoidType() &&
1142 RequireCompleteType(TyBeginLoc, ElemTy,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001143 diag::err_invalid_incomplete_type_use, FullRange))
Eli Friedman576cbd02012-02-29 00:00:28 +00001144 return ExprError();
1145
1146 if (RequireNonAbstractType(TyBeginLoc, Ty,
1147 diag::err_allocation_of_abstract_type))
1148 return ExprError();
1149
Douglas Gregor8ec51732010-09-08 21:40:08 +00001150 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001151 InitializationKind Kind =
1152 Exprs.size() ? ListInitialization
1153 ? InitializationKind::CreateDirectList(TyBeginLoc)
1154 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1155 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1156 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1157 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001158
Richard Smith90061902013-09-23 02:20:00 +00001159 if (Result.isInvalid() || !ListInitialization)
1160 return Result;
1161
1162 Expr *Inner = Result.get();
1163 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1164 Inner = BTE->getSubExpr();
Richard Smith1ae689c2015-01-28 22:06:01 +00001165 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1166 // If we created a CXXTemporaryObjectExpr, that node also represents the
1167 // functional cast. Otherwise, create an explicit cast to represent
1168 // the syntactic form of a functional-style cast that was used here.
1169 //
1170 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1171 // would give a more consistent AST representation than using a
1172 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1173 // is sometimes handled by initialization and sometimes not.
Richard Smith90061902013-09-23 02:20:00 +00001174 QualType ResultType = Result.get()->getType();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001175 Result = CXXFunctionalCastExpr::Create(
Richard Smith90061902013-09-23 02:20:00 +00001176 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001177 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
Sebastian Redl2b80af42012-02-13 19:55:43 +00001178 }
1179
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001180 return Result;
Argyrios Kyrtzidis857fcc22008-08-22 15:38:55 +00001181}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001182
John McCall284c48f2011-01-27 09:37:56 +00001183/// doesUsualArrayDeleteWantSize - Answers whether the usual
1184/// operator delete[] for the given type has a size_t parameter.
1185static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1186 QualType allocType) {
1187 const RecordType *record =
1188 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1189 if (!record) return false;
1190
1191 // Try to find an operator delete[] in class scope.
1192
1193 DeclarationName deleteName =
1194 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1195 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1196 S.LookupQualifiedName(ops, record->getDecl());
1197
1198 // We're just doing this for information.
1199 ops.suppressDiagnostics();
1200
1201 // Very likely: there's no operator delete[].
1202 if (ops.empty()) return false;
1203
1204 // If it's ambiguous, it should be illegal to call operator delete[]
1205 // on this thing, so it doesn't matter if we allocate extra space or not.
1206 if (ops.isAmbiguous()) return false;
1207
1208 LookupResult::Filter filter = ops.makeFilter();
1209 while (filter.hasNext()) {
1210 NamedDecl *del = filter.next()->getUnderlyingDecl();
1211
1212 // C++0x [basic.stc.dynamic.deallocation]p2:
1213 // A template instance is never a usual deallocation function,
1214 // regardless of its signature.
1215 if (isa<FunctionTemplateDecl>(del)) {
1216 filter.erase();
1217 continue;
1218 }
1219
1220 // C++0x [basic.stc.dynamic.deallocation]p2:
1221 // If class T does not declare [an operator delete[] with one
1222 // parameter] but does declare a member deallocation function
1223 // named operator delete[] with exactly two parameters, the
1224 // second of which has type std::size_t, then this function
1225 // is a usual deallocation function.
1226 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
1227 filter.erase();
1228 continue;
1229 }
1230 }
1231 filter.done();
1232
1233 if (!ops.isSingleResult()) return false;
1234
1235 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
1236 return (del->getNumParams() == 2);
1237}
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00001238
Sebastian Redld74dd492012-02-12 18:41:05 +00001239/// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
James Dennettf14a6e52012-06-15 22:23:43 +00001240///
Sebastian Redld74dd492012-02-12 18:41:05 +00001241/// E.g.:
Sebastian Redlbd150f42008-11-21 19:14:01 +00001242/// @code new (memory) int[size][4] @endcode
1243/// or
1244/// @code ::new Foo(23, "hello") @endcode
Sebastian Redld74dd492012-02-12 18:41:05 +00001245///
1246/// \param StartLoc The first location of the expression.
1247/// \param UseGlobal True if 'new' was prefixed with '::'.
1248/// \param PlacementLParen Opening paren of the placement arguments.
1249/// \param PlacementArgs Placement new arguments.
1250/// \param PlacementRParen Closing paren of the placement arguments.
1251/// \param TypeIdParens If the type is in parens, the source range.
1252/// \param D The type to be allocated, as well as array dimensions.
James Dennettf14a6e52012-06-15 22:23:43 +00001253/// \param Initializer The initializing expression or initializer-list, or null
1254/// if there is none.
John McCalldadc5752010-08-24 06:29:42 +00001255ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00001256Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001257 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258 SourceLocation PlacementRParen, SourceRange TypeIdParens,
Sebastian Redl6047f072012-02-16 12:22:20 +00001259 Declarator &D, Expr *Initializer) {
Richard Smith74aeef52013-04-26 16:15:35 +00001260 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
Richard Smith30482bc2011-02-20 03:19:35 +00001261
Craig Topperc3ec1492014-05-26 06:22:03 +00001262 Expr *ArraySize = nullptr;
Sebastian Redl351bb782008-12-02 14:43:59 +00001263 // If the specified type is an array, unwrap it and save the expression.
1264 if (D.getNumTypeObjects() > 0 &&
1265 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
James Dennettf14a6e52012-06-15 22:23:43 +00001266 DeclaratorChunk &Chunk = D.getTypeObject(0);
Richard Smith30482bc2011-02-20 03:19:35 +00001267 if (TypeContainsAuto)
1268 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1269 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001270 if (Chunk.Arr.hasStatic)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001271 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1272 << D.getSourceRange());
Sebastian Redl351bb782008-12-02 14:43:59 +00001273 if (!Chunk.Arr.NumElts)
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001274 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1275 << D.getSourceRange());
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001276
Sebastian Redl351bb782008-12-02 14:43:59 +00001277 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001278 D.DropFirstTypeObject();
Sebastian Redl351bb782008-12-02 14:43:59 +00001279 }
1280
Douglas Gregor73341c42009-09-11 00:18:58 +00001281 // Every dimension shall be of constant size.
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001282 if (ArraySize) {
1283 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
Douglas Gregor73341c42009-09-11 00:18:58 +00001284 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1285 break;
1286
1287 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1288 if (Expr *NumElts = (Expr *)Array.NumElts) {
Richard Smithf4c51d92012-02-04 09:53:13 +00001289 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001290 if (getLangOpts().CPlusPlus14) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001291 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1292 // shall be a converted constant expression (5.19) of type std::size_t
1293 // and shall evaluate to a strictly positive value.
1294 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1295 assert(IntWidth && "Builtin type of size 0?");
1296 llvm::APSInt Value(IntWidth);
1297 Array.NumElts
1298 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1299 CCEK_NewExpr)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001300 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001301 } else {
1302 Array.NumElts
Craig Topperc3ec1492014-05-26 06:22:03 +00001303 = VerifyIntegerConstantExpression(NumElts, nullptr,
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001304 diag::err_new_array_nonconst)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001305 .get();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001306 }
Richard Smithf4c51d92012-02-04 09:53:13 +00001307 if (!Array.NumElts)
1308 return ExprError();
Douglas Gregor73341c42009-09-11 00:18:58 +00001309 }
1310 }
1311 }
1312 }
Sebastian Redld7b3d7d2009-10-25 21:45:37 +00001313
Craig Topperc3ec1492014-05-26 06:22:03 +00001314 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
John McCall8cb7bdf2010-06-04 23:28:52 +00001315 QualType AllocType = TInfo->getType();
Chris Lattnerf6d1c9c2009-04-25 08:06:05 +00001316 if (D.isInvalidType())
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001317 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001318
Sebastian Redl6047f072012-02-16 12:22:20 +00001319 SourceRange DirectInitRange;
1320 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1321 DirectInitRange = List->getSourceRange();
1322
David Blaikie7b97aef2012-11-07 00:12:38 +00001323 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001324 PlacementLParen,
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001325 PlacementArgs,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001326 PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001327 TypeIdParens,
Mike Stump11289f42009-09-09 15:08:12 +00001328 AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001329 TInfo,
John McCallb268a282010-08-23 23:25:46 +00001330 ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001331 DirectInitRange,
1332 Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001333 TypeContainsAuto);
Douglas Gregord0fefba2009-05-21 00:00:09 +00001334}
1335
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001336static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1337 Expr *Init) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001338 if (!Init)
1339 return true;
Sebastian Redleb54f082012-02-17 08:42:32 +00001340 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1341 return PLE->getNumExprs() == 0;
Sebastian Redl6047f072012-02-16 12:22:20 +00001342 if (isa<ImplicitValueInitExpr>(Init))
1343 return true;
1344 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1345 return !CCE->isListInitialization() &&
1346 CCE->getConstructor()->isDefaultConstructor();
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001347 else if (Style == CXXNewExpr::ListInit) {
1348 assert(isa<InitListExpr>(Init) &&
1349 "Shouldn't create list CXXConstructExprs for arrays.");
1350 return true;
1351 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001352 return false;
1353}
1354
John McCalldadc5752010-08-24 06:29:42 +00001355ExprResult
David Blaikie7b97aef2012-11-07 00:12:38 +00001356Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001357 SourceLocation PlacementLParen,
1358 MultiExprArg PlacementArgs,
1359 SourceLocation PlacementRParen,
Douglas Gregorf2753b32010-07-13 15:54:32 +00001360 SourceRange TypeIdParens,
Douglas Gregord0fefba2009-05-21 00:00:09 +00001361 QualType AllocType,
Douglas Gregor0744ef62010-09-07 21:49:58 +00001362 TypeSourceInfo *AllocTypeInfo,
John McCallb268a282010-08-23 23:25:46 +00001363 Expr *ArraySize,
Sebastian Redl6047f072012-02-16 12:22:20 +00001364 SourceRange DirectInitRange,
1365 Expr *Initializer,
Richard Smith30482bc2011-02-20 03:19:35 +00001366 bool TypeMayContainAuto) {
Douglas Gregor0744ef62010-09-07 21:49:58 +00001367 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
David Blaikie7b97aef2012-11-07 00:12:38 +00001368 SourceLocation StartLoc = Range.getBegin();
Sebastian Redl351bb782008-12-02 14:43:59 +00001369
Sebastian Redl6047f072012-02-16 12:22:20 +00001370 CXXNewExpr::InitializationStyle initStyle;
1371 if (DirectInitRange.isValid()) {
1372 assert(Initializer && "Have parens but no initializer.");
1373 initStyle = CXXNewExpr::CallInit;
1374 } else if (Initializer && isa<InitListExpr>(Initializer))
1375 initStyle = CXXNewExpr::ListInit;
1376 else {
1377 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1378 isa<CXXConstructExpr>(Initializer)) &&
1379 "Initializer expression that cannot have been implicitly created.");
1380 initStyle = CXXNewExpr::NoInit;
1381 }
1382
1383 Expr **Inits = &Initializer;
1384 unsigned NumInits = Initializer ? 1 : 0;
Richard Smithdd2ca572012-11-26 08:32:48 +00001385 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1386 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1387 Inits = List->getExprs();
1388 NumInits = List->getNumExprs();
Sebastian Redl6047f072012-02-16 12:22:20 +00001389 }
1390
Richard Smith66204ec2014-03-12 17:42:45 +00001391 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
Richard Smith27d807c2013-04-30 13:56:41 +00001392 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
Sebastian Redl6047f072012-02-16 12:22:20 +00001393 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
Richard Smith30482bc2011-02-20 03:19:35 +00001394 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1395 << AllocType << TypeRange);
Richard Smith66204ec2014-03-12 17:42:45 +00001396 if (initStyle == CXXNewExpr::ListInit ||
1397 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001398 return ExprError(Diag(Inits[0]->getLocStart(),
Richard Smith66204ec2014-03-12 17:42:45 +00001399 diag::err_auto_new_list_init)
Sebastian Redl6047f072012-02-16 12:22:20 +00001400 << AllocType << TypeRange);
1401 if (NumInits > 1) {
1402 Expr *FirstBad = Inits[1];
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001403 return ExprError(Diag(FirstBad->getLocStart(),
Richard Smith30482bc2011-02-20 03:19:35 +00001404 diag::err_auto_new_ctor_multiple_expressions)
1405 << AllocType << TypeRange);
1406 }
Sebastian Redl6047f072012-02-16 12:22:20 +00001407 Expr *Deduce = Inits[0];
Richard Smith061f1e22013-04-30 21:23:01 +00001408 QualType DeducedType;
Richard Smith74801c82012-07-08 04:13:07 +00001409 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
Richard Smith30482bc2011-02-20 03:19:35 +00001410 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
Sebastian Redld74dd492012-02-12 18:41:05 +00001411 << AllocType << Deduce->getType()
1412 << TypeRange << Deduce->getSourceRange());
Richard Smith061f1e22013-04-30 21:23:01 +00001413 if (DeducedType.isNull())
Richard Smith9647d3c2011-03-17 16:11:59 +00001414 return ExprError();
Richard Smith061f1e22013-04-30 21:23:01 +00001415 AllocType = DeducedType;
Richard Smith30482bc2011-02-20 03:19:35 +00001416 }
Sebastian Redld74dd492012-02-12 18:41:05 +00001417
Douglas Gregorcda95f42010-05-16 16:01:03 +00001418 // Per C++0x [expr.new]p5, the type being constructed may be a
1419 // typedef of an array type.
John McCallb268a282010-08-23 23:25:46 +00001420 if (!ArraySize) {
Douglas Gregorcda95f42010-05-16 16:01:03 +00001421 if (const ConstantArrayType *Array
1422 = Context.getAsConstantArrayType(AllocType)) {
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001423 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1424 Context.getSizeType(),
1425 TypeRange.getEnd());
Douglas Gregorcda95f42010-05-16 16:01:03 +00001426 AllocType = Array->getElementType();
1427 }
1428 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001429
Douglas Gregor3999e152010-10-06 16:00:31 +00001430 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1431 return ExprError();
1432
Craig Topperc3ec1492014-05-26 06:22:03 +00001433 if (initStyle == CXXNewExpr::ListInit &&
1434 isStdInitializerList(AllocType, nullptr)) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001435 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1436 diag::warn_dangling_std_initializer_list)
Sebastian Redl73cfbeb2012-02-19 16:31:05 +00001437 << /*at end of FE*/0 << Inits[0]->getSourceRange();
Sebastian Redld74dd492012-02-12 18:41:05 +00001438 }
1439
John McCall31168b02011-06-15 23:02:42 +00001440 // In ARC, infer 'retaining' for the allocated
David Blaikiebbafb8a2012-03-11 07:00:24 +00001441 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001442 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1443 AllocType->isObjCLifetimeType()) {
1444 AllocType = Context.getLifetimeQualifiedType(AllocType,
1445 AllocType->getObjCARCImplicitLifetime());
1446 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001447
John McCall31168b02011-06-15 23:02:42 +00001448 QualType ResultType = Context.getPointerType(AllocType);
1449
John McCall5e77d762013-04-16 07:28:30 +00001450 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1451 ExprResult result = CheckPlaceholderExpr(ArraySize);
1452 if (result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001453 ArraySize = result.get();
John McCall5e77d762013-04-16 07:28:30 +00001454 }
Richard Smith8dd34252012-02-04 07:07:42 +00001455 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1456 // integral or enumeration type with a non-negative value."
1457 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1458 // enumeration type, or a class type for which a single non-explicit
1459 // conversion function to integral or unscoped enumeration type exists.
Richard Smithccc11812013-05-21 19:05:48 +00001460 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
Larisse Voufobf4aa572013-06-18 03:08:53 +00001461 // std::size_t.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001462 if (ArraySize && !ArraySize->isTypeDependent()) {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001463 ExprResult ConvertedSize;
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001464 if (getLangOpts().CPlusPlus14) {
Alp Toker965f8822013-11-27 05:22:15 +00001465 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1466
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001467 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1468 AA_Converting);
Richard Smithccc11812013-05-21 19:05:48 +00001469
Larisse Voufobf4aa572013-06-18 03:08:53 +00001470 if (!ConvertedSize.isInvalid() &&
1471 ArraySize->getType()->getAs<RecordType>())
Larisse Voufo9f380c52013-06-18 01:27:47 +00001472 // Diagnose the compatibility of this conversion.
1473 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1474 << ArraySize->getType() << 0 << "'size_t'";
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001475 } else {
1476 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1477 protected:
1478 Expr *ArraySize;
1479
1480 public:
1481 SizeConvertDiagnoser(Expr *ArraySize)
1482 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1483 ArraySize(ArraySize) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001484
1485 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1486 QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001487 return S.Diag(Loc, diag::err_array_size_not_integral)
1488 << S.getLangOpts().CPlusPlus11 << T;
1489 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001490
1491 SemaDiagnosticBuilder diagnoseIncomplete(
1492 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001493 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1494 << T << ArraySize->getSourceRange();
1495 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001496
1497 SemaDiagnosticBuilder diagnoseExplicitConv(
1498 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001499 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1500 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001501
1502 SemaDiagnosticBuilder noteExplicitConv(
1503 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001504 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1505 << ConvTy->isEnumeralType() << ConvTy;
1506 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001507
1508 SemaDiagnosticBuilder diagnoseAmbiguous(
1509 Sema &S, SourceLocation Loc, QualType T) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001510 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1511 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001512
1513 SemaDiagnosticBuilder noteAmbiguous(
1514 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001515 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1516 << ConvTy->isEnumeralType() << ConvTy;
1517 }
Richard Smithccc11812013-05-21 19:05:48 +00001518
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001519 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1520 QualType T,
1521 QualType ConvTy) override {
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001522 return S.Diag(Loc,
1523 S.getLangOpts().CPlusPlus11
1524 ? diag::warn_cxx98_compat_array_size_conversion
1525 : diag::ext_array_size_conversion)
1526 << T << ConvTy->isEnumeralType() << ConvTy;
1527 }
1528 } SizeDiagnoser(ArraySize);
Richard Smithccc11812013-05-21 19:05:48 +00001529
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001530 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1531 SizeDiagnoser);
1532 }
Douglas Gregor4799d032010-06-30 00:20:43 +00001533 if (ConvertedSize.isInvalid())
1534 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001536 ArraySize = ConvertedSize.get();
John McCall9b80c212012-01-11 00:14:46 +00001537 QualType SizeType = ArraySize->getType();
Larisse Voufo0f1394c2013-06-15 20:17:46 +00001538
Douglas Gregor0bf31402010-10-08 23:50:27 +00001539 if (!SizeType->isIntegralOrUnscopedEnumerationType())
Douglas Gregor4799d032010-06-30 00:20:43 +00001540 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001541
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001542 // C++98 [expr.new]p7:
1543 // The expression in a direct-new-declarator shall have integral type
1544 // with a non-negative value.
1545 //
1546 // Let's see if this is a constant < 0. If so, we reject it out of
1547 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1548 // array type.
1549 //
1550 // Note: such a construct has well-defined semantics in C++11: it throws
1551 // std::bad_array_new_length.
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001552 if (!ArraySize->isValueDependent()) {
1553 llvm::APSInt Value;
Richard Smithf4c51d92012-02-04 09:53:13 +00001554 // We've already performed any required implicit conversion to integer or
1555 // unscoped enumeration type.
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001556 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001557 if (Value < llvm::APSInt(
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558 llvm::APInt::getNullValue(Value.getBitWidth()),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001559 Value.isUnsigned())) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001560 if (getLangOpts().CPlusPlus11)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001561 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001562 diag::warn_typecheck_negative_array_new_size)
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001563 << ArraySize->getSourceRange();
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001564 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001565 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001566 diag::err_typecheck_negative_array_size)
1567 << ArraySize->getSourceRange());
1568 } else if (!AllocType->isDependentType()) {
1569 unsigned ActiveSizeBits =
1570 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1571 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001572 if (getLangOpts().CPlusPlus11)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001573 Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001574 diag::warn_array_new_too_large)
1575 << Value.toString(10)
1576 << ArraySize->getSourceRange();
1577 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00001578 return ExprError(Diag(ArraySize->getLocStart(),
Richard Smithbcc9bcb2012-02-04 05:35:53 +00001579 diag::err_array_too_large)
1580 << Value.toString(10)
1581 << ArraySize->getSourceRange());
Douglas Gregorcaa1bf42010-08-18 00:39:00 +00001582 }
1583 }
Douglas Gregorf2753b32010-07-13 15:54:32 +00001584 } else if (TypeIdParens.isValid()) {
1585 // Can't have dynamic array size when the type-id is in parentheses.
1586 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1587 << ArraySize->getSourceRange()
1588 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1589 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001590
Douglas Gregorf2753b32010-07-13 15:54:32 +00001591 TypeIdParens = SourceRange();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001592 }
Sebastian Redl351bb782008-12-02 14:43:59 +00001593 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001594
John McCall036f2f62011-05-15 07:14:44 +00001595 // Note that we do *not* convert the argument in any way. It can
1596 // be signed, larger than size_t, whatever.
Sebastian Redl351bb782008-12-02 14:43:59 +00001597 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00001598
Craig Topperc3ec1492014-05-26 06:22:03 +00001599 FunctionDecl *OperatorNew = nullptr;
1600 FunctionDecl *OperatorDelete = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001601
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001602 if (!AllocType->isDependentType() &&
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001603 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00001604 FindAllocationFunctions(StartLoc,
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001605 SourceRange(PlacementLParen, PlacementRParen),
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001606 UseGlobal, AllocType, ArraySize, PlacementArgs,
1607 OperatorNew, OperatorDelete))
Sebastian Redl6d4256c2009-03-15 17:47:39 +00001608 return ExprError();
John McCall284c48f2011-01-27 09:37:56 +00001609
1610 // If this is an array allocation, compute whether the usual array
1611 // deallocation function for the type has a size_t parameter.
1612 bool UsualArrayDeleteWantsSize = false;
1613 if (ArraySize && !AllocType->isDependentType())
1614 UsualArrayDeleteWantsSize
1615 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1616
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001617 SmallVector<Expr *, 8> AllPlaceArgs;
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001618 if (OperatorNew) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001619 const FunctionProtoType *Proto =
Richard Smithd6f9e732014-05-13 19:56:21 +00001620 OperatorNew->getType()->getAs<FunctionProtoType>();
1621 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1622 : VariadicDoesNotApply;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623
Richard Smithd6f9e732014-05-13 19:56:21 +00001624 // We've already converted the placement args, just fill in any default
1625 // arguments. Skip the first parameter because we don't have a corresponding
1626 // argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001627 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1628 PlacementArgs, AllPlaceArgs, CallType))
Fariborz Jahanian835026e2009-11-24 18:29:37 +00001629 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001630
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001631 if (!AllPlaceArgs.empty())
1632 PlacementArgs = AllPlaceArgs;
Eli Friedmanff4b4072012-02-18 04:48:30 +00001633
Richard Smithd6f9e732014-05-13 19:56:21 +00001634 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001635 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
Eli Friedmanff4b4072012-02-18 04:48:30 +00001636
1637 // FIXME: Missing call to CheckFunctionCall or equivalent
Fariborz Jahanian1eab66c2009-11-19 18:39:40 +00001638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001639
Nick Lewycky411fc652012-01-24 21:15:41 +00001640 // Warn if the type is over-aligned and is being allocated by global operator
1641 // new.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001642 if (PlacementArgs.empty() && OperatorNew &&
Nick Lewycky411fc652012-01-24 21:15:41 +00001643 (OperatorNew->isImplicit() ||
Pavel Labatha174d872016-03-04 10:00:08 +00001644 (OperatorNew->getLocStart().isValid() &&
1645 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
Nick Lewycky411fc652012-01-24 21:15:41 +00001646 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1647 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1648 if (Align > SuitableAlign)
1649 Diag(StartLoc, diag::warn_overaligned_type)
1650 << AllocType
1651 << unsigned(Align / Context.getCharWidth())
1652 << unsigned(SuitableAlign / Context.getCharWidth());
1653 }
1654 }
1655
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001656 QualType InitType = AllocType;
Sebastian Redl6047f072012-02-16 12:22:20 +00001657 // Array 'new' can't have any initializers except empty parentheses.
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001658 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1659 // dialect distinction.
1660 if (ResultType->isArrayType() || ArraySize) {
1661 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1662 SourceRange InitRange(Inits[0]->getLocStart(),
1663 Inits[NumInits - 1]->getLocEnd());
1664 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1665 return ExprError();
1666 }
1667 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1668 // We do the initialization typechecking against the array type
1669 // corresponding to the number of initializers + 1 (to also check
1670 // default-initialization).
1671 unsigned NumElements = ILE->getNumInits() + 1;
1672 InitType = Context.getConstantArrayType(AllocType,
1673 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1674 ArrayType::Normal, 0);
1675 }
Anders Carlssonc6bb0e12010-05-03 15:45:23 +00001676 }
1677
Richard Smithdd2ca572012-11-26 08:32:48 +00001678 // If we can perform the initialization, and we've not already done so,
1679 // do it now.
Douglas Gregor85dabae2009-12-16 01:38:02 +00001680 if (!AllocType->isDependentType() &&
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00001681 !Expr::hasAnyTypeDependentArguments(
Richard Smithc6abd962014-07-25 01:12:44 +00001682 llvm::makeArrayRef(Inits, NumInits))) {
Sebastian Redld74dd492012-02-12 18:41:05 +00001683 // C++11 [expr.new]p15:
Douglas Gregor85dabae2009-12-16 01:38:02 +00001684 // A new-expression that creates an object of type T initializes that
1685 // object as follows:
1686 InitializationKind Kind
1687 // - If the new-initializer is omitted, the object is default-
1688 // initialized (8.5); if no initialization is performed,
1689 // the object has indeterminate value
Sebastian Redl6047f072012-02-16 12:22:20 +00001690 = initStyle == CXXNewExpr::NoInit
1691 ? InitializationKind::CreateDefault(TypeRange.getBegin())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001692 // - Otherwise, the new-initializer is interpreted according to the
Douglas Gregor85dabae2009-12-16 01:38:02 +00001693 // initialization rules of 8.5 for direct-initialization.
Sebastian Redl6047f072012-02-16 12:22:20 +00001694 : initStyle == CXXNewExpr::ListInit
1695 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1696 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1697 DirectInitRange.getBegin(),
1698 DirectInitRange.getEnd());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699
Douglas Gregor85dabae2009-12-16 01:38:02 +00001700 InitializedEntity Entity
Sebastian Redlb8fc4772012-02-16 12:59:47 +00001701 = InitializedEntity::InitializeNew(StartLoc, InitType);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00001702 InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001703 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
Sebastian Redl6047f072012-02-16 12:22:20 +00001704 MultiExprArg(Inits, NumInits));
Douglas Gregor85dabae2009-12-16 01:38:02 +00001705 if (FullInit.isInvalid())
1706 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001707
Sebastian Redl6047f072012-02-16 12:22:20 +00001708 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1709 // we don't want the initialized object to be destructed.
1710 if (CXXBindTemporaryExpr *Binder =
1711 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001712 FullInit = Binder->getSubExpr();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001713
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001714 Initializer = FullInit.get();
Sebastian Redlbd150f42008-11-21 19:14:01 +00001715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001716
Douglas Gregor6642ca22010-02-26 05:06:18 +00001717 // Mark the new and delete operators as referenced.
Nick Lewyckya096b142013-02-12 08:08:54 +00001718 if (OperatorNew) {
Richard Smith22262ab2013-05-04 06:44:46 +00001719 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1720 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001721 MarkFunctionReferenced(StartLoc, OperatorNew);
Nick Lewyckya096b142013-02-12 08:08:54 +00001722 }
1723 if (OperatorDelete) {
Richard Smith22262ab2013-05-04 06:44:46 +00001724 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1725 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001726 MarkFunctionReferenced(StartLoc, OperatorDelete);
Nick Lewyckya096b142013-02-12 08:08:54 +00001727 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00001728
John McCall928a2572011-07-13 20:12:57 +00001729 // C++0x [expr.new]p17:
1730 // If the new expression creates an array of objects of class type,
1731 // access and ambiguity control are done for the destructor.
David Blaikie631a4862012-03-10 23:40:02 +00001732 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1733 if (ArraySize && !BaseAllocType->isDependentType()) {
1734 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1735 if (CXXDestructorDecl *dtor = LookupDestructor(
1736 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1737 MarkFunctionReferenced(StartLoc, dtor);
1738 CheckDestructorAccess(StartLoc, dtor,
1739 PDiag(diag::err_access_dtor)
1740 << BaseAllocType);
Richard Smith22262ab2013-05-04 06:44:46 +00001741 if (DiagnoseUseOfDecl(dtor, StartLoc))
1742 return ExprError();
David Blaikie631a4862012-03-10 23:40:02 +00001743 }
John McCall928a2572011-07-13 20:12:57 +00001744 }
1745 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001746
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001747 return new (Context)
1748 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
1749 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1750 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1751 Range, DirectInitRange);
Sebastian Redlbd150f42008-11-21 19:14:01 +00001752}
1753
Sebastian Redl6047f072012-02-16 12:22:20 +00001754/// \brief Checks that a type is suitable as the allocated type
Sebastian Redlbd150f42008-11-21 19:14:01 +00001755/// in a new-expression.
Douglas Gregord0fefba2009-05-21 00:00:09 +00001756bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00001757 SourceRange R) {
Sebastian Redlbd150f42008-11-21 19:14:01 +00001758 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1759 // abstract class type or array thereof.
Douglas Gregorac1fb652009-03-24 19:52:54 +00001760 if (AllocType->isFunctionType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001761 return Diag(Loc, diag::err_bad_new_type)
1762 << AllocType << 0 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001763 else if (AllocType->isReferenceType())
Douglas Gregord0fefba2009-05-21 00:00:09 +00001764 return Diag(Loc, diag::err_bad_new_type)
1765 << AllocType << 1 << R;
Douglas Gregorac1fb652009-03-24 19:52:54 +00001766 else if (!AllocType->isDependentType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001767 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
Sebastian Redlbd150f42008-11-21 19:14:01 +00001768 return true;
Douglas Gregord0fefba2009-05-21 00:00:09 +00001769 else if (RequireNonAbstractType(Loc, AllocType,
Douglas Gregorac1fb652009-03-24 19:52:54 +00001770 diag::err_allocation_of_abstract_type))
1771 return true;
Douglas Gregor3999e152010-10-06 16:00:31 +00001772 else if (AllocType->isVariablyModifiedType())
1773 return Diag(Loc, diag::err_variably_modified_new_type)
1774 << AllocType;
Douglas Gregor39d1a092011-04-15 19:46:20 +00001775 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1776 return Diag(Loc, diag::err_address_space_qualified_new)
1777 << AllocType.getUnqualifiedType() << AddressSpace;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001778 else if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +00001779 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1780 QualType BaseAllocType = Context.getBaseElementType(AT);
1781 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1782 BaseAllocType->isObjCLifetimeType())
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00001783 return Diag(Loc, diag::err_arc_new_array_without_ownership)
John McCall31168b02011-06-15 23:02:42 +00001784 << BaseAllocType;
1785 }
1786 }
Douglas Gregor39d1a092011-04-15 19:46:20 +00001787
Sebastian Redlbd150f42008-11-21 19:14:01 +00001788 return false;
1789}
1790
Douglas Gregor6642ca22010-02-26 05:06:18 +00001791/// \brief Determine whether the given function is a non-placement
1792/// deallocation function.
Richard Smith1cdec012013-09-29 04:40:38 +00001793static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001794 if (FD->isInvalidDecl())
1795 return false;
1796
1797 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1798 return Method->isUsualDeallocationFunction();
1799
Richard Smith1cdec012013-09-29 04:40:38 +00001800 if (FD->getOverloadedOperator() != OO_Delete &&
1801 FD->getOverloadedOperator() != OO_Array_Delete)
1802 return false;
1803
1804 if (FD->getNumParams() == 1)
1805 return true;
1806
1807 return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1808 S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1809 S.Context.getSizeType());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001810}
1811
Sebastian Redlfaf68082008-12-03 20:26:15 +00001812/// FindAllocationFunctions - Finds the overloads of operator new and delete
1813/// that are appropriate for the allocation.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00001814bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1815 bool UseGlobal, QualType AllocType,
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001816 bool IsArray, MultiExprArg PlaceArgs,
Sebastian Redlfaf68082008-12-03 20:26:15 +00001817 FunctionDecl *&OperatorNew,
Mike Stump11289f42009-09-09 15:08:12 +00001818 FunctionDecl *&OperatorDelete) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00001819 // --- Choosing an allocation function ---
1820 // C++ 5.3.4p8 - 14 & 18
1821 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1822 // in the scope of the allocated class.
1823 // 2) If an array size is given, look for operator new[], else look for
1824 // operator new.
1825 // 3) The first argument is always size_t. Append the arguments from the
1826 // placement form.
Sebastian Redlfaf68082008-12-03 20:26:15 +00001827
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001828 SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
Sebastian Redlfaf68082008-12-03 20:26:15 +00001829 // We don't care about the actual value of this argument.
1830 // FIXME: Should the Sema create the expression and embed it in the syntax
1831 // tree? Or should the consumer just recalculate the value?
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00001832 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
Douglas Gregore8bbc122011-09-02 00:18:52 +00001833 Context.getTargetInfo().getPointerWidth(0)),
Anders Carlssona471db02009-08-16 20:29:29 +00001834 Context.getSizeType(),
1835 SourceLocation());
1836 AllocArgs[0] = &Size;
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001837 std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
Sebastian Redlfaf68082008-12-03 20:26:15 +00001838
Douglas Gregor6642ca22010-02-26 05:06:18 +00001839 // C++ [expr.new]p8:
1840 // If the allocated type is a non-array type, the allocation
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001841 // function's name is operator new and the deallocation function's
Douglas Gregor6642ca22010-02-26 05:06:18 +00001842 // name is operator delete. If the allocated type is an array
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001843 // type, the allocation function's name is operator new[] and the
1844 // deallocation function's name is operator delete[].
Sebastian Redlfaf68082008-12-03 20:26:15 +00001845 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1846 IsArray ? OO_Array_New : OO_New);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001847 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1848 IsArray ? OO_Array_Delete : OO_Delete);
1849
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001850 QualType AllocElemType = Context.getBaseElementType(AllocType);
1851
1852 if (AllocElemType->isRecordType() && !UseGlobal) {
Mike Stump11289f42009-09-09 15:08:12 +00001853 CXXRecordDecl *Record
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001854 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001855 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1856 /*AllowMissing=*/true, OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001857 return true;
Sebastian Redlfaf68082008-12-03 20:26:15 +00001858 }
Aaron Ballman324fbee2013-05-30 01:55:39 +00001859
Sebastian Redlfaf68082008-12-03 20:26:15 +00001860 if (!OperatorNew) {
1861 // Didn't find a member overload. Look for a global one.
1862 DeclareGlobalNewDelete();
Sebastian Redl33a31012008-12-04 22:20:51 +00001863 DeclContext *TUDecl = Context.getTranslationUnitDecl();
Alp Tokerbfa39342014-01-14 12:51:41 +00001864 bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001865 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Aaron Ballman324fbee2013-05-30 01:55:39 +00001866 /*AllowMissing=*/FallbackEnabled, OperatorNew,
1867 /*Diagnose=*/!FallbackEnabled)) {
1868 if (!FallbackEnabled)
1869 return true;
1870
1871 // MSVC will fall back on trying to find a matching global operator new
1872 // if operator new[] cannot be found. Also, MSVC will leak by not
1873 // generating a call to operator delete or operator delete[], but we
1874 // will not replicate that bug.
1875 NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
1876 DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1877 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00001878 /*AllowMissing=*/false, OperatorNew))
Sebastian Redlfaf68082008-12-03 20:26:15 +00001879 return true;
Aaron Ballman324fbee2013-05-30 01:55:39 +00001880 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00001881 }
1882
John McCall0f55a032010-04-20 02:18:25 +00001883 // We don't need an operator delete if we're running under
1884 // -fno-exceptions.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001885 if (!getLangOpts().Exceptions) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001886 OperatorDelete = nullptr;
John McCall0f55a032010-04-20 02:18:25 +00001887 return false;
1888 }
1889
Douglas Gregor6642ca22010-02-26 05:06:18 +00001890 // C++ [expr.new]p19:
1891 //
1892 // If the new-expression begins with a unary :: operator, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001893 // deallocation function's name is looked up in the global
Douglas Gregor6642ca22010-02-26 05:06:18 +00001894 // scope. Otherwise, if the allocated type is a class type T or an
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001895 // array thereof, the deallocation function's name is looked up in
Douglas Gregor6642ca22010-02-26 05:06:18 +00001896 // the scope of T. If this lookup fails to find the name, or if
1897 // the allocated type is not a class type or array thereof, the
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00001898 // deallocation function's name is looked up in the global scope.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001899 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001900 if (AllocElemType->isRecordType() && !UseGlobal) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001901 CXXRecordDecl *RD
Argyrios Kyrtzidis1194d5e2010-08-25 23:14:56 +00001902 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
Douglas Gregor6642ca22010-02-26 05:06:18 +00001903 LookupQualifiedName(FoundDelete, RD);
1904 }
John McCallfb6f5262010-03-18 08:19:33 +00001905 if (FoundDelete.isAmbiguous())
1906 return true; // FIXME: clean up expressions?
Douglas Gregor6642ca22010-02-26 05:06:18 +00001907
1908 if (FoundDelete.empty()) {
1909 DeclareGlobalNewDelete();
1910 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
1911 }
1912
1913 FoundDelete.suppressDiagnostics();
John McCalla0296f72010-03-19 07:35:19 +00001914
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001915 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
John McCalla0296f72010-03-19 07:35:19 +00001916
John McCalld3be2c82010-09-14 21:34:24 +00001917 // Whether we're looking for a placement operator delete is dictated
1918 // by whether we selected a placement operator new, not by whether
1919 // we had explicit placement arguments. This matters for things like
1920 // struct A { void *operator new(size_t, int = 0); ... };
1921 // A *a = new A()
Dmitri Gribenkobe022102013-05-10 13:22:23 +00001922 bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
John McCalld3be2c82010-09-14 21:34:24 +00001923
1924 if (isPlacementNew) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00001925 // C++ [expr.new]p20:
1926 // A declaration of a placement deallocation function matches the
1927 // declaration of a placement allocation function if it has the
1928 // same number of parameters and, after parameter transformations
1929 // (8.3.5), all parameter types except the first are
1930 // identical. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001931 //
Douglas Gregor6642ca22010-02-26 05:06:18 +00001932 // To perform this comparison, we compute the function type that
1933 // the deallocation function should have, and use that type both
1934 // for template argument deduction and for comparison purposes.
John McCalldb40c7f2010-12-14 08:05:40 +00001935 //
1936 // FIXME: this comparison should ignore CC and the like.
Douglas Gregor6642ca22010-02-26 05:06:18 +00001937 QualType ExpectedFunctionType;
1938 {
1939 const FunctionProtoType *Proto
1940 = OperatorNew->getType()->getAs<FunctionProtoType>();
John McCalldb40c7f2010-12-14 08:05:40 +00001941
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001942 SmallVector<QualType, 4> ArgTypes;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943 ArgTypes.push_back(Context.VoidPtrTy);
Alp Toker9cacbab2014-01-20 20:26:09 +00001944 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
1945 ArgTypes.push_back(Proto->getParamType(I));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001946
John McCalldb40c7f2010-12-14 08:05:40 +00001947 FunctionProtoType::ExtProtoInfo EPI;
1948 EPI.Variadic = Proto->isVariadic();
1949
Douglas Gregor6642ca22010-02-26 05:06:18 +00001950 ExpectedFunctionType
Jordan Rose5c382722013-03-08 21:51:21 +00001951 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
Douglas Gregor6642ca22010-02-26 05:06:18 +00001952 }
1953
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001954 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001955 DEnd = FoundDelete.end();
1956 D != DEnd; ++D) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001957 FunctionDecl *Fn = nullptr;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001958 if (FunctionTemplateDecl *FnTmpl
Douglas Gregor6642ca22010-02-26 05:06:18 +00001959 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
1960 // Perform template argument deduction to try to match the
1961 // expected function type.
Craig Toppere6706e42012-09-19 02:26:47 +00001962 TemplateDeductionInfo Info(StartLoc);
Craig Topperc3ec1492014-05-26 06:22:03 +00001963 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
1964 Info))
Douglas Gregor6642ca22010-02-26 05:06:18 +00001965 continue;
1966 } else
1967 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
1968
1969 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
John McCalla0296f72010-03-19 07:35:19 +00001970 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001971 }
1972 } else {
1973 // C++ [expr.new]p20:
1974 // [...] Any non-placement deallocation function matches a
1975 // non-placement allocation function. [...]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001976 for (LookupResult::iterator D = FoundDelete.begin(),
Douglas Gregor6642ca22010-02-26 05:06:18 +00001977 DEnd = FoundDelete.end();
1978 D != DEnd; ++D) {
1979 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
Richard Smith1cdec012013-09-29 04:40:38 +00001980 if (isNonPlacementDeallocationFunction(*this, Fn))
John McCalla0296f72010-03-19 07:35:19 +00001981 Matches.push_back(std::make_pair(D.getPair(), Fn));
Douglas Gregor6642ca22010-02-26 05:06:18 +00001982 }
Richard Smith1cdec012013-09-29 04:40:38 +00001983
1984 // C++1y [expr.new]p22:
1985 // For a non-placement allocation function, the normal deallocation
1986 // function lookup is used
1987 // C++1y [expr.delete]p?:
1988 // If [...] deallocation function lookup finds both a usual deallocation
1989 // function with only a pointer parameter and a usual deallocation
1990 // function with both a pointer parameter and a size parameter, then the
1991 // selected deallocation function shall be the one with two parameters.
1992 // Otherwise, the selected deallocation function shall be the function
1993 // with one parameter.
1994 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
1995 if (Matches[0].second->getNumParams() == 1)
1996 Matches.erase(Matches.begin());
1997 else
1998 Matches.erase(Matches.begin() + 1);
1999 assert(Matches[0].second->getNumParams() == 2 &&
Richard Smith2eaf2062014-02-03 07:04:10 +00002000 "found an unexpected usual deallocation function");
Richard Smith1cdec012013-09-29 04:40:38 +00002001 }
Douglas Gregor6642ca22010-02-26 05:06:18 +00002002 }
2003
2004 // C++ [expr.new]p20:
2005 // [...] If the lookup finds a single matching deallocation
2006 // function, that function will be called; otherwise, no
2007 // deallocation function will be called.
2008 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00002009 OperatorDelete = Matches[0].second;
Douglas Gregor6642ca22010-02-26 05:06:18 +00002010
2011 // C++0x [expr.new]p20:
2012 // If the lookup finds the two-parameter form of a usual
2013 // deallocation function (3.7.4.2) and that function, considered
2014 // as a placement deallocation function, would have been
2015 // selected as a match for the allocation function, the program
2016 // is ill-formed.
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002017 if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
Richard Smith1cdec012013-09-29 04:40:38 +00002018 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
Douglas Gregor6642ca22010-02-26 05:06:18 +00002019 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
Dmitri Gribenkobe022102013-05-10 13:22:23 +00002020 << SourceRange(PlaceArgs.front()->getLocStart(),
2021 PlaceArgs.back()->getLocEnd());
Richard Smith1cdec012013-09-29 04:40:38 +00002022 if (!OperatorDelete->isImplicit())
2023 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2024 << DeleteName;
John McCallfb6f5262010-03-18 08:19:33 +00002025 } else {
2026 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
John McCalla0296f72010-03-19 07:35:19 +00002027 Matches[0].first);
Douglas Gregor6642ca22010-02-26 05:06:18 +00002028 }
2029 }
2030
Sebastian Redlfaf68082008-12-03 20:26:15 +00002031 return false;
2032}
2033
Richard Smithd6f9e732014-05-13 19:56:21 +00002034/// \brief Find an fitting overload for the allocation function
2035/// in the specified scope.
2036///
2037/// \param StartLoc The location of the 'new' token.
NAKAMURA Takumi5182b5a2014-05-14 08:07:56 +00002038/// \param Range The range of the placement arguments.
Richard Smithd6f9e732014-05-13 19:56:21 +00002039/// \param Name The name of the function ('operator new' or 'operator new[]').
2040/// \param Args The placement arguments specified.
2041/// \param Ctx The scope in which we should search; either a class scope or the
2042/// translation unit.
2043/// \param AllowMissing If \c true, report an error if we can't find any
2044/// allocation functions. Otherwise, succeed but don't fill in \p
2045/// Operator.
2046/// \param Operator Filled in with the found allocation function. Unchanged if
2047/// no allocation function was found.
2048/// \param Diagnose If \c true, issue errors if the allocation function is not
2049/// usable.
Sebastian Redl1df2bbe2009-02-09 18:24:27 +00002050bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00002051 DeclarationName Name, MultiExprArg Args,
2052 DeclContext *Ctx,
Alexis Hunt1f69a022011-05-12 22:46:29 +00002053 bool AllowMissing, FunctionDecl *&Operator,
2054 bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002055 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
2056 LookupQualifiedName(R, Ctx);
John McCall9f3059a2009-10-09 21:13:30 +00002057 if (R.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002058 if (AllowMissing || !Diagnose)
Sebastian Redl33a31012008-12-04 22:20:51 +00002059 return false;
Sebastian Redl33a31012008-12-04 22:20:51 +00002060 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00002061 << Name << Range;
Sebastian Redl33a31012008-12-04 22:20:51 +00002062 }
2063
John McCallfb6f5262010-03-18 08:19:33 +00002064 if (R.isAmbiguous())
2065 return true;
2066
2067 R.suppressDiagnostics();
John McCall9f3059a2009-10-09 21:13:30 +00002068
Richard Smith100b24a2014-04-17 01:52:14 +00002069 OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002070 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
Douglas Gregor80a6cc52009-09-30 00:03:47 +00002071 Alloc != AllocEnd; ++Alloc) {
Douglas Gregor55297ac2008-12-23 00:26:44 +00002072 // Even member operator new/delete are implicitly treated as
2073 // static, so don't use AddMemberCandidate.
John McCalla0296f72010-03-19 07:35:19 +00002074 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
Chandler Carruth93538422010-02-03 11:02:14 +00002075
John McCalla0296f72010-03-19 07:35:19 +00002076 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2077 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002078 /*ExplicitTemplateArgs=*/nullptr,
Dmitri Gribenko08c86682013-05-10 00:20:06 +00002079 Args, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00002080 /*SuppressUserConversions=*/false);
Douglas Gregorbb3e12f2009-09-29 18:16:17 +00002081 continue;
Chandler Carruth93538422010-02-03 11:02:14 +00002082 }
2083
John McCalla0296f72010-03-19 07:35:19 +00002084 FunctionDecl *Fn = cast<FunctionDecl>(D);
Dmitri Gribenko08c86682013-05-10 00:20:06 +00002085 AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
Chandler Carruth93538422010-02-03 11:02:14 +00002086 /*SuppressUserConversions=*/false);
Sebastian Redl33a31012008-12-04 22:20:51 +00002087 }
2088
2089 // Do the resolution.
2090 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00002091 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
Sebastian Redl33a31012008-12-04 22:20:51 +00002092 case OR_Success: {
2093 // Got one!
2094 FunctionDecl *FnDecl = Best->Function;
Richard Smith921bd202012-02-26 09:11:52 +00002095 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
2096 Best->FoundDecl, Diagnose) == AR_inaccessible)
2097 return true;
2098
Richard Smithd6f9e732014-05-13 19:56:21 +00002099 Operator = FnDecl;
Sebastian Redl33a31012008-12-04 22:20:51 +00002100 return false;
2101 }
2102
2103 case OR_No_Viable_Function:
Chandler Carruthe6c88182011-06-08 10:26:03 +00002104 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002105 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
2106 << Name << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00002107 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00002108 }
Sebastian Redl33a31012008-12-04 22:20:51 +00002109 return true;
2110
2111 case OR_Ambiguous:
Chandler Carruthe6c88182011-06-08 10:26:03 +00002112 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002113 Diag(StartLoc, diag::err_ovl_ambiguous_call)
2114 << Name << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00002115 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00002116 }
Sebastian Redl33a31012008-12-04 22:20:51 +00002117 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002118
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002119 case OR_Deleted: {
Chandler Carruthe6c88182011-06-08 10:26:03 +00002120 if (Diagnose) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002121 Diag(StartLoc, diag::err_ovl_deleted_call)
2122 << Best->Function->isDeleted()
2123 << Name
2124 << getDeletedOrUnavailableSuffix(Best->Function)
2125 << Range;
Dmitri Gribenko08c86682013-05-10 00:20:06 +00002126 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
Chandler Carruthe6c88182011-06-08 10:26:03 +00002127 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00002128 return true;
Sebastian Redl33a31012008-12-04 22:20:51 +00002129 }
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00002130 }
David Blaikie83d382b2011-09-23 05:06:16 +00002131 llvm_unreachable("Unreachable, bad result from BestViableFunction");
Sebastian Redl33a31012008-12-04 22:20:51 +00002132}
2133
2134
Sebastian Redlfaf68082008-12-03 20:26:15 +00002135/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2136/// delete. These are:
2137/// @code
Sebastian Redl37588092011-03-14 18:08:30 +00002138/// // C++03:
Sebastian Redlfaf68082008-12-03 20:26:15 +00002139/// void* operator new(std::size_t) throw(std::bad_alloc);
2140/// void* operator new[](std::size_t) throw(std::bad_alloc);
2141/// void operator delete(void *) throw();
2142/// void operator delete[](void *) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002143/// // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002144/// void* operator new(std::size_t);
2145/// void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002146/// void operator delete(void *) noexcept;
2147/// void operator delete[](void *) noexcept;
2148/// // C++1y:
2149/// void* operator new(std::size_t);
2150/// void* operator new[](std::size_t);
2151/// void operator delete(void *) noexcept;
2152/// void operator delete[](void *) noexcept;
2153/// void operator delete(void *, std::size_t) noexcept;
2154/// void operator delete[](void *, std::size_t) noexcept;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002155/// @endcode
2156/// Note that the placement and nothrow forms of new are *not* implicitly
2157/// declared. Their use requires including \<new\>.
Mike Stump11289f42009-09-09 15:08:12 +00002158void Sema::DeclareGlobalNewDelete() {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002159 if (GlobalNewDeleteDeclared)
2160 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002161
Douglas Gregor87f54062009-09-15 22:30:29 +00002162 // C++ [basic.std.dynamic]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002163 // [...] The following allocation and deallocation functions (18.4) are
2164 // implicitly declared in global scope in each translation unit of a
Douglas Gregor87f54062009-09-15 22:30:29 +00002165 // program
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002166 //
Sebastian Redl37588092011-03-14 18:08:30 +00002167 // C++03:
Douglas Gregor87f54062009-09-15 22:30:29 +00002168 // void* operator new(std::size_t) throw(std::bad_alloc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002169 // void* operator new[](std::size_t) throw(std::bad_alloc);
2170 // void operator delete(void*) throw();
Douglas Gregor87f54062009-09-15 22:30:29 +00002171 // void operator delete[](void*) throw();
Richard Smith1cdec012013-09-29 04:40:38 +00002172 // C++11:
Sebastian Redl37588092011-03-14 18:08:30 +00002173 // void* operator new(std::size_t);
2174 // void* operator new[](std::size_t);
Richard Smith1cdec012013-09-29 04:40:38 +00002175 // void operator delete(void*) noexcept;
2176 // void operator delete[](void*) noexcept;
2177 // C++1y:
2178 // void* operator new(std::size_t);
2179 // void* operator new[](std::size_t);
2180 // void operator delete(void*) noexcept;
2181 // void operator delete[](void*) noexcept;
2182 // void operator delete(void*, std::size_t) noexcept;
2183 // void operator delete[](void*, std::size_t) noexcept;
Douglas Gregor87f54062009-09-15 22:30:29 +00002184 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002185 // These implicit declarations introduce only the function names operator
Douglas Gregor87f54062009-09-15 22:30:29 +00002186 // new, operator new[], operator delete, operator delete[].
2187 //
2188 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2189 // "std" or "bad_alloc" as necessary to form the exception specification.
2190 // However, we do not make these implicit declarations visible to name
2191 // lookup.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002192 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
Douglas Gregor87f54062009-09-15 22:30:29 +00002193 // The "std::bad_alloc" class has not yet been declared, so build it
2194 // implicitly.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002195 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2196 getOrCreateStdNamespace(),
Abramo Bagnara29c2d462011-03-09 14:09:51 +00002197 SourceLocation(), SourceLocation(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002198 &PP.getIdentifierTable().get("bad_alloc"),
Craig Topperc3ec1492014-05-26 06:22:03 +00002199 nullptr);
Argyrios Kyrtzidis2d688102010-08-02 07:14:54 +00002200 getStdBadAlloc()->setImplicit(true);
Douglas Gregor87f54062009-09-15 22:30:29 +00002201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202
Sebastian Redlfaf68082008-12-03 20:26:15 +00002203 GlobalNewDeleteDeclared = true;
2204
2205 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2206 QualType SizeT = Context.getSizeType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002207 bool AssumeSaneOperatorNew = getLangOpts().AssumeSaneOperatorNew;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002208
Sebastian Redlfaf68082008-12-03 20:26:15 +00002209 DeclareGlobalAllocationFunction(
2210 Context.DeclarationNames.getCXXOperatorName(OO_New),
Richard Smith1cdec012013-09-29 04:40:38 +00002211 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002212 DeclareGlobalAllocationFunction(
2213 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
Richard Smith1cdec012013-09-29 04:40:38 +00002214 VoidPtr, SizeT, QualType(), AssumeSaneOperatorNew);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002215 DeclareGlobalAllocationFunction(
2216 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2217 Context.VoidTy, VoidPtr);
2218 DeclareGlobalAllocationFunction(
2219 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2220 Context.VoidTy, VoidPtr);
Richard Smith1cdec012013-09-29 04:40:38 +00002221 if (getLangOpts().SizedDeallocation) {
2222 DeclareGlobalAllocationFunction(
2223 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2224 Context.VoidTy, VoidPtr, Context.getSizeType());
2225 DeclareGlobalAllocationFunction(
2226 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2227 Context.VoidTy, VoidPtr, Context.getSizeType());
2228 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002229}
2230
2231/// DeclareGlobalAllocationFunction - Declares a single implicit global
2232/// allocation function if it doesn't already exist.
2233void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
Richard Smith1cdec012013-09-29 04:40:38 +00002234 QualType Return,
2235 QualType Param1, QualType Param2,
David Majnemer631a90b2015-02-04 07:23:21 +00002236 bool AddRestrictAttr) {
Sebastian Redlfaf68082008-12-03 20:26:15 +00002237 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
Richard Smith1cdec012013-09-29 04:40:38 +00002238 unsigned NumParams = Param2.isNull() ? 1 : 2;
Sebastian Redlfaf68082008-12-03 20:26:15 +00002239
2240 // Check if this function is already declared.
Serge Pavlovd5489072013-09-14 12:00:01 +00002241 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2242 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2243 Alloc != AllocEnd; ++Alloc) {
2244 // Only look at non-template functions, as it is the predefined,
2245 // non-templated allocation function we are trying to declare here.
2246 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
Richard Smith1cdec012013-09-29 04:40:38 +00002247 if (Func->getNumParams() == NumParams) {
2248 QualType InitialParam1Type =
2249 Context.getCanonicalType(Func->getParamDecl(0)
2250 ->getType().getUnqualifiedType());
2251 QualType InitialParam2Type =
2252 NumParams == 2
2253 ? Context.getCanonicalType(Func->getParamDecl(1)
2254 ->getType().getUnqualifiedType())
2255 : QualType();
Chandler Carruth93538422010-02-03 11:02:14 +00002256 // FIXME: Do we need to check for default arguments here?
Richard Smith1cdec012013-09-29 04:40:38 +00002257 if (InitialParam1Type == Param1 &&
2258 (NumParams == 1 || InitialParam2Type == Param2)) {
David Majnemer631a90b2015-02-04 07:23:21 +00002259 if (AddRestrictAttr && !Func->hasAttr<RestrictAttr>())
2260 Func->addAttr(RestrictAttr::CreateImplicit(
2261 Context, RestrictAttr::GNU_malloc));
Serge Pavlovd5489072013-09-14 12:00:01 +00002262 // Make the function visible to name lookup, even if we found it in
2263 // an unimported module. It either is an implicitly-declared global
Richard Smith42713d72013-07-14 02:01:48 +00002264 // allocation function, or is suppressing that function.
2265 Func->setHidden(false);
Chandler Carruth93538422010-02-03 11:02:14 +00002266 return;
Douglas Gregorc1a42fd2010-08-18 15:06:25 +00002267 }
Chandler Carruth93538422010-02-03 11:02:14 +00002268 }
Sebastian Redlfaf68082008-12-03 20:26:15 +00002269 }
2270 }
Reid Kleckner7270ef52015-03-19 17:03:58 +00002271
Richard Smithc015bc22014-02-07 22:39:53 +00002272 FunctionProtoType::ExtProtoInfo EPI;
2273
Richard Smithf8b417c2014-02-08 00:42:45 +00002274 QualType BadAllocType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002275 bool HasBadAllocExceptionSpec
Douglas Gregor87f54062009-09-15 22:30:29 +00002276 = (Name.getCXXOverloadedOperator() == OO_New ||
2277 Name.getCXXOverloadedOperator() == OO_Array_New);
John McCalldb40c7f2010-12-14 08:05:40 +00002278 if (HasBadAllocExceptionSpec) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002279 if (!getLangOpts().CPlusPlus11) {
Richard Smithf8b417c2014-02-08 00:42:45 +00002280 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
Richard Smithc015bc22014-02-07 22:39:53 +00002281 assert(StdBadAlloc && "Must have std::bad_alloc declared");
Richard Smith8acb4282014-07-31 21:57:55 +00002282 EPI.ExceptionSpec.Type = EST_Dynamic;
2283 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
Sebastian Redl37588092011-03-14 18:08:30 +00002284 }
Sebastian Redlfa453cf2011-03-12 11:50:43 +00002285 } else {
Richard Smith8acb4282014-07-31 21:57:55 +00002286 EPI.ExceptionSpec =
2287 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
John McCalldb40c7f2010-12-14 08:05:40 +00002288 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002289
Richard Smith1cdec012013-09-29 04:40:38 +00002290 QualType Params[] = { Param1, Param2 };
2291
2292 QualType FnType = Context.getFunctionType(
Craig Topper5fc8fc22014-08-27 06:28:36 +00002293 Return, llvm::makeArrayRef(Params, NumParams), EPI);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002294 FunctionDecl *Alloc =
Abramo Bagnaradff19302011-03-08 08:55:46 +00002295 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2296 SourceLocation(), Name,
Craig Topperc3ec1492014-05-26 06:22:03 +00002297 FnType, /*TInfo=*/nullptr, SC_None, false, true);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002298 Alloc->setImplicit();
Larisse Voufo404e1422015-02-04 02:34:32 +00002299
2300 // Implicit sized deallocation functions always have default visibility.
2301 Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
2302 VisibilityAttr::Default));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002303
David Majnemer631a90b2015-02-04 07:23:21 +00002304 if (AddRestrictAttr)
2305 Alloc->addAttr(
2306 RestrictAttr::CreateImplicit(Context, RestrictAttr::GNU_malloc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Richard Smith1cdec012013-09-29 04:40:38 +00002308 ParmVarDecl *ParamDecls[2];
Richard Smithbdd14642014-02-04 01:14:30 +00002309 for (unsigned I = 0; I != NumParams; ++I) {
Richard Smith1cdec012013-09-29 04:40:38 +00002310 ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
Craig Topperc3ec1492014-05-26 06:22:03 +00002311 SourceLocation(), nullptr,
2312 Params[I], /*TInfo=*/nullptr,
2313 SC_None, nullptr);
Richard Smithbdd14642014-02-04 01:14:30 +00002314 ParamDecls[I]->setImplicit();
2315 }
Craig Topper5fc8fc22014-08-27 06:28:36 +00002316 Alloc->setParams(llvm::makeArrayRef(ParamDecls, NumParams));
Sebastian Redlfaf68082008-12-03 20:26:15 +00002317
John McCallcc14d1f2010-08-24 08:50:51 +00002318 Context.getTranslationUnitDecl()->addDecl(Alloc);
Richard Smithdebcd502014-05-16 02:14:42 +00002319 IdResolver.tryAddTopLevelDecl(Alloc, Name);
Sebastian Redlfaf68082008-12-03 20:26:15 +00002320}
2321
Richard Smith1cdec012013-09-29 04:40:38 +00002322FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2323 bool CanProvideSize,
2324 DeclarationName Name) {
2325 DeclareGlobalNewDelete();
2326
2327 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2328 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2329
2330 // C++ [expr.new]p20:
2331 // [...] Any non-placement deallocation function matches a
2332 // non-placement allocation function. [...]
2333 llvm::SmallVector<FunctionDecl*, 2> Matches;
2334 for (LookupResult::iterator D = FoundDelete.begin(),
2335 DEnd = FoundDelete.end();
2336 D != DEnd; ++D) {
2337 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2338 if (isNonPlacementDeallocationFunction(*this, Fn))
2339 Matches.push_back(Fn);
2340 }
2341
2342 // C++1y [expr.delete]p?:
2343 // If the type is complete and deallocation function lookup finds both a
2344 // usual deallocation function with only a pointer parameter and a usual
2345 // deallocation function with both a pointer parameter and a size
2346 // parameter, then the selected deallocation function shall be the one
2347 // with two parameters. Otherwise, the selected deallocation function
2348 // shall be the function with one parameter.
2349 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2350 unsigned NumArgs = CanProvideSize ? 2 : 1;
2351 if (Matches[0]->getNumParams() != NumArgs)
2352 Matches.erase(Matches.begin());
2353 else
2354 Matches.erase(Matches.begin() + 1);
2355 assert(Matches[0]->getNumParams() == NumArgs &&
Richard Smith2eaf2062014-02-03 07:04:10 +00002356 "found an unexpected usual deallocation function");
Richard Smith1cdec012013-09-29 04:40:38 +00002357 }
2358
Artem Belevich94a55e82015-09-22 17:22:59 +00002359 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads)
2360 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2361
Richard Smith1cdec012013-09-29 04:40:38 +00002362 assert(Matches.size() == 1 &&
2363 "unexpectedly have multiple usual deallocation functions");
2364 return Matches.front();
2365}
2366
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002367bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2368 DeclarationName Name,
Alexis Hunt1f69a022011-05-12 22:46:29 +00002369 FunctionDecl* &Operator, bool Diagnose) {
John McCall27b18f82009-11-17 02:14:36 +00002370 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002371 // Try to find operator delete/operator delete[] in class scope.
John McCall27b18f82009-11-17 02:14:36 +00002372 LookupQualifiedName(Found, RD);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002373
John McCall27b18f82009-11-17 02:14:36 +00002374 if (Found.isAmbiguous())
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002375 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002376
Chandler Carruthb6f99172010-06-28 00:30:51 +00002377 Found.suppressDiagnostics();
2378
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002379 SmallVector<DeclAccessPair,4> Matches;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002380 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2381 F != FEnd; ++F) {
Chandler Carruth9b418232010-08-08 07:04:00 +00002382 NamedDecl *ND = (*F)->getUnderlyingDecl();
2383
2384 // Ignore template operator delete members from the check for a usual
2385 // deallocation function.
2386 if (isa<FunctionTemplateDecl>(ND))
2387 continue;
2388
2389 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
John McCall66a87592010-08-04 00:31:26 +00002390 Matches.push_back(F.getPair());
2391 }
2392
Artem Belevich94a55e82015-09-22 17:22:59 +00002393 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads)
2394 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2395
John McCall66a87592010-08-04 00:31:26 +00002396 // There's exactly one suitable operator; pick it.
2397 if (Matches.size() == 1) {
2398 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
Alexis Hunt1f69a022011-05-12 22:46:29 +00002399
2400 if (Operator->isDeleted()) {
2401 if (Diagnose) {
2402 Diag(StartLoc, diag::err_deleted_function_use);
Richard Smith852265f2012-03-30 20:53:28 +00002403 NoteDeletedFunction(Operator);
Alexis Hunt1f69a022011-05-12 22:46:29 +00002404 }
2405 return true;
2406 }
2407
Richard Smith921bd202012-02-26 09:11:52 +00002408 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2409 Matches[0], Diagnose) == AR_inaccessible)
2410 return true;
2411
John McCall66a87592010-08-04 00:31:26 +00002412 return false;
2413
2414 // We found multiple suitable operators; complain about the ambiguity.
2415 } else if (!Matches.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002416 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002417 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2418 << Name << RD;
John McCall66a87592010-08-04 00:31:26 +00002419
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002420 for (SmallVectorImpl<DeclAccessPair>::iterator
Alexis Huntf91729462011-05-12 22:46:25 +00002421 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2422 Diag((*F)->getUnderlyingDecl()->getLocation(),
2423 diag::note_member_declared_here) << Name;
2424 }
John McCall66a87592010-08-04 00:31:26 +00002425 return true;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002426 }
2427
2428 // We did find operator delete/operator delete[] declarations, but
2429 // none of them were suitable.
2430 if (!Found.empty()) {
Alexis Hunt1f69a022011-05-12 22:46:29 +00002431 if (Diagnose) {
Alexis Huntf91729462011-05-12 22:46:25 +00002432 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2433 << Name << RD;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002434
Alexis Huntf91729462011-05-12 22:46:25 +00002435 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2436 F != FEnd; ++F)
2437 Diag((*F)->getUnderlyingDecl()->getLocation(),
2438 diag::note_member_declared_here) << Name;
2439 }
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002440 return true;
2441 }
2442
Craig Topperc3ec1492014-05-26 06:22:03 +00002443 Operator = nullptr;
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002444 return false;
2445}
2446
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002447namespace {
2448/// \brief Checks whether delete-expression, and new-expression used for
2449/// initializing deletee have the same array form.
2450class MismatchingNewDeleteDetector {
2451public:
2452 enum MismatchResult {
2453 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2454 NoMismatch,
2455 /// Indicates that variable is initialized with mismatching form of \a new.
2456 VarInitMismatches,
2457 /// Indicates that member is initialized with mismatching form of \a new.
2458 MemberInitMismatches,
2459 /// Indicates that 1 or more constructors' definitions could not been
2460 /// analyzed, and they will be checked again at the end of translation unit.
2461 AnalyzeLater
2462 };
2463
2464 /// \param EndOfTU True, if this is the final analysis at the end of
2465 /// translation unit. False, if this is the initial analysis at the point
2466 /// delete-expression was encountered.
2467 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2468 : IsArrayForm(false), Field(nullptr), EndOfTU(EndOfTU),
2469 HasUndefinedConstructors(false) {}
2470
2471 /// \brief Checks whether pointee of a delete-expression is initialized with
2472 /// matching form of new-expression.
2473 ///
2474 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2475 /// point where delete-expression is encountered, then a warning will be
2476 /// issued immediately. If return value is \c AnalyzeLater at the point where
2477 /// delete-expression is seen, then member will be analyzed at the end of
2478 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2479 /// couldn't be analyzed. If at least one constructor initializes the member
2480 /// with matching type of new, the return value is \c NoMismatch.
2481 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2482 /// \brief Analyzes a class member.
2483 /// \param Field Class member to analyze.
2484 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2485 /// for deleting the \p Field.
2486 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2487 /// List of mismatching new-expressions used for initialization of the pointee
2488 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2489 /// Indicates whether delete-expression was in array form.
2490 bool IsArrayForm;
2491 FieldDecl *Field;
2492
2493private:
2494 const bool EndOfTU;
2495 /// \brief Indicates that there is at least one constructor without body.
2496 bool HasUndefinedConstructors;
2497 /// \brief Returns \c CXXNewExpr from given initialization expression.
2498 /// \param E Expression used for initializing pointee in delete-expression.
NAKAMURA Takumi4bd67d82015-05-19 06:47:23 +00002499 /// E can be a single-element \c InitListExpr consisting of new-expression.
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002500 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2501 /// \brief Returns whether member is initialized with mismatching form of
2502 /// \c new either by the member initializer or in-class initialization.
2503 ///
2504 /// If bodies of all constructors are not visible at the end of translation
2505 /// unit or at least one constructor initializes member with the matching
2506 /// form of \c new, mismatch cannot be proven, and this function will return
2507 /// \c NoMismatch.
2508 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2509 /// \brief Returns whether variable is initialized with mismatching form of
2510 /// \c new.
2511 ///
2512 /// If variable is initialized with matching form of \c new or variable is not
2513 /// initialized with a \c new expression, this function will return true.
2514 /// If variable is initialized with mismatching form of \c new, returns false.
2515 /// \param D Variable to analyze.
2516 bool hasMatchingVarInit(const DeclRefExpr *D);
2517 /// \brief Checks whether the constructor initializes pointee with mismatching
2518 /// form of \c new.
2519 ///
2520 /// Returns true, if member is initialized with matching form of \c new in
2521 /// member initializer list. Returns false, if member is initialized with the
2522 /// matching form of \c new in this constructor's initializer or given
2523 /// constructor isn't defined at the point where delete-expression is seen, or
2524 /// member isn't initialized by the constructor.
2525 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2526 /// \brief Checks whether member is initialized with matching form of
2527 /// \c new in member initializer list.
2528 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2529 /// Checks whether member is initialized with mismatching form of \c new by
2530 /// in-class initializer.
2531 MismatchResult analyzeInClassInitializer();
2532};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002533}
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002534
2535MismatchingNewDeleteDetector::MismatchResult
2536MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2537 NewExprs.clear();
2538 assert(DE && "Expected delete-expression");
2539 IsArrayForm = DE->isArrayForm();
2540 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2541 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2542 return analyzeMemberExpr(ME);
2543 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2544 if (!hasMatchingVarInit(D))
2545 return VarInitMismatches;
2546 }
2547 return NoMismatch;
2548}
2549
2550const CXXNewExpr *
2551MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2552 assert(E != nullptr && "Expected a valid initializer expression");
2553 E = E->IgnoreParenImpCasts();
2554 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2555 if (ILE->getNumInits() == 1)
2556 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2557 }
2558
2559 return dyn_cast_or_null<const CXXNewExpr>(E);
2560}
2561
2562bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2563 const CXXCtorInitializer *CI) {
2564 const CXXNewExpr *NE = nullptr;
2565 if (Field == CI->getMember() &&
2566 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2567 if (NE->isArray() == IsArrayForm)
2568 return true;
2569 else
2570 NewExprs.push_back(NE);
2571 }
2572 return false;
2573}
2574
2575bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2576 const CXXConstructorDecl *CD) {
2577 if (CD->isImplicit())
2578 return false;
2579 const FunctionDecl *Definition = CD;
2580 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2581 HasUndefinedConstructors = true;
2582 return EndOfTU;
2583 }
2584 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2585 if (hasMatchingNewInCtorInit(CI))
2586 return true;
2587 }
2588 return false;
2589}
2590
2591MismatchingNewDeleteDetector::MismatchResult
2592MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2593 assert(Field != nullptr && "This should be called only for members");
Ismail Pazarbasi7ff18362015-10-26 19:20:24 +00002594 const Expr *InitExpr = Field->getInClassInitializer();
2595 if (!InitExpr)
2596 return EndOfTU ? NoMismatch : AnalyzeLater;
2597 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002598 if (NE->isArray() != IsArrayForm) {
2599 NewExprs.push_back(NE);
2600 return MemberInitMismatches;
2601 }
2602 }
2603 return NoMismatch;
2604}
2605
2606MismatchingNewDeleteDetector::MismatchResult
2607MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2608 bool DeleteWasArrayForm) {
2609 assert(Field != nullptr && "Analysis requires a valid class member.");
2610 this->Field = Field;
2611 IsArrayForm = DeleteWasArrayForm;
2612 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2613 for (const auto *CD : RD->ctors()) {
2614 if (hasMatchingNewInCtor(CD))
2615 return NoMismatch;
2616 }
2617 if (HasUndefinedConstructors)
2618 return EndOfTU ? NoMismatch : AnalyzeLater;
2619 if (!NewExprs.empty())
2620 return MemberInitMismatches;
2621 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2622 : NoMismatch;
2623}
2624
2625MismatchingNewDeleteDetector::MismatchResult
2626MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2627 assert(ME != nullptr && "Expected a member expression");
2628 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2629 return analyzeField(F, IsArrayForm);
2630 return NoMismatch;
2631}
2632
2633bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2634 const CXXNewExpr *NE = nullptr;
2635 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2636 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2637 NE->isArray() != IsArrayForm) {
2638 NewExprs.push_back(NE);
2639 }
2640 }
2641 return NewExprs.empty();
2642}
2643
2644static void
2645DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2646 const MismatchingNewDeleteDetector &Detector) {
2647 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2648 FixItHint H;
2649 if (!Detector.IsArrayForm)
2650 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2651 else {
2652 SourceLocation RSquare = Lexer::findLocationAfterToken(
2653 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2654 SemaRef.getLangOpts(), true);
2655 if (RSquare.isValid())
2656 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2657 }
2658 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2659 << Detector.IsArrayForm << H;
2660
2661 for (const auto *NE : Detector.NewExprs)
2662 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2663 << Detector.IsArrayForm;
2664}
2665
2666void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2667 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2668 return;
2669 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2670 switch (Detector.analyzeDeleteExpr(DE)) {
2671 case MismatchingNewDeleteDetector::VarInitMismatches:
2672 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2673 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2674 break;
2675 }
2676 case MismatchingNewDeleteDetector::AnalyzeLater: {
2677 DeleteExprs[Detector.Field].push_back(
2678 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2679 break;
2680 }
2681 case MismatchingNewDeleteDetector::NoMismatch:
2682 break;
2683 }
2684}
2685
2686void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2687 bool DeleteWasArrayForm) {
2688 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2689 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2690 case MismatchingNewDeleteDetector::VarInitMismatches:
2691 llvm_unreachable("This analysis should have been done for class members.");
2692 case MismatchingNewDeleteDetector::AnalyzeLater:
2693 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
2694 "translation unit.");
2695 case MismatchingNewDeleteDetector::MemberInitMismatches:
2696 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
2697 break;
2698 case MismatchingNewDeleteDetector::NoMismatch:
2699 break;
2700 }
2701}
2702
Sebastian Redlbd150f42008-11-21 19:14:01 +00002703/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2704/// @code ::delete ptr; @endcode
2705/// or
2706/// @code delete [] ptr; @endcode
John McCalldadc5752010-08-24 06:29:42 +00002707ExprResult
Sebastian Redlbd150f42008-11-21 19:14:01 +00002708Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
John Wiegley01296292011-04-08 18:41:53 +00002709 bool ArrayForm, Expr *ExE) {
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002710 // C++ [expr.delete]p1:
2711 // The operand shall have a pointer type, or a class type having a single
Richard Smithccc11812013-05-21 19:05:48 +00002712 // non-explicit conversion function to a pointer type. The result has type
2713 // void.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002714 //
Sebastian Redlbd150f42008-11-21 19:14:01 +00002715 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2716
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002717 ExprResult Ex = ExE;
Craig Topperc3ec1492014-05-26 06:22:03 +00002718 FunctionDecl *OperatorDelete = nullptr;
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002719 bool ArrayFormAsWritten = ArrayForm;
John McCall284c48f2011-01-27 09:37:56 +00002720 bool UsualArrayDeleteWantsSize = false;
Mike Stump11289f42009-09-09 15:08:12 +00002721
John Wiegley01296292011-04-08 18:41:53 +00002722 if (!Ex.get()->isTypeDependent()) {
John McCallef429022012-03-09 04:08:29 +00002723 // Perform lvalue-to-rvalue cast, if needed.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002724 Ex = DefaultLvalueConversion(Ex.get());
Eli Friedman89a4a2c2012-12-13 00:37:17 +00002725 if (Ex.isInvalid())
2726 return ExprError();
John McCallef429022012-03-09 04:08:29 +00002727
John Wiegley01296292011-04-08 18:41:53 +00002728 QualType Type = Ex.get()->getType();
Sebastian Redlbd150f42008-11-21 19:14:01 +00002729
Richard Smithccc11812013-05-21 19:05:48 +00002730 class DeleteConverter : public ContextualImplicitConverter {
2731 public:
2732 DeleteConverter() : ContextualImplicitConverter(false, true) {}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002733
Craig Toppere14c0f82014-03-12 04:55:44 +00002734 bool match(QualType ConvType) override {
Richard Smithccc11812013-05-21 19:05:48 +00002735 // FIXME: If we have an operator T* and an operator void*, we must pick
2736 // the operator T*.
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002737 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
Eli Friedmana170cd62010-08-05 02:49:48 +00002738 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
Richard Smithccc11812013-05-21 19:05:48 +00002739 return true;
2740 return false;
Douglas Gregor0fea62d2009-09-09 23:39:55 +00002741 }
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002742
Richard Smithccc11812013-05-21 19:05:48 +00002743 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002744 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00002745 return S.Diag(Loc, diag::err_delete_operand) << T;
2746 }
2747
2748 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002749 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00002750 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2751 }
2752
2753 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002754 QualType T,
2755 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002756 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2757 }
2758
2759 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00002760 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002761 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2762 << ConvTy;
2763 }
2764
2765 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002766 QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00002767 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2768 }
2769
2770 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
Craig Toppere14c0f82014-03-12 04:55:44 +00002771 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002772 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2773 << ConvTy;
2774 }
2775
2776 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00002777 QualType T,
2778 QualType ConvTy) override {
Richard Smithccc11812013-05-21 19:05:48 +00002779 llvm_unreachable("conversion functions are permitted");
2780 }
2781 } Converter;
2782
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002783 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
Richard Smithccc11812013-05-21 19:05:48 +00002784 if (Ex.isInvalid())
2785 return ExprError();
2786 Type = Ex.get()->getType();
2787 if (!Converter.match(Type))
2788 // FIXME: PerformContextualImplicitConversion should return ExprError
2789 // itself in this case.
2790 return ExprError();
Sebastian Redl8d2ccae2009-02-26 14:39:58 +00002791
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002792 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002793 QualType PointeeElem = Context.getBaseElementType(Pointee);
2794
2795 if (unsigned AddressSpace = Pointee.getAddressSpace())
2796 return Diag(Ex.get()->getLocStart(),
2797 diag::err_address_space_qualified_delete)
2798 << Pointee.getUnqualifiedType() << AddressSpace;
2799
Craig Topperc3ec1492014-05-26 06:22:03 +00002800 CXXRecordDecl *PointeeRD = nullptr;
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002801 if (Pointee->isVoidType() && !isSFINAEContext()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002802 // The C++ standard bans deleting a pointer to a non-object type, which
Douglas Gregorbb3348e2010-05-24 17:01:56 +00002803 // effectively bans deletion of "void*". However, most compilers support
2804 // this, so we treat it as a warning unless we're in a SFINAE context.
2805 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
John Wiegley01296292011-04-08 18:41:53 +00002806 << Type << Ex.get()->getSourceRange();
Eli Friedmanae4280f2011-07-26 22:25:31 +00002807 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
Sebastian Redl6d4256c2009-03-15 17:47:39 +00002808 return ExprError(Diag(StartLoc, diag::err_delete_operand)
John Wiegley01296292011-04-08 18:41:53 +00002809 << Type << Ex.get()->getSourceRange());
Eli Friedmanae4280f2011-07-26 22:25:31 +00002810 } else if (!Pointee->isDependentType()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00002811 // FIXME: This can result in errors if the definition was imported from a
2812 // module but is hidden.
Eli Friedmanae4280f2011-07-26 22:25:31 +00002813 if (!RequireCompleteType(StartLoc, Pointee,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002814 diag::warn_delete_incomplete, Ex.get())) {
Eli Friedmanae4280f2011-07-26 22:25:31 +00002815 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2816 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2817 }
2818 }
2819
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002820 if (Pointee->isArrayType() && !ArrayForm) {
2821 Diag(StartLoc, diag::warn_delete_array_type)
John Wiegley01296292011-04-08 18:41:53 +00002822 << Type << Ex.get()->getSourceRange()
Craig Topper07fa1762015-11-15 02:31:46 +00002823 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
Argyrios Kyrtzidis14ec9f62010-09-13 20:15:54 +00002824 ArrayForm = true;
2825 }
2826
Anders Carlssona471db02009-08-16 20:29:29 +00002827 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2828 ArrayForm ? OO_Array_Delete : OO_Delete);
2829
Eli Friedmanae4280f2011-07-26 22:25:31 +00002830 if (PointeeRD) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831 if (!UseGlobal &&
Eli Friedmanae4280f2011-07-26 22:25:31 +00002832 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2833 OperatorDelete))
Anders Carlsson654e5c72009-11-14 03:17:38 +00002834 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002835
John McCall284c48f2011-01-27 09:37:56 +00002836 // If we're allocating an array of records, check whether the
2837 // usual operator delete[] has a size_t parameter.
2838 if (ArrayForm) {
2839 // If the user specifically asked to use the global allocator,
2840 // we'll need to do the lookup into the class.
2841 if (UseGlobal)
2842 UsualArrayDeleteWantsSize =
2843 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2844
2845 // Otherwise, the usual operator delete[] should be the
2846 // function we just found.
Richard Smithf03bd302013-12-05 08:30:59 +00002847 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
John McCall284c48f2011-01-27 09:37:56 +00002848 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2849 }
2850
Richard Smitheec915d62012-02-18 04:13:32 +00002851 if (!PointeeRD->hasIrrelevantDestructor())
Eli Friedmanae4280f2011-07-26 22:25:31 +00002852 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00002853 MarkFunctionReferenced(StartLoc,
Fariborz Jahanian37d06562009-09-03 23:18:17 +00002854 const_cast<CXXDestructorDecl*>(Dtor));
Richard Smith22262ab2013-05-04 06:44:46 +00002855 if (DiagnoseUseOfDecl(Dtor, StartLoc))
2856 return ExprError();
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00002857 }
Argyrios Kyrtzidis8bd42852011-05-24 19:53:26 +00002858
Nico Weber5a9259c2016-01-15 21:45:31 +00002859 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
2860 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
2861 /*WarnOnNonAbstractTypes=*/!ArrayForm,
2862 SourceLocation());
Anders Carlssona471db02009-08-16 20:29:29 +00002863 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864
Richard Smith1cdec012013-09-29 04:40:38 +00002865 if (!OperatorDelete)
Anders Carlssone1d34ba02009-11-15 18:45:20 +00002866 // Look for a global declaration.
Richard Smith1cdec012013-09-29 04:40:38 +00002867 OperatorDelete = FindUsualDeallocationFunction(
Richard Smithdb0ac552015-12-18 22:40:25 +00002868 StartLoc, isCompleteType(StartLoc, Pointee) &&
Richard Smith1cdec012013-09-29 04:40:38 +00002869 (!ArrayForm || UsualArrayDeleteWantsSize ||
2870 Pointee.isDestructedType()),
2871 DeleteName);
Mike Stump11289f42009-09-09 15:08:12 +00002872
Eli Friedmanfa0df832012-02-02 03:46:19 +00002873 MarkFunctionReferenced(StartLoc, OperatorDelete);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002874
Douglas Gregorfa778132011-02-01 15:50:11 +00002875 // Check access and ambiguity of operator delete and destructor.
Eli Friedmanae4280f2011-07-26 22:25:31 +00002876 if (PointeeRD) {
2877 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
John Wiegley01296292011-04-08 18:41:53 +00002878 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
Douglas Gregorfa778132011-02-01 15:50:11 +00002879 PDiag(diag::err_access_dtor) << PointeeElem);
2880 }
2881 }
Sebastian Redlbd150f42008-11-21 19:14:01 +00002882 }
2883
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002884 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002885 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
2886 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
Ismail Pazarbasie5768d12015-05-18 19:59:11 +00002887 AnalyzeDeleteExprMismatch(Result);
2888 return Result;
Sebastian Redlbd150f42008-11-21 19:14:01 +00002889}
2890
Nico Weber5a9259c2016-01-15 21:45:31 +00002891void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
2892 bool IsDelete, bool CallCanBeVirtual,
2893 bool WarnOnNonAbstractTypes,
2894 SourceLocation DtorLoc) {
2895 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
2896 return;
2897
2898 // C++ [expr.delete]p3:
2899 // In the first alternative (delete object), if the static type of the
2900 // object to be deleted is different from its dynamic type, the static
2901 // type shall be a base class of the dynamic type of the object to be
2902 // deleted and the static type shall have a virtual destructor or the
2903 // behavior is undefined.
2904 //
2905 const CXXRecordDecl *PointeeRD = dtor->getParent();
2906 // Note: a final class cannot be derived from, no issue there
2907 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
2908 return;
2909
2910 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
2911 if (PointeeRD->isAbstract()) {
2912 // If the class is abstract, we warn by default, because we're
2913 // sure the code has undefined behavior.
2914 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
2915 << ClassType;
2916 } else if (WarnOnNonAbstractTypes) {
2917 // Otherwise, if this is not an array delete, it's a bit suspect,
2918 // but not necessarily wrong.
2919 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
2920 << ClassType;
2921 }
2922 if (!IsDelete) {
2923 std::string TypeStr;
2924 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
2925 Diag(DtorLoc, diag::note_delete_non_virtual)
2926 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
2927 }
2928}
2929
Douglas Gregor633caca2009-11-23 23:44:04 +00002930/// \brief Check the use of the given variable as a C++ condition in an if,
2931/// while, do-while, or switch statement.
John McCalldadc5752010-08-24 06:29:42 +00002932ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
John McCall7decc9e2010-11-18 06:31:45 +00002933 SourceLocation StmtLoc,
2934 bool ConvertToBoolean) {
Richard Smith27d807c2013-04-30 13:56:41 +00002935 if (ConditionVar->isInvalidDecl())
2936 return ExprError();
2937
Douglas Gregor633caca2009-11-23 23:44:04 +00002938 QualType T = ConditionVar->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002939
Douglas Gregor633caca2009-11-23 23:44:04 +00002940 // C++ [stmt.select]p2:
2941 // The declarator shall not specify a function or an array.
2942 if (T->isFunctionType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002943 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002944 diag::err_invalid_use_of_function_type)
2945 << ConditionVar->getSourceRange());
2946 else if (T->isArrayType())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002947 return ExprError(Diag(ConditionVar->getLocation(),
Douglas Gregor633caca2009-11-23 23:44:04 +00002948 diag::err_invalid_use_of_array_type)
2949 << ConditionVar->getSourceRange());
Douglas Gregor0156d1c2009-11-24 16:07:02 +00002950
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00002951 ExprResult Condition = DeclRefExpr::Create(
2952 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
2953 /*enclosing*/ false, ConditionVar->getLocation(),
2954 ConditionVar->getType().getNonReferenceType(), VK_LValue);
Eli Friedman2dfa7932012-01-16 21:00:51 +00002955
Eli Friedmanfa0df832012-02-02 03:46:19 +00002956 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
Eli Friedman2dfa7932012-01-16 21:00:51 +00002957
John Wiegley01296292011-04-08 18:41:53 +00002958 if (ConvertToBoolean) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00002959 Condition = CheckBooleanCondition(Condition.get(), StmtLoc);
John Wiegley01296292011-04-08 18:41:53 +00002960 if (Condition.isInvalid())
2961 return ExprError();
2962 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002963
Benjamin Kramer62b95d82012-08-23 21:35:17 +00002964 return Condition;
Douglas Gregor633caca2009-11-23 23:44:04 +00002965}
2966
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002967/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
John Wiegley01296292011-04-08 18:41:53 +00002968ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr) {
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002969 // C++ 6.4p4:
2970 // The value of a condition that is an initialized declaration in a statement
2971 // other than a switch statement is the value of the declared variable
2972 // implicitly converted to type bool. If that conversion is ill-formed, the
2973 // program is ill-formed.
2974 // The value of a condition that is an expression is the value of the
2975 // expression, implicitly converted to bool.
2976 //
Douglas Gregor5fb53972009-01-14 15:45:31 +00002977 return PerformContextuallyConvertToBool(CondExpr);
Argyrios Kyrtzidis7620ee42008-09-10 02:17:11 +00002978}
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002979
2980/// Helper function to determine whether this is the (deprecated) C++
2981/// conversion from a string literal to a pointer to non-const char or
2982/// non-const wchar_t (for narrow and wide string literals,
2983/// respectively).
Mike Stump11289f42009-09-09 15:08:12 +00002984bool
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002985Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
2986 // Look inside the implicit cast, if it exists.
2987 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
2988 From = Cast->getSubExpr();
2989
2990 // A string literal (2.13.4) that is not a wide string literal can
2991 // be converted to an rvalue of type "pointer to char"; a wide
2992 // string literal can be converted to an rvalue of type "pointer
2993 // to wchar_t" (C++ 4.2p2).
Douglas Gregor689999d2010-06-22 23:47:37 +00002994 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002995 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00002996 if (const BuiltinType *ToPointeeType
John McCall9dd450b2009-09-21 23:43:11 +00002997 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00002998 // This conversion is considered only when there is an
2999 // explicit appropriate pointer target type (C++ 4.2p2).
Douglas Gregorfb65e592011-07-27 05:40:30 +00003000 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3001 switch (StrLit->getKind()) {
3002 case StringLiteral::UTF8:
3003 case StringLiteral::UTF16:
3004 case StringLiteral::UTF32:
3005 // We don't allow UTF literals to be implicitly converted
3006 break;
3007 case StringLiteral::Ascii:
3008 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3009 ToPointeeType->getKind() == BuiltinType::Char_S);
3010 case StringLiteral::Wide:
3011 return ToPointeeType->isWideCharType();
3012 }
3013 }
Douglas Gregoraa1e21d2008-09-12 00:47:35 +00003014 }
3015
3016 return false;
3017}
Douglas Gregor39c16d42008-10-24 04:54:22 +00003018
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003019static ExprResult BuildCXXCastArgument(Sema &S,
John McCalle3027922010-08-25 11:45:40 +00003020 SourceLocation CastLoc,
3021 QualType Ty,
3022 CastKind Kind,
3023 CXXMethodDecl *Method,
John McCall30909032011-09-21 08:36:56 +00003024 DeclAccessPair FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003025 bool HadMultipleCandidates,
John McCalle3027922010-08-25 11:45:40 +00003026 Expr *From) {
Douglas Gregora4253922010-04-16 22:17:36 +00003027 switch (Kind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003028 default: llvm_unreachable("Unhandled cast kind!");
John McCalle3027922010-08-25 11:45:40 +00003029 case CK_ConstructorConversion: {
Douglas Gregorc7a31072011-10-10 22:41:00 +00003030 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
Benjamin Kramerf0623432012-08-23 22:51:59 +00003031 SmallVector<Expr*, 8> ConstructorArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003032
Richard Smith72d74052013-07-20 19:41:36 +00003033 if (S.RequireNonAbstractType(CastLoc, Ty,
3034 diag::err_allocation_of_abstract_type))
3035 return ExprError();
3036
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003037 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
John McCallfaf5fb42010-08-26 23:41:50 +00003038 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003039
John McCall5dadb652012-04-07 03:04:20 +00003040 S.CheckConstructorAccess(CastLoc, Constructor,
3041 InitializedEntity::InitializeTemporary(Ty),
3042 Constructor->getAccess());
Richard Smith7c9442a2015-02-24 21:44:43 +00003043 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003044 return ExprError();
Richard Smithd59b8322012-12-19 01:39:02 +00003045
Richard Smithf8adcdc2014-07-17 05:12:35 +00003046 ExprResult Result = S.BuildCXXConstructExpr(
3047 CastLoc, Ty, cast<CXXConstructorDecl>(Method),
3048 ConstructorArgs, HadMultipleCandidates,
3049 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3050 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregora4253922010-04-16 22:17:36 +00003051 if (Result.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00003052 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003053
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003054 return S.MaybeBindToTemporary(Result.getAs<Expr>());
Douglas Gregora4253922010-04-16 22:17:36 +00003055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003056
John McCalle3027922010-08-25 11:45:40 +00003057 case CK_UserDefinedConversion: {
Douglas Gregora4253922010-04-16 22:17:36 +00003058 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003059
Richard Smithd3f2d322015-02-24 21:16:19 +00003060 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
Richard Smith7c9442a2015-02-24 21:44:43 +00003061 if (S.DiagnoseUseOfDecl(Method, CastLoc))
Richard Smithd3f2d322015-02-24 21:16:19 +00003062 return ExprError();
3063
Douglas Gregora4253922010-04-16 22:17:36 +00003064 // Create an implicit call expr that calls it.
Eli Friedman2fb85122012-03-01 01:30:04 +00003065 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3066 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003067 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00003068 if (Result.isInvalid())
3069 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00003070 // Record usage of conversion in an implicit cast.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003071 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3072 CK_UserDefinedConversion, Result.get(),
3073 nullptr, Result.get()->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003074
Douglas Gregor668443e2011-01-20 00:18:04 +00003075 return S.MaybeBindToTemporary(Result.get());
Douglas Gregora4253922010-04-16 22:17:36 +00003076 }
3077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003078}
Douglas Gregora4253922010-04-16 22:17:36 +00003079
Douglas Gregor5fb53972009-01-14 15:45:31 +00003080/// PerformImplicitConversion - Perform an implicit conversion of the
3081/// expression From to the type ToType using the pre-computed implicit
John Wiegley01296292011-04-08 18:41:53 +00003082/// conversion sequence ICS. Returns the converted
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00003083/// expression. Action is the kind of conversion we're performing,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003084/// used in the error message.
John Wiegley01296292011-04-08 18:41:53 +00003085ExprResult
3086Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003087 const ImplicitConversionSequence &ICS,
John McCall31168b02011-06-15 23:02:42 +00003088 AssignmentAction Action,
3089 CheckedConversionKind CCK) {
John McCall0d1da222010-01-12 00:44:57 +00003090 switch (ICS.getKind()) {
John Wiegley01296292011-04-08 18:41:53 +00003091 case ImplicitConversionSequence::StandardConversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003092 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3093 Action, CCK);
John Wiegley01296292011-04-08 18:41:53 +00003094 if (Res.isInvalid())
3095 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003096 From = Res.get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003097 break;
John Wiegley01296292011-04-08 18:41:53 +00003098 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003099
Anders Carlsson110b07b2009-09-15 06:28:28 +00003100 case ImplicitConversionSequence::UserDefinedConversion: {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003101
Fariborz Jahanian2fee79a2009-08-28 22:04:50 +00003102 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
John McCall8cb679e2010-11-15 09:13:47 +00003103 CastKind CastKind;
Anders Carlsson110b07b2009-09-15 06:28:28 +00003104 QualType BeforeToType;
Richard Smithd3f2d322015-02-24 21:16:19 +00003105 assert(FD && "no conversion function for user-defined conversion seq");
Anders Carlsson110b07b2009-09-15 06:28:28 +00003106 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
John McCalle3027922010-08-25 11:45:40 +00003107 CastKind = CK_UserDefinedConversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003108
Anders Carlsson110b07b2009-09-15 06:28:28 +00003109 // If the user-defined conversion is specified by a conversion function,
3110 // the initial standard conversion sequence converts the source type to
3111 // the implicit object parameter of the conversion function.
3112 BeforeToType = Context.getTagDeclType(Conv->getParent());
John McCalla03edda2010-12-04 09:57:16 +00003113 } else {
3114 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
John McCalle3027922010-08-25 11:45:40 +00003115 CastKind = CK_ConstructorConversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003116 // Do no conversion if dealing with ... for the first conversion.
Douglas Gregor3153da72009-11-20 02:31:03 +00003117 if (!ICS.UserDefined.EllipsisConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003118 // If the user-defined conversion is specified by a constructor, the
Nico Weberb58e51c2014-11-19 05:21:39 +00003119 // initial standard conversion sequence converts the source type to
3120 // the type required by the argument of the constructor
Douglas Gregor3153da72009-11-20 02:31:03 +00003121 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123 }
Richard Smith72d74052013-07-20 19:41:36 +00003124 // Watch out for ellipsis conversion.
Fariborz Jahanianeec642f2009-11-06 00:55:14 +00003125 if (!ICS.UserDefined.EllipsisConversion) {
John Wiegley01296292011-04-08 18:41:53 +00003126 ExprResult Res =
Richard Smith507840d2011-11-29 22:48:16 +00003127 PerformImplicitConversion(From, BeforeToType,
3128 ICS.UserDefined.Before, AA_Converting,
3129 CCK);
John Wiegley01296292011-04-08 18:41:53 +00003130 if (Res.isInvalid())
3131 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003132 From = Res.get();
Fariborz Jahanian55824512009-11-06 00:23:08 +00003133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003134
3135 ExprResult CastArg
Douglas Gregora4253922010-04-16 22:17:36 +00003136 = BuildCXXCastArgument(*this,
3137 From->getLocStart(),
Anders Carlssone9766d52009-09-09 21:33:21 +00003138 ToType.getNonReferenceType(),
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003139 CastKind, cast<CXXMethodDecl>(FD),
3140 ICS.UserDefined.FoundConversionFunction,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003141 ICS.UserDefined.HadMultipleCandidates,
John McCallb268a282010-08-23 23:25:46 +00003142 From);
Anders Carlssone9766d52009-09-09 21:33:21 +00003143
3144 if (CastArg.isInvalid())
John Wiegley01296292011-04-08 18:41:53 +00003145 return ExprError();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003146
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003147 From = CastArg.get();
Eli Friedmane96f1d32009-11-27 04:41:50 +00003148
Richard Smith507840d2011-11-29 22:48:16 +00003149 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3150 AA_Converting, CCK);
Fariborz Jahanianda21efb2009-10-16 19:20:59 +00003151 }
John McCall0d1da222010-01-12 00:44:57 +00003152
3153 case ImplicitConversionSequence::AmbiguousConversion:
John McCall5c32be02010-08-24 20:38:10 +00003154 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
John McCall0d1da222010-01-12 00:44:57 +00003155 PDiag(diag::err_typecheck_ambiguous_condition)
3156 << From->getSourceRange());
John Wiegley01296292011-04-08 18:41:53 +00003157 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158
Douglas Gregor39c16d42008-10-24 04:54:22 +00003159 case ImplicitConversionSequence::EllipsisConversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003160 llvm_unreachable("Cannot perform an ellipsis conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003161
3162 case ImplicitConversionSequence::BadConversion:
John Wiegley01296292011-04-08 18:41:53 +00003163 return ExprError();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003164 }
3165
3166 // Everything went well.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003167 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003168}
3169
Richard Smith507840d2011-11-29 22:48:16 +00003170/// PerformImplicitConversion - Perform an implicit conversion of the
Douglas Gregor39c16d42008-10-24 04:54:22 +00003171/// expression From to the type ToType by following the standard
John Wiegley01296292011-04-08 18:41:53 +00003172/// conversion sequence SCS. Returns the converted
Douglas Gregor47d3f272008-12-19 17:40:08 +00003173/// expression. Flavor is the context in which we're performing this
3174/// conversion, for use in error messages.
John Wiegley01296292011-04-08 18:41:53 +00003175ExprResult
Richard Smith507840d2011-11-29 22:48:16 +00003176Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor47d3f272008-12-19 17:40:08 +00003177 const StandardConversionSequence& SCS,
John McCall31168b02011-06-15 23:02:42 +00003178 AssignmentAction Action,
3179 CheckedConversionKind CCK) {
3180 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3181
Mike Stump87c57ac2009-05-16 07:39:55 +00003182 // Overall FIXME: we are recomputing too many types here and doing far too
3183 // much extra work. What this means is that we need to keep track of more
3184 // information that is computed when we try the implicit conversion initially,
3185 // so that we don't need to recompute anything here.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003186 QualType FromType = From->getType();
John McCall31168b02011-06-15 23:02:42 +00003187
Douglas Gregor2fe98832008-11-03 19:09:14 +00003188 if (SCS.CopyConstructor) {
Anders Carlsson549c5bd2009-05-19 04:45:15 +00003189 // FIXME: When can ToType be a reference type?
3190 assert(!ToType->isReferenceType());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003191 if (SCS.Second == ICK_Derived_To_Base) {
Benjamin Kramerf0623432012-08-23 22:51:59 +00003192 SmallVector<Expr*, 8> ConstructorArgs;
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003193 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00003194 From, /*FIXME:ConstructLoc*/SourceLocation(),
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003195 ConstructorArgs))
John Wiegley01296292011-04-08 18:41:53 +00003196 return ExprError();
Richard Smithf8adcdc2014-07-17 05:12:35 +00003197 return BuildCXXConstructExpr(
3198 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
3199 ConstructorArgs, /*HadMultipleCandidates*/ false,
3200 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3201 CXXConstructExpr::CK_Complete, SourceRange());
Fariborz Jahanian49850df2009-09-25 18:59:21 +00003202 }
Richard Smithf8adcdc2014-07-17 05:12:35 +00003203 return BuildCXXConstructExpr(
3204 /*FIXME:ConstructLoc*/ SourceLocation(), ToType, SCS.CopyConstructor,
3205 From, /*HadMultipleCandidates*/ false,
3206 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3207 CXXConstructExpr::CK_Complete, SourceRange());
Douglas Gregor2fe98832008-11-03 19:09:14 +00003208 }
3209
Douglas Gregor980fb162010-04-29 18:24:40 +00003210 // Resolve overloaded function references.
3211 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3212 DeclAccessPair Found;
3213 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3214 true, Found);
3215 if (!Fn)
John Wiegley01296292011-04-08 18:41:53 +00003216 return ExprError();
Douglas Gregor980fb162010-04-29 18:24:40 +00003217
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003218 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
John Wiegley01296292011-04-08 18:41:53 +00003219 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003220
Douglas Gregor980fb162010-04-29 18:24:40 +00003221 From = FixOverloadedFunctionReference(From, Found, Fn);
3222 FromType = From->getType();
3223 }
3224
Richard Smitha23ab512013-05-23 00:30:41 +00003225 // If we're converting to an atomic type, first convert to the corresponding
3226 // non-atomic type.
3227 QualType ToAtomicType;
3228 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3229 ToAtomicType = ToType;
3230 ToType = ToAtomic->getValueType();
3231 }
3232
George Burgess IV8d141e02015-12-14 22:00:49 +00003233 QualType InitialFromType = FromType;
Richard Smith507840d2011-11-29 22:48:16 +00003234 // Perform the first implicit conversion.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003235 switch (SCS.First) {
3236 case ICK_Identity:
David Majnemer3087a2b2014-12-28 21:47:31 +00003237 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3238 FromType = FromAtomic->getValueType().getUnqualifiedType();
3239 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3240 From, /*BasePath=*/nullptr, VK_RValue);
3241 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00003242 break;
3243
Eli Friedman946b7b52012-01-24 22:51:26 +00003244 case ICK_Lvalue_To_Rvalue: {
John McCall526ab472011-10-25 17:37:35 +00003245 assert(From->getObjectKind() != OK_ObjCProperty);
Eli Friedman946b7b52012-01-24 22:51:26 +00003246 ExprResult FromRes = DefaultLvalueConversion(From);
3247 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003248 From = FromRes.get();
David Majnemere7029bc2014-12-16 06:31:17 +00003249 FromType = From->getType();
John McCall34376a62010-12-04 03:47:34 +00003250 break;
Eli Friedman946b7b52012-01-24 22:51:26 +00003251 }
John McCall34376a62010-12-04 03:47:34 +00003252
Douglas Gregor39c16d42008-10-24 04:54:22 +00003253 case ICK_Array_To_Pointer:
Douglas Gregor171c45a2009-02-18 21:56:37 +00003254 FromType = Context.getArrayDecayedType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00003255 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003256 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor171c45a2009-02-18 21:56:37 +00003257 break;
3258
3259 case ICK_Function_To_Pointer:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003260 FromType = Context.getPointerType(FromType);
Richard Smith507840d2011-11-29 22:48:16 +00003261 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003262 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003263 break;
3264
3265 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003266 llvm_unreachable("Improper first standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003267 }
3268
Richard Smith507840d2011-11-29 22:48:16 +00003269 // Perform the second implicit conversion
Douglas Gregor39c16d42008-10-24 04:54:22 +00003270 switch (SCS.Second) {
3271 case ICK_Identity:
Richard Smith410cc892014-11-26 03:26:53 +00003272 // C++ [except.spec]p5:
3273 // [For] assignment to and initialization of pointers to functions,
3274 // pointers to member functions, and references to functions: the
3275 // target entity shall allow at least the exceptions allowed by the
3276 // source value in the assignment or initialization.
3277 switch (Action) {
3278 case AA_Assigning:
3279 case AA_Initializing:
3280 // Note, function argument passing and returning are initialization.
3281 case AA_Passing:
3282 case AA_Returning:
3283 case AA_Sending:
3284 case AA_Passing_CFAudited:
3285 if (CheckExceptionSpecCompatibility(From, ToType))
3286 return ExprError();
3287 break;
3288
3289 case AA_Casting:
3290 case AA_Converting:
3291 // Casts and implicit conversions are not initialization, so are not
3292 // checked for exception specification mismatches.
3293 break;
3294 }
Sebastian Redl5d431642009-10-10 12:04:10 +00003295 // Nothing else to do.
Douglas Gregor39c16d42008-10-24 04:54:22 +00003296 break;
3297
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00003298 case ICK_NoReturn_Adjustment:
3299 // If both sides are functions (or pointers/references to them), there could
3300 // be incompatible exception declarations.
3301 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003302 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003303
Richard Smith507840d2011-11-29 22:48:16 +00003304 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003305 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00003306 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307
Douglas Gregor39c16d42008-10-24 04:54:22 +00003308 case ICK_Integral_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003309 case ICK_Integral_Conversion:
Richard Smithb9c5a602012-09-13 21:18:54 +00003310 if (ToType->isBooleanType()) {
3311 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3312 SCS.Second == ICK_Integral_Promotion &&
3313 "only enums with fixed underlying type can promote to bool");
3314 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003315 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003316 } else {
3317 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003318 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Richard Smithb9c5a602012-09-13 21:18:54 +00003319 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003320 break;
3321
3322 case ICK_Floating_Promotion:
Douglas Gregor39c16d42008-10-24 04:54:22 +00003323 case ICK_Floating_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00003324 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003325 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003326 break;
3327
3328 case ICK_Complex_Promotion:
John McCall8cb679e2010-11-15 09:13:47 +00003329 case ICK_Complex_Conversion: {
3330 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3331 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3332 CastKind CK;
3333 if (FromEl->isRealFloatingType()) {
3334 if (ToEl->isRealFloatingType())
3335 CK = CK_FloatingComplexCast;
3336 else
3337 CK = CK_FloatingComplexToIntegralComplex;
3338 } else if (ToEl->isRealFloatingType()) {
3339 CK = CK_IntegralComplexToFloatingComplex;
3340 } else {
3341 CK = CK_IntegralComplexCast;
3342 }
Richard Smith507840d2011-11-29 22:48:16 +00003343 From = ImpCastExprToType(From, ToType, CK,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003344 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003345 break;
John McCall8cb679e2010-11-15 09:13:47 +00003346 }
Eli Friedman06ed2a52009-10-20 08:27:19 +00003347
Douglas Gregor39c16d42008-10-24 04:54:22 +00003348 case ICK_Floating_Integral:
Douglas Gregor49b4d732010-06-22 23:07:26 +00003349 if (ToType->isRealFloatingType())
Richard Smith507840d2011-11-29 22:48:16 +00003350 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003351 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003352 else
Richard Smith507840d2011-11-29 22:48:16 +00003353 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003354 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00003355 break;
3356
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00003357 case ICK_Compatible_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00003358 From = ImpCastExprToType(From, ToType, CK_NoOp,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003359 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003360 break;
3361
John McCall31168b02011-06-15 23:02:42 +00003362 case ICK_Writeback_Conversion:
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003363 case ICK_Pointer_Conversion: {
Douglas Gregor6dd3a6a2010-12-02 21:47:04 +00003364 if (SCS.IncompatibleObjC && Action != AA_Casting) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00003365 // Diagnose incompatible Objective-C conversions
Douglas Gregor2720dc62011-06-11 04:42:12 +00003366 if (Action == AA_Initializing || Action == AA_Assigning)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003367 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003368 diag::ext_typecheck_convert_incompatible_pointer)
3369 << ToType << From->getType() << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003370 << From->getSourceRange() << 0;
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003371 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003372 Diag(From->getLocStart(),
Fariborz Jahanian413e0642011-03-21 19:08:42 +00003373 diag::ext_typecheck_convert_incompatible_pointer)
3374 << From->getType() << ToType << Action
Anna Zaks3b402712011-07-28 19:51:27 +00003375 << From->getSourceRange() << 0;
John McCall31168b02011-06-15 23:02:42 +00003376
Douglas Gregor33823722011-06-11 01:09:30 +00003377 if (From->getType()->isObjCObjectPointerType() &&
3378 ToType->isObjCObjectPointerType())
3379 EmitRelatedResultTypeNote(From);
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003380 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00003381 else if (getLangOpts().ObjCAutoRefCount &&
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003382 !CheckObjCARCUnavailableWeakConversion(ToType,
3383 From->getType())) {
John McCall9c3467e2011-09-09 06:12:06 +00003384 if (Action == AA_Initializing)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003385 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003386 diag::err_arc_weak_unavailable_assign);
3387 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003388 Diag(From->getLocStart(),
John McCall9c3467e2011-09-09 06:12:06 +00003389 diag::err_arc_convesion_of_weak_unavailable)
3390 << (Action == AA_Casting) << From->getType() << ToType
3391 << From->getSourceRange();
3392 }
Fariborz Jahanianf2913402011-07-08 17:41:42 +00003393
John McCall8cb679e2010-11-15 09:13:47 +00003394 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003395 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003396 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003397 return ExprError();
John McCallcd78e802011-09-10 01:16:55 +00003398
3399 // Make sure we extend blocks if necessary.
3400 // FIXME: doing this here is really ugly.
3401 if (Kind == CK_BlockPointerToObjCPointerCast) {
3402 ExprResult E = From;
3403 (void) PrepareCastToObjCObjectPointer(E);
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003404 From = E.get();
John McCallcd78e802011-09-10 01:16:55 +00003405 }
Fariborz Jahanian374089e2013-07-31 17:12:26 +00003406 if (getLangOpts().ObjCAutoRefCount)
3407 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
Richard Smith507840d2011-11-29 22:48:16 +00003408 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003409 .get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003410 break;
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003413 case ICK_Pointer_Member: {
John McCall8cb679e2010-11-15 09:13:47 +00003414 CastKind Kind = CK_Invalid;
John McCallcf142162010-08-07 06:22:56 +00003415 CXXCastPath BasePath;
Douglas Gregor58281352011-01-27 00:58:17 +00003416 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003417 return ExprError();
Sebastian Redl5d431642009-10-10 12:04:10 +00003418 if (CheckExceptionSpecCompatibility(From, ToType))
John Wiegley01296292011-04-08 18:41:53 +00003419 return ExprError();
David Majnemerd96b9972014-08-08 00:10:39 +00003420
3421 // We may not have been able to figure out what this member pointer resolved
3422 // to up until this exact point. Attempt to lock-in it's inheritance model.
David Majnemerfc22e472015-06-12 17:55:44 +00003423 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
Richard Smithdb0ac552015-12-18 22:40:25 +00003424 (void)isCompleteType(From->getExprLoc(), From->getType());
3425 (void)isCompleteType(From->getExprLoc(), ToType);
David Majnemerfc22e472015-06-12 17:55:44 +00003426 }
David Majnemerd96b9972014-08-08 00:10:39 +00003427
Richard Smith507840d2011-11-29 22:48:16 +00003428 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003429 .get();
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00003430 break;
3431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003432
Abramo Bagnara7ccce982011-04-07 09:26:19 +00003433 case ICK_Boolean_Conversion:
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003434 // Perform half-to-boolean conversion via float.
3435 if (From->getType()->isHalfType()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003436 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00003437 FromType = Context.FloatTy;
3438 }
3439
Richard Smith507840d2011-11-29 22:48:16 +00003440 From = ImpCastExprToType(From, Context.BoolTy,
3441 ScalarTypeToBooleanCastKind(FromType),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003442 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor39c16d42008-10-24 04:54:22 +00003443 break;
3444
Douglas Gregor88d292c2010-05-13 16:44:06 +00003445 case ICK_Derived_To_Base: {
John McCallcf142162010-08-07 06:22:56 +00003446 CXXCastPath BasePath;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447 if (CheckDerivedToBaseConversion(From->getType(),
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003448 ToType.getNonReferenceType(),
3449 From->getLocStart(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450 From->getSourceRange(),
Douglas Gregor88d292c2010-05-13 16:44:06 +00003451 &BasePath,
Douglas Gregor58281352011-01-27 00:58:17 +00003452 CStyle))
John Wiegley01296292011-04-08 18:41:53 +00003453 return ExprError();
Douglas Gregor88d292c2010-05-13 16:44:06 +00003454
Richard Smith507840d2011-11-29 22:48:16 +00003455 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3456 CK_DerivedToBase, From->getValueKind(),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003457 &BasePath, CCK).get();
Douglas Gregor02ba0ea2009-11-06 01:02:41 +00003458 break;
Douglas Gregor88d292c2010-05-13 16:44:06 +00003459 }
3460
Douglas Gregor46188682010-05-18 22:42:18 +00003461 case ICK_Vector_Conversion:
Richard Smith507840d2011-11-29 22:48:16 +00003462 From = ImpCastExprToType(From, ToType, CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003463 VK_RValue, /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003464 break;
3465
George Burgess IVdf1ed002016-01-13 01:52:39 +00003466 case ICK_Vector_Splat: {
Fariborz Jahanian28d94b12015-03-05 23:06:09 +00003467 // Vector splat from any arithmetic type to a vector.
George Burgess IVdf1ed002016-01-13 01:52:39 +00003468 Expr *Elem = prepareVectorSplat(ToType, From).get();
3469 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3470 /*BasePath=*/nullptr, CCK).get();
Douglas Gregor46188682010-05-18 22:42:18 +00003471 break;
George Burgess IVdf1ed002016-01-13 01:52:39 +00003472 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473
Douglas Gregor46188682010-05-18 22:42:18 +00003474 case ICK_Complex_Real:
John McCall8cb679e2010-11-15 09:13:47 +00003475 // Case 1. x -> _Complex y
3476 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3477 QualType ElType = ToComplex->getElementType();
3478 bool isFloatingComplex = ElType->isRealFloatingType();
3479
3480 // x -> y
3481 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3482 // do nothing
3483 } else if (From->getType()->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003484 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003485 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
John McCall8cb679e2010-11-15 09:13:47 +00003486 } else {
3487 assert(From->getType()->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003488 From = ImpCastExprToType(From, ElType,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003489 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
John McCall8cb679e2010-11-15 09:13:47 +00003490 }
3491 // y -> _Complex y
Richard Smith507840d2011-11-29 22:48:16 +00003492 From = ImpCastExprToType(From, ToType,
3493 isFloatingComplex ? CK_FloatingRealToComplex
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003494 : CK_IntegralRealToComplex).get();
John McCall8cb679e2010-11-15 09:13:47 +00003495
3496 // Case 2. _Complex x -> y
3497 } else {
3498 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3499 assert(FromComplex);
3500
3501 QualType ElType = FromComplex->getElementType();
3502 bool isFloatingComplex = ElType->isRealFloatingType();
3503
3504 // _Complex x -> x
Richard Smith507840d2011-11-29 22:48:16 +00003505 From = ImpCastExprToType(From, ElType,
3506 isFloatingComplex ? CK_FloatingComplexToReal
3507 : CK_IntegralComplexToReal,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003508 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003509
3510 // x -> y
3511 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3512 // do nothing
3513 } else if (ToType->isRealFloatingType()) {
Richard Smith507840d2011-11-29 22:48:16 +00003514 From = ImpCastExprToType(From, ToType,
3515 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003516 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003517 } else {
3518 assert(ToType->isIntegerType());
Richard Smith507840d2011-11-29 22:48:16 +00003519 From = ImpCastExprToType(From, ToType,
3520 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003521 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall8cb679e2010-11-15 09:13:47 +00003522 }
3523 }
Douglas Gregor46188682010-05-18 22:42:18 +00003524 break;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003525
3526 case ICK_Block_Pointer_Conversion: {
Richard Smith507840d2011-11-29 22:48:16 +00003527 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003528 VK_RValue, /*BasePath=*/nullptr, CCK).get();
John McCall31168b02011-06-15 23:02:42 +00003529 break;
3530 }
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00003531
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003532 case ICK_TransparentUnionConversion: {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003533 ExprResult FromRes = From;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003534 Sema::AssignConvertType ConvTy =
John Wiegley01296292011-04-08 18:41:53 +00003535 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3536 if (FromRes.isInvalid())
3537 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003538 From = FromRes.get();
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00003539 assert ((ConvTy == Sema::Compatible) &&
3540 "Improper transparent union conversion");
3541 (void)ConvTy;
3542 break;
3543 }
3544
Guy Benyei259f9f42013-02-07 16:05:33 +00003545 case ICK_Zero_Event_Conversion:
3546 From = ImpCastExprToType(From, ToType,
3547 CK_ZeroToOCLEvent,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003548 From->getValueKind()).get();
Guy Benyei259f9f42013-02-07 16:05:33 +00003549 break;
3550
Douglas Gregor46188682010-05-18 22:42:18 +00003551 case ICK_Lvalue_To_Rvalue:
3552 case ICK_Array_To_Pointer:
3553 case ICK_Function_To_Pointer:
3554 case ICK_Qualification:
3555 case ICK_Num_Conversion_Kinds:
George Burgess IV78ed9b42015-10-11 20:37:14 +00003556 case ICK_C_Only_Conversion:
David Blaikie83d382b2011-09-23 05:06:16 +00003557 llvm_unreachable("Improper second standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003558 }
3559
3560 switch (SCS.Third) {
3561 case ICK_Identity:
3562 // Nothing to do.
3563 break;
3564
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003565 case ICK_Qualification: {
3566 // The qualification keeps the category of the inner expression, unless the
3567 // target type isn't a reference.
John McCall2536c6d2010-08-25 10:28:54 +00003568 ExprValueKind VK = ToType->isReferenceType() ?
Eli Friedmanbe4b3632011-09-27 21:58:52 +00003569 From->getValueKind() : VK_RValue;
Richard Smith507840d2011-11-29 22:48:16 +00003570 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003571 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
Douglas Gregore489a7d2010-02-28 18:30:25 +00003572
Douglas Gregore981bb02011-03-14 16:13:32 +00003573 if (SCS.DeprecatedStringLiteralToCharPtr &&
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003574 !getLangOpts().WritableStrings) {
3575 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3576 ? diag::ext_deprecated_string_literal_conversion
3577 : diag::warn_deprecated_string_literal_conversion)
Douglas Gregore489a7d2010-02-28 18:30:25 +00003578 << ToType.getNonReferenceType();
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003579 }
Douglas Gregore489a7d2010-02-28 18:30:25 +00003580
Douglas Gregor39c16d42008-10-24 04:54:22 +00003581 break;
Richard Smitha23ab512013-05-23 00:30:41 +00003582 }
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003583
Douglas Gregor39c16d42008-10-24 04:54:22 +00003584 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003585 llvm_unreachable("Improper third standard conversion");
Douglas Gregor39c16d42008-10-24 04:54:22 +00003586 }
3587
Douglas Gregor298f43d2012-04-12 20:42:30 +00003588 // If this conversion sequence involved a scalar -> atomic conversion, perform
3589 // that conversion now.
Richard Smitha23ab512013-05-23 00:30:41 +00003590 if (!ToAtomicType.isNull()) {
3591 assert(Context.hasSameType(
3592 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3593 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
Nikola Smiljanic01a75982014-05-29 10:55:11 +00003594 VK_RValue, nullptr, CCK).get();
Richard Smitha23ab512013-05-23 00:30:41 +00003595 }
3596
George Burgess IV8d141e02015-12-14 22:00:49 +00003597 // If this conversion sequence succeeded and involved implicitly converting a
3598 // _Nullable type to a _Nonnull one, complain.
3599 if (CCK == CCK_ImplicitConversion)
3600 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3601 From->getLocStart());
3602
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00003603 return From;
Douglas Gregor39c16d42008-10-24 04:54:22 +00003604}
3605
Chandler Carruth8e172c62011-05-01 06:51:22 +00003606/// \brief Check the completeness of a type in a unary type trait.
3607///
3608/// If the particular type trait requires a complete type, tries to complete
3609/// it. If completing the type fails, a diagnostic is emitted and false
3610/// returned. If completing the type succeeds or no completion was required,
3611/// returns true.
Alp Toker95e7ff22014-01-01 05:57:51 +00003612static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003613 SourceLocation Loc,
3614 QualType ArgTy) {
3615 // C++0x [meta.unary.prop]p3:
3616 // For all of the class templates X declared in this Clause, instantiating
3617 // that template with a template argument that is a class template
3618 // specialization may result in the implicit instantiation of the template
3619 // argument if and only if the semantics of X require that the argument
3620 // must be a complete type.
3621 // We apply this rule to all the type trait expressions used to implement
3622 // these class templates. We also try to follow any GCC documented behavior
3623 // in these expressions to ensure portability of standard libraries.
3624 switch (UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003625 default: llvm_unreachable("not a UTT");
Chandler Carruth8e172c62011-05-01 06:51:22 +00003626 // is_complete_type somewhat obviously cannot require a complete type.
3627 case UTT_IsCompleteType:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003628 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003629
3630 // These traits are modeled on the type predicates in C++0x
3631 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3632 // requiring a complete type, as whether or not they return true cannot be
3633 // impacted by the completeness of the type.
3634 case UTT_IsVoid:
3635 case UTT_IsIntegral:
3636 case UTT_IsFloatingPoint:
3637 case UTT_IsArray:
3638 case UTT_IsPointer:
3639 case UTT_IsLvalueReference:
3640 case UTT_IsRvalueReference:
3641 case UTT_IsMemberFunctionPointer:
3642 case UTT_IsMemberObjectPointer:
3643 case UTT_IsEnum:
3644 case UTT_IsUnion:
3645 case UTT_IsClass:
3646 case UTT_IsFunction:
3647 case UTT_IsReference:
3648 case UTT_IsArithmetic:
3649 case UTT_IsFundamental:
3650 case UTT_IsObject:
3651 case UTT_IsScalar:
3652 case UTT_IsCompound:
3653 case UTT_IsMemberPointer:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003654 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003655
3656 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3657 // which requires some of its traits to have the complete type. However,
3658 // the completeness of the type cannot impact these traits' semantics, and
3659 // so they don't require it. This matches the comments on these traits in
3660 // Table 49.
3661 case UTT_IsConst:
3662 case UTT_IsVolatile:
3663 case UTT_IsSigned:
3664 case UTT_IsUnsigned:
David Majnemer213bea32015-11-16 06:58:51 +00003665
3666 // This type trait always returns false, checking the type is moot.
3667 case UTT_IsInterfaceClass:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003668 return true;
3669
David Majnemer213bea32015-11-16 06:58:51 +00003670 // C++14 [meta.unary.prop]:
3671 // If T is a non-union class type, T shall be a complete type.
3672 case UTT_IsEmpty:
3673 case UTT_IsPolymorphic:
3674 case UTT_IsAbstract:
3675 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
3676 if (!RD->isUnion())
3677 return !S.RequireCompleteType(
3678 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3679 return true;
3680
3681 // C++14 [meta.unary.prop]:
3682 // If T is a class type, T shall be a complete type.
3683 case UTT_IsFinal:
3684 case UTT_IsSealed:
3685 if (ArgTy->getAsCXXRecordDecl())
3686 return !S.RequireCompleteType(
3687 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3688 return true;
3689
3690 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3691 // applied to a complete type.
Chandler Carruth8e172c62011-05-01 06:51:22 +00003692 case UTT_IsTrivial:
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003693 case UTT_IsTriviallyCopyable:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003694 case UTT_IsStandardLayout:
3695 case UTT_IsPOD:
3696 case UTT_IsLiteral:
David Majnemer213bea32015-11-16 06:58:51 +00003697
Alp Toker73287bf2014-01-20 00:24:09 +00003698 case UTT_IsDestructible:
3699 case UTT_IsNothrowDestructible:
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003700 // Fall-through
Chandler Carruth8e172c62011-05-01 06:51:22 +00003701
Chandler Carrutha62d8a52011-05-01 19:18:02 +00003702 // These trait expressions are designed to help implement predicates in
Chandler Carruth8e172c62011-05-01 06:51:22 +00003703 // [meta.unary.prop] despite not being named the same. They are specified
3704 // by both GCC and the Embarcadero C++ compiler, and require the complete
3705 // type due to the overarching C++0x type predicates being implemented
3706 // requiring the complete type.
3707 case UTT_HasNothrowAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00003708 case UTT_HasNothrowMoveAssign:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003709 case UTT_HasNothrowConstructor:
3710 case UTT_HasNothrowCopy:
3711 case UTT_HasTrivialAssign:
Joao Matosc9523d42013-03-27 01:34:16 +00003712 case UTT_HasTrivialMoveAssign:
Alexis Huntf479f1b2011-05-09 18:22:59 +00003713 case UTT_HasTrivialDefaultConstructor:
Joao Matosc9523d42013-03-27 01:34:16 +00003714 case UTT_HasTrivialMoveConstructor:
Chandler Carruth8e172c62011-05-01 06:51:22 +00003715 case UTT_HasTrivialCopy:
3716 case UTT_HasTrivialDestructor:
3717 case UTT_HasVirtualDestructor:
3718 // Arrays of unknown bound are expressly allowed.
3719 QualType ElTy = ArgTy;
3720 if (ArgTy->isIncompleteArrayType())
3721 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3722
3723 // The void type is expressly allowed.
3724 if (ElTy->isVoidType())
3725 return true;
3726
3727 return !S.RequireCompleteType(
3728 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
John Wiegleyd3522222011-04-28 02:06:46 +00003729 }
Chandler Carruth8e172c62011-05-01 06:51:22 +00003730}
3731
Joao Matosc9523d42013-03-27 01:34:16 +00003732static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3733 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3734 bool (CXXRecordDecl::*HasTrivial)() const,
3735 bool (CXXRecordDecl::*HasNonTrivial)() const,
3736 bool (CXXMethodDecl::*IsDesiredOp)() const)
3737{
3738 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3739 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3740 return true;
3741
3742 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3743 DeclarationNameInfo NameInfo(Name, KeyLoc);
3744 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3745 if (Self.LookupQualifiedName(Res, RD)) {
3746 bool FoundOperator = false;
3747 Res.suppressDiagnostics();
3748 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3749 Op != OpEnd; ++Op) {
3750 if (isa<FunctionTemplateDecl>(*Op))
3751 continue;
3752
3753 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3754 if((Operator->*IsDesiredOp)()) {
3755 FoundOperator = true;
3756 const FunctionProtoType *CPT =
3757 Operator->getType()->getAs<FunctionProtoType>();
3758 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
Alp Toker73287bf2014-01-20 00:24:09 +00003759 if (!CPT || !CPT->isNothrow(C))
Joao Matosc9523d42013-03-27 01:34:16 +00003760 return false;
3761 }
3762 }
3763 return FoundOperator;
3764 }
3765 return false;
3766}
3767
Alp Toker95e7ff22014-01-01 05:57:51 +00003768static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
Chandler Carruth8e172c62011-05-01 06:51:22 +00003769 SourceLocation KeyLoc, QualType T) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00003770 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegleyd3522222011-04-28 02:06:46 +00003771
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003772 ASTContext &C = Self.Context;
3773 switch(UTT) {
Alp Toker95e7ff22014-01-01 05:57:51 +00003774 default: llvm_unreachable("not a UTT");
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003775 // Type trait expressions corresponding to the primary type category
3776 // predicates in C++0x [meta.unary.cat].
3777 case UTT_IsVoid:
3778 return T->isVoidType();
3779 case UTT_IsIntegral:
3780 return T->isIntegralType(C);
3781 case UTT_IsFloatingPoint:
3782 return T->isFloatingType();
3783 case UTT_IsArray:
3784 return T->isArrayType();
3785 case UTT_IsPointer:
3786 return T->isPointerType();
3787 case UTT_IsLvalueReference:
3788 return T->isLValueReferenceType();
3789 case UTT_IsRvalueReference:
3790 return T->isRValueReferenceType();
3791 case UTT_IsMemberFunctionPointer:
3792 return T->isMemberFunctionPointerType();
3793 case UTT_IsMemberObjectPointer:
3794 return T->isMemberDataPointerType();
3795 case UTT_IsEnum:
3796 return T->isEnumeralType();
Chandler Carruth100f3a92011-05-01 06:11:03 +00003797 case UTT_IsUnion:
Chandler Carruthaf858862011-05-01 09:29:58 +00003798 return T->isUnionType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003799 case UTT_IsClass:
Joao Matosdc86f942012-08-31 18:45:21 +00003800 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003801 case UTT_IsFunction:
3802 return T->isFunctionType();
3803
3804 // Type trait expressions which correspond to the convenient composition
3805 // predicates in C++0x [meta.unary.comp].
3806 case UTT_IsReference:
3807 return T->isReferenceType();
3808 case UTT_IsArithmetic:
Chandler Carruthaf858862011-05-01 09:29:58 +00003809 return T->isArithmeticType() && !T->isEnumeralType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003810 case UTT_IsFundamental:
Chandler Carruthaf858862011-05-01 09:29:58 +00003811 return T->isFundamentalType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003812 case UTT_IsObject:
Chandler Carruthaf858862011-05-01 09:29:58 +00003813 return T->isObjectType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003814 case UTT_IsScalar:
John McCall31168b02011-06-15 23:02:42 +00003815 // Note: semantic analysis depends on Objective-C lifetime types to be
3816 // considered scalar types. However, such types do not actually behave
3817 // like scalar types at run time (since they may require retain/release
3818 // operations), so we report them as non-scalar.
3819 if (T->isObjCLifetimeType()) {
3820 switch (T.getObjCLifetime()) {
3821 case Qualifiers::OCL_None:
3822 case Qualifiers::OCL_ExplicitNone:
3823 return true;
3824
3825 case Qualifiers::OCL_Strong:
3826 case Qualifiers::OCL_Weak:
3827 case Qualifiers::OCL_Autoreleasing:
3828 return false;
3829 }
3830 }
3831
Chandler Carruth7ba7bd32011-05-01 09:29:55 +00003832 return T->isScalarType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003833 case UTT_IsCompound:
Chandler Carruthaf858862011-05-01 09:29:58 +00003834 return T->isCompoundType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003835 case UTT_IsMemberPointer:
3836 return T->isMemberPointerType();
3837
3838 // Type trait expressions which correspond to the type property predicates
3839 // in C++0x [meta.unary.prop].
3840 case UTT_IsConst:
3841 return T.isConstQualified();
3842 case UTT_IsVolatile:
3843 return T.isVolatileQualified();
3844 case UTT_IsTrivial:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003845 return T.isTrivialType(C);
Alexis Huntd9a5cc12011-05-13 00:31:07 +00003846 case UTT_IsTriviallyCopyable:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003847 return T.isTriviallyCopyableType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003848 case UTT_IsStandardLayout:
3849 return T->isStandardLayoutType();
3850 case UTT_IsPOD:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003851 return T.isPODType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003852 case UTT_IsLiteral:
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003853 return T->isLiteralType(C);
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003854 case UTT_IsEmpty:
3855 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3856 return !RD->isUnion() && RD->isEmpty();
3857 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003858 case UTT_IsPolymorphic:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003859 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00003860 return !RD->isUnion() && RD->isPolymorphic();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003861 return false;
3862 case UTT_IsAbstract:
Chandler Carruth100f3a92011-05-01 06:11:03 +00003863 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00003864 return !RD->isUnion() && RD->isAbstract();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003865 return false;
David Majnemer213bea32015-11-16 06:58:51 +00003866 // __is_interface_class only returns true when CL is invoked in /CLR mode and
3867 // even then only when it is used with the 'interface struct ...' syntax
3868 // Clang doesn't support /CLR which makes this type trait moot.
John McCallbf4a7d72012-09-25 07:32:49 +00003869 case UTT_IsInterfaceClass:
John McCallbf4a7d72012-09-25 07:32:49 +00003870 return false;
Douglas Gregordca70af2011-12-03 18:14:24 +00003871 case UTT_IsFinal:
David Majnemera5433082013-10-18 00:33:31 +00003872 case UTT_IsSealed:
3873 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
David Majnemer213bea32015-11-16 06:58:51 +00003874 return RD->hasAttr<FinalAttr>();
David Majnemera5433082013-10-18 00:33:31 +00003875 return false;
John Wiegley65497cc2011-04-27 23:09:49 +00003876 case UTT_IsSigned:
3877 return T->isSignedIntegerType();
John Wiegley65497cc2011-04-27 23:09:49 +00003878 case UTT_IsUnsigned:
3879 return T->isUnsignedIntegerType();
Chandler Carruthd2479ea2011-05-01 06:11:07 +00003880
3881 // Type trait expressions which query classes regarding their construction,
3882 // destruction, and copying. Rather than being based directly on the
3883 // related type predicates in the standard, they are specified by both
3884 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
3885 // specifications.
3886 //
3887 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
3888 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
Richard Smith92f241f2012-12-08 02:53:02 +00003889 //
3890 // Note that these builtins do not behave as documented in g++: if a class
3891 // has both a trivial and a non-trivial special member of a particular kind,
3892 // they return false! For now, we emulate this behavior.
3893 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
3894 // does not correctly compute triviality in the presence of multiple special
3895 // members of the same kind. Revisit this once the g++ bug is fixed.
Alexis Huntf479f1b2011-05-09 18:22:59 +00003896 case UTT_HasTrivialDefaultConstructor:
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003897 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3898 // If __is_pod (type) is true then the trait is true, else if type is
3899 // a cv class or union type (or array thereof) with a trivial default
3900 // constructor ([class.ctor]) then the trait is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003901 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003902 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003903 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3904 return RD->hasTrivialDefaultConstructor() &&
3905 !RD->hasNonTrivialDefaultConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003906 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00003907 case UTT_HasTrivialMoveConstructor:
3908 // This trait is implemented by MSVC 2012 and needed to parse the
3909 // standard library headers. Specifically this is used as the logic
3910 // behind std::is_trivially_move_constructible (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003911 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00003912 return true;
3913 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3914 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
3915 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003916 case UTT_HasTrivialCopy:
3917 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3918 // If __is_pod (type) is true or type is a reference type then
3919 // the trait is true, else if type is a cv class or union type
3920 // with a trivial copy constructor ([class.copy]) then the trait
3921 // is true, else it is false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003922 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003923 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003924 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3925 return RD->hasTrivialCopyConstructor() &&
3926 !RD->hasNonTrivialCopyConstructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003927 return false;
Joao Matosc9523d42013-03-27 01:34:16 +00003928 case UTT_HasTrivialMoveAssign:
3929 // This trait is implemented by MSVC 2012 and needed to parse the
3930 // standard library headers. Specifically it is used as the logic
3931 // behind std::is_trivially_move_assignable (20.9.4.3)
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003932 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00003933 return true;
3934 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
3935 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
3936 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003937 case UTT_HasTrivialAssign:
3938 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
3939 // If type is const qualified or is a reference type then the
3940 // trait is false. Otherwise if __is_pod (type) is true then the
3941 // trait is true, else if type is a cv class or union type with
3942 // a trivial copy assignment ([class.copy]) then the trait is
3943 // true, else it is false.
3944 // Note: the const and reference restrictions are interesting,
3945 // given that const and reference members don't prevent a class
3946 // from having a trivial copy assignment operator (but do cause
3947 // errors if the copy assignment operator is actually used, q.v.
3948 // [class.copy]p12).
3949
Richard Smith92f241f2012-12-08 02:53:02 +00003950 if (T.isConstQualified())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003951 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00003952 if (T.isPODType(C))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003953 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00003954 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3955 return RD->hasTrivialCopyAssignment() &&
3956 !RD->hasNonTrivialCopyAssignment();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00003957 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00003958 case UTT_IsDestructible:
3959 case UTT_IsNothrowDestructible:
David Majnemerac73de92015-08-11 03:03:28 +00003960 // C++14 [meta.unary.prop]:
3961 // For reference types, is_destructible<T>::value is true.
3962 if (T->isReferenceType())
3963 return true;
3964
3965 // Objective-C++ ARC: autorelease types don't require destruction.
3966 if (T->isObjCLifetimeType() &&
3967 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
3968 return true;
3969
3970 // C++14 [meta.unary.prop]:
3971 // For incomplete types and function types, is_destructible<T>::value is
3972 // false.
3973 if (T->isIncompleteType() || T->isFunctionType())
3974 return false;
3975
3976 // C++14 [meta.unary.prop]:
3977 // For object types and given U equal to remove_all_extents_t<T>, if the
3978 // expression std::declval<U&>().~U() is well-formed when treated as an
3979 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
3980 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
3981 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
3982 if (!Destructor)
3983 return false;
3984 // C++14 [dcl.fct.def.delete]p2:
3985 // A program that refers to a deleted function implicitly or
3986 // explicitly, other than to declare it, is ill-formed.
3987 if (Destructor->isDeleted())
3988 return false;
3989 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
3990 return false;
3991 if (UTT == UTT_IsNothrowDestructible) {
3992 const FunctionProtoType *CPT =
3993 Destructor->getType()->getAs<FunctionProtoType>();
3994 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3995 if (!CPT || !CPT->isNothrow(C))
3996 return false;
3997 }
3998 }
3999 return true;
4000
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004001 case UTT_HasTrivialDestructor:
Alp Toker73287bf2014-01-20 00:24:09 +00004002 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004003 // If __is_pod (type) is true or type is a reference type
4004 // then the trait is true, else if type is a cv class or union
4005 // type (or array thereof) with a trivial destructor
4006 // ([class.dtor]) then the trait is true, else it is
4007 // false.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004008 if (T.isPODType(C) || T->isReferenceType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004009 return true;
John McCall31168b02011-06-15 23:02:42 +00004010
4011 // Objective-C++ ARC: autorelease types don't require destruction.
4012 if (T->isObjCLifetimeType() &&
4013 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4014 return true;
4015
Richard Smith92f241f2012-12-08 02:53:02 +00004016 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4017 return RD->hasTrivialDestructor();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004018 return false;
4019 // TODO: Propagate nothrowness for implicitly declared special members.
4020 case UTT_HasNothrowAssign:
4021 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4022 // If type is const qualified or is a reference type then the
4023 // trait is false. Otherwise if __has_trivial_assign (type)
4024 // is true then the trait is true, else if type is a cv class
4025 // or union type with copy assignment operators that are known
4026 // not to throw an exception then the trait is true, else it is
4027 // false.
4028 if (C.getBaseElementType(T).isConstQualified())
4029 return false;
4030 if (T->isReferenceType())
4031 return false;
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004032 if (T.isPODType(C) || T->isObjCLifetimeType())
Joao Matosc9523d42013-03-27 01:34:16 +00004033 return true;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004034
Joao Matosc9523d42013-03-27 01:34:16 +00004035 if (const RecordType *RT = T->getAs<RecordType>())
4036 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4037 &CXXRecordDecl::hasTrivialCopyAssignment,
4038 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4039 &CXXMethodDecl::isCopyAssignmentOperator);
4040 return false;
4041 case UTT_HasNothrowMoveAssign:
4042 // This trait is implemented by MSVC 2012 and needed to parse the
4043 // standard library headers. Specifically this is used as the logic
4044 // behind std::is_nothrow_move_assignable (20.9.4.3).
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004045 if (T.isPODType(C))
Joao Matosc9523d42013-03-27 01:34:16 +00004046 return true;
4047
4048 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4049 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4050 &CXXRecordDecl::hasTrivialMoveAssignment,
4051 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4052 &CXXMethodDecl::isMoveAssignmentOperator);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004053 return false;
4054 case UTT_HasNothrowCopy:
4055 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4056 // If __has_trivial_copy (type) is true then the trait is true, else
4057 // if type is a cv class or union type with copy constructors that are
4058 // known not to throw an exception then the trait is true, else it is
4059 // false.
John McCall31168b02011-06-15 23:02:42 +00004060 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004061 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004062 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4063 if (RD->hasTrivialCopyConstructor() &&
4064 !RD->hasNonTrivialCopyConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004065 return true;
4066
4067 bool FoundConstructor = false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004068 unsigned FoundTQs;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004069 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004070 // A template constructor is never a copy constructor.
4071 // FIXME: However, it may actually be selected at the actual overload
4072 // resolution point.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004073 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004074 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004075 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004076 if (Constructor->isCopyConstructor(FoundTQs)) {
4077 FoundConstructor = true;
4078 const FunctionProtoType *CPT
4079 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004080 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4081 if (!CPT)
4082 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004083 // TODO: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004084 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004085 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
Richard Smith938f40b2011-06-11 17:19:42 +00004086 return false;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004087 }
4088 }
4089
Richard Smith938f40b2011-06-11 17:19:42 +00004090 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004091 }
4092 return false;
4093 case UTT_HasNothrowConstructor:
Alp Tokerb4bca412014-01-20 00:23:47 +00004094 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004095 // If __has_trivial_constructor (type) is true then the trait is
4096 // true, else if type is a cv class or union type (or array
4097 // thereof) with a default constructor that is known not to
4098 // throw an exception then the trait is true, else it is false.
John McCall31168b02011-06-15 23:02:42 +00004099 if (T.isPODType(C) || T->isObjCLifetimeType())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004100 return true;
Richard Smith92f241f2012-12-08 02:53:02 +00004101 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4102 if (RD->hasTrivialDefaultConstructor() &&
4103 !RD->hasNonTrivialDefaultConstructor())
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004104 return true;
4105
Alp Tokerb4bca412014-01-20 00:23:47 +00004106 bool FoundConstructor = false;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004107 for (const auto *ND : Self.LookupConstructors(RD)) {
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004108 // FIXME: In C++0x, a constructor template can be a default constructor.
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004109 if (isa<FunctionTemplateDecl>(ND))
Sebastian Redl5c649bc2010-09-13 22:18:28 +00004110 continue;
Aaron Ballmane4de1a512015-07-21 22:33:52 +00004111 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
Sebastian Redlc15c3262010-09-13 22:02:47 +00004112 if (Constructor->isDefaultConstructor()) {
Alp Tokerb4bca412014-01-20 00:23:47 +00004113 FoundConstructor = true;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004114 const FunctionProtoType *CPT
4115 = Constructor->getType()->getAs<FunctionProtoType>();
Richard Smithf623c962012-04-17 00:58:00 +00004116 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4117 if (!CPT)
4118 return false;
Alp Tokerb4bca412014-01-20 00:23:47 +00004119 // FIXME: check whether evaluating default arguments can throw.
Sebastian Redlc15c3262010-09-13 22:02:47 +00004120 // For now, we'll be conservative and assume that they can throw.
Aaron Ballmand4a392c2015-07-21 21:07:11 +00004121 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
Alp Tokerb4bca412014-01-20 00:23:47 +00004122 return false;
Sebastian Redlc15c3262010-09-13 22:02:47 +00004123 }
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004124 }
Alp Tokerb4bca412014-01-20 00:23:47 +00004125 return FoundConstructor;
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004126 }
4127 return false;
4128 case UTT_HasVirtualDestructor:
4129 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4130 // If type is a class type with a virtual destructor ([class.dtor])
4131 // then the trait is true, else it is false.
Richard Smith92f241f2012-12-08 02:53:02 +00004132 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Sebastian Redl058fc822010-09-14 23:40:14 +00004133 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004134 return Destructor->isVirtual();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004135 return false;
Chandler Carruthd2479ea2011-05-01 06:11:07 +00004136
4137 // These type trait expressions are modeled on the specifications for the
4138 // Embarcadero C++0x type trait functions:
4139 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4140 case UTT_IsCompleteType:
4141 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4142 // Returns True if and only if T is a complete type at the point of the
4143 // function call.
4144 return !T->isIncompleteType();
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004145 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004146}
Sebastian Redl5822f082009-02-07 20:10:22 +00004147
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004148/// \brief Determine whether T has a non-trivial Objective-C lifetime in
4149/// ARC mode.
4150static bool hasNontrivialObjCLifetime(QualType T) {
4151 switch (T.getObjCLifetime()) {
4152 case Qualifiers::OCL_ExplicitNone:
4153 return false;
4154
4155 case Qualifiers::OCL_Strong:
4156 case Qualifiers::OCL_Weak:
4157 case Qualifiers::OCL_Autoreleasing:
4158 return true;
4159
4160 case Qualifiers::OCL_None:
4161 return T->isObjCLifetimeType();
4162 }
4163
4164 llvm_unreachable("Unknown ObjC lifetime qualifier");
4165}
4166
Alp Tokercbb90342013-12-13 20:49:58 +00004167static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4168 QualType RhsT, SourceLocation KeyLoc);
4169
Douglas Gregor29c42f22012-02-24 07:38:34 +00004170static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4171 ArrayRef<TypeSourceInfo *> Args,
4172 SourceLocation RParenLoc) {
Alp Toker95e7ff22014-01-01 05:57:51 +00004173 if (Kind <= UTT_Last)
4174 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4175
Alp Tokercbb90342013-12-13 20:49:58 +00004176 if (Kind <= BTT_Last)
4177 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4178 Args[1]->getType(), RParenLoc);
4179
Douglas Gregor29c42f22012-02-24 07:38:34 +00004180 switch (Kind) {
Alp Toker73287bf2014-01-20 00:24:09 +00004181 case clang::TT_IsConstructible:
4182 case clang::TT_IsNothrowConstructible:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004183 case clang::TT_IsTriviallyConstructible: {
4184 // C++11 [meta.unary.prop]:
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004185 // is_trivially_constructible is defined as:
Douglas Gregor29c42f22012-02-24 07:38:34 +00004186 //
Dmitri Gribenko85e87642012-02-24 20:03:35 +00004187 // is_constructible<T, Args...>::value is true and the variable
Richard Smith8b86f2d2013-11-04 01:48:18 +00004188 // definition for is_constructible, as defined below, is known to call
4189 // no operation that is not trivial.
Douglas Gregor29c42f22012-02-24 07:38:34 +00004190 //
4191 // The predicate condition for a template specialization
4192 // is_constructible<T, Args...> shall be satisfied if and only if the
4193 // following variable definition would be well-formed for some invented
4194 // variable t:
4195 //
4196 // T t(create<Args>()...);
Alp Toker40f9b1c2013-12-12 21:23:03 +00004197 assert(!Args.empty());
Eli Friedman9ea1e162013-09-11 02:53:02 +00004198
4199 // Precondition: T and all types in the parameter pack Args shall be
4200 // complete types, (possibly cv-qualified) void, or arrays of
4201 // unknown bound.
Aaron Ballman2bf2cad2015-07-21 21:18:29 +00004202 for (const auto *TSI : Args) {
4203 QualType ArgTy = TSI->getType();
Eli Friedman9ea1e162013-09-11 02:53:02 +00004204 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004205 continue;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004206
4207 if (S.RequireCompleteType(KWLoc, ArgTy,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004208 diag::err_incomplete_type_used_in_type_trait_expr))
4209 return false;
4210 }
Eli Friedman9ea1e162013-09-11 02:53:02 +00004211
David Majnemer9658ecc2015-11-13 05:32:43 +00004212 // Make sure the first argument is not incomplete nor a function type.
4213 QualType T = Args[0]->getType();
4214 if (T->isIncompleteType() || T->isFunctionType())
Douglas Gregor29c42f22012-02-24 07:38:34 +00004215 return false;
Eli Friedman9ea1e162013-09-11 02:53:02 +00004216
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004217 // Make sure the first argument is not an abstract type.
David Majnemer9658ecc2015-11-13 05:32:43 +00004218 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
Nikola Smiljanic1b4b6ba2014-04-15 11:30:15 +00004219 if (RD && RD->isAbstract())
4220 return false;
4221
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004222 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4223 SmallVector<Expr *, 2> ArgExprs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004224 ArgExprs.reserve(Args.size() - 1);
4225 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
David Majnemer9658ecc2015-11-13 05:32:43 +00004226 QualType ArgTy = Args[I]->getType();
4227 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4228 ArgTy = S.Context.getRValueReferenceType(ArgTy);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004229 OpaqueArgExprs.push_back(
David Majnemer9658ecc2015-11-13 05:32:43 +00004230 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4231 ArgTy.getNonLValueExprType(S.Context),
4232 Expr::getValueKindForType(ArgTy)));
Douglas Gregor29c42f22012-02-24 07:38:34 +00004233 }
Richard Smitha507bfc2014-07-23 20:07:08 +00004234 for (Expr &E : OpaqueArgExprs)
4235 ArgExprs.push_back(&E);
4236
Douglas Gregor29c42f22012-02-24 07:38:34 +00004237 // Perform the initialization in an unevaluated context within a SFINAE
4238 // trap at translation unit scope.
4239 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4240 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4241 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4242 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4243 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4244 RParenLoc));
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004245 InitializationSequence Init(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004246 if (Init.Failed())
4247 return false;
Alp Toker73287bf2014-01-20 00:24:09 +00004248
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004249 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004250 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4251 return false;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004252
Alp Toker73287bf2014-01-20 00:24:09 +00004253 if (Kind == clang::TT_IsConstructible)
4254 return true;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004255
Alp Toker73287bf2014-01-20 00:24:09 +00004256 if (Kind == clang::TT_IsNothrowConstructible)
4257 return S.canThrow(Result.get()) == CT_Cannot;
4258
4259 if (Kind == clang::TT_IsTriviallyConstructible) {
4260 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4261 // lifetime, this is a non-trivial construction.
4262 if (S.getLangOpts().ObjCAutoRefCount &&
David Majnemer9658ecc2015-11-13 05:32:43 +00004263 hasNontrivialObjCLifetime(T.getNonReferenceType()))
Alp Toker73287bf2014-01-20 00:24:09 +00004264 return false;
4265
4266 // The initialization succeeded; now make sure there are no non-trivial
4267 // calls.
4268 return !Result.get()->hasNonTrivialCall(S.Context);
4269 }
4270
4271 llvm_unreachable("unhandled type trait");
4272 return false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004273 }
Alp Tokercbb90342013-12-13 20:49:58 +00004274 default: llvm_unreachable("not a TT");
Douglas Gregor29c42f22012-02-24 07:38:34 +00004275 }
4276
4277 return false;
4278}
4279
4280ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4281 ArrayRef<TypeSourceInfo *> Args,
4282 SourceLocation RParenLoc) {
Alp Toker5294e6e2013-12-25 01:47:02 +00004283 QualType ResultType = Context.getLogicalOperationType();
Alp Tokercbb90342013-12-13 20:49:58 +00004284
Alp Toker95e7ff22014-01-01 05:57:51 +00004285 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4286 *this, Kind, KWLoc, Args[0]->getType()))
4287 return ExprError();
4288
Douglas Gregor29c42f22012-02-24 07:38:34 +00004289 bool Dependent = false;
4290 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4291 if (Args[I]->getType()->isDependentType()) {
4292 Dependent = true;
4293 break;
4294 }
4295 }
Alp Tokercbb90342013-12-13 20:49:58 +00004296
4297 bool Result = false;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004298 if (!Dependent)
Alp Tokercbb90342013-12-13 20:49:58 +00004299 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4300
4301 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4302 RParenLoc, Result);
Douglas Gregor29c42f22012-02-24 07:38:34 +00004303}
4304
Alp Toker88f64e62013-12-13 21:19:30 +00004305ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4306 ArrayRef<ParsedType> Args,
Douglas Gregor29c42f22012-02-24 07:38:34 +00004307 SourceLocation RParenLoc) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00004308 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
Douglas Gregor29c42f22012-02-24 07:38:34 +00004309 ConvertedArgs.reserve(Args.size());
4310
4311 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4312 TypeSourceInfo *TInfo;
4313 QualType T = GetTypeFromParser(Args[I], &TInfo);
4314 if (!TInfo)
4315 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4316
4317 ConvertedArgs.push_back(TInfo);
4318 }
Alp Tokercbb90342013-12-13 20:49:58 +00004319
Douglas Gregor29c42f22012-02-24 07:38:34 +00004320 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4321}
4322
Alp Tokercbb90342013-12-13 20:49:58 +00004323static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4324 QualType RhsT, SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004325 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4326 "Cannot evaluate traits of dependent types");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004327
4328 switch(BTT) {
John McCall388ef532011-01-28 22:02:36 +00004329 case BTT_IsBaseOf: {
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004330 // C++0x [meta.rel]p2
John McCall388ef532011-01-28 22:02:36 +00004331 // Base is a base class of Derived without regard to cv-qualifiers or
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004332 // Base and Derived are not unions and name the same class type without
4333 // regard to cv-qualifiers.
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004334
John McCall388ef532011-01-28 22:02:36 +00004335 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4336 if (!lhsRecord) return false;
4337
4338 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4339 if (!rhsRecord) return false;
4340
4341 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4342 == (lhsRecord == rhsRecord));
4343
4344 if (lhsRecord == rhsRecord)
4345 return !lhsRecord->getDecl()->isUnion();
4346
4347 // C++0x [meta.rel]p2:
4348 // If Base and Derived are class types and are different types
4349 // (ignoring possible cv-qualifiers) then Derived shall be a
4350 // complete type.
4351 if (Self.RequireCompleteType(KeyLoc, RhsT,
4352 diag::err_incomplete_type_used_in_type_trait_expr))
4353 return false;
4354
4355 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4356 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4357 }
John Wiegley65497cc2011-04-27 23:09:49 +00004358 case BTT_IsSame:
4359 return Self.Context.hasSameType(LhsT, RhsT);
Francois Pichet34b21132010-12-08 22:35:30 +00004360 case BTT_TypeCompatible:
4361 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4362 RhsT.getUnqualifiedType());
John Wiegley65497cc2011-04-27 23:09:49 +00004363 case BTT_IsConvertible:
Douglas Gregor8006e762011-01-27 20:28:01 +00004364 case BTT_IsConvertibleTo: {
4365 // C++0x [meta.rel]p4:
4366 // Given the following function prototype:
4367 //
4368 // template <class T>
4369 // typename add_rvalue_reference<T>::type create();
4370 //
4371 // the predicate condition for a template specialization
4372 // is_convertible<From, To> shall be satisfied if and only if
4373 // the return expression in the following code would be
4374 // well-formed, including any implicit conversions to the return
4375 // type of the function:
4376 //
4377 // To test() {
4378 // return create<From>();
4379 // }
4380 //
4381 // Access checking is performed as if in a context unrelated to To and
4382 // From. Only the validity of the immediate context of the expression
4383 // of the return-statement (including conversions to the return type)
4384 // is considered.
4385 //
4386 // We model the initialization as a copy-initialization of a temporary
4387 // of the appropriate type, which for this expression is identical to the
4388 // return statement (since NRVO doesn't apply).
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004389
4390 // Functions aren't allowed to return function or array types.
4391 if (RhsT->isFunctionType() || RhsT->isArrayType())
4392 return false;
4393
4394 // A return statement in a void function must have void type.
4395 if (RhsT->isVoidType())
4396 return LhsT->isVoidType();
4397
4398 // A function definition requires a complete, non-abstract return type.
Richard Smithdb0ac552015-12-18 22:40:25 +00004399 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004400 return false;
4401
4402 // Compute the result of add_rvalue_reference.
Douglas Gregor8006e762011-01-27 20:28:01 +00004403 if (LhsT->isObjectType() || LhsT->isFunctionType())
4404 LhsT = Self.Context.getRValueReferenceType(LhsT);
Eli Friedman1d4c3cf2012-08-14 02:06:07 +00004405
4406 // Build a fake source and destination for initialization.
Douglas Gregor8006e762011-01-27 20:28:01 +00004407 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
Douglas Gregorc03a1082011-01-28 02:26:04 +00004408 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
Douglas Gregor8006e762011-01-27 20:28:01 +00004409 Expr::getValueKindForType(LhsT));
4410 Expr *FromPtr = &From;
4411 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4412 SourceLocation()));
4413
Eli Friedmana59b1902012-01-25 01:05:57 +00004414 // Perform the initialization in an unevaluated context within a SFINAE
4415 // trap at translation unit scope.
4416 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
Douglas Gregoredb76852011-01-27 22:31:44 +00004417 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4418 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004419 InitializationSequence Init(Self, To, Kind, FromPtr);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004420 if (Init.Failed())
Douglas Gregor8006e762011-01-27 20:28:01 +00004421 return false;
Douglas Gregoredb76852011-01-27 22:31:44 +00004422
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004423 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
Douglas Gregor8006e762011-01-27 20:28:01 +00004424 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4425 }
Alp Toker73287bf2014-01-20 00:24:09 +00004426
4427 case BTT_IsNothrowAssignable:
Douglas Gregor1be329d2012-02-23 07:33:15 +00004428 case BTT_IsTriviallyAssignable: {
4429 // C++11 [meta.unary.prop]p3:
4430 // is_trivially_assignable is defined as:
4431 // is_assignable<T, U>::value is true and the assignment, as defined by
4432 // is_assignable, is known to call no operation that is not trivial
4433 //
4434 // is_assignable is defined as:
4435 // The expression declval<T>() = declval<U>() is well-formed when
4436 // treated as an unevaluated operand (Clause 5).
4437 //
4438 // For both, T and U shall be complete types, (possibly cv-qualified)
4439 // void, or arrays of unknown bound.
4440 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4441 Self.RequireCompleteType(KeyLoc, LhsT,
4442 diag::err_incomplete_type_used_in_type_trait_expr))
4443 return false;
4444 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4445 Self.RequireCompleteType(KeyLoc, RhsT,
4446 diag::err_incomplete_type_used_in_type_trait_expr))
4447 return false;
4448
4449 // cv void is never assignable.
4450 if (LhsT->isVoidType() || RhsT->isVoidType())
4451 return false;
4452
4453 // Build expressions that emulate the effect of declval<T>() and
4454 // declval<U>().
4455 if (LhsT->isObjectType() || LhsT->isFunctionType())
4456 LhsT = Self.Context.getRValueReferenceType(LhsT);
4457 if (RhsT->isObjectType() || RhsT->isFunctionType())
4458 RhsT = Self.Context.getRValueReferenceType(RhsT);
4459 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4460 Expr::getValueKindForType(LhsT));
4461 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4462 Expr::getValueKindForType(RhsT));
4463
4464 // Attempt the assignment in an unevaluated context within a SFINAE
4465 // trap at translation unit scope.
4466 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4467 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4468 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
Craig Topperc3ec1492014-05-26 06:22:03 +00004469 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4470 &Rhs);
Douglas Gregor1be329d2012-02-23 07:33:15 +00004471 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4472 return false;
4473
Alp Toker73287bf2014-01-20 00:24:09 +00004474 if (BTT == BTT_IsNothrowAssignable)
4475 return Self.canThrow(Result.get()) == CT_Cannot;
Douglas Gregor6bd56ca2012-06-29 00:49:17 +00004476
Alp Toker73287bf2014-01-20 00:24:09 +00004477 if (BTT == BTT_IsTriviallyAssignable) {
4478 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4479 // lifetime, this is a non-trivial assignment.
4480 if (Self.getLangOpts().ObjCAutoRefCount &&
4481 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4482 return false;
4483
4484 return !Result.get()->hasNonTrivialCall(Self.Context);
4485 }
4486
4487 llvm_unreachable("unhandled type trait");
4488 return false;
Douglas Gregor1be329d2012-02-23 07:33:15 +00004489 }
Alp Tokercbb90342013-12-13 20:49:58 +00004490 default: llvm_unreachable("not a BTT");
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004491 }
4492 llvm_unreachable("Unknown type trait or not implemented");
4493}
4494
John Wiegley6242b6a2011-04-28 00:16:57 +00004495ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4496 SourceLocation KWLoc,
4497 ParsedType Ty,
4498 Expr* DimExpr,
4499 SourceLocation RParen) {
4500 TypeSourceInfo *TSInfo;
4501 QualType T = GetTypeFromParser(Ty, &TSInfo);
4502 if (!TSInfo)
4503 TSInfo = Context.getTrivialTypeSourceInfo(T);
4504
4505 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4506}
4507
4508static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4509 QualType T, Expr *DimExpr,
4510 SourceLocation KeyLoc) {
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004511 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
John Wiegley6242b6a2011-04-28 00:16:57 +00004512
4513 switch(ATT) {
4514 case ATT_ArrayRank:
4515 if (T->isArrayType()) {
4516 unsigned Dim = 0;
4517 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4518 ++Dim;
4519 T = AT->getElementType();
4520 }
4521 return Dim;
John Wiegley6242b6a2011-04-28 00:16:57 +00004522 }
John Wiegleyd3522222011-04-28 02:06:46 +00004523 return 0;
4524
John Wiegley6242b6a2011-04-28 00:16:57 +00004525 case ATT_ArrayExtent: {
4526 llvm::APSInt Value;
4527 uint64_t Dim;
Richard Smithf4c51d92012-02-04 09:53:13 +00004528 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
Douglas Gregore2b37442012-05-04 22:38:52 +00004529 diag::err_dimension_expr_not_constant_integer,
Richard Smithf4c51d92012-02-04 09:53:13 +00004530 false).isInvalid())
4531 return 0;
4532 if (Value.isSigned() && Value.isNegative()) {
Daniel Dunbar900cead2012-03-09 21:38:22 +00004533 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4534 << DimExpr->getSourceRange();
Richard Smithf4c51d92012-02-04 09:53:13 +00004535 return 0;
John Wiegleyd3522222011-04-28 02:06:46 +00004536 }
Richard Smithf4c51d92012-02-04 09:53:13 +00004537 Dim = Value.getLimitedValue();
John Wiegley6242b6a2011-04-28 00:16:57 +00004538
4539 if (T->isArrayType()) {
4540 unsigned D = 0;
4541 bool Matched = false;
4542 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4543 if (Dim == D) {
4544 Matched = true;
4545 break;
4546 }
4547 ++D;
4548 T = AT->getElementType();
4549 }
4550
John Wiegleyd3522222011-04-28 02:06:46 +00004551 if (Matched && T->isArrayType()) {
4552 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4553 return CAT->getSize().getLimitedValue();
4554 }
John Wiegley6242b6a2011-04-28 00:16:57 +00004555 }
John Wiegleyd3522222011-04-28 02:06:46 +00004556 return 0;
John Wiegley6242b6a2011-04-28 00:16:57 +00004557 }
4558 }
4559 llvm_unreachable("Unknown type trait or not implemented");
4560}
4561
4562ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4563 SourceLocation KWLoc,
4564 TypeSourceInfo *TSInfo,
4565 Expr* DimExpr,
4566 SourceLocation RParen) {
4567 QualType T = TSInfo->getType();
John Wiegley6242b6a2011-04-28 00:16:57 +00004568
Chandler Carruthc5276e52011-05-01 08:48:21 +00004569 // FIXME: This should likely be tracked as an APInt to remove any host
4570 // assumptions about the width of size_t on the target.
Chandler Carruth0d1a54f2011-05-01 08:41:10 +00004571 uint64_t Value = 0;
4572 if (!T->isDependentType())
4573 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4574
Chandler Carruthc5276e52011-05-01 08:48:21 +00004575 // While the specification for these traits from the Embarcadero C++
4576 // compiler's documentation says the return type is 'unsigned int', Clang
4577 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4578 // compiler, there is no difference. On several other platforms this is an
4579 // important distinction.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004580 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4581 RParen, Context.getSizeType());
John Wiegley6242b6a2011-04-28 00:16:57 +00004582}
4583
John Wiegleyf9f65842011-04-25 06:54:41 +00004584ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004585 SourceLocation KWLoc,
4586 Expr *Queried,
4587 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004588 // If error parsing the expression, ignore.
4589 if (!Queried)
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004590 return ExprError();
John Wiegleyf9f65842011-04-25 06:54:41 +00004591
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004592 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004593
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004594 return Result;
John Wiegleyf9f65842011-04-25 06:54:41 +00004595}
4596
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004597static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4598 switch (ET) {
4599 case ET_IsLValueExpr: return E->isLValue();
4600 case ET_IsRValueExpr: return E->isRValue();
4601 }
4602 llvm_unreachable("Expression trait not covered by switch");
4603}
4604
John Wiegleyf9f65842011-04-25 06:54:41 +00004605ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004606 SourceLocation KWLoc,
4607 Expr *Queried,
4608 SourceLocation RParen) {
John Wiegleyf9f65842011-04-25 06:54:41 +00004609 if (Queried->isTypeDependent()) {
4610 // Delay type-checking for type-dependent expressions.
4611 } else if (Queried->getType()->isPlaceholderType()) {
4612 ExprResult PE = CheckPlaceholderExpr(Queried);
4613 if (PE.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004614 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
John Wiegleyf9f65842011-04-25 06:54:41 +00004615 }
4616
Chandler Carruth20b9bc82011-05-01 07:44:20 +00004617 bool Value = EvaluateExpressionTrait(ET, Queried);
Chandler Carruthf57eba32011-05-01 08:48:19 +00004618
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00004619 return new (Context)
4620 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
John Wiegleyf9f65842011-04-25 06:54:41 +00004621}
4622
Richard Trieu82402a02011-09-15 21:56:47 +00004623QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
John McCall7decc9e2010-11-18 06:31:45 +00004624 ExprValueKind &VK,
4625 SourceLocation Loc,
4626 bool isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004627 assert(!LHS.get()->getType()->isPlaceholderType() &&
4628 !RHS.get()->getType()->isPlaceholderType() &&
John McCall0b645e92011-06-30 17:15:34 +00004629 "placeholders should have been weeded out by now");
4630
4631 // The LHS undergoes lvalue conversions if this is ->*.
4632 if (isIndirect) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004633 LHS = DefaultLvalueConversion(LHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004634 if (LHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004635 }
4636
4637 // The RHS always undergoes lvalue conversions.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004638 RHS = DefaultLvalueConversion(RHS.get());
Richard Trieu82402a02011-09-15 21:56:47 +00004639 if (RHS.isInvalid()) return QualType();
John McCall0b645e92011-06-30 17:15:34 +00004640
Sebastian Redl5822f082009-02-07 20:10:22 +00004641 const char *OpSpelling = isIndirect ? "->*" : ".*";
4642 // C++ 5.5p2
4643 // The binary operator .* [p3: ->*] binds its second operand, which shall
4644 // be of type "pointer to member of T" (where T is a completely-defined
4645 // class type) [...]
Richard Trieu82402a02011-09-15 21:56:47 +00004646 QualType RHSType = RHS.get()->getType();
4647 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
Douglas Gregorac1fb652009-03-24 19:52:54 +00004648 if (!MemPtr) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004649 Diag(Loc, diag::err_bad_memptr_rhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004650 << OpSpelling << RHSType << RHS.get()->getSourceRange();
Sebastian Redl5822f082009-02-07 20:10:22 +00004651 return QualType();
Mike Stump11289f42009-09-09 15:08:12 +00004652 }
Douglas Gregorac1fb652009-03-24 19:52:54 +00004653
Sebastian Redl5822f082009-02-07 20:10:22 +00004654 QualType Class(MemPtr->getClass(), 0);
4655
Douglas Gregord07ba342010-10-13 20:41:14 +00004656 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4657 // member pointer points must be completely-defined. However, there is no
4658 // reason for this semantic distinction, and the rule is not enforced by
4659 // other compilers. Therefore, we do not check this property, as it is
4660 // likely to be considered a defect.
Sebastian Redlc72350e2010-04-10 10:14:54 +00004661
Sebastian Redl5822f082009-02-07 20:10:22 +00004662 // C++ 5.5p2
4663 // [...] to its first operand, which shall be of class T or of a class of
4664 // which T is an unambiguous and accessible base class. [p3: a pointer to
4665 // such a class]
Richard Trieu82402a02011-09-15 21:56:47 +00004666 QualType LHSType = LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004667 if (isIndirect) {
Richard Trieu82402a02011-09-15 21:56:47 +00004668 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4669 LHSType = Ptr->getPointeeType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004670 else {
4671 Diag(Loc, diag::err_bad_memptr_lhs)
Richard Trieu82402a02011-09-15 21:56:47 +00004672 << OpSpelling << 1 << LHSType
Douglas Gregora771f462010-03-31 17:46:05 +00004673 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
Sebastian Redl5822f082009-02-07 20:10:22 +00004674 return QualType();
4675 }
4676 }
4677
Richard Trieu82402a02011-09-15 21:56:47 +00004678 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004679 // If we want to check the hierarchy, we need a complete type.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004680 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4681 OpSpelling, (int)isIndirect)) {
Sebastian Redl26a0f1c2010-04-23 17:18:26 +00004682 return QualType();
4683 }
Richard Smithdb05cd32013-12-12 03:40:18 +00004684
Richard Smith0f59cb32015-12-18 21:45:41 +00004685 if (!IsDerivedFrom(Loc, LHSType, Class)) {
Sebastian Redl5822f082009-02-07 20:10:22 +00004686 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
Richard Trieu82402a02011-09-15 21:56:47 +00004687 << (int)isIndirect << LHS.get()->getType();
Sebastian Redl5822f082009-02-07 20:10:22 +00004688 return QualType();
4689 }
Richard Smithdb05cd32013-12-12 03:40:18 +00004690
4691 CXXCastPath BasePath;
4692 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
4693 SourceRange(LHS.get()->getLocStart(),
4694 RHS.get()->getLocEnd()),
4695 &BasePath))
4696 return QualType();
4697
Eli Friedman1fcf66b2010-01-16 00:00:48 +00004698 // Cast LHS to type of use.
4699 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
Eli Friedmanbe4b3632011-09-27 21:58:52 +00004700 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004701 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
Richard Trieu82402a02011-09-15 21:56:47 +00004702 &BasePath);
Sebastian Redl5822f082009-02-07 20:10:22 +00004703 }
4704
Richard Trieu82402a02011-09-15 21:56:47 +00004705 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
Fariborz Jahanian1bc0f9a2009-11-18 21:54:48 +00004706 // Diagnose use of pointer-to-member type which when used as
4707 // the functional cast in a pointer-to-member expression.
4708 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4709 return QualType();
4710 }
John McCall7decc9e2010-11-18 06:31:45 +00004711
Sebastian Redl5822f082009-02-07 20:10:22 +00004712 // C++ 5.5p2
4713 // The result is an object or a function of the type specified by the
4714 // second operand.
4715 // The cv qualifiers are the union of those in the pointer and the left side,
4716 // in accordance with 5.5p5 and 5.2.5.
Sebastian Redl5822f082009-02-07 20:10:22 +00004717 QualType Result = MemPtr->getPointeeType();
Richard Trieu82402a02011-09-15 21:56:47 +00004718 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
John McCall7decc9e2010-11-18 06:31:45 +00004719
Douglas Gregor1d042092011-01-26 16:40:18 +00004720 // C++0x [expr.mptr.oper]p6:
4721 // In a .* expression whose object expression is an rvalue, the program is
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722 // ill-formed if the second operand is a pointer to member function with
4723 // ref-qualifier &. In a ->* expression or in a .* expression whose object
4724 // expression is an lvalue, the program is ill-formed if the second operand
Douglas Gregor1d042092011-01-26 16:40:18 +00004725 // is a pointer to member function with ref-qualifier &&.
4726 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4727 switch (Proto->getRefQualifier()) {
4728 case RQ_None:
4729 // Do nothing
4730 break;
4731
4732 case RQ_LValue:
Richard Trieu82402a02011-09-15 21:56:47 +00004733 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00004734 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00004735 << RHSType << 1 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00004736 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
Douglas Gregor1d042092011-01-26 16:40:18 +00004738 case RQ_RValue:
Richard Trieu82402a02011-09-15 21:56:47 +00004739 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
Douglas Gregor1d042092011-01-26 16:40:18 +00004740 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
Richard Trieu82402a02011-09-15 21:56:47 +00004741 << RHSType << 0 << LHS.get()->getSourceRange();
Douglas Gregor1d042092011-01-26 16:40:18 +00004742 break;
4743 }
4744 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004745
John McCall7decc9e2010-11-18 06:31:45 +00004746 // C++ [expr.mptr.oper]p6:
4747 // The result of a .* expression whose second operand is a pointer
4748 // to a data member is of the same value category as its
4749 // first operand. The result of a .* expression whose second
4750 // operand is a pointer to a member function is a prvalue. The
4751 // result of an ->* expression is an lvalue if its second operand
4752 // is a pointer to data member and a prvalue otherwise.
John McCall0009fcc2011-04-26 20:42:42 +00004753 if (Result->isFunctionType()) {
John McCall7decc9e2010-11-18 06:31:45 +00004754 VK = VK_RValue;
John McCall0009fcc2011-04-26 20:42:42 +00004755 return Context.BoundMemberTy;
4756 } else if (isIndirect) {
John McCall7decc9e2010-11-18 06:31:45 +00004757 VK = VK_LValue;
John McCall0009fcc2011-04-26 20:42:42 +00004758 } else {
Richard Trieu82402a02011-09-15 21:56:47 +00004759 VK = LHS.get()->getValueKind();
John McCall0009fcc2011-04-26 20:42:42 +00004760 }
John McCall7decc9e2010-11-18 06:31:45 +00004761
Sebastian Redl5822f082009-02-07 20:10:22 +00004762 return Result;
4763}
Sebastian Redl1a99f442009-04-16 17:51:27 +00004764
Sebastian Redl1a99f442009-04-16 17:51:27 +00004765/// \brief Try to convert a type to another according to C++0x 5.16p3.
4766///
4767/// This is part of the parameter validation for the ? operator. If either
4768/// value operand is a class type, the two operands are attempted to be
4769/// converted to each other. This function does the conversion in one direction.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004770/// It returns true if the program is ill-formed and has already been diagnosed
4771/// as such.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004772static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4773 SourceLocation QuestionLoc,
Douglas Gregor838fcc32010-03-26 20:14:36 +00004774 bool &HaveConversion,
4775 QualType &ToType) {
4776 HaveConversion = false;
4777 ToType = To->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004778
4779 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004780 SourceLocation());
Sebastian Redl1a99f442009-04-16 17:51:27 +00004781 // C++0x 5.16p3
4782 // The process for determining whether an operand expression E1 of type T1
4783 // can be converted to match an operand expression E2 of type T2 is defined
4784 // as follows:
4785 // -- If E2 is an lvalue:
John McCall086a4642010-11-24 05:12:34 +00004786 bool ToIsLvalue = To->isLValue();
Douglas Gregorf9edf802010-03-26 20:59:55 +00004787 if (ToIsLvalue) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004788 // E1 can be converted to match E2 if E1 can be implicitly converted to
4789 // type "lvalue reference to T2", subject to the constraint that in the
4790 // conversion the reference must bind directly to E1.
Douglas Gregor838fcc32010-03-26 20:14:36 +00004791 QualType T = Self.Context.getLValueReferenceType(ToType);
4792 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004793
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004794 InitializationSequence InitSeq(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004795 if (InitSeq.isDirectReferenceBinding()) {
4796 ToType = T;
4797 HaveConversion = true;
4798 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004799 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800
Douglas Gregor838fcc32010-03-26 20:14:36 +00004801 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004802 return InitSeq.Diagnose(Self, Entity, Kind, From);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004803 }
John McCall65eb8792010-02-25 01:37:24 +00004804
Sebastian Redl1a99f442009-04-16 17:51:27 +00004805 // -- If E2 is an rvalue, or if the conversion above cannot be done:
4806 // -- if E1 and E2 have class type, and the underlying class types are
4807 // the same or one is a base class of the other:
4808 QualType FTy = From->getType();
4809 QualType TTy = To->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004810 const RecordType *FRec = FTy->getAs<RecordType>();
4811 const RecordType *TRec = TTy->getAs<RecordType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004812 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
Richard Smith0f59cb32015-12-18 21:45:41 +00004813 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
4814 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
4815 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004816 // E1 can be converted to match E2 if the class of T2 is the
4817 // same type as, or a base class of, the class of T1, and
4818 // [cv2 > cv1].
John McCall65eb8792010-02-25 01:37:24 +00004819 if (FRec == TRec || FDerivedFromT) {
4820 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004821 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004822 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004823 if (InitSeq) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004824 HaveConversion = true;
4825 return false;
4826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827
Douglas Gregor838fcc32010-03-26 20:14:36 +00004828 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004829 return InitSeq.Diagnose(Self, Entity, Kind, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004831 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
Douglas Gregor838fcc32010-03-26 20:14:36 +00004833 return false;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004834 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004835
Douglas Gregor838fcc32010-03-26 20:14:36 +00004836 // -- Otherwise: E1 can be converted to match E2 if E1 can be
4837 // implicitly converted to the type that expression E2 would have
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004838 // if E2 were converted to an rvalue (or the type it has, if E2 is
Douglas Gregorf9edf802010-03-26 20:59:55 +00004839 // an rvalue).
4840 //
4841 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
4842 // to the array-to-pointer or function-to-pointer conversions.
4843 if (!TTy->getAs<TagType>())
4844 TTy = TTy.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004845
Douglas Gregor838fcc32010-03-26 20:14:36 +00004846 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004847 InitializationSequence InitSeq(Self, Entity, Kind, From);
Sebastian Redlc7ca5872011-06-05 12:23:28 +00004848 HaveConversion = !InitSeq.Failed();
Douglas Gregor838fcc32010-03-26 20:14:36 +00004849 ToType = TTy;
4850 if (InitSeq.isAmbiguous())
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004851 return InitSeq.Diagnose(Self, Entity, Kind, From);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004852
Sebastian Redl1a99f442009-04-16 17:51:27 +00004853 return false;
4854}
4855
4856/// \brief Try to find a common type for two according to C++0x 5.16p5.
4857///
4858/// This is part of the parameter validation for the ? operator. If either
4859/// value operand is a class type, overload resolution is used to find a
4860/// conversion to a common type.
John Wiegley01296292011-04-08 18:41:53 +00004861static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004862 SourceLocation QuestionLoc) {
John Wiegley01296292011-04-08 18:41:53 +00004863 Expr *Args[2] = { LHS.get(), RHS.get() };
Richard Smith100b24a2014-04-17 01:52:14 +00004864 OverloadCandidateSet CandidateSet(QuestionLoc,
4865 OverloadCandidateSet::CSK_Operator);
Richard Smithe54c3072013-05-05 15:51:06 +00004866 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004867 CandidateSet);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004868
4869 OverloadCandidateSet::iterator Best;
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004870 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
John Wiegley01296292011-04-08 18:41:53 +00004871 case OR_Success: {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004872 // We found a match. Perform the conversions on the arguments and move on.
John Wiegley01296292011-04-08 18:41:53 +00004873 ExprResult LHSRes =
4874 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
4875 Best->Conversions[0], Sema::AA_Converting);
4876 if (LHSRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004877 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004878 LHS = LHSRes;
John Wiegley01296292011-04-08 18:41:53 +00004879
4880 ExprResult RHSRes =
4881 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
4882 Best->Conversions[1], Sema::AA_Converting);
4883 if (RHSRes.isInvalid())
4884 break;
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004885 RHS = RHSRes;
Chandler Carruth30141632011-02-25 19:41:05 +00004886 if (Best->Function)
Eli Friedmanfa0df832012-02-02 03:46:19 +00004887 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004888 return false;
John Wiegley01296292011-04-08 18:41:53 +00004889 }
4890
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004891 case OR_No_Viable_Function:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004892
4893 // Emit a better diagnostic if one of the expressions is a null pointer
4894 // constant and the other is a pointer type. In this case, the user most
4895 // likely forgot to take the address of the other expression.
John Wiegley01296292011-04-08 18:41:53 +00004896 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004897 return true;
4898
4899 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00004900 << LHS.get()->getType() << RHS.get()->getType()
4901 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004902 return true;
4903
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004904 case OR_Ambiguous:
Chandler Carrutha8bea4b2011-02-18 23:54:50 +00004905 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
John Wiegley01296292011-04-08 18:41:53 +00004906 << LHS.get()->getType() << RHS.get()->getType()
4907 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Mike Stump87c57ac2009-05-16 07:39:55 +00004908 // FIXME: Print the possible common types by printing the return types of
4909 // the viable candidates.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004910 break;
4911
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004912 case OR_Deleted:
David Blaikie83d382b2011-09-23 05:06:16 +00004913 llvm_unreachable("Conditional operator has only built-in overloads");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004914 }
4915 return true;
4916}
4917
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004918/// \brief Perform an "extended" implicit conversion as returned by
4919/// TryClassUnification.
John Wiegley01296292011-04-08 18:41:53 +00004920static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
Douglas Gregor838fcc32010-03-26 20:14:36 +00004921 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
John Wiegley01296292011-04-08 18:41:53 +00004922 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
Douglas Gregor838fcc32010-03-26 20:14:36 +00004923 SourceLocation());
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004924 Expr *Arg = E.get();
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00004925 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00004926 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
Douglas Gregor838fcc32010-03-26 20:14:36 +00004927 if (Result.isInvalid())
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004928 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004929
John Wiegley01296292011-04-08 18:41:53 +00004930 E = Result;
Sebastian Redl5775af1a2009-04-17 16:30:52 +00004931 return false;
4932}
4933
Sebastian Redl1a99f442009-04-16 17:51:27 +00004934/// \brief Check the operands of ?: under C++ semantics.
4935///
4936/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
4937/// extension. In this case, LHS == Cond. (But they're not aliases.)
Richard Smithf2b084f2012-08-08 06:13:49 +00004938QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
4939 ExprResult &RHS, ExprValueKind &VK,
4940 ExprObjectKind &OK,
Sebastian Redl1a99f442009-04-16 17:51:27 +00004941 SourceLocation QuestionLoc) {
Mike Stump87c57ac2009-05-16 07:39:55 +00004942 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
4943 // interface pointers.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004944
Richard Smith45edb702012-08-07 22:06:48 +00004945 // C++11 [expr.cond]p1
Sebastian Redl1a99f442009-04-16 17:51:27 +00004946 // The first expression is contextually converted to bool.
John Wiegley01296292011-04-08 18:41:53 +00004947 if (!Cond.get()->isTypeDependent()) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00004948 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
John Wiegley01296292011-04-08 18:41:53 +00004949 if (CondRes.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004950 return QualType();
Benjamin Kramer62b95d82012-08-23 21:35:17 +00004951 Cond = CondRes;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004952 }
4953
John McCall7decc9e2010-11-18 06:31:45 +00004954 // Assume r-value.
4955 VK = VK_RValue;
John McCall4bc41ae2010-11-18 19:01:18 +00004956 OK = OK_Ordinary;
John McCall7decc9e2010-11-18 06:31:45 +00004957
Sebastian Redl1a99f442009-04-16 17:51:27 +00004958 // Either of the arguments dependent?
John Wiegley01296292011-04-08 18:41:53 +00004959 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
Sebastian Redl1a99f442009-04-16 17:51:27 +00004960 return Context.DependentTy;
4961
Richard Smith45edb702012-08-07 22:06:48 +00004962 // C++11 [expr.cond]p2
Sebastian Redl1a99f442009-04-16 17:51:27 +00004963 // If either the second or the third operand has type (cv) void, ...
John Wiegley01296292011-04-08 18:41:53 +00004964 QualType LTy = LHS.get()->getType();
4965 QualType RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004966 bool LVoid = LTy->isVoidType();
4967 bool RVoid = RTy->isVoidType();
4968 if (LVoid || RVoid) {
Richard Smith6a6a4bb2014-01-27 04:19:56 +00004969 // ... one of the following shall hold:
4970 // -- The second or the third operand (but not both) is a (possibly
4971 // parenthesized) throw-expression; the result is of the type
4972 // and value category of the other.
4973 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
4974 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
4975 if (LThrow != RThrow) {
4976 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
4977 VK = NonThrow->getValueKind();
4978 // DR (no number yet): the result is a bit-field if the
4979 // non-throw-expression operand is a bit-field.
4980 OK = NonThrow->getObjectKind();
4981 return NonThrow->getType();
Richard Smith45edb702012-08-07 22:06:48 +00004982 }
4983
Sebastian Redl1a99f442009-04-16 17:51:27 +00004984 // -- Both the second and third operands have type void; the result is of
Richard Smith45edb702012-08-07 22:06:48 +00004985 // type void and is a prvalue.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004986 if (LVoid && RVoid)
4987 return Context.VoidTy;
4988
4989 // Neither holds, error.
4990 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
4991 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
John Wiegley01296292011-04-08 18:41:53 +00004992 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00004993 return QualType();
4994 }
4995
4996 // Neither is void.
4997
Richard Smithf2b084f2012-08-08 06:13:49 +00004998 // C++11 [expr.cond]p3
Sebastian Redl1a99f442009-04-16 17:51:27 +00004999 // Otherwise, if the second and third operand have different types, and
Richard Smithf2b084f2012-08-08 06:13:49 +00005000 // either has (cv) class type [...] an attempt is made to convert each of
5001 // those operands to the type of the other.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005002 if (!Context.hasSameType(LTy, RTy) &&
Sebastian Redl1a99f442009-04-16 17:51:27 +00005003 (LTy->isRecordType() || RTy->isRecordType())) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005004 // These return true if a single direction is already ambiguous.
Douglas Gregor838fcc32010-03-26 20:14:36 +00005005 QualType L2RType, R2LType;
5006 bool HaveL2R, HaveR2L;
John Wiegley01296292011-04-08 18:41:53 +00005007 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005008 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005009 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
Sebastian Redl1a99f442009-04-16 17:51:27 +00005010 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011
Sebastian Redl1a99f442009-04-16 17:51:27 +00005012 // If both can be converted, [...] the program is ill-formed.
5013 if (HaveL2R && HaveR2L) {
5014 Diag(QuestionLoc, diag::err_conditional_ambiguous)
John Wiegley01296292011-04-08 18:41:53 +00005015 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005016 return QualType();
5017 }
5018
5019 // If exactly one conversion is possible, that conversion is applied to
5020 // the chosen operand and the converted operands are used in place of the
5021 // original operands for the remainder of this section.
5022 if (HaveL2R) {
John Wiegley01296292011-04-08 18:41:53 +00005023 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005024 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005025 LTy = LHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005026 } else if (HaveR2L) {
John Wiegley01296292011-04-08 18:41:53 +00005027 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
Sebastian Redl1a99f442009-04-16 17:51:27 +00005028 return QualType();
John Wiegley01296292011-04-08 18:41:53 +00005029 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005030 }
5031 }
5032
Richard Smithf2b084f2012-08-08 06:13:49 +00005033 // C++11 [expr.cond]p3
5034 // if both are glvalues of the same value category and the same type except
5035 // for cv-qualification, an attempt is made to convert each of those
5036 // operands to the type of the other.
5037 ExprValueKind LVK = LHS.get()->getValueKind();
5038 ExprValueKind RVK = RHS.get()->getValueKind();
5039 if (!Context.hasSameType(LTy, RTy) &&
5040 Context.hasSameUnqualifiedType(LTy, RTy) &&
5041 LVK == RVK && LVK != VK_RValue) {
5042 // Since the unqualified types are reference-related and we require the
5043 // result to be as if a reference bound directly, the only conversion
5044 // we can perform is to add cv-qualifiers.
5045 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
5046 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
5047 if (RCVR.isStrictSupersetOf(LCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005048 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005049 LTy = LHS.get()->getType();
5050 }
5051 else if (LCVR.isStrictSupersetOf(RCVR)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005052 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
Richard Smithf2b084f2012-08-08 06:13:49 +00005053 RTy = RHS.get()->getType();
5054 }
5055 }
5056
5057 // C++11 [expr.cond]p4
John McCall7decc9e2010-11-18 06:31:45 +00005058 // If the second and third operands are glvalues of the same value
5059 // category and have the same type, the result is of that type and
5060 // value category and it is a bit-field if the second or the third
5061 // operand is a bit-field, or if both are bit-fields.
John McCall4bc41ae2010-11-18 19:01:18 +00005062 // We only extend this to bitfields, not to the crazy other kinds of
5063 // l-values.
Douglas Gregor697a3912010-04-01 22:47:07 +00005064 bool Same = Context.hasSameType(LTy, RTy);
Richard Smithf2b084f2012-08-08 06:13:49 +00005065 if (Same && LVK == RVK && LVK != VK_RValue &&
John Wiegley01296292011-04-08 18:41:53 +00005066 LHS.get()->isOrdinaryOrBitFieldObject() &&
5067 RHS.get()->isOrdinaryOrBitFieldObject()) {
5068 VK = LHS.get()->getValueKind();
5069 if (LHS.get()->getObjectKind() == OK_BitField ||
5070 RHS.get()->getObjectKind() == OK_BitField)
John McCall4bc41ae2010-11-18 19:01:18 +00005071 OK = OK_BitField;
John McCall7decc9e2010-11-18 06:31:45 +00005072 return LTy;
Fariborz Jahanianc60da032010-09-25 01:08:05 +00005073 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005074
Richard Smithf2b084f2012-08-08 06:13:49 +00005075 // C++11 [expr.cond]p5
5076 // Otherwise, the result is a prvalue. If the second and third operands
Sebastian Redl1a99f442009-04-16 17:51:27 +00005077 // do not have the same type, and either has (cv) class type, ...
5078 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5079 // ... overload resolution is used to determine the conversions (if any)
5080 // to be applied to the operands. If the overload resolution fails, the
5081 // program is ill-formed.
5082 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5083 return QualType();
5084 }
5085
Richard Smithf2b084f2012-08-08 06:13:49 +00005086 // C++11 [expr.cond]p6
5087 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
Sebastian Redl1a99f442009-04-16 17:51:27 +00005088 // conversions are performed on the second and third operands.
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005089 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5090 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
John Wiegley01296292011-04-08 18:41:53 +00005091 if (LHS.isInvalid() || RHS.isInvalid())
5092 return QualType();
5093 LTy = LHS.get()->getType();
5094 RTy = RHS.get()->getType();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005095
5096 // After those conversions, one of the following shall hold:
5097 // -- The second and third operands have the same type; the result
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005098 // is of that type. If the operands have class type, the result
5099 // is a prvalue temporary of the result type, which is
5100 // copy-initialized from either the second operand or the third
5101 // operand depending on the value of the first operand.
5102 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5103 if (LTy->isRecordType()) {
5104 // The operands have class type. Make a temporary copy.
David Blaikie6154ef92012-09-10 22:05:41 +00005105 if (RequireNonAbstractType(QuestionLoc, LTy,
5106 diag::err_allocation_of_abstract_type))
5107 return QualType();
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005108 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
David Blaikie6154ef92012-09-10 22:05:41 +00005109
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005110 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5111 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005112 LHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005113 if (LHSCopy.isInvalid())
5114 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005115
5116 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5117 SourceLocation(),
John Wiegley01296292011-04-08 18:41:53 +00005118 RHS);
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005119 if (RHSCopy.isInvalid())
5120 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005121
John Wiegley01296292011-04-08 18:41:53 +00005122 LHS = LHSCopy;
5123 RHS = RHSCopy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005124 }
5125
Sebastian Redl1a99f442009-04-16 17:51:27 +00005126 return LTy;
Douglas Gregorfa6010b2010-05-19 23:40:50 +00005127 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005128
Douglas Gregor46188682010-05-18 22:42:18 +00005129 // Extension: conditional operator involving vector types.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130 if (LTy->isVectorType() || RTy->isVectorType())
Ulrich Weigand3c5038a2015-07-30 14:08:36 +00005131 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5132 /*AllowBothBool*/true,
5133 /*AllowBoolConversions*/false);
Douglas Gregor46188682010-05-18 22:42:18 +00005134
Sebastian Redl1a99f442009-04-16 17:51:27 +00005135 // -- The second and third operands have arithmetic or enumeration type;
5136 // the usual arithmetic conversions are performed to bring them to a
5137 // common type, and the result is of that type.
5138 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005139 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
John Wiegley01296292011-04-08 18:41:53 +00005140 if (LHS.isInvalid() || RHS.isInvalid())
5141 return QualType();
Anton Korobeynikov5f951ee2014-11-14 22:09:15 +00005142
5143 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5144 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5145
5146 return ResTy;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005147 }
5148
5149 // -- The second and third operands have pointer type, or one has pointer
Richard Smithf2b084f2012-08-08 06:13:49 +00005150 // type and the other is a null pointer constant, or both are null
5151 // pointer constants, at least one of which is non-integral; pointer
5152 // conversions and qualification conversions are performed to bring them
5153 // to their composite pointer type. The result is of the composite
5154 // pointer type.
Eli Friedman81390df2010-01-02 22:56:07 +00005155 // -- The second and third operands have pointer to member type, or one has
5156 // pointer to member type and the other is a null pointer constant;
5157 // pointer to member conversions and qualification conversions are
5158 // performed to bring them to a common type, whose cv-qualification
5159 // shall match the cv-qualification of either the second or the third
5160 // operand. The result is of the common type.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005161 bool NonStandardCompositeType = false;
Douglas Gregor19175ff2010-04-16 23:20:25 +00005162 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
Craig Topperc3ec1492014-05-26 06:22:03 +00005163 isSFINAEContext() ? nullptr
5164 : &NonStandardCompositeType);
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005165 if (!Composite.isNull()) {
5166 if (NonStandardCompositeType)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005167 Diag(QuestionLoc,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005168 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
5169 << LTy << RTy << Composite
John Wiegley01296292011-04-08 18:41:53 +00005170 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005171
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005172 return Composite;
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005173 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005174
Douglas Gregor697a3912010-04-01 22:47:07 +00005175 // Similarly, attempt to find composite type of two objective-c pointers.
Fariborz Jahanian798d2bd2009-12-10 20:46:08 +00005176 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5177 if (!Composite.isNull())
5178 return Composite;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005179
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005180 // Check if we are using a null with a non-pointer type.
John Wiegley01296292011-04-08 18:41:53 +00005181 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
Chandler Carruth9c9127e2011-02-19 00:13:59 +00005182 return QualType();
5183
Sebastian Redl1a99f442009-04-16 17:51:27 +00005184 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
John Wiegley01296292011-04-08 18:41:53 +00005185 << LHS.get()->getType() << RHS.get()->getType()
5186 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
Sebastian Redl1a99f442009-04-16 17:51:27 +00005187 return QualType();
5188}
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005189
5190/// \brief Find a merged pointer type and convert the two expressions to it.
5191///
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005192/// This finds the composite pointer type (or member pointer type) for @p E1
Richard Smithf2b084f2012-08-08 06:13:49 +00005193/// and @p E2 according to C++11 5.9p2. It converts both expressions to this
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005194/// type and returns it.
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005195/// It does not emit diagnostics.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005196///
Douglas Gregor19175ff2010-04-16 23:20:25 +00005197/// \param Loc The location of the operator requiring these two expressions to
5198/// be converted to the composite pointer type.
5199///
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005200/// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
5201/// a non-standard (but still sane) composite type to which both expressions
5202/// can be converted. When such a type is chosen, \c *NonStandardCompositeType
5203/// will be set true.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005204QualType Sema::FindCompositePointerType(SourceLocation Loc,
Douglas Gregor19175ff2010-04-16 23:20:25 +00005205 Expr *&E1, Expr *&E2,
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005206 bool *NonStandardCompositeType) {
5207 if (NonStandardCompositeType)
5208 *NonStandardCompositeType = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005209
David Blaikiebbafb8a2012-03-11 07:00:24 +00005210 assert(getLangOpts().CPlusPlus && "This function assumes C++");
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005211 QualType T1 = E1->getType(), T2 = E2->getType();
Mike Stump11289f42009-09-09 15:08:12 +00005212
Richard Smithf2b084f2012-08-08 06:13:49 +00005213 // C++11 5.9p2
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005214 // Pointer conversions and qualification conversions are performed on
5215 // pointer operands to bring them to their composite pointer type. If
5216 // one operand is a null pointer constant, the composite pointer type is
Richard Smithf2b084f2012-08-08 06:13:49 +00005217 // std::nullptr_t if the other operand is also a null pointer constant or,
5218 // if the other operand is a pointer, the type of the other operand.
5219 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
5220 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
5221 if (T1->isNullPtrType() &&
5222 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005223 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00005224 return T1;
5225 }
5226 if (T2->isNullPtrType() &&
5227 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005228 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Richard Smithf2b084f2012-08-08 06:13:49 +00005229 return T2;
5230 }
5231 return QualType();
5232 }
5233
Douglas Gregor56751b52009-09-25 04:25:58 +00005234 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005235 if (T2->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005236 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005237 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005238 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005239 return T2;
5240 }
Douglas Gregor56751b52009-09-25 04:25:58 +00005241 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
Eli Friedman06ed2a52009-10-20 08:27:19 +00005242 if (T1->isMemberPointerType())
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005243 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
Eli Friedman06ed2a52009-10-20 08:27:19 +00005244 else
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005245 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005246 return T1;
5247 }
Mike Stump11289f42009-09-09 15:08:12 +00005248
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005249 // Now both have to be pointers or member pointers.
Sebastian Redl658262f2009-11-16 21:03:45 +00005250 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
5251 (!T2->isPointerType() && !T2->isMemberPointerType()))
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005252 return QualType();
5253
5254 // Otherwise, of one of the operands has type "pointer to cv1 void," then
5255 // the other has type "pointer to cv2 T" and the composite pointer type is
5256 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
5257 // Otherwise, the composite pointer type is a pointer type similar to the
5258 // type of one of the operands, with a cv-qualification signature that is
5259 // the union of the cv-qualification signatures of the operand types.
5260 // In practice, the first part here is redundant; it's subsumed by the second.
5261 // What we do here is, we build the two possible composite types, and try the
5262 // conversions in both directions. If only one works, or if the two composite
5263 // types are the same, we have succeeded.
John McCall8ccfcb52009-09-24 19:53:00 +00005264 // FIXME: extended qualifiers?
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005265 typedef SmallVector<unsigned, 4> QualifierVector;
Sebastian Redl658262f2009-11-16 21:03:45 +00005266 QualifierVector QualifierUnion;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005267 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
Sebastian Redl658262f2009-11-16 21:03:45 +00005268 ContainingClassVector;
5269 ContainingClassVector MemberOfClass;
5270 QualType Composite1 = Context.getCanonicalType(T1),
5271 Composite2 = Context.getCanonicalType(T2);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005272 unsigned NeedConstBefore = 0;
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005273 do {
5274 const PointerType *Ptr1, *Ptr2;
5275 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5276 (Ptr2 = Composite2->getAs<PointerType>())) {
5277 Composite1 = Ptr1->getPointeeType();
5278 Composite2 = Ptr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005280 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005281 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005282 if (NonStandardCompositeType &&
5283 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5284 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005285
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005286 QualifierUnion.push_back(
5287 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
Craig Topperc3ec1492014-05-26 06:22:03 +00005288 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005289 continue;
5290 }
Mike Stump11289f42009-09-09 15:08:12 +00005291
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005292 const MemberPointerType *MemPtr1, *MemPtr2;
5293 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5294 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5295 Composite1 = MemPtr1->getPointeeType();
5296 Composite2 = MemPtr2->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005297
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005298 // If we're allowed to create a non-standard composite type, keep track
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299 // of where we need to fill in additional 'const' qualifiers.
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005300 if (NonStandardCompositeType &&
5301 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5302 NeedConstBefore = QualifierUnion.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005304 QualifierUnion.push_back(
5305 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5306 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5307 MemPtr2->getClass()));
5308 continue;
5309 }
Mike Stump11289f42009-09-09 15:08:12 +00005310
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005311 // FIXME: block pointer types?
Mike Stump11289f42009-09-09 15:08:12 +00005312
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005313 // Cannot unwrap any more types.
5314 break;
5315 } while (true);
Mike Stump11289f42009-09-09 15:08:12 +00005316
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005317 if (NeedConstBefore && NonStandardCompositeType) {
5318 // Extension: Add 'const' to qualifiers that come before the first qualifier
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005319 // mismatch, so that our (non-standard!) composite type meets the
Douglas Gregor6f5f6422010-02-25 22:29:57 +00005320 // requirements of C++ [conv.qual]p4 bullet 3.
5321 for (unsigned I = 0; I != NeedConstBefore; ++I) {
5322 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
5323 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5324 *NonStandardCompositeType = true;
5325 }
5326 }
5327 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005328
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005329 // Rewrap the composites as pointers or member pointers with the union CVRs.
Sebastian Redl658262f2009-11-16 21:03:45 +00005330 ContainingClassVector::reverse_iterator MOC
5331 = MemberOfClass.rbegin();
5332 for (QualifierVector::reverse_iterator
5333 I = QualifierUnion.rbegin(),
5334 E = QualifierUnion.rend();
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005335 I != E; (void)++I, ++MOC) {
John McCall8ccfcb52009-09-24 19:53:00 +00005336 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005337 if (MOC->first && MOC->second) {
5338 // Rebuild member pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005339 Composite1 = Context.getMemberPointerType(
5340 Context.getQualifiedType(Composite1, Quals),
5341 MOC->first);
5342 Composite2 = Context.getMemberPointerType(
5343 Context.getQualifiedType(Composite2, Quals),
5344 MOC->second);
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005345 } else {
5346 // Rebuild pointer type
John McCall8ccfcb52009-09-24 19:53:00 +00005347 Composite1
5348 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5349 Composite2
5350 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
Douglas Gregorb00b10e2009-08-24 17:42:35 +00005351 }
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005352 }
5353
Douglas Gregor19175ff2010-04-16 23:20:25 +00005354 // Try to convert to the first composite pointer type.
5355 InitializedEntity Entity1
5356 = InitializedEntity::InitializeTemporary(Composite1);
5357 InitializationKind Kind
5358 = InitializationKind::CreateCopy(Loc, SourceLocation());
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005359 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
5360 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
Mike Stump11289f42009-09-09 15:08:12 +00005361
Douglas Gregor19175ff2010-04-16 23:20:25 +00005362 if (E1ToC1 && E2ToC1) {
5363 // Conversion to Composite1 is viable.
5364 if (!Context.hasSameType(Composite1, Composite2)) {
5365 // Composite2 is a different type from Composite1. Check whether
5366 // Composite2 is also viable.
5367 InitializedEntity Entity2
5368 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005369 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5370 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005371 if (E1ToC2 && E2ToC2) {
5372 // Both Composite1 and Composite2 are viable and are different;
5373 // this is an ambiguity.
5374 return QualType();
5375 }
5376 }
5377
5378 // Convert E1 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00005379 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005380 = E1ToC1.Perform(*this, Entity1, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005381 if (E1Result.isInvalid())
5382 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005383 E1 = E1Result.getAs<Expr>();
Douglas Gregor19175ff2010-04-16 23:20:25 +00005384
5385 // Convert E2 to Composite1
John McCalldadc5752010-08-24 06:29:42 +00005386 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005387 = E2ToC1.Perform(*this, Entity1, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005388 if (E2Result.isInvalid())
5389 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005390 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005391
Douglas Gregor19175ff2010-04-16 23:20:25 +00005392 return Composite1;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005393 }
5394
Douglas Gregor19175ff2010-04-16 23:20:25 +00005395 // Check whether Composite2 is viable.
5396 InitializedEntity Entity2
5397 = InitializedEntity::InitializeTemporary(Composite2);
Dmitri Gribenko8f8930f2013-05-03 15:05:50 +00005398 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5399 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005400 if (!E1ToC2 || !E2ToC2)
5401 return QualType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005402
Douglas Gregor19175ff2010-04-16 23:20:25 +00005403 // Convert E1 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00005404 ExprResult E1Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005405 = E1ToC2.Perform(*this, Entity2, Kind, E1);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005406 if (E1Result.isInvalid())
5407 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005408 E1 = E1Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005409
Douglas Gregor19175ff2010-04-16 23:20:25 +00005410 // Convert E2 to Composite2
John McCalldadc5752010-08-24 06:29:42 +00005411 ExprResult E2Result
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00005412 = E2ToC2.Perform(*this, Entity2, Kind, E2);
Douglas Gregor19175ff2010-04-16 23:20:25 +00005413 if (E2Result.isInvalid())
5414 return QualType();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005415 E2 = E2Result.getAs<Expr>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005416
Douglas Gregor19175ff2010-04-16 23:20:25 +00005417 return Composite2;
Sebastian Redl3b7ef5e2009-04-19 19:26:31 +00005418}
Anders Carlsson85a307d2009-05-17 18:41:29 +00005419
John McCalldadc5752010-08-24 06:29:42 +00005420ExprResult Sema::MaybeBindToTemporary(Expr *E) {
Douglas Gregor298087b2010-11-01 21:10:29 +00005421 if (!E)
5422 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
John McCall31168b02011-06-15 23:02:42 +00005424 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5425
5426 // If the result is a glvalue, we shouldn't bind it.
5427 if (!E->isRValue())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005428 return E;
Mike Stump11289f42009-09-09 15:08:12 +00005429
John McCall31168b02011-06-15 23:02:42 +00005430 // In ARC, calls that return a retainable type can return retained,
5431 // in which case we have to insert a consuming cast.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005432 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00005433 E->getType()->isObjCRetainableType()) {
5434
5435 bool ReturnsRetained;
5436
5437 // For actual calls, we compute this by examining the type of the
5438 // called value.
5439 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5440 Expr *Callee = Call->getCallee()->IgnoreParens();
5441 QualType T = Callee->getType();
5442
5443 if (T == Context.BoundMemberTy) {
5444 // Handle pointer-to-members.
5445 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5446 T = BinOp->getRHS()->getType();
5447 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5448 T = Mem->getMemberDecl()->getType();
5449 }
5450
5451 if (const PointerType *Ptr = T->getAs<PointerType>())
5452 T = Ptr->getPointeeType();
5453 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5454 T = Ptr->getPointeeType();
5455 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5456 T = MemPtr->getPointeeType();
5457
5458 const FunctionType *FTy = T->getAs<FunctionType>();
5459 assert(FTy && "call to value not of function type?");
5460 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5461
5462 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5463 // type always produce a +1 object.
5464 } else if (isa<StmtExpr>(E)) {
5465 ReturnsRetained = true;
5466
Ted Kremeneke65b0862012-03-06 20:05:56 +00005467 // We hit this case with the lambda conversion-to-block optimization;
5468 // we don't want any extra casts here.
5469 } else if (isa<CastExpr>(E) &&
5470 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005471 return E;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005472
John McCall31168b02011-06-15 23:02:42 +00005473 // For message sends and property references, we try to find an
5474 // actual method. FIXME: we should infer retention by selector in
5475 // cases where we don't have an actual method.
Ted Kremeneke65b0862012-03-06 20:05:56 +00005476 } else {
Craig Topperc3ec1492014-05-26 06:22:03 +00005477 ObjCMethodDecl *D = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00005478 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5479 D = Send->getMethodDecl();
Patrick Beard0caa3942012-04-19 00:25:12 +00005480 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5481 D = BoxedExpr->getBoxingMethod();
Ted Kremeneke65b0862012-03-06 20:05:56 +00005482 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5483 D = ArrayLit->getArrayWithObjectsMethod();
5484 } else if (ObjCDictionaryLiteral *DictLit
5485 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5486 D = DictLit->getDictWithObjectsMethod();
5487 }
John McCall31168b02011-06-15 23:02:42 +00005488
5489 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
John McCall32a4da02011-08-03 07:02:44 +00005490
5491 // Don't do reclaims on performSelector calls; despite their
5492 // return type, the invoked method doesn't necessarily actually
5493 // return an object.
5494 if (!ReturnsRetained &&
5495 D && D->getMethodFamily() == OMF_performSelector)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005496 return E;
John McCall31168b02011-06-15 23:02:42 +00005497 }
5498
John McCall16de4d22011-11-14 19:53:16 +00005499 // Don't reclaim an object of Class type.
5500 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005501 return E;
John McCall16de4d22011-11-14 19:53:16 +00005502
John McCall4db5c3c2011-07-07 06:58:02 +00005503 ExprNeedsCleanups = true;
5504
John McCall2d637d22011-09-10 06:18:15 +00005505 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5506 : CK_ARCReclaimReturnedObject);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005507 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5508 VK_RValue);
John McCall31168b02011-06-15 23:02:42 +00005509 }
5510
David Blaikiebbafb8a2012-03-11 07:00:24 +00005511 if (!getLangOpts().CPlusPlus)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005512 return E;
Douglas Gregor363b1512009-12-24 18:51:59 +00005513
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005514 // Search for the base element type (cf. ASTContext::getBaseElementType) with
5515 // a fast path for the common case that the type is directly a RecordType.
5516 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
Craig Topperc3ec1492014-05-26 06:22:03 +00005517 const RecordType *RT = nullptr;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005518 while (!RT) {
5519 switch (T->getTypeClass()) {
5520 case Type::Record:
5521 RT = cast<RecordType>(T);
5522 break;
5523 case Type::ConstantArray:
5524 case Type::IncompleteArray:
5525 case Type::VariableArray:
5526 case Type::DependentSizedArray:
5527 T = cast<ArrayType>(T)->getElementType().getTypePtr();
5528 break;
5529 default:
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005530 return E;
Peter Collingbournec331a1e2012-01-26 03:33:51 +00005531 }
5532 }
Mike Stump11289f42009-09-09 15:08:12 +00005533
Richard Smithfd555f62012-02-22 02:04:18 +00005534 // That should be enough to guarantee that this type is complete, if we're
5535 // not processing a decltype expression.
Jeffrey Yasskinbbc4eea2011-01-27 19:17:54 +00005536 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Richard Smitheec915d62012-02-18 04:13:32 +00005537 if (RD->isInvalidDecl() || RD->isDependentContext())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005538 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00005539
5540 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
Craig Topperc3ec1492014-05-26 06:22:03 +00005541 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
John McCall31168b02011-06-15 23:02:42 +00005542
John McCall31168b02011-06-15 23:02:42 +00005543 if (Destructor) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00005544 MarkFunctionReferenced(E->getExprLoc(), Destructor);
John McCall8e36d532010-04-07 00:41:46 +00005545 CheckDestructorAccess(E->getExprLoc(), Destructor,
5546 PDiag(diag::err_access_dtor_temp)
5547 << E->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00005548 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5549 return ExprError();
John McCall31168b02011-06-15 23:02:42 +00005550
Richard Smithfd555f62012-02-22 02:04:18 +00005551 // If destructor is trivial, we can avoid the extra copy.
5552 if (Destructor->isTrivial())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005553 return E;
Richard Smitheec915d62012-02-18 04:13:32 +00005554
John McCall28fc7092011-11-10 05:35:25 +00005555 // We need a cleanup, but we don't need to remember the temporary.
John McCall31168b02011-06-15 23:02:42 +00005556 ExprNeedsCleanups = true;
Richard Smithfd555f62012-02-22 02:04:18 +00005557 }
Richard Smitheec915d62012-02-18 04:13:32 +00005558
5559 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
Richard Smithfd555f62012-02-22 02:04:18 +00005560 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5561
5562 if (IsDecltype)
5563 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5564
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005565 return Bind;
Anders Carlsson2d4cada2009-05-30 20:36:53 +00005566}
5567
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005568ExprResult
John McCall5d413782010-12-06 08:20:24 +00005569Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005570 if (SubExpr.isInvalid())
5571 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005572
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005573 return MaybeCreateExprWithCleanups(SubExpr.get());
Douglas Gregorb6ea6082009-12-22 22:17:25 +00005574}
5575
John McCall28fc7092011-11-10 05:35:25 +00005576Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
Alp Toker028ed912013-12-06 17:56:43 +00005577 assert(SubExpr && "subexpression can't be null!");
John McCall28fc7092011-11-10 05:35:25 +00005578
Eli Friedman3bda6b12012-02-02 23:15:15 +00005579 CleanupVarDeclMarking();
5580
John McCall28fc7092011-11-10 05:35:25 +00005581 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5582 assert(ExprCleanupObjects.size() >= FirstCleanup);
5583 assert(ExprNeedsCleanups || ExprCleanupObjects.size() == FirstCleanup);
5584 if (!ExprNeedsCleanups)
5585 return SubExpr;
5586
Craig Topper5fc8fc22014-08-27 06:28:36 +00005587 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5588 ExprCleanupObjects.size() - FirstCleanup);
John McCall28fc7092011-11-10 05:35:25 +00005589
5590 Expr *E = ExprWithCleanups::Create(Context, SubExpr, Cleanups);
5591 DiscardCleanupsInEvaluationContext();
5592
5593 return E;
5594}
5595
John McCall5d413782010-12-06 08:20:24 +00005596Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
Alp Toker028ed912013-12-06 17:56:43 +00005597 assert(SubStmt && "sub-statement can't be null!");
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005598
Eli Friedman3bda6b12012-02-02 23:15:15 +00005599 CleanupVarDeclMarking();
5600
John McCall31168b02011-06-15 23:02:42 +00005601 if (!ExprNeedsCleanups)
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005602 return SubStmt;
5603
5604 // FIXME: In order to attach the temporaries, wrap the statement into
5605 // a StmtExpr; currently this is only used for asm statements.
5606 // This is hacky, either create a new CXXStmtWithTemporaries statement or
5607 // a new AsmStmtWithTemporaries.
Nico Webera2a0eb92012-12-29 20:03:39 +00005608 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005609 SourceLocation(),
5610 SourceLocation());
5611 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5612 SourceLocation());
John McCall5d413782010-12-06 08:20:24 +00005613 return MaybeCreateExprWithCleanups(E);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00005614}
5615
Richard Smithfd555f62012-02-22 02:04:18 +00005616/// Process the expression contained within a decltype. For such expressions,
5617/// certain semantic checks on temporaries are delayed until this point, and
5618/// are omitted for the 'topmost' call in the decltype expression. If the
5619/// topmost call bound a temporary, strip that temporary off the expression.
5620ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005621 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
Richard Smithfd555f62012-02-22 02:04:18 +00005622
5623 // C++11 [expr.call]p11:
5624 // If a function call is a prvalue of object type,
5625 // -- if the function call is either
5626 // -- the operand of a decltype-specifier, or
5627 // -- the right operand of a comma operator that is the operand of a
5628 // decltype-specifier,
5629 // a temporary object is not introduced for the prvalue.
5630
5631 // Recursively rebuild ParenExprs and comma expressions to strip out the
5632 // outermost CXXBindTemporaryExpr, if any.
5633 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5634 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5635 if (SubExpr.isInvalid())
5636 return ExprError();
5637 if (SubExpr.get() == PE->getSubExpr())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005638 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005639 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
Richard Smithfd555f62012-02-22 02:04:18 +00005640 }
5641 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5642 if (BO->getOpcode() == BO_Comma) {
5643 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5644 if (RHS.isInvalid())
5645 return ExprError();
5646 if (RHS.get() == BO->getRHS())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005647 return E;
5648 return new (Context) BinaryOperator(
5649 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5650 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
Richard Smithfd555f62012-02-22 02:04:18 +00005651 }
5652 }
5653
5654 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
Craig Topperc3ec1492014-05-26 06:22:03 +00005655 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5656 : nullptr;
Richard Smith202dc132014-02-18 03:51:47 +00005657 if (TopCall)
5658 E = TopCall;
5659 else
Craig Topperc3ec1492014-05-26 06:22:03 +00005660 TopBind = nullptr;
Richard Smithfd555f62012-02-22 02:04:18 +00005661
5662 // Disable the special decltype handling now.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005663 ExprEvalContexts.back().IsDecltype = false;
Richard Smithfd555f62012-02-22 02:04:18 +00005664
Richard Smithf86b0ae2012-07-28 19:54:11 +00005665 // In MS mode, don't perform any extra checking of call return types within a
5666 // decltype expression.
Alp Tokerbfa39342014-01-14 12:51:41 +00005667 if (getLangOpts().MSVCCompat)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005668 return E;
Richard Smithf86b0ae2012-07-28 19:54:11 +00005669
Richard Smithfd555f62012-02-22 02:04:18 +00005670 // Perform the semantic checks we delayed until this point.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005671 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5672 I != N; ++I) {
5673 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
Richard Smithfd555f62012-02-22 02:04:18 +00005674 if (Call == TopCall)
5675 continue;
5676
David Majnemerced8bdf2015-02-25 17:36:15 +00005677 if (CheckCallReturnType(Call->getCallReturnType(Context),
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005678 Call->getLocStart(),
Richard Smithfd555f62012-02-22 02:04:18 +00005679 Call, Call->getDirectCallee()))
5680 return ExprError();
5681 }
5682
5683 // Now all relevant types are complete, check the destructors are accessible
5684 // and non-deleted, and annotate them on the temporaries.
Benjamin Kramer671f4c02012-11-15 15:18:42 +00005685 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5686 I != N; ++I) {
5687 CXXBindTemporaryExpr *Bind =
5688 ExprEvalContexts.back().DelayedDecltypeBinds[I];
Richard Smithfd555f62012-02-22 02:04:18 +00005689 if (Bind == TopBind)
5690 continue;
5691
5692 CXXTemporary *Temp = Bind->getTemporary();
5693
5694 CXXRecordDecl *RD =
5695 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5696 CXXDestructorDecl *Destructor = LookupDestructor(RD);
5697 Temp->setDestructor(Destructor);
5698
Richard Smith7d847b12012-05-11 22:20:10 +00005699 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5700 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
Richard Smithfd555f62012-02-22 02:04:18 +00005701 PDiag(diag::err_access_dtor_temp)
Richard Smith7d847b12012-05-11 22:20:10 +00005702 << Bind->getType());
Richard Smith22262ab2013-05-04 06:44:46 +00005703 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5704 return ExprError();
Richard Smithfd555f62012-02-22 02:04:18 +00005705
5706 // We need a cleanup, but we don't need to remember the temporary.
5707 ExprNeedsCleanups = true;
5708 }
5709
5710 // Possibly strip off the top CXXBindTemporaryExpr.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005711 return E;
Richard Smithfd555f62012-02-22 02:04:18 +00005712}
5713
Richard Smith79c927b2013-11-06 19:31:51 +00005714/// Note a set of 'operator->' functions that were used for a member access.
5715static void noteOperatorArrows(Sema &S,
Craig Topper00bbdcf2014-06-28 23:22:23 +00005716 ArrayRef<FunctionDecl *> OperatorArrows) {
Richard Smith79c927b2013-11-06 19:31:51 +00005717 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5718 // FIXME: Make this configurable?
5719 unsigned Limit = 9;
5720 if (OperatorArrows.size() > Limit) {
5721 // Produce Limit-1 normal notes and one 'skipping' note.
5722 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5723 SkipCount = OperatorArrows.size() - (Limit - 1);
5724 }
5725
5726 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5727 if (I == SkipStart) {
5728 S.Diag(OperatorArrows[I]->getLocation(),
5729 diag::note_operator_arrows_suppressed)
5730 << SkipCount;
5731 I += SkipCount;
5732 } else {
5733 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5734 << OperatorArrows[I]->getCallResultType();
5735 ++I;
5736 }
5737 }
5738}
5739
Nico Weber964d3322015-02-16 22:35:45 +00005740ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
5741 SourceLocation OpLoc,
5742 tok::TokenKind OpKind,
5743 ParsedType &ObjectType,
5744 bool &MayBePseudoDestructor) {
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005745 // Since this might be a postfix expression, get rid of ParenListExprs.
John McCalldadc5752010-08-24 06:29:42 +00005746 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
John McCallb268a282010-08-23 23:25:46 +00005747 if (Result.isInvalid()) return ExprError();
5748 Base = Result.get();
Mike Stump11289f42009-09-09 15:08:12 +00005749
John McCall526ab472011-10-25 17:37:35 +00005750 Result = CheckPlaceholderExpr(Base);
5751 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005752 Base = Result.get();
John McCall526ab472011-10-25 17:37:35 +00005753
John McCallb268a282010-08-23 23:25:46 +00005754 QualType BaseType = Base->getType();
Douglas Gregore610ada2010-02-24 18:44:31 +00005755 MayBePseudoDestructor = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005756 if (BaseType->isDependentType()) {
Douglas Gregor41127182009-11-04 22:49:18 +00005757 // If we have a pointer to a dependent type and are using the -> operator,
5758 // the object type is the type that the pointer points to. We might still
5759 // have enough information about that type to do something useful.
5760 if (OpKind == tok::arrow)
5761 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5762 BaseType = Ptr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005763
John McCallba7bf592010-08-24 05:47:05 +00005764 ObjectType = ParsedType::make(BaseType);
Douglas Gregore610ada2010-02-24 18:44:31 +00005765 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005766 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005767 }
Mike Stump11289f42009-09-09 15:08:12 +00005768
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005769 // C++ [over.match.oper]p8:
Mike Stump11289f42009-09-09 15:08:12 +00005770 // [...] When operator->returns, the operator-> is applied to the value
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005771 // returned, with the original second operand.
5772 if (OpKind == tok::arrow) {
Richard Smith79c927b2013-11-06 19:31:51 +00005773 QualType StartingType = BaseType;
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005774 bool NoArrowOperatorFound = false;
5775 bool FirstIteration = true;
5776 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
John McCallc1538c02009-09-30 01:01:30 +00005777 // The set of types we've considered so far.
John McCallbd0465b2009-09-30 01:30:54 +00005778 llvm::SmallPtrSet<CanQualType,8> CTypes;
Richard Smith79c927b2013-11-06 19:31:51 +00005779 SmallVector<FunctionDecl*, 8> OperatorArrows;
John McCallbd0465b2009-09-30 01:30:54 +00005780 CTypes.insert(Context.getCanonicalType(BaseType));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005781
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005782 while (BaseType->isRecordType()) {
Richard Smith79c927b2013-11-06 19:31:51 +00005783 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5784 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
Richard Smith9dbc5742013-11-06 19:43:09 +00005785 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
Richard Smith79c927b2013-11-06 19:31:51 +00005786 noteOperatorArrows(*this, OperatorArrows);
5787 Diag(OpLoc, diag::note_operator_arrow_depth)
5788 << getLangOpts().ArrowDepth;
5789 return ExprError();
5790 }
5791
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005792 Result = BuildOverloadedArrowExpr(
5793 S, Base, OpLoc,
5794 // When in a template specialization and on the first loop iteration,
5795 // potentially give the default diagnostic (with the fixit in a
5796 // separate note) instead of having the error reported back to here
5797 // and giving a diagnostic with a fixit attached to the error itself.
5798 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
Craig Topperc3ec1492014-05-26 06:22:03 +00005799 ? nullptr
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005800 : &NoArrowOperatorFound);
5801 if (Result.isInvalid()) {
5802 if (NoArrowOperatorFound) {
5803 if (FirstIteration) {
5804 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Richard Smith9dbc5742013-11-06 19:43:09 +00005805 << BaseType << 1 << Base->getSourceRange()
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005806 << FixItHint::CreateReplacement(OpLoc, ".");
5807 OpKind = tok::period;
5808 break;
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00005809 }
5810 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5811 << BaseType << Base->getSourceRange();
5812 CallExpr *CE = dyn_cast<CallExpr>(Base);
Craig Topperc3ec1492014-05-26 06:22:03 +00005813 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
Kaelyn Uhrain957c8b12013-07-31 20:16:17 +00005814 Diag(CD->getLocStart(),
5815 diag::note_member_reference_arrow_from_operator_arrow);
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005816 }
5817 }
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005818 return ExprError();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005819 }
John McCallb268a282010-08-23 23:25:46 +00005820 Base = Result.get();
5821 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
Richard Smith79c927b2013-11-06 19:31:51 +00005822 OperatorArrows.push_back(OpCall->getDirectCallee());
John McCallb268a282010-08-23 23:25:46 +00005823 BaseType = Base->getType();
John McCallc1538c02009-09-30 01:01:30 +00005824 CanQualType CBaseType = Context.getCanonicalType(BaseType);
David Blaikie82e95a32014-11-19 07:49:47 +00005825 if (!CTypes.insert(CBaseType).second) {
Richard Smith79c927b2013-11-06 19:31:51 +00005826 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
5827 noteOperatorArrows(*this, OperatorArrows);
Fariborz Jahanian10ce9582009-09-30 00:19:41 +00005828 return ExprError();
5829 }
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005830 FirstIteration = false;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005831 }
Mike Stump11289f42009-09-09 15:08:12 +00005832
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00005833 if (OpKind == tok::arrow &&
5834 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
Douglas Gregore4f764f2009-11-20 19:58:21 +00005835 BaseType = BaseType->getPointeeType();
5836 }
Mike Stump11289f42009-09-09 15:08:12 +00005837
Douglas Gregorbf3a8262012-01-12 16:11:24 +00005838 // Objective-C properties allow "." access on Objective-C pointer types,
5839 // so adjust the base type to the object type itself.
5840 if (BaseType->isObjCObjectPointerType())
5841 BaseType = BaseType->getPointeeType();
5842
5843 // C++ [basic.lookup.classref]p2:
5844 // [...] If the type of the object expression is of pointer to scalar
5845 // type, the unqualified-id is looked up in the context of the complete
5846 // postfix-expression.
5847 //
5848 // This also indicates that we could be parsing a pseudo-destructor-name.
5849 // Note that Objective-C class and object types can be pseudo-destructor
John McCall9d145df2015-12-14 19:12:54 +00005850 // expressions or normal member (ivar or property) access expressions, and
5851 // it's legal for the type to be incomplete if this is a pseudo-destructor
5852 // call. We'll do more incomplete-type checks later in the lookup process,
5853 // so just skip this check for ObjC types.
Douglas Gregorbf3a8262012-01-12 16:11:24 +00005854 if (BaseType->isObjCObjectOrInterfaceType()) {
John McCall9d145df2015-12-14 19:12:54 +00005855 ObjectType = ParsedType::make(BaseType);
Douglas Gregorbf3a8262012-01-12 16:11:24 +00005856 MayBePseudoDestructor = true;
John McCall9d145df2015-12-14 19:12:54 +00005857 return Base;
Douglas Gregorbf3a8262012-01-12 16:11:24 +00005858 } else if (!BaseType->isRecordType()) {
David Blaikieefdccaa2016-01-15 23:43:34 +00005859 ObjectType = nullptr;
Douglas Gregore610ada2010-02-24 18:44:31 +00005860 MayBePseudoDestructor = true;
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00005861 return Base;
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005862 }
Mike Stump11289f42009-09-09 15:08:12 +00005863
Douglas Gregor3024f072012-04-16 07:05:22 +00005864 // The object type must be complete (or dependent), or
5865 // C++11 [expr.prim.general]p3:
5866 // Unlike the object expression in other contexts, *this is not required to
5867 // be of complete type for purposes of class member access (5.2.5) outside
5868 // the member function body.
Douglas Gregor3fad6172009-11-17 05:17:33 +00005869 if (!BaseType->isDependentType() &&
Douglas Gregor3024f072012-04-16 07:05:22 +00005870 !isThisOutsideMemberFunctionBody(BaseType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005871 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
Douglas Gregor3fad6172009-11-17 05:17:33 +00005872 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005873
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005874 // C++ [basic.lookup.classref]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005875 // If the id-expression in a class member access (5.2.5) is an
Douglas Gregor3fad6172009-11-17 05:17:33 +00005876 // unqualified-id, and the type of the object expression is of a class
Douglas Gregor2b6ca462009-09-03 21:38:09 +00005877 // type C (or of pointer to a class type C), the unqualified-id is looked
5878 // up in the scope of class C. [...]
John McCallba7bf592010-08-24 05:47:05 +00005879 ObjectType = ParsedType::make(BaseType);
Benjamin Kramer62b95d82012-08-23 21:35:17 +00005880 return Base;
Douglas Gregorb7bfe792009-09-02 22:59:36 +00005881}
5882
Eli Friedman6601b552012-01-25 04:29:24 +00005883static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
David Blaikie1d578782011-12-16 16:03:09 +00005884 tok::TokenKind& OpKind, SourceLocation OpLoc) {
Eli Friedman6601b552012-01-25 04:29:24 +00005885 if (Base->hasPlaceholderType()) {
5886 ExprResult result = S.CheckPlaceholderExpr(Base);
5887 if (result.isInvalid()) return true;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00005888 Base = result.get();
Eli Friedman6601b552012-01-25 04:29:24 +00005889 }
5890 ObjectType = Base->getType();
5891
David Blaikie1d578782011-12-16 16:03:09 +00005892 // C++ [expr.pseudo]p2:
5893 // The left-hand side of the dot operator shall be of scalar type. The
5894 // left-hand side of the arrow operator shall be of pointer to scalar type.
5895 // This scalar type is the object type.
Eli Friedman6601b552012-01-25 04:29:24 +00005896 // Note that this is rather different from the normal handling for the
5897 // arrow operator.
David Blaikie1d578782011-12-16 16:03:09 +00005898 if (OpKind == tok::arrow) {
5899 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
5900 ObjectType = Ptr->getPointeeType();
5901 } else if (!Base->isTypeDependent()) {
5902 // The user wrote "p->" when she probably meant "p."; fix it.
5903 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5904 << ObjectType << true
5905 << FixItHint::CreateReplacement(OpLoc, ".");
5906 if (S.isSFINAEContext())
5907 return true;
5908
5909 OpKind = tok::period;
5910 }
5911 }
5912
5913 return false;
5914}
5915
John McCalldadc5752010-08-24 06:29:42 +00005916ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00005917 SourceLocation OpLoc,
5918 tok::TokenKind OpKind,
5919 const CXXScopeSpec &SS,
5920 TypeSourceInfo *ScopeTypeInfo,
5921 SourceLocation CCLoc,
5922 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00005923 PseudoDestructorTypeStorage Destructed) {
Douglas Gregor678f90d2010-02-25 01:56:36 +00005924 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005925
Eli Friedman0ce4de42012-01-25 04:35:06 +00005926 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00005927 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
5928 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005929
Douglas Gregorc5c57342012-09-10 14:57:06 +00005930 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
5931 !ObjectType->isVectorType()) {
Alp Tokerbfa39342014-01-14 12:51:41 +00005932 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
Nico Weber4bc64992012-01-23 06:08:16 +00005933 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00005934 else {
Nico Weber58829272012-01-23 05:50:57 +00005935 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
5936 << ObjectType << Base->getSourceRange();
Reid Klecknere5025072014-05-01 16:50:23 +00005937 return ExprError();
5938 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005939 }
5940
5941 // C++ [expr.pseudo]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005942 // [...] The cv-unqualified versions of the object type and of the type
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005943 // designated by the pseudo-destructor-name shall be the same type.
Douglas Gregor678f90d2010-02-25 01:56:36 +00005944 if (DestructedTypeInfo) {
5945 QualType DestructedType = DestructedTypeInfo->getType();
5946 SourceLocation DestructedTypeStart
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005947 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
John McCall31168b02011-06-15 23:02:42 +00005948 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
5949 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
5950 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
5951 << ObjectType << DestructedType << Base->getSourceRange()
5952 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005953
John McCall31168b02011-06-15 23:02:42 +00005954 // Recover by setting the destructed type to the object type.
5955 DestructedType = ObjectType;
5956 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
Douglas Gregor678f90d2010-02-25 01:56:36 +00005957 DestructedTypeStart);
John McCall31168b02011-06-15 23:02:42 +00005958 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5959 } else if (DestructedType.getObjCLifetime() !=
5960 ObjectType.getObjCLifetime()) {
5961
5962 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
5963 // Okay: just pretend that the user provided the correctly-qualified
5964 // type.
5965 } else {
5966 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
5967 << ObjectType << DestructedType << Base->getSourceRange()
5968 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
5969 }
5970
5971 // Recover by setting the destructed type to the object type.
5972 DestructedType = ObjectType;
5973 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
5974 DestructedTypeStart);
5975 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
5976 }
Douglas Gregor678f90d2010-02-25 01:56:36 +00005977 }
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005978 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005979
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005980 // C++ [expr.pseudo]p2:
5981 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
5982 // form
5983 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005984 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005985 //
5986 // shall designate the same scalar type.
5987 if (ScopeTypeInfo) {
5988 QualType ScopeType = ScopeTypeInfo->getType();
5989 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
John McCallb86a6b82010-06-11 17:36:40 +00005990 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005991
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005992 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005993 diag::err_pseudo_dtor_type_mismatch)
John McCallb268a282010-08-23 23:25:46 +00005994 << ObjectType << ScopeType << Base->getSourceRange()
Abramo Bagnara1108e7b2010-05-20 10:00:11 +00005995 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005996
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005997 ScopeType = QualType();
Craig Topperc3ec1492014-05-26 06:22:03 +00005998 ScopeTypeInfo = nullptr;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00005999 }
6000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006001
John McCallb268a282010-08-23 23:25:46 +00006002 Expr *Result
6003 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6004 OpKind == tok::arrow, OpLoc,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006005 SS.getWithLocInContext(Context),
John McCallb268a282010-08-23 23:25:46 +00006006 ScopeTypeInfo,
6007 CCLoc,
6008 TildeLoc,
6009 Destructed);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006010
David Majnemerced8bdf2015-02-25 17:36:15 +00006011 return Result;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006012}
6013
John McCalldadc5752010-08-24 06:29:42 +00006014ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
John McCalla2c4e722011-02-25 05:21:17 +00006015 SourceLocation OpLoc,
6016 tok::TokenKind OpKind,
6017 CXXScopeSpec &SS,
6018 UnqualifiedId &FirstTypeName,
6019 SourceLocation CCLoc,
6020 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006021 UnqualifiedId &SecondTypeName) {
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006022 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6023 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6024 "Invalid first type name in pseudo-destructor");
6025 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6026 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6027 "Invalid second type name in pseudo-destructor");
6028
Eli Friedman0ce4de42012-01-25 04:35:06 +00006029 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006030 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6031 return ExprError();
Douglas Gregor678f90d2010-02-25 01:56:36 +00006032
6033 // Compute the object type that we should use for name lookup purposes. Only
6034 // record types and dependent types matter.
John McCallba7bf592010-08-24 05:47:05 +00006035 ParsedType ObjectTypePtrForLookup;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006036 if (!SS.isSet()) {
John McCalla2c4e722011-02-25 05:21:17 +00006037 if (ObjectType->isRecordType())
6038 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
John McCallba7bf592010-08-24 05:47:05 +00006039 else if (ObjectType->isDependentType())
6040 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006042
6043 // Convert the name of the type being destructed (following the ~) into a
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006044 // type (with source-location information).
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006045 QualType DestructedType;
Craig Topperc3ec1492014-05-26 06:22:03 +00006046 TypeSourceInfo *DestructedTypeInfo = nullptr;
Douglas Gregor678f90d2010-02-25 01:56:36 +00006047 PseudoDestructorTypeStorage Destructed;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006048 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006049 ParsedType T = getTypeName(*SecondTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006050 SecondTypeName.StartLocation,
Fariborz Jahanian87967422011-02-08 18:05:59 +00006051 S, &SS, true, false, ObjectTypePtrForLookup);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006052 if (!T &&
Douglas Gregor678f90d2010-02-25 01:56:36 +00006053 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6054 (!SS.isSet() && ObjectType->isDependentType()))) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006055 // The name of the type being destroyed is a dependent name, and we
Douglas Gregor678f90d2010-02-25 01:56:36 +00006056 // couldn't find anything useful in scope. Just store the identifier and
6057 // it's location, and we'll perform (qualified) name lookup again at
6058 // template instantiation time.
6059 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6060 SecondTypeName.StartLocation);
6061 } else if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006062 Diag(SecondTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006063 diag::err_pseudo_dtor_destructor_non_type)
6064 << SecondTypeName.Identifier << ObjectType;
6065 if (isSFINAEContext())
6066 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006067
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006068 // Recover by assuming we had the right type all along.
6069 DestructedType = ObjectType;
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006070 } else
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006071 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006072 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006073 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006074 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006075 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006076 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006077 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006078 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006079 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006080 TemplateId->TemplateNameLoc,
6081 TemplateId->LAngleLoc,
6082 TemplateArgsPtr,
6083 TemplateId->RAngleLoc);
6084 if (T.isInvalid() || !T.get()) {
6085 // Recover by assuming we had the right type all along.
6086 DestructedType = ObjectType;
6087 } else
6088 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006090
6091 // If we've performed some kind of recovery, (re-)build the type source
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006092 // information.
Douglas Gregor678f90d2010-02-25 01:56:36 +00006093 if (!DestructedType.isNull()) {
6094 if (!DestructedTypeInfo)
6095 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006096 SecondTypeName.StartLocation);
Douglas Gregor678f90d2010-02-25 01:56:36 +00006097 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006099
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006100 // Convert the name of the scope type (the type prior to '::') into a type.
Craig Topperc3ec1492014-05-26 06:22:03 +00006101 TypeSourceInfo *ScopeTypeInfo = nullptr;
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006102 QualType ScopeType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006103 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006104 FirstTypeName.Identifier) {
6105 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006106 ParsedType T = getTypeName(*FirstTypeName.Identifier,
John McCallba7bf592010-08-24 05:47:05 +00006107 FirstTypeName.StartLocation,
Douglas Gregora6ce6082011-02-25 18:19:59 +00006108 S, &SS, true, false, ObjectTypePtrForLookup);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006109 if (!T) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006110 Diag(FirstTypeName.StartLocation,
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006111 diag::err_pseudo_dtor_destructor_non_type)
6112 << FirstTypeName.Identifier << ObjectType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006113
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006114 if (isSFINAEContext())
6115 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006116
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006117 // Just drop this type. It's unnecessary anyway.
6118 ScopeType = QualType();
6119 } else
6120 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006121 } else {
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006122 // Resolve the template-id to a type.
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006123 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
Benjamin Kramercc4c49d2012-08-23 23:38:35 +00006124 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006125 TemplateId->NumArgs);
Douglas Gregore7c20652011-03-02 00:47:37 +00006126 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
Abramo Bagnara48c05be2012-02-06 14:41:24 +00006127 TemplateId->TemplateKWLoc,
Douglas Gregore7c20652011-03-02 00:47:37 +00006128 TemplateId->Template,
Douglas Gregorb1dd23f2010-02-24 22:38:50 +00006129 TemplateId->TemplateNameLoc,
6130 TemplateId->LAngleLoc,
6131 TemplateArgsPtr,
6132 TemplateId->RAngleLoc);
6133 if (T.isInvalid() || !T.get()) {
6134 // Recover by dropping this type.
6135 ScopeType = QualType();
6136 } else
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006137 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
Douglas Gregor0d5b0a12010-02-24 21:29:12 +00006138 }
6139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006140
Douglas Gregor90ad9222010-02-24 23:02:30 +00006141 if (!ScopeType.isNull() && !ScopeTypeInfo)
6142 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6143 FirstTypeName.StartLocation);
6144
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006145
John McCallb268a282010-08-23 23:25:46 +00006146 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
Douglas Gregorcdbd5152010-02-24 23:50:37 +00006147 ScopeTypeInfo, CCLoc, TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006148 Destructed);
Douglas Gregore610ada2010-02-24 18:44:31 +00006149}
6150
David Blaikie1d578782011-12-16 16:03:09 +00006151ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6152 SourceLocation OpLoc,
6153 tok::TokenKind OpKind,
6154 SourceLocation TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006155 const DeclSpec& DS) {
Eli Friedman0ce4de42012-01-25 04:35:06 +00006156 QualType ObjectType;
David Blaikie1d578782011-12-16 16:03:09 +00006157 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6158 return ExprError();
6159
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006160 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6161 false);
David Blaikie1d578782011-12-16 16:03:09 +00006162
6163 TypeLocBuilder TLB;
6164 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6165 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6166 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6167 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6168
6169 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
Craig Topperc3ec1492014-05-26 06:22:03 +00006170 nullptr, SourceLocation(), TildeLoc,
David Majnemerced8bdf2015-02-25 17:36:15 +00006171 Destructed);
David Blaikie1d578782011-12-16 16:03:09 +00006172}
6173
John Wiegley01296292011-04-08 18:41:53 +00006174ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
Eli Friedman2fb85122012-03-01 01:30:04 +00006175 CXXConversionDecl *Method,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006176 bool HadMultipleCandidates) {
Eli Friedman98b01ed2012-03-01 04:01:32 +00006177 if (Method->getParent()->isLambda() &&
6178 Method->getConversionType()->isBlockPointerType()) {
6179 // This is a lambda coversion to block pointer; check if the argument
6180 // is a LambdaExpr.
6181 Expr *SubE = E;
6182 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6183 if (CE && CE->getCastKind() == CK_NoOp)
6184 SubE = CE->getSubExpr();
6185 SubE = SubE->IgnoreParens();
6186 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6187 SubE = BE->getSubExpr();
6188 if (isa<LambdaExpr>(SubE)) {
6189 // For the conversion to block pointer on a lambda expression, we
6190 // construct a special BlockLiteral instead; this doesn't really make
6191 // a difference in ARC, but outside of ARC the resulting block literal
6192 // follows the normal lifetime rules for block literals instead of being
6193 // autoreleased.
6194 DiagnosticErrorTrap Trap(Diags);
6195 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6196 E->getExprLoc(),
6197 Method, E);
6198 if (Exp.isInvalid())
6199 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6200 return Exp;
6201 }
6202 }
Eli Friedman98b01ed2012-03-01 04:01:32 +00006203
Craig Topperc3ec1492014-05-26 06:22:03 +00006204 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
John Wiegley01296292011-04-08 18:41:53 +00006205 FoundDecl, Method);
6206 if (Exp.isInvalid())
Douglas Gregor668443e2011-01-20 00:18:04 +00006207 return true;
Eli Friedmanf7195532009-12-09 04:53:56 +00006208
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00006209 MemberExpr *ME = new (Context) MemberExpr(
6210 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6211 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006212 if (HadMultipleCandidates)
6213 ME->setHadMultipleCandidates(true);
Nick Lewyckya096b142013-02-12 08:08:54 +00006214 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006215
Alp Toker314cc812014-01-25 16:55:45 +00006216 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +00006217 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6218 ResultType = ResultType.getNonLValueExprType(Context);
6219
Douglas Gregor27381f32009-11-23 12:27:39 +00006220 CXXMemberCallExpr *CE =
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006221 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
John Wiegley01296292011-04-08 18:41:53 +00006222 Exp.get()->getLocEnd());
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006223 return CE;
6224}
6225
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006226ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6227 SourceLocation RParen) {
Aaron Ballmanedc80842015-04-27 22:31:12 +00006228 // If the operand is an unresolved lookup expression, the expression is ill-
6229 // formed per [over.over]p1, because overloaded function names cannot be used
6230 // without arguments except in explicit contexts.
6231 ExprResult R = CheckPlaceholderExpr(Operand);
6232 if (R.isInvalid())
6233 return R;
6234
6235 // The operand may have been modified when checking the placeholder type.
6236 Operand = R.get();
6237
Aaron Ballman6c93b3e2014-12-17 21:57:17 +00006238 if (ActiveTemplateInstantiations.empty() &&
6239 Operand->HasSideEffects(Context, false)) {
6240 // The expression operand for noexcept is in an unevaluated expression
6241 // context, so side effects could result in unintended consequences.
6242 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6243 }
6244
Richard Smithf623c962012-04-17 00:58:00 +00006245 CanThrowResult CanThrow = canThrow(Operand);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006246 return new (Context)
6247 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006248}
6249
6250ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6251 Expr *Operand, SourceLocation RParen) {
6252 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
Sebastian Redl22e3a932010-09-10 20:55:37 +00006253}
6254
Eli Friedmanf798f652012-05-24 22:04:19 +00006255static bool IsSpecialDiscardedValue(Expr *E) {
6256 // In C++11, discarded-value expressions of a certain form are special,
6257 // according to [expr]p10:
6258 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6259 // expression is an lvalue of volatile-qualified type and it has
6260 // one of the following forms:
6261 E = E->IgnoreParens();
6262
Eli Friedmanc49c2262012-05-24 22:36:31 +00006263 // - id-expression (5.1.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006264 if (isa<DeclRefExpr>(E))
6265 return true;
6266
Eli Friedmanc49c2262012-05-24 22:36:31 +00006267 // - subscripting (5.2.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006268 if (isa<ArraySubscriptExpr>(E))
6269 return true;
6270
Eli Friedmanc49c2262012-05-24 22:36:31 +00006271 // - class member access (5.2.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006272 if (isa<MemberExpr>(E))
6273 return true;
6274
Eli Friedmanc49c2262012-05-24 22:36:31 +00006275 // - indirection (5.3.1),
Eli Friedmanf798f652012-05-24 22:04:19 +00006276 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6277 if (UO->getOpcode() == UO_Deref)
6278 return true;
6279
6280 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
Eli Friedmanc49c2262012-05-24 22:36:31 +00006281 // - pointer-to-member operation (5.5),
Eli Friedmanf798f652012-05-24 22:04:19 +00006282 if (BO->isPtrMemOp())
6283 return true;
6284
Eli Friedmanc49c2262012-05-24 22:36:31 +00006285 // - comma expression (5.18) where the right operand is one of the above.
Eli Friedmanf798f652012-05-24 22:04:19 +00006286 if (BO->getOpcode() == BO_Comma)
6287 return IsSpecialDiscardedValue(BO->getRHS());
6288 }
6289
Eli Friedmanc49c2262012-05-24 22:36:31 +00006290 // - conditional expression (5.16) where both the second and the third
Eli Friedmanf798f652012-05-24 22:04:19 +00006291 // operands are one of the above, or
6292 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6293 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6294 IsSpecialDiscardedValue(CO->getFalseExpr());
6295 // The related edge case of "*x ?: *x".
6296 if (BinaryConditionalOperator *BCO =
6297 dyn_cast<BinaryConditionalOperator>(E)) {
6298 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6299 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6300 IsSpecialDiscardedValue(BCO->getFalseExpr());
6301 }
6302
6303 // Objective-C++ extensions to the rule.
6304 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6305 return true;
6306
6307 return false;
6308}
6309
John McCall34376a62010-12-04 03:47:34 +00006310/// Perform the conversions required for an expression used in a
6311/// context that ignores the result.
John Wiegley01296292011-04-08 18:41:53 +00006312ExprResult Sema::IgnoredValueConversions(Expr *E) {
John McCall526ab472011-10-25 17:37:35 +00006313 if (E->hasPlaceholderType()) {
6314 ExprResult result = CheckPlaceholderExpr(E);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006315 if (result.isInvalid()) return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006316 E = result.get();
John McCall526ab472011-10-25 17:37:35 +00006317 }
6318
John McCallfee942d2010-12-02 02:07:15 +00006319 // C99 6.3.2.1:
6320 // [Except in specific positions,] an lvalue that does not have
6321 // array type is converted to the value stored in the
6322 // designated object (and is no longer an lvalue).
John McCalld68b2d02011-06-27 21:24:11 +00006323 if (E->isRValue()) {
6324 // In C, function designators (i.e. expressions of function type)
6325 // are r-values, but we still want to do function-to-pointer decay
6326 // on them. This is both technically correct and convenient for
6327 // some clients.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006328 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
John McCalld68b2d02011-06-27 21:24:11 +00006329 return DefaultFunctionArrayConversion(E);
6330
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006331 return E;
John McCalld68b2d02011-06-27 21:24:11 +00006332 }
John McCallfee942d2010-12-02 02:07:15 +00006333
Eli Friedmanf798f652012-05-24 22:04:19 +00006334 if (getLangOpts().CPlusPlus) {
6335 // The C++11 standard defines the notion of a discarded-value expression;
6336 // normally, we don't need to do anything to handle it, but if it is a
6337 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6338 // conversion.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006339 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
Eli Friedmanf798f652012-05-24 22:04:19 +00006340 E->getType().isVolatileQualified() &&
6341 IsSpecialDiscardedValue(E)) {
6342 ExprResult Res = DefaultLvalueConversion(E);
6343 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006344 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006345 E = Res.get();
Faisal Valia17d19f2013-11-07 05:17:06 +00006346 }
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006347 return E;
Eli Friedmanf798f652012-05-24 22:04:19 +00006348 }
John McCall34376a62010-12-04 03:47:34 +00006349
6350 // GCC seems to also exclude expressions of incomplete enum type.
6351 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6352 if (!T->getDecl()->isComplete()) {
6353 // FIXME: stupid workaround for a codegen bug!
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006354 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006355 return E;
John McCall34376a62010-12-04 03:47:34 +00006356 }
6357 }
6358
John Wiegley01296292011-04-08 18:41:53 +00006359 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6360 if (Res.isInvalid())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006361 return E;
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006362 E = Res.get();
John Wiegley01296292011-04-08 18:41:53 +00006363
John McCallca61b652010-12-04 12:29:11 +00006364 if (!E->getType()->isVoidType())
6365 RequireCompleteType(E->getExprLoc(), E->getType(),
6366 diag::err_incomplete_type);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006367 return E;
John McCall34376a62010-12-04 03:47:34 +00006368}
6369
Faisal Valia17d19f2013-11-07 05:17:06 +00006370// If we can unambiguously determine whether Var can never be used
6371// in a constant expression, return true.
6372// - if the variable and its initializer are non-dependent, then
6373// we can unambiguously check if the variable is a constant expression.
6374// - if the initializer is not value dependent - we can determine whether
6375// it can be used to initialize a constant expression. If Init can not
6376// be used to initialize a constant expression we conclude that Var can
6377// never be a constant expression.
6378// - FXIME: if the initializer is dependent, we can still do some analysis and
6379// identify certain cases unambiguously as non-const by using a Visitor:
6380// - such as those that involve odr-use of a ParmVarDecl, involve a new
6381// delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
6382static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
6383 ASTContext &Context) {
6384 if (isa<ParmVarDecl>(Var)) return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00006385 const VarDecl *DefVD = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006386
6387 // If there is no initializer - this can not be a constant expression.
6388 if (!Var->getAnyInitializer(DefVD)) return true;
6389 assert(DefVD);
6390 if (DefVD->isWeak()) return false;
6391 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
Richard Smithc941ba92014-02-06 23:35:16 +00006392
Faisal Valia17d19f2013-11-07 05:17:06 +00006393 Expr *Init = cast<Expr>(Eval->Value);
6394
6395 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
Richard Smithc941ba92014-02-06 23:35:16 +00006396 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6397 // of value-dependent expressions, and use it here to determine whether the
6398 // initializer is a potential constant expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006399 return false;
Richard Smithc941ba92014-02-06 23:35:16 +00006400 }
6401
Faisal Valia17d19f2013-11-07 05:17:06 +00006402 return !IsVariableAConstantExpression(Var, Context);
6403}
6404
Faisal Valiab3d6462013-12-07 20:22:44 +00006405/// \brief Check if the current lambda has any potential captures
6406/// that must be captured by any of its enclosing lambdas that are ready to
6407/// capture. If there is a lambda that can capture a nested
6408/// potential-capture, go ahead and do so. Also, check to see if any
6409/// variables are uncaptureable or do not involve an odr-use so do not
6410/// need to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006411
Faisal Valiab3d6462013-12-07 20:22:44 +00006412static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6413 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6414
Faisal Valia17d19f2013-11-07 05:17:06 +00006415 assert(!S.isUnevaluatedContext());
6416 assert(S.CurContext->isDependentContext());
Faisal Valiab3d6462013-12-07 20:22:44 +00006417 assert(CurrentLSI->CallOperator == S.CurContext &&
6418 "The current call operator must be synchronized with Sema's CurContext");
6419
6420 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6421
6422 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6423 S.FunctionScopes.data(), S.FunctionScopes.size());
6424
6425 // All the potentially captureable variables in the current nested
Faisal Valia17d19f2013-11-07 05:17:06 +00006426 // lambda (within a generic outer lambda), must be captured by an
6427 // outer lambda that is enclosed within a non-dependent context.
Faisal Valiab3d6462013-12-07 20:22:44 +00006428 const unsigned NumPotentialCaptures =
6429 CurrentLSI->getNumPotentialVariableCaptures();
6430 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
Craig Topperc3ec1492014-05-26 06:22:03 +00006431 Expr *VarExpr = nullptr;
6432 VarDecl *Var = nullptr;
Faisal Valia17d19f2013-11-07 05:17:06 +00006433 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
Faisal Valiab3d6462013-12-07 20:22:44 +00006434 // If the variable is clearly identified as non-odr-used and the full
6435 // expression is not instantiation dependent, only then do we not
6436 // need to check enclosing lambda's for speculative captures.
6437 // For e.g.:
6438 // Even though 'x' is not odr-used, it should be captured.
6439 // int test() {
6440 // const int x = 10;
6441 // auto L = [=](auto a) {
6442 // (void) +x + a;
6443 // };
6444 // }
6445 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
Faisal Valia17d19f2013-11-07 05:17:06 +00006446 !IsFullExprInstantiationDependent)
Faisal Valiab3d6462013-12-07 20:22:44 +00006447 continue;
6448
6449 // If we have a capture-capable lambda for the variable, go ahead and
6450 // capture the variable in that lambda (and all its enclosing lambdas).
6451 if (const Optional<unsigned> Index =
6452 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6453 FunctionScopesArrayRef, Var, S)) {
6454 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6455 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6456 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00006457 }
6458 const bool IsVarNeverAConstantExpression =
6459 VariableCanNeverBeAConstantExpression(Var, S.Context);
6460 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6461 // This full expression is not instantiation dependent or the variable
6462 // can not be used in a constant expression - which means
6463 // this variable must be odr-used here, so diagnose a
6464 // capture violation early, if the variable is un-captureable.
6465 // This is purely for diagnosing errors early. Otherwise, this
6466 // error would get diagnosed when the lambda becomes capture ready.
6467 QualType CaptureType, DeclRefType;
6468 SourceLocation ExprLoc = VarExpr->getExprLoc();
6469 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6470 /*EllipsisLoc*/ SourceLocation(),
6471 /*BuildAndDiagnose*/false, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006472 DeclRefType, nullptr)) {
Faisal Valia17d19f2013-11-07 05:17:06 +00006473 // We will never be able to capture this variable, and we need
6474 // to be able to in any and all instantiations, so diagnose it.
6475 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6476 /*EllipsisLoc*/ SourceLocation(),
6477 /*BuildAndDiagnose*/true, CaptureType,
Craig Topperc3ec1492014-05-26 06:22:03 +00006478 DeclRefType, nullptr);
Faisal Valia17d19f2013-11-07 05:17:06 +00006479 }
6480 }
6481 }
6482
Faisal Valiab3d6462013-12-07 20:22:44 +00006483 // Check if 'this' needs to be captured.
Faisal Valia17d19f2013-11-07 05:17:06 +00006484 if (CurrentLSI->hasPotentialThisCapture()) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006485 // If we have a capture-capable lambda for 'this', go ahead and capture
6486 // 'this' in that lambda (and all its enclosing lambdas).
6487 if (const Optional<unsigned> Index =
6488 getStackIndexOfNearestEnclosingCaptureCapableLambda(
Craig Topperc3ec1492014-05-26 06:22:03 +00006489 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
Faisal Valiab3d6462013-12-07 20:22:44 +00006490 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6491 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6492 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6493 &FunctionScopeIndexOfCapturableLambda);
Faisal Valia17d19f2013-11-07 05:17:06 +00006494 }
6495 }
Faisal Valiab3d6462013-12-07 20:22:44 +00006496
6497 // Reset all the potential captures at the end of each full-expression.
Faisal Valia17d19f2013-11-07 05:17:06 +00006498 CurrentLSI->clearPotentialCaptures();
6499}
6500
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006501static ExprResult attemptRecovery(Sema &SemaRef,
6502 const TypoCorrectionConsumer &Consumer,
6503 TypoCorrection TC) {
6504 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6505 Consumer.getLookupResult().getLookupKind());
6506 const CXXScopeSpec *SS = Consumer.getSS();
6507 CXXScopeSpec NewSS;
6508
6509 // Use an approprate CXXScopeSpec for building the expr.
6510 if (auto *NNS = TC.getCorrectionSpecifier())
6511 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
6512 else if (SS && !TC.WillReplaceSpecifier())
6513 NewSS = *SS;
6514
Richard Smithde6d6c42015-12-29 19:43:10 +00006515 if (auto *ND = TC.getFoundDecl()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006516 R.setLookupName(ND->getDeclName());
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006517 R.addDecl(ND);
6518 if (ND->isCXXClassMember()) {
Nick Lewycky01ad4ae2014-12-13 02:54:28 +00006519 // Figure out the correct naming class to add to the LookupResult.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006520 CXXRecordDecl *Record = nullptr;
6521 if (auto *NNS = TC.getCorrectionSpecifier())
6522 Record = NNS->getAsType()->getAsCXXRecordDecl();
6523 if (!Record)
Olivier Goffarted13fab2015-01-09 09:37:26 +00006524 Record =
6525 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
6526 if (Record)
6527 R.setNamingClass(Record);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006528
6529 // Detect and handle the case where the decl might be an implicit
6530 // member.
6531 bool MightBeImplicitMember;
6532 if (!Consumer.isAddressOfOperand())
6533 MightBeImplicitMember = true;
6534 else if (!NewSS.isEmpty())
6535 MightBeImplicitMember = false;
6536 else if (R.isOverloadedResult())
6537 MightBeImplicitMember = false;
6538 else if (R.isUnresolvableResult())
6539 MightBeImplicitMember = true;
6540 else
6541 MightBeImplicitMember = isa<FieldDecl>(ND) ||
6542 isa<IndirectFieldDecl>(ND) ||
6543 isa<MSPropertyDecl>(ND);
6544
6545 if (MightBeImplicitMember)
6546 return SemaRef.BuildPossibleImplicitMemberExpr(
6547 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00006548 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006549 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
6550 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
6551 Ivar->getIdentifier());
6552 }
6553 }
6554
Kaelyn Takata6f71ce22014-11-20 22:06:33 +00006555 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
6556 /*AcceptInvalidDecl*/ true);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006557}
6558
Kaelyn Takata6c759512014-10-27 18:07:37 +00006559namespace {
Kaelyn Takata57e07c92014-11-20 22:06:44 +00006560class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
6561 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
6562
6563public:
6564 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
6565 : TypoExprs(TypoExprs) {}
6566 bool VisitTypoExpr(TypoExpr *TE) {
6567 TypoExprs.insert(TE);
6568 return true;
6569 }
6570};
6571
Kaelyn Takata6c759512014-10-27 18:07:37 +00006572class TransformTypos : public TreeTransform<TransformTypos> {
6573 typedef TreeTransform<TransformTypos> BaseTransform;
6574
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006575 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
6576 // process of being initialized.
Kaelyn Takata49d84322014-11-11 23:26:56 +00006577 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006578 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006579 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006580 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006581
6582 /// \brief Emit diagnostics for all of the TypoExprs encountered.
6583 /// If the TypoExprs were successfully corrected, then the diagnostics should
6584 /// suggest the corrections. Otherwise the diagnostics will not suggest
6585 /// anything (having been passed an empty TypoCorrection).
6586 void EmitAllDiagnostics() {
6587 for (auto E : TypoExprs) {
6588 TypoExpr *TE = cast<TypoExpr>(E);
6589 auto &State = SemaRef.getTypoExprState(TE);
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006590 if (State.DiagHandler) {
6591 TypoCorrection TC = State.Consumer->getCurrentCorrection();
6592 ExprResult Replacement = TransformCache[TE];
6593
6594 // Extract the NamedDecl from the transformed TypoExpr and add it to the
6595 // TypoCorrection, replacing the existing decls. This ensures the right
6596 // NamedDecl is used in diagnostics e.g. in the case where overload
6597 // resolution was used to select one from several possible decls that
6598 // had been stored in the TypoCorrection.
6599 if (auto *ND = getDeclFromExpr(
6600 Replacement.isInvalid() ? nullptr : Replacement.get()))
6601 TC.setCorrectionDecl(ND);
6602
6603 State.DiagHandler(TC);
6604 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00006605 SemaRef.clearDelayedTypo(TE);
6606 }
6607 }
6608
6609 /// \brief If corrections for the first TypoExpr have been exhausted for a
6610 /// given combination of the other TypoExprs, retry those corrections against
6611 /// the next combination of substitutions for the other TypoExprs by advancing
6612 /// to the next potential correction of the second TypoExpr. For the second
6613 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
6614 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
6615 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
6616 /// TransformCache). Returns true if there is still any untried combinations
6617 /// of corrections.
6618 bool CheckAndAdvanceTypoExprCorrectionStreams() {
6619 for (auto TE : TypoExprs) {
6620 auto &State = SemaRef.getTypoExprState(TE);
6621 TransformCache.erase(TE);
6622 if (!State.Consumer->finished())
6623 return true;
6624 State.Consumer->resetCorrectionStream();
6625 }
6626 return false;
6627 }
6628
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006629 NamedDecl *getDeclFromExpr(Expr *E) {
6630 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
6631 E = OverloadResolution[OE];
6632
6633 if (!E)
6634 return nullptr;
6635 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00006636 return DRE->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006637 if (auto *ME = dyn_cast<MemberExpr>(E))
Richard Smithde6d6c42015-12-29 19:43:10 +00006638 return ME->getFoundDecl();
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006639 // FIXME: Add any other expr types that could be be seen by the delayed typo
6640 // correction TreeTransform for which the corresponding TypoCorrection could
Nick Lewycky39f9dbc2014-12-16 21:48:39 +00006641 // contain multiple decls.
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006642 return nullptr;
6643 }
6644
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006645 ExprResult TryTransform(Expr *E) {
6646 Sema::SFINAETrap Trap(SemaRef);
6647 ExprResult Res = TransformExpr(E);
6648 if (Trap.hasErrorOccurred() || Res.isInvalid())
6649 return ExprError();
6650
6651 return ExprFilter(Res.get());
6652 }
6653
Kaelyn Takata6c759512014-10-27 18:07:37 +00006654public:
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006655 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
6656 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
Kaelyn Takata6c759512014-10-27 18:07:37 +00006657
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006658 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
6659 MultiExprArg Args,
6660 SourceLocation RParenLoc,
6661 Expr *ExecConfig = nullptr) {
6662 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
6663 RParenLoc, ExecConfig);
6664 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
Reid Klecknera9e65ba2014-12-13 01:11:23 +00006665 if (Result.isUsable()) {
Reid Klecknera7fe33e2014-12-13 00:53:10 +00006666 Expr *ResultCall = Result.get();
6667 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
6668 ResultCall = BE->getSubExpr();
6669 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
6670 OverloadResolution[OE] = CE->getCallee();
6671 }
Kaelyn Takatafe408a72014-10-27 18:07:46 +00006672 }
6673 return Result;
6674 }
6675
Kaelyn Takata6c759512014-10-27 18:07:37 +00006676 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
6677
Saleem Abdulrasoola1742412015-10-31 00:39:15 +00006678 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
6679
Saleem Abdulrasool407f36b2016-02-07 02:30:55 +00006680 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
6681 return Owned(E);
6682 }
6683
Saleem Abdulrasool02e19a12016-02-07 02:30:59 +00006684 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
6685 return Owned(E);
6686 }
6687
Kaelyn Takata6c759512014-10-27 18:07:37 +00006688 ExprResult Transform(Expr *E) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006689 ExprResult Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006690 while (true) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006691 Res = TryTransform(E);
Kaelyn Takata49d84322014-11-11 23:26:56 +00006692
Kaelyn Takata6c759512014-10-27 18:07:37 +00006693 // Exit if either the transform was valid or if there were no TypoExprs
6694 // to transform that still have any untried correction candidates..
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006695 if (!Res.isInvalid() ||
Kaelyn Takata6c759512014-10-27 18:07:37 +00006696 !CheckAndAdvanceTypoExprCorrectionStreams())
6697 break;
6698 }
6699
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006700 // Ensure none of the TypoExprs have multiple typo correction candidates
6701 // with the same edit length that pass all the checks and filters.
6702 // TODO: Properly handle various permutations of possible corrections when
6703 // there is more than one potentially ambiguous typo correction.
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00006704 // Also, disable typo correction while attempting the transform when
6705 // handling potentially ambiguous typo corrections as any new TypoExprs will
6706 // have been introduced by the application of one of the correction
6707 // candidates and add little to no value if corrected.
6708 SemaRef.DisableTypoCorrection = true;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006709 while (!AmbiguousTypoExprs.empty()) {
6710 auto TE = AmbiguousTypoExprs.back();
6711 auto Cached = TransformCache[TE];
Kaelyn Takata7a503692015-01-27 22:01:39 +00006712 auto &State = SemaRef.getTypoExprState(TE);
6713 State.Consumer->saveCurrentPosition();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006714 TransformCache.erase(TE);
6715 if (!TryTransform(E).isInvalid()) {
Kaelyn Takata7a503692015-01-27 22:01:39 +00006716 State.Consumer->resetCorrectionStream();
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006717 TransformCache.erase(TE);
6718 Res = ExprError();
6719 break;
Kaelyn Takata7a503692015-01-27 22:01:39 +00006720 }
6721 AmbiguousTypoExprs.remove(TE);
6722 State.Consumer->restoreSavedPosition();
6723 TransformCache[TE] = Cached;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006724 }
Kaelyn Takata26ffc5f2015-06-25 23:47:39 +00006725 SemaRef.DisableTypoCorrection = false;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006726
Kaelyn Takata57e07c92014-11-20 22:06:44 +00006727 // Ensure that all of the TypoExprs within the current Expr have been found.
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006728 if (!Res.isUsable())
Kaelyn Takata57e07c92014-11-20 22:06:44 +00006729 FindTypoExprs(TypoExprs).TraverseStmt(E);
6730
Kaelyn Takata6c759512014-10-27 18:07:37 +00006731 EmitAllDiagnostics();
6732
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006733 return Res;
Kaelyn Takata6c759512014-10-27 18:07:37 +00006734 }
6735
6736 ExprResult TransformTypoExpr(TypoExpr *E) {
6737 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
6738 // cached transformation result if there is one and the TypoExpr isn't the
6739 // first one that was encountered.
6740 auto &CacheEntry = TransformCache[E];
6741 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
6742 return CacheEntry;
6743 }
6744
6745 auto &State = SemaRef.getTypoExprState(E);
6746 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
6747
6748 // For the first TypoExpr and an uncached TypoExpr, find the next likely
6749 // typo correction and return it.
6750 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
Richard Smithde6d6c42015-12-29 19:43:10 +00006751 if (InitDecl && TC.getFoundDecl() == InitDecl)
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006752 continue;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006753 ExprResult NE = State.RecoveryHandler ?
6754 State.RecoveryHandler(SemaRef, E, TC) :
6755 attemptRecovery(SemaRef, *State.Consumer, TC);
6756 if (!NE.isInvalid()) {
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006757 // Check whether there may be a second viable correction with the same
6758 // edit distance; if so, remember this TypoExpr may have an ambiguous
6759 // correction so it can be more thoroughly vetted later.
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006760 TypoCorrection Next;
Kaelyn Takata5ca2ecd2014-11-21 18:47:58 +00006761 if ((Next = State.Consumer->peekNextCorrection()) &&
6762 Next.getEditDistance(false) == TC.getEditDistance(false)) {
6763 AmbiguousTypoExprs.insert(E);
6764 } else {
6765 AmbiguousTypoExprs.remove(E);
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006766 }
6767 assert(!NE.isUnset() &&
6768 "Typo was transformed into a valid-but-null ExprResult");
Kaelyn Takata6c759512014-10-27 18:07:37 +00006769 return CacheEntry = NE;
Kaelyn Takata3f9794f2014-11-20 22:06:30 +00006770 }
Kaelyn Takata6c759512014-10-27 18:07:37 +00006771 }
6772 return CacheEntry = ExprError();
6773 }
6774};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006775}
Faisal Valia17d19f2013-11-07 05:17:06 +00006776
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006777ExprResult
6778Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
6779 llvm::function_ref<ExprResult(Expr *)> Filter) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00006780 // If the current evaluation context indicates there are uncorrected typos
6781 // and the current expression isn't guaranteed to not have typos, try to
6782 // resolve any TypoExpr nodes that might be in the expression.
Kaelyn Takatac71dda22014-12-02 22:05:35 +00006783 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
Kaelyn Takata49d84322014-11-11 23:26:56 +00006784 (E->isTypeDependent() || E->isValueDependent() ||
6785 E->isInstantiationDependent())) {
Kaelyn Takatac49838b2015-01-28 21:10:46 +00006786 auto TyposInContext = ExprEvalContexts.back().NumTypos;
6787 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
6788 ExprEvalContexts.back().NumTypos = ~0U;
Kaelyn Takata49d84322014-11-11 23:26:56 +00006789 auto TyposResolved = DelayedTypos.size();
Kaelyn Takatab8499f02015-05-05 19:17:03 +00006790 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
Kaelyn Takatac49838b2015-01-28 21:10:46 +00006791 ExprEvalContexts.back().NumTypos = TyposInContext;
Kaelyn Takata49d84322014-11-11 23:26:56 +00006792 TyposResolved -= DelayedTypos.size();
Nick Lewycky4d59b772014-12-16 22:02:06 +00006793 if (Result.isInvalid() || Result.get() != E) {
Kaelyn Takata49d84322014-11-11 23:26:56 +00006794 ExprEvalContexts.back().NumTypos -= TyposResolved;
6795 return Result;
6796 }
Nick Lewycky4d59b772014-12-16 22:02:06 +00006797 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
Kaelyn Takata49d84322014-11-11 23:26:56 +00006798 }
6799 return E;
6800}
6801
Richard Smith945f8d32013-01-14 22:39:08 +00006802ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006803 bool DiscardedValue,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00006804 bool IsConstexpr,
6805 bool IsLambdaInitCaptureInitializer) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00006806 ExprResult FullExpr = FE;
John Wiegley01296292011-04-08 18:41:53 +00006807
6808 if (!FullExpr.get())
Douglas Gregora6e053e2010-12-15 01:34:56 +00006809 return ExprError();
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00006810
6811 // If we are an init-expression in a lambdas init-capture, we should not
6812 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
6813 // containing full-expression is done).
6814 // template<class ... Ts> void test(Ts ... t) {
6815 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
6816 // return a;
6817 // }() ...);
6818 // }
6819 // FIXME: This is a hack. It would be better if we pushed the lambda scope
6820 // when we parse the lambda introducer, and teach capturing (but not
6821 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
6822 // corresponding class yet (that is, have LambdaScopeInfo either represent a
6823 // lambda where we've entered the introducer but not the body, or represent a
6824 // lambda where we've entered the body, depending on where the
6825 // parser/instantiation has got to).
6826 if (!IsLambdaInitCaptureInitializer &&
6827 DiagnoseUnexpandedParameterPack(FullExpr.get()))
Douglas Gregor506bd562010-12-13 22:49:22 +00006828 return ExprError();
6829
Douglas Gregorb5af2e92013-03-07 22:57:58 +00006830 // Top-level expressions default to 'id' when we're in a debugger.
Richard Smith945f8d32013-01-14 22:39:08 +00006831 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
Douglas Gregorb5af2e92013-03-07 22:57:58 +00006832 FullExpr.get()->getType() == Context.UnknownAnyTy) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006833 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
Douglas Gregor95715f92011-12-15 00:53:32 +00006834 if (FullExpr.isInvalid())
6835 return ExprError();
6836 }
Douglas Gregor0ec210b2011-03-07 02:05:23 +00006837
Richard Smith945f8d32013-01-14 22:39:08 +00006838 if (DiscardedValue) {
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006839 FullExpr = CheckPlaceholderExpr(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00006840 if (FullExpr.isInvalid())
6841 return ExprError();
6842
Nikola Smiljanic01a75982014-05-29 10:55:11 +00006843 FullExpr = IgnoredValueConversions(FullExpr.get());
Richard Smith945f8d32013-01-14 22:39:08 +00006844 if (FullExpr.isInvalid())
6845 return ExprError();
6846 }
John Wiegley01296292011-04-08 18:41:53 +00006847
Kaelyn Takata49d84322014-11-11 23:26:56 +00006848 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
6849 if (FullExpr.isInvalid())
6850 return ExprError();
Kaelyn Takata6c759512014-10-27 18:07:37 +00006851
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006852 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
Faisal Valia17d19f2013-11-07 05:17:06 +00006853
Faisal Vali218e94b2013-11-12 03:56:08 +00006854 // At the end of this full expression (which could be a deeply nested
6855 // lambda), if there is a potential capture within the nested lambda,
6856 // have the outer capture-able lambda try and capture it.
Faisal Valia17d19f2013-11-07 05:17:06 +00006857 // Consider the following code:
6858 // void f(int, int);
6859 // void f(const int&, double);
6860 // void foo() {
6861 // const int x = 10, y = 20;
6862 // auto L = [=](auto a) {
6863 // auto M = [=](auto b) {
6864 // f(x, b); <-- requires x to be captured by L and M
6865 // f(y, a); <-- requires y to be captured by L, but not all Ms
6866 // };
6867 // };
6868 // }
6869
6870 // FIXME: Also consider what happens for something like this that involves
6871 // the gnu-extension statement-expressions or even lambda-init-captures:
6872 // void f() {
6873 // const int n = 0;
6874 // auto L = [&](auto a) {
6875 // +n + ({ 0; a; });
6876 // };
6877 // }
6878 //
Faisal Vali218e94b2013-11-12 03:56:08 +00006879 // Here, we see +n, and then the full-expression 0; ends, so we don't
6880 // capture n (and instead remove it from our list of potential captures),
6881 // and then the full-expression +n + ({ 0; }); ends, but it's too late
6882 // for us to see that we need to capture n after all.
Faisal Valia17d19f2013-11-07 05:17:06 +00006883
Faisal Vali8bc2bc72013-11-12 03:48:27 +00006884 LambdaScopeInfo *const CurrentLSI = getCurLambda();
6885 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
6886 // even if CurContext is not a lambda call operator. Refer to that Bug Report
6887 // for an example of the code that might cause this asynchrony.
6888 // By ensuring we are in the context of a lambda's call operator
6889 // we can fix the bug (we only need to check whether we need to capture
6890 // if we are within a lambda's body); but per the comments in that
6891 // PR, a proper fix would entail :
6892 // "Alternative suggestion:
6893 // - Add to Sema an integer holding the smallest (outermost) scope
6894 // index that we are *lexically* within, and save/restore/set to
6895 // FunctionScopes.size() in InstantiatingTemplate's
6896 // constructor/destructor.
6897 // - Teach the handful of places that iterate over FunctionScopes to
Faisal Valiab3d6462013-12-07 20:22:44 +00006898 // stop at the outermost enclosing lexical scope."
6899 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
6900 if (IsInLambdaDeclContext && CurrentLSI &&
Faisal Vali8bc2bc72013-11-12 03:48:27 +00006901 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
Faisal Valiab3d6462013-12-07 20:22:44 +00006902 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
6903 *this);
John McCall5d413782010-12-06 08:20:24 +00006904 return MaybeCreateExprWithCleanups(FullExpr);
Anders Carlsson85a307d2009-05-17 18:41:29 +00006905}
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006906
6907StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
6908 if (!FullStmt) return StmtError();
6909
John McCall5d413782010-12-06 08:20:24 +00006910 return MaybeCreateStmtWithCleanups(FullStmt);
Argyrios Kyrtzidis3050d9b2010-11-02 02:33:08 +00006911}
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006912
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006913Sema::IfExistsResult
6914Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
6915 CXXScopeSpec &SS,
6916 const DeclarationNameInfo &TargetNameInfo) {
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006917 DeclarationName TargetName = TargetNameInfo.getName();
6918 if (!TargetName)
Douglas Gregor43edb322011-10-24 22:31:10 +00006919 return IER_DoesNotExist;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006920
Douglas Gregor43edb322011-10-24 22:31:10 +00006921 // If the name itself is dependent, then the result is dependent.
6922 if (TargetName.isDependentName())
6923 return IER_Dependent;
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006924
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006925 // Do the redeclaration lookup in the current scope.
6926 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
6927 Sema::NotForRedeclaration);
Douglas Gregor43edb322011-10-24 22:31:10 +00006928 LookupParsedName(R, S, &SS);
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006929 R.suppressDiagnostics();
Douglas Gregor43edb322011-10-24 22:31:10 +00006930
6931 switch (R.getResultKind()) {
6932 case LookupResult::Found:
6933 case LookupResult::FoundOverloaded:
6934 case LookupResult::FoundUnresolvedValue:
6935 case LookupResult::Ambiguous:
6936 return IER_Exists;
6937
6938 case LookupResult::NotFound:
6939 return IER_DoesNotExist;
6940
6941 case LookupResult::NotFoundInCurrentInstantiation:
6942 return IER_Dependent;
6943 }
David Blaikie8a40f702012-01-17 06:56:22 +00006944
6945 llvm_unreachable("Invalid LookupResult Kind!");
Francois Pichet4a7de3e2011-05-06 20:48:22 +00006946}
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006947
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00006948Sema::IfExistsResult
6949Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
6950 bool IsIfExists, CXXScopeSpec &SS,
6951 UnqualifiedId &Name) {
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006952 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
Douglas Gregor4a2a8f72011-10-25 03:44:56 +00006953
6954 // Check for unexpanded parameter packs.
6955 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
6956 collectUnexpandedParameterPacks(SS, Unexpanded);
6957 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
6958 if (!Unexpanded.empty()) {
6959 DiagnoseUnexpandedParameterPacks(KeywordLoc,
6960 IsIfExists? UPPC_IfExists
6961 : UPPC_IfNotExists,
6962 Unexpanded);
6963 return IER_Error;
6964 }
6965
Douglas Gregordeb4a2be2011-10-25 01:33:02 +00006966 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
6967}