Bug Summary

File:tools/clang/lib/Sema/SemaExprCXX.cpp
Warning:line 513, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaExprCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp -faddrsig
1//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9///
10/// \file
11/// Implements semantic analysis for C++ expressions.
12///
13//===----------------------------------------------------------------------===//
14
15#include "clang/Sema/SemaInternal.h"
16#include "TreeTransform.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTLambda.h"
20#include "clang/AST/CXXInheritance.h"
21#include "clang/AST/CharUnits.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/RecursiveASTVisitor.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/AlignedAllocation.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/Preprocessor.h"
31#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Initialization.h"
33#include "clang/Sema/Lookup.h"
34#include "clang/Sema/ParsedTemplate.h"
35#include "clang/Sema/Scope.h"
36#include "clang/Sema/ScopeInfo.h"
37#include "clang/Sema/SemaLambda.h"
38#include "clang/Sema/TemplateDeduction.h"
39#include "llvm/ADT/APInt.h"
40#include "llvm/ADT/STLExtras.h"
41#include "llvm/Support/ErrorHandling.h"
42using namespace clang;
43using namespace sema;
44
45/// Handle the result of the special case name lookup for inheriting
46/// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
47/// constructor names in member using declarations, even if 'X' is not the
48/// name of the corresponding type.
49ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
50 SourceLocation NameLoc,
51 IdentifierInfo &Name) {
52 NestedNameSpecifier *NNS = SS.getScopeRep();
53
54 // Convert the nested-name-specifier into a type.
55 QualType Type;
56 switch (NNS->getKind()) {
57 case NestedNameSpecifier::TypeSpec:
58 case NestedNameSpecifier::TypeSpecWithTemplate:
59 Type = QualType(NNS->getAsType(), 0);
60 break;
61
62 case NestedNameSpecifier::Identifier:
63 // Strip off the last layer of the nested-name-specifier and build a
64 // typename type for it.
65 assert(NNS->getAsIdentifier() == &Name && "not a constructor name")((NNS->getAsIdentifier() == &Name && "not a constructor name"
) ? static_cast<void> (0) : __assert_fail ("NNS->getAsIdentifier() == &Name && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 65, __PRETTY_FUNCTION__))
;
66 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
67 NNS->getAsIdentifier());
68 break;
69
70 case NestedNameSpecifier::Global:
71 case NestedNameSpecifier::Super:
72 case NestedNameSpecifier::Namespace:
73 case NestedNameSpecifier::NamespaceAlias:
74 llvm_unreachable("Nested name specifier is not a type for inheriting ctor")::llvm::llvm_unreachable_internal("Nested name specifier is not a type for inheriting ctor"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 74)
;
75 }
76
77 // This reference to the type is located entirely at the location of the
78 // final identifier in the qualified-id.
79 return CreateParsedType(Type,
80 Context.getTrivialTypeSourceInfo(Type, NameLoc));
81}
82
83ParsedType Sema::getConstructorName(IdentifierInfo &II,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 bool EnteringContext) {
87 CXXRecordDecl *CurClass = getCurrentClass(S, &SS);
88 assert(CurClass && &II == CurClass->getIdentifier() &&((CurClass && &II == CurClass->getIdentifier()
&& "not a constructor name") ? static_cast<void>
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 89, __PRETTY_FUNCTION__))
89 "not a constructor name")((CurClass && &II == CurClass->getIdentifier()
&& "not a constructor name") ? static_cast<void>
(0) : __assert_fail ("CurClass && &II == CurClass->getIdentifier() && \"not a constructor name\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 89, __PRETTY_FUNCTION__))
;
90
91 // When naming a constructor as a member of a dependent context (eg, in a
92 // friend declaration or an inherited constructor declaration), form an
93 // unresolved "typename" type.
94 if (CurClass->isDependentContext() && !EnteringContext) {
95 QualType T = Context.getDependentNameType(ETK_None, SS.getScopeRep(), &II);
96 return ParsedType::make(T);
97 }
98
99 if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass))
100 return ParsedType();
101
102 // Find the injected-class-name declaration. Note that we make no attempt to
103 // diagnose cases where the injected-class-name is shadowed: the only
104 // declaration that can validly shadow the injected-class-name is a
105 // non-static data member, and if the class contains both a non-static data
106 // member and a constructor then it is ill-formed (we check that in
107 // CheckCompletedCXXClass).
108 CXXRecordDecl *InjectedClassName = nullptr;
109 for (NamedDecl *ND : CurClass->lookup(&II)) {
110 auto *RD = dyn_cast<CXXRecordDecl>(ND);
111 if (RD && RD->isInjectedClassName()) {
112 InjectedClassName = RD;
113 break;
114 }
115 }
116 if (!InjectedClassName) {
117 if (!CurClass->isInvalidDecl()) {
118 // FIXME: RequireCompleteDeclContext doesn't check dependent contexts
119 // properly. Work around it here for now.
120 Diag(SS.getLastQualifierNameLoc(),
121 diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange();
122 }
123 return ParsedType();
124 }
125
126 QualType T = Context.getTypeDeclType(InjectedClassName);
127 DiagnoseUseOfDecl(InjectedClassName, NameLoc);
128 MarkAnyDeclReferenced(NameLoc, InjectedClassName, /*OdrUse=*/false);
129
130 return ParsedType::make(T);
131}
132
133ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
134 IdentifierInfo &II,
135 SourceLocation NameLoc,
136 Scope *S, CXXScopeSpec &SS,
137 ParsedType ObjectTypePtr,
138 bool EnteringContext) {
139 // Determine where to perform name lookup.
140
141 // FIXME: This area of the standard is very messy, and the current
142 // wording is rather unclear about which scopes we search for the
143 // destructor name; see core issues 399 and 555. Issue 399 in
144 // particular shows where the current description of destructor name
145 // lookup is completely out of line with existing practice, e.g.,
146 // this appears to be ill-formed:
147 //
148 // namespace N {
149 // template <typename T> struct S {
150 // ~S();
151 // };
152 // }
153 //
154 // void f(N::S<int>* s) {
155 // s->N::S<int>::~S();
156 // }
157 //
158 // See also PR6358 and PR6359.
159 // For this reason, we're currently only doing the C++03 version of this
160 // code; the C++0x version has to wait until we get a proper spec.
161 QualType SearchType;
162 DeclContext *LookupCtx = nullptr;
163 bool isDependent = false;
164 bool LookInScope = false;
165
166 if (SS.isInvalid())
167 return nullptr;
168
169 // If we have an object type, it's because we are in a
170 // pseudo-destructor-expression or a member access expression, and
171 // we know what type we're looking for.
172 if (ObjectTypePtr)
173 SearchType = GetTypeFromParser(ObjectTypePtr);
174
175 if (SS.isSet()) {
176 NestedNameSpecifier *NNS = SS.getScopeRep();
177
178 bool AlreadySearched = false;
179 bool LookAtPrefix = true;
180 // C++11 [basic.lookup.qual]p6:
181 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
182 // the type-names are looked up as types in the scope designated by the
183 // nested-name-specifier. Similarly, in a qualified-id of the form:
184 //
185 // nested-name-specifier[opt] class-name :: ~ class-name
186 //
187 // the second class-name is looked up in the same scope as the first.
188 //
189 // Here, we determine whether the code below is permitted to look at the
190 // prefix of the nested-name-specifier.
191 DeclContext *DC = computeDeclContext(SS, EnteringContext);
192 if (DC && DC->isFileContext()) {
193 AlreadySearched = true;
194 LookupCtx = DC;
195 isDependent = false;
196 } else if (DC && isa<CXXRecordDecl>(DC)) {
197 LookAtPrefix = false;
198 LookInScope = true;
199 }
200
201 // The second case from the C++03 rules quoted further above.
202 NestedNameSpecifier *Prefix = nullptr;
203 if (AlreadySearched) {
204 // Nothing left to do.
205 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
206 CXXScopeSpec PrefixSS;
207 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
208 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
209 isDependent = isDependentScopeSpecifier(PrefixSS);
210 } else if (ObjectTypePtr) {
211 LookupCtx = computeDeclContext(SearchType);
212 isDependent = SearchType->isDependentType();
213 } else {
214 LookupCtx = computeDeclContext(SS, EnteringContext);
215 isDependent = LookupCtx && LookupCtx->isDependentContext();
216 }
217 } else if (ObjectTypePtr) {
218 // C++ [basic.lookup.classref]p3:
219 // If the unqualified-id is ~type-name, the type-name is looked up
220 // in the context of the entire postfix-expression. If the type T
221 // of the object expression is of a class type C, the type-name is
222 // also looked up in the scope of class C. At least one of the
223 // lookups shall find a name that refers to (possibly
224 // cv-qualified) T.
225 LookupCtx = computeDeclContext(SearchType);
226 isDependent = SearchType->isDependentType();
227 assert((isDependent || !SearchType->isIncompleteType()) &&(((isDependent || !SearchType->isIncompleteType()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 228, __PRETTY_FUNCTION__))
228 "Caller should have completed object type")(((isDependent || !SearchType->isIncompleteType()) &&
"Caller should have completed object type") ? static_cast<
void> (0) : __assert_fail ("(isDependent || !SearchType->isIncompleteType()) && \"Caller should have completed object type\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 228, __PRETTY_FUNCTION__))
;
229
230 LookInScope = true;
231 } else {
232 // Perform lookup into the current scope (only).
233 LookInScope = true;
234 }
235
236 TypeDecl *NonMatchingTypeDecl = nullptr;
237 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
238 for (unsigned Step = 0; Step != 2; ++Step) {
239 // Look for the name first in the computed lookup context (if we
240 // have one) and, if that fails to find a match, in the scope (if
241 // we're allowed to look there).
242 Found.clear();
243 if (Step == 0 && LookupCtx) {
244 if (RequireCompleteDeclContext(SS, LookupCtx))
245 return nullptr;
246 LookupQualifiedName(Found, LookupCtx);
247 } else if (Step == 1 && LookInScope && S) {
248 LookupName(Found, S);
249 } else {
250 continue;
251 }
252
253 // FIXME: Should we be suppressing ambiguities here?
254 if (Found.isAmbiguous())
255 return nullptr;
256
257 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
258 QualType T = Context.getTypeDeclType(Type);
259 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
260
261 if (SearchType.isNull() || SearchType->isDependentType() ||
262 Context.hasSameUnqualifiedType(T, SearchType)) {
263 // We found our type!
264
265 return CreateParsedType(T,
266 Context.getTrivialTypeSourceInfo(T, NameLoc));
267 }
268
269 if (!SearchType.isNull())
270 NonMatchingTypeDecl = Type;
271 }
272
273 // If the name that we found is a class template name, and it is
274 // the same name as the template name in the last part of the
275 // nested-name-specifier (if present) or the object type, then
276 // this is the destructor for that class.
277 // FIXME: This is a workaround until we get real drafting for core
278 // issue 399, for which there isn't even an obvious direction.
279 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
280 QualType MemberOfType;
281 if (SS.isSet()) {
282 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
283 // Figure out the type of the context, if it has one.
284 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
285 MemberOfType = Context.getTypeDeclType(Record);
286 }
287 }
288 if (MemberOfType.isNull())
289 MemberOfType = SearchType;
290
291 if (MemberOfType.isNull())
292 continue;
293
294 // We're referring into a class template specialization. If the
295 // class template we found is the same as the template being
296 // specialized, we found what we are looking for.
297 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
298 if (ClassTemplateSpecializationDecl *Spec
299 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
300 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
301 Template->getCanonicalDecl())
302 return CreateParsedType(
303 MemberOfType,
304 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
305 }
306
307 continue;
308 }
309
310 // We're referring to an unresolved class template
311 // specialization. Determine whether we class template we found
312 // is the same as the template being specialized or, if we don't
313 // know which template is being specialized, that it at least
314 // has the same name.
315 if (const TemplateSpecializationType *SpecType
316 = MemberOfType->getAs<TemplateSpecializationType>()) {
317 TemplateName SpecName = SpecType->getTemplateName();
318
319 // The class template we found is the same template being
320 // specialized.
321 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
322 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
323 return CreateParsedType(
324 MemberOfType,
325 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
326
327 continue;
328 }
329
330 // The class template we found has the same name as the
331 // (dependent) template name being specialized.
332 if (DependentTemplateName *DepTemplate
333 = SpecName.getAsDependentTemplateName()) {
334 if (DepTemplate->isIdentifier() &&
335 DepTemplate->getIdentifier() == Template->getIdentifier())
336 return CreateParsedType(
337 MemberOfType,
338 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
339
340 continue;
341 }
342 }
343 }
344 }
345
346 if (isDependent) {
347 // We didn't find our type, but that's okay: it's dependent
348 // anyway.
349
350 // FIXME: What if we have no nested-name-specifier?
351 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
352 SS.getWithLocInContext(Context),
353 II, NameLoc);
354 return ParsedType::make(T);
355 }
356
357 if (NonMatchingTypeDecl) {
358 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
359 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
360 << T << SearchType;
361 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
362 << T;
363 } else if (ObjectTypePtr)
364 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
365 << &II;
366 else {
367 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
368 diag::err_destructor_class_name);
369 if (S) {
370 const DeclContext *Ctx = S->getEntity();
371 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
372 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
373 Class->getNameAsString());
374 }
375 }
376
377 return nullptr;
378}
379
380ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS,
381 ParsedType ObjectType) {
382 if (DS.getTypeSpecType() == DeclSpec::TST_error)
383 return nullptr;
384
385 if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) {
386 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
387 return nullptr;
388 }
389
390 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype &&((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 391, __PRETTY_FUNCTION__))
391 "unexpected type in getDestructorType")((DS.getTypeSpecType() == DeclSpec::TST_decltype && "unexpected type in getDestructorType"
) ? static_cast<void> (0) : __assert_fail ("DS.getTypeSpecType() == DeclSpec::TST_decltype && \"unexpected type in getDestructorType\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 391, __PRETTY_FUNCTION__))
;
392 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
393
394 // If we know the type of the object, check that the correct destructor
395 // type was named now; we can give better diagnostics this way.
396 QualType SearchType = GetTypeFromParser(ObjectType);
397 if (!SearchType.isNull() && !SearchType->isDependentType() &&
398 !Context.hasSameUnqualifiedType(T, SearchType)) {
399 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
400 << T << SearchType;
401 return nullptr;
402 }
403
404 return ParsedType::make(T);
405}
406
407bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
408 const UnqualifiedId &Name) {
409 assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId)((Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId) ?
static_cast<void> (0) : __assert_fail ("Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 409, __PRETTY_FUNCTION__))
;
410
411 if (!SS.isValid())
412 return false;
413
414 switch (SS.getScopeRep()->getKind()) {
415 case NestedNameSpecifier::Identifier:
416 case NestedNameSpecifier::TypeSpec:
417 case NestedNameSpecifier::TypeSpecWithTemplate:
418 // Per C++11 [over.literal]p2, literal operators can only be declared at
419 // namespace scope. Therefore, this unqualified-id cannot name anything.
420 // Reject it early, because we have no AST representation for this in the
421 // case where the scope is dependent.
422 Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace)
423 << SS.getScopeRep();
424 return true;
425
426 case NestedNameSpecifier::Global:
427 case NestedNameSpecifier::Super:
428 case NestedNameSpecifier::Namespace:
429 case NestedNameSpecifier::NamespaceAlias:
430 return false;
431 }
432
433 llvm_unreachable("unknown nested name specifier kind")::llvm::llvm_unreachable_internal("unknown nested name specifier kind"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 433)
;
434}
435
436/// Build a C++ typeid expression with a type operand.
437ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
438 SourceLocation TypeidLoc,
439 TypeSourceInfo *Operand,
440 SourceLocation RParenLoc) {
441 // C++ [expr.typeid]p4:
442 // The top-level cv-qualifiers of the lvalue expression or the type-id
443 // that is the operand of typeid are always ignored.
444 // If the type of the type-id is a class type or a reference to a class
445 // type, the class shall be completely-defined.
446 Qualifiers Quals;
447 QualType T
448 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
449 Quals);
450 if (T->getAs<RecordType>() &&
451 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
452 return ExprError();
453
454 if (T->isVariablyModifiedType())
455 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
456
457 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
458 SourceRange(TypeidLoc, RParenLoc));
459}
460
461/// Build a C++ typeid expression with an expression operand.
462ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
463 SourceLocation TypeidLoc,
464 Expr *E,
465 SourceLocation RParenLoc) {
466 bool WasEvaluated = false;
467 if (E && !E->isTypeDependent()) {
13
Assuming 'E' is null
468 if (E->getType()->isPlaceholderType()) {
469 ExprResult result = CheckPlaceholderExpr(E);
470 if (result.isInvalid()) return ExprError();
471 E = result.get();
472 }
473
474 QualType T = E->getType();
475 if (const RecordType *RecordT = T->getAs<RecordType>()) {
476 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
477 // C++ [expr.typeid]p3:
478 // [...] If the type of the expression is a class type, the class
479 // shall be completely-defined.
480 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
481 return ExprError();
482
483 // C++ [expr.typeid]p3:
484 // When typeid is applied to an expression other than an glvalue of a
485 // polymorphic class type [...] [the] expression is an unevaluated
486 // operand. [...]
487 if (RecordD->isPolymorphic() && E->isGLValue()) {
488 // The subexpression is potentially evaluated; switch the context
489 // and recheck the subexpression.
490 ExprResult Result = TransformToPotentiallyEvaluated(E);
491 if (Result.isInvalid()) return ExprError();
492 E = Result.get();
493
494 // We require a vtable to query the type at run time.
495 MarkVTableUsed(TypeidLoc, RecordD);
496 WasEvaluated = true;
497 }
498 }
499
500 // C++ [expr.typeid]p4:
501 // [...] If the type of the type-id is a reference to a possibly
502 // cv-qualified type, the result of the typeid expression refers to a
503 // std::type_info object representing the cv-unqualified referenced
504 // type.
505 Qualifiers Quals;
506 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
507 if (!Context.hasSameType(T, UnqualT)) {
508 T = UnqualT;
509 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
510 }
511 }
512
513 if (E->getType()->isVariablyModifiedType())
14
Called C++ object pointer is null
514 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
515 << E->getType());
516 else if (!inTemplateInstantiation() &&
517 E->HasSideEffects(Context, WasEvaluated)) {
518 // The expression operand for typeid is in an unevaluated expression
519 // context, so side effects could result in unintended consequences.
520 Diag(E->getExprLoc(), WasEvaluated
521 ? diag::warn_side_effects_typeid
522 : diag::warn_side_effects_unevaluated_context);
523 }
524
525 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
526 SourceRange(TypeidLoc, RParenLoc));
527}
528
529/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
530ExprResult
531Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
532 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
533 // OpenCL C++ 1.0 s2.9: typeid is not supported.
534 if (getLangOpts().OpenCLCPlusPlus) {
1
Assuming the condition is false
2
Taking false branch
535 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
536 << "typeid");
537 }
538
539 // Find the std::type_info type.
540 if (!getStdNamespace())
3
Assuming the condition is false
4
Taking false branch
541 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
542
543 if (!CXXTypeInfoDecl) {
5
Assuming the condition is false
6
Taking false branch
544 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
545 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
546 LookupQualifiedName(R, getStdNamespace());
547 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
548 // Microsoft's typeinfo doesn't have type_info in std but in the global
549 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
550 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
551 LookupQualifiedName(R, Context.getTranslationUnitDecl());
552 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
553 }
554 if (!CXXTypeInfoDecl)
555 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
556 }
557
558 if (!getLangOpts().RTTI) {
7
Assuming the condition is false
8
Taking false branch
559 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
560 }
561
562 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
563
564 if (isType) {
9
Assuming 'isType' is 0
10
Taking false branch
565 // The operand is a type; handle it as such.
566 TypeSourceInfo *TInfo = nullptr;
567 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
568 &TInfo);
569 if (T.isNull())
570 return ExprError();
571
572 if (!TInfo)
573 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
574
575 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
576 }
577
578 // The operand is an expression.
579 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
11
Passing value via 3rd parameter 'E'
12
Calling 'Sema::BuildCXXTypeId'
580}
581
582/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
583/// a single GUID.
584static void
585getUuidAttrOfType(Sema &SemaRef, QualType QT,
586 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
587 // Optionally remove one level of pointer, reference or array indirection.
588 const Type *Ty = QT.getTypePtr();
589 if (QT->isPointerType() || QT->isReferenceType())
590 Ty = QT->getPointeeType().getTypePtr();
591 else if (QT->isArrayType())
592 Ty = Ty->getBaseElementTypeUnsafe();
593
594 const auto *TD = Ty->getAsTagDecl();
595 if (!TD)
596 return;
597
598 if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) {
599 UuidAttrs.insert(Uuid);
600 return;
601 }
602
603 // __uuidof can grab UUIDs from template arguments.
604 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) {
605 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
606 for (const TemplateArgument &TA : TAL.asArray()) {
607 const UuidAttr *UuidForTA = nullptr;
608 if (TA.getKind() == TemplateArgument::Type)
609 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
610 else if (TA.getKind() == TemplateArgument::Declaration)
611 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
612
613 if (UuidForTA)
614 UuidAttrs.insert(UuidForTA);
615 }
616 }
617}
618
619/// Build a Microsoft __uuidof expression with a type operand.
620ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
621 SourceLocation TypeidLoc,
622 TypeSourceInfo *Operand,
623 SourceLocation RParenLoc) {
624 StringRef UuidStr;
625 if (!Operand->getType()->isDependentType()) {
626 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
627 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
628 if (UuidAttrs.empty())
629 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
630 if (UuidAttrs.size() > 1)
631 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
632 UuidStr = UuidAttrs.back()->getGuid();
633 }
634
635 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
636 SourceRange(TypeidLoc, RParenLoc));
637}
638
639/// Build a Microsoft __uuidof expression with an expression operand.
640ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
641 SourceLocation TypeidLoc,
642 Expr *E,
643 SourceLocation RParenLoc) {
644 StringRef UuidStr;
645 if (!E->getType()->isDependentType()) {
646 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
647 UuidStr = "00000000-0000-0000-0000-000000000000";
648 } else {
649 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
650 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
651 if (UuidAttrs.empty())
652 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
653 if (UuidAttrs.size() > 1)
654 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
655 UuidStr = UuidAttrs.back()->getGuid();
656 }
657 }
658
659 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
660 SourceRange(TypeidLoc, RParenLoc));
661}
662
663/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
664ExprResult
665Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
666 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
667 // If MSVCGuidDecl has not been cached, do the lookup.
668 if (!MSVCGuidDecl) {
669 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
670 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
671 LookupQualifiedName(R, Context.getTranslationUnitDecl());
672 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
673 if (!MSVCGuidDecl)
674 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
675 }
676
677 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
678
679 if (isType) {
680 // The operand is a type; handle it as such.
681 TypeSourceInfo *TInfo = nullptr;
682 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
683 &TInfo);
684 if (T.isNull())
685 return ExprError();
686
687 if (!TInfo)
688 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
689
690 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
691 }
692
693 // The operand is an expression.
694 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
695}
696
697/// ActOnCXXBoolLiteral - Parse {true,false} literals.
698ExprResult
699Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
700 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 701, __PRETTY_FUNCTION__))
701 "Unknown C++ Boolean value!")(((Kind == tok::kw_true || Kind == tok::kw_false) && "Unknown C++ Boolean value!"
) ? static_cast<void> (0) : __assert_fail ("(Kind == tok::kw_true || Kind == tok::kw_false) && \"Unknown C++ Boolean value!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 701, __PRETTY_FUNCTION__))
;
702 return new (Context)
703 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
704}
705
706/// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
707ExprResult
708Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
709 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
710}
711
712/// ActOnCXXThrow - Parse throw expressions.
713ExprResult
714Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
715 bool IsThrownVarInScope = false;
716 if (Ex) {
717 // C++0x [class.copymove]p31:
718 // When certain criteria are met, an implementation is allowed to omit the
719 // copy/move construction of a class object [...]
720 //
721 // - in a throw-expression, when the operand is the name of a
722 // non-volatile automatic object (other than a function or catch-
723 // clause parameter) whose scope does not extend beyond the end of the
724 // innermost enclosing try-block (if there is one), the copy/move
725 // operation from the operand to the exception object (15.1) can be
726 // omitted by constructing the automatic object directly into the
727 // exception object
728 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
729 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
730 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
731 for( ; S; S = S->getParent()) {
732 if (S->isDeclScope(Var)) {
733 IsThrownVarInScope = true;
734 break;
735 }
736
737 if (S->getFlags() &
738 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
739 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
740 Scope::TryScope))
741 break;
742 }
743 }
744 }
745 }
746
747 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
748}
749
750ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
751 bool IsThrownVarInScope) {
752 // Don't report an error if 'throw' is used in system headers.
753 if (!getLangOpts().CXXExceptions &&
754 !getSourceManager().isInSystemHeader(OpLoc) &&
755 (!getLangOpts().OpenMPIsDevice ||
756 !getLangOpts().OpenMPHostCXXExceptions ||
757 isInOpenMPTargetExecutionDirective() ||
758 isInOpenMPDeclareTargetContext()))
759 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
760
761 // Exceptions aren't allowed in CUDA device code.
762 if (getLangOpts().CUDA)
763 CUDADiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions)
764 << "throw" << CurrentCUDATarget();
765
766 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
767 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
768
769 if (Ex && !Ex->isTypeDependent()) {
770 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
771 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
772 return ExprError();
773
774 // Initialize the exception result. This implicitly weeds out
775 // abstract types or types with inaccessible copy constructors.
776
777 // C++0x [class.copymove]p31:
778 // When certain criteria are met, an implementation is allowed to omit the
779 // copy/move construction of a class object [...]
780 //
781 // - in a throw-expression, when the operand is the name of a
782 // non-volatile automatic object (other than a function or
783 // catch-clause
784 // parameter) whose scope does not extend beyond the end of the
785 // innermost enclosing try-block (if there is one), the copy/move
786 // operation from the operand to the exception object (15.1) can be
787 // omitted by constructing the automatic object directly into the
788 // exception object
789 const VarDecl *NRVOVariable = nullptr;
790 if (IsThrownVarInScope)
791 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, CES_Strict);
792
793 InitializedEntity Entity = InitializedEntity::InitializeException(
794 OpLoc, ExceptionObjectTy,
795 /*NRVO=*/NRVOVariable != nullptr);
796 ExprResult Res = PerformMoveOrCopyInitialization(
797 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
798 if (Res.isInvalid())
799 return ExprError();
800 Ex = Res.get();
801 }
802
803 return new (Context)
804 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
805}
806
807static void
808collectPublicBases(CXXRecordDecl *RD,
809 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
810 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
811 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
812 bool ParentIsPublic) {
813 for (const CXXBaseSpecifier &BS : RD->bases()) {
814 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
815 bool NewSubobject;
816 // Virtual bases constitute the same subobject. Non-virtual bases are
817 // always distinct subobjects.
818 if (BS.isVirtual())
819 NewSubobject = VBases.insert(BaseDecl).second;
820 else
821 NewSubobject = true;
822
823 if (NewSubobject)
824 ++SubobjectsSeen[BaseDecl];
825
826 // Only add subobjects which have public access throughout the entire chain.
827 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
828 if (PublicPath)
829 PublicSubobjectsSeen.insert(BaseDecl);
830
831 // Recurse on to each base subobject.
832 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
833 PublicPath);
834 }
835}
836
837static void getUnambiguousPublicSubobjects(
838 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
839 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
840 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
841 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
842 SubobjectsSeen[RD] = 1;
843 PublicSubobjectsSeen.insert(RD);
844 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
845 /*ParentIsPublic=*/true);
846
847 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
848 // Skip ambiguous objects.
849 if (SubobjectsSeen[PublicSubobject] > 1)
850 continue;
851
852 Objects.push_back(PublicSubobject);
853 }
854}
855
856/// CheckCXXThrowOperand - Validate the operand of a throw.
857bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
858 QualType ExceptionObjectTy, Expr *E) {
859 // If the type of the exception would be an incomplete type or a pointer
860 // to an incomplete type other than (cv) void the program is ill-formed.
861 QualType Ty = ExceptionObjectTy;
862 bool isPointer = false;
863 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
864 Ty = Ptr->getPointeeType();
865 isPointer = true;
866 }
867 if (!isPointer || !Ty->isVoidType()) {
868 if (RequireCompleteType(ThrowLoc, Ty,
869 isPointer ? diag::err_throw_incomplete_ptr
870 : diag::err_throw_incomplete,
871 E->getSourceRange()))
872 return true;
873
874 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
875 diag::err_throw_abstract_type, E))
876 return true;
877 }
878
879 // If the exception has class type, we need additional handling.
880 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
881 if (!RD)
882 return false;
883
884 // If we are throwing a polymorphic class type or pointer thereof,
885 // exception handling will make use of the vtable.
886 MarkVTableUsed(ThrowLoc, RD);
887
888 // If a pointer is thrown, the referenced object will not be destroyed.
889 if (isPointer)
890 return false;
891
892 // If the class has a destructor, we must be able to call it.
893 if (!RD->hasIrrelevantDestructor()) {
894 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
895 MarkFunctionReferenced(E->getExprLoc(), Destructor);
896 CheckDestructorAccess(E->getExprLoc(), Destructor,
897 PDiag(diag::err_access_dtor_exception) << Ty);
898 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
899 return true;
900 }
901 }
902
903 // The MSVC ABI creates a list of all types which can catch the exception
904 // object. This list also references the appropriate copy constructor to call
905 // if the object is caught by value and has a non-trivial copy constructor.
906 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
907 // We are only interested in the public, unambiguous bases contained within
908 // the exception object. Bases which are ambiguous or otherwise
909 // inaccessible are not catchable types.
910 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
911 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
912
913 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
914 // Attempt to lookup the copy constructor. Various pieces of machinery
915 // will spring into action, like template instantiation, which means this
916 // cannot be a simple walk of the class's decls. Instead, we must perform
917 // lookup and overload resolution.
918 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
919 if (!CD)
920 continue;
921
922 // Mark the constructor referenced as it is used by this throw expression.
923 MarkFunctionReferenced(E->getExprLoc(), CD);
924
925 // Skip this copy constructor if it is trivial, we don't need to record it
926 // in the catchable type data.
927 if (CD->isTrivial())
928 continue;
929
930 // The copy constructor is non-trivial, create a mapping from this class
931 // type to this constructor.
932 // N.B. The selection of copy constructor is not sensitive to this
933 // particular throw-site. Lookup will be performed at the catch-site to
934 // ensure that the copy constructor is, in fact, accessible (via
935 // friendship or any other means).
936 Context.addCopyConstructorForExceptionObject(Subobject, CD);
937
938 // We don't keep the instantiated default argument expressions around so
939 // we must rebuild them here.
940 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
941 if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)))
942 return true;
943 }
944 }
945 }
946
947 return false;
948}
949
950static QualType adjustCVQualifiersForCXXThisWithinLambda(
951 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
952 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
953
954 QualType ClassType = ThisTy->getPointeeType();
955 LambdaScopeInfo *CurLSI = nullptr;
956 DeclContext *CurDC = CurSemaContext;
957
958 // Iterate through the stack of lambdas starting from the innermost lambda to
959 // the outermost lambda, checking if '*this' is ever captured by copy - since
960 // that could change the cv-qualifiers of the '*this' object.
961 // The object referred to by '*this' starts out with the cv-qualifiers of its
962 // member function. We then start with the innermost lambda and iterate
963 // outward checking to see if any lambda performs a by-copy capture of '*this'
964 // - and if so, any nested lambda must respect the 'constness' of that
965 // capturing lamdbda's call operator.
966 //
967
968 // Since the FunctionScopeInfo stack is representative of the lexical
969 // nesting of the lambda expressions during initial parsing (and is the best
970 // place for querying information about captures about lambdas that are
971 // partially processed) and perhaps during instantiation of function templates
972 // that contain lambda expressions that need to be transformed BUT not
973 // necessarily during instantiation of a nested generic lambda's function call
974 // operator (which might even be instantiated at the end of the TU) - at which
975 // time the DeclContext tree is mature enough to query capture information
976 // reliably - we use a two pronged approach to walk through all the lexically
977 // enclosing lambda expressions:
978 //
979 // 1) Climb down the FunctionScopeInfo stack as long as each item represents
980 // a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically
981 // enclosed by the call-operator of the LSI below it on the stack (while
982 // tracking the enclosing DC for step 2 if needed). Note the topmost LSI on
983 // the stack represents the innermost lambda.
984 //
985 // 2) If we run out of enclosing LSI's, check if the enclosing DeclContext
986 // represents a lambda's call operator. If it does, we must be instantiating
987 // a generic lambda's call operator (represented by the Current LSI, and
988 // should be the only scenario where an inconsistency between the LSI and the
989 // DeclContext should occur), so climb out the DeclContexts if they
990 // represent lambdas, while querying the corresponding closure types
991 // regarding capture information.
992
993 // 1) Climb down the function scope info stack.
994 for (int I = FunctionScopes.size();
995 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) &&
996 (!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() ==
997 cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator);
998 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
999 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
1000
1001 if (!CurLSI->isCXXThisCaptured())
1002 continue;
1003
1004 auto C = CurLSI->getCXXThisCapture();
1005
1006 if (C.isCopyCapture()) {
1007 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1008 if (CurLSI->CallOperator->isConst())
1009 ClassType.addConst();
1010 return ASTCtx.getPointerType(ClassType);
1011 }
1012 }
1013
1014 // 2) We've run out of ScopeInfos but check if CurDC is a lambda (which can
1015 // happen during instantiation of its nested generic lambda call operator)
1016 if (isLambdaCallOperator(CurDC)) {
1017 assert(CurLSI && "While computing 'this' capture-type for a generic "((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1018, __PRETTY_FUNCTION__))
1018 "lambda, we must have a corresponding LambdaScopeInfo")((CurLSI && "While computing 'this' capture-type for a generic "
"lambda, we must have a corresponding LambdaScopeInfo") ? static_cast
<void> (0) : __assert_fail ("CurLSI && \"While computing 'this' capture-type for a generic \" \"lambda, we must have a corresponding LambdaScopeInfo\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1018, __PRETTY_FUNCTION__))
;
1019 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) &&((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1023, __PRETTY_FUNCTION__))
1020 "While computing 'this' capture-type for a generic lambda, when we "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1023, __PRETTY_FUNCTION__))
1021 "run out of enclosing LSI's, yet the enclosing DC is a "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1023, __PRETTY_FUNCTION__))
1022 "lambda-call-operator we must be (i.e. Current LSI) in a generic "((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1023, __PRETTY_FUNCTION__))
1023 "lambda call oeprator")((isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator
) && "While computing 'this' capture-type for a generic lambda, when we "
"run out of enclosing LSI's, yet the enclosing DC is a " "lambda-call-operator we must be (i.e. Current LSI) in a generic "
"lambda call oeprator") ? static_cast<void> (0) : __assert_fail
("isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && \"While computing 'this' capture-type for a generic lambda, when we \" \"run out of enclosing LSI's, yet the enclosing DC is a \" \"lambda-call-operator we must be (i.e. Current LSI) in a generic \" \"lambda call oeprator\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1023, __PRETTY_FUNCTION__))
;
1024 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator))((CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator
)) ? static_cast<void> (0) : __assert_fail ("CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1024, __PRETTY_FUNCTION__))
;
1025
1026 auto IsThisCaptured =
1027 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
1028 IsConst = false;
1029 IsByCopy = false;
1030 for (auto &&C : Closure->captures()) {
1031 if (C.capturesThis()) {
1032 if (C.getCaptureKind() == LCK_StarThis)
1033 IsByCopy = true;
1034 if (Closure->getLambdaCallOperator()->isConst())
1035 IsConst = true;
1036 return true;
1037 }
1038 }
1039 return false;
1040 };
1041
1042 bool IsByCopyCapture = false;
1043 bool IsConstCapture = false;
1044 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
1045 while (Closure &&
1046 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
1047 if (IsByCopyCapture) {
1048 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1049 if (IsConstCapture)
1050 ClassType.addConst();
1051 return ASTCtx.getPointerType(ClassType);
1052 }
1053 Closure = isLambdaCallOperator(Closure->getParent())
1054 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
1055 : nullptr;
1056 }
1057 }
1058 return ASTCtx.getPointerType(ClassType);
1059}
1060
1061QualType Sema::getCurrentThisType() {
1062 DeclContext *DC = getFunctionLevelDeclContext();
1063 QualType ThisTy = CXXThisTypeOverride;
1064
1065 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
1066 if (method && method->isInstance())
1067 ThisTy = method->getThisType(Context);
1068 }
1069
1070 if (ThisTy.isNull() && isLambdaCallOperator(CurContext) &&
1071 inTemplateInstantiation()) {
1072
1073 assert(isa<CXXRecordDecl>(DC) &&((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1074, __PRETTY_FUNCTION__))
1074 "Trying to get 'this' type from static method?")((isa<CXXRecordDecl>(DC) && "Trying to get 'this' type from static method?"
) ? static_cast<void> (0) : __assert_fail ("isa<CXXRecordDecl>(DC) && \"Trying to get 'this' type from static method?\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1074, __PRETTY_FUNCTION__))
;
1075
1076 // This is a lambda call operator that is being instantiated as a default
1077 // initializer. DC must point to the enclosing class type, so we can recover
1078 // the 'this' type from it.
1079
1080 QualType ClassTy = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
1081 // There are no cv-qualifiers for 'this' within default initializers,
1082 // per [expr.prim.general]p4.
1083 ThisTy = Context.getPointerType(ClassTy);
1084 }
1085
1086 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
1087 // might need to be adjusted if the lambda or any of its enclosing lambda's
1088 // captures '*this' by copy.
1089 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
1090 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
1091 CurContext, Context);
1092 return ThisTy;
1093}
1094
1095Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1096 Decl *ContextDecl,
1097 Qualifiers CXXThisTypeQuals,
1098 bool Enabled)
1099 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1100{
1101 if (!Enabled || !ContextDecl)
1102 return;
1103
1104 CXXRecordDecl *Record = nullptr;
1105 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1106 Record = Template->getTemplatedDecl();
1107 else
1108 Record = cast<CXXRecordDecl>(ContextDecl);
1109
1110 QualType T = S.Context.getRecordType(Record);
1111 T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals);
1112
1113 S.CXXThisTypeOverride = S.Context.getPointerType(T);
1114
1115 this->Enabled = true;
1116}
1117
1118
1119Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1120 if (Enabled) {
1121 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1122 }
1123}
1124
1125static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1126 QualType ThisTy, SourceLocation Loc,
1127 const bool ByCopy) {
1128
1129 QualType AdjustedThisTy = ThisTy;
1130 // The type of the corresponding data member (not a 'this' pointer if 'by
1131 // copy').
1132 QualType CaptureThisFieldTy = ThisTy;
1133 if (ByCopy) {
1134 // If we are capturing the object referred to by '*this' by copy, ignore any
1135 // cv qualifiers inherited from the type of the member function for the type
1136 // of the closure-type's corresponding data member and any use of 'this'.
1137 CaptureThisFieldTy = ThisTy->getPointeeType();
1138 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1139 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1140 }
1141
1142 FieldDecl *Field = FieldDecl::Create(
1143 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1144 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1145 ICIS_NoInit);
1146
1147 Field->setImplicit(true);
1148 Field->setAccess(AS_private);
1149 RD->addDecl(Field);
1150 Expr *This =
1151 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1152 if (ByCopy) {
1153 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1154 UO_Deref,
1155 This).get();
1156 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1157 nullptr, CaptureThisFieldTy, Loc);
1158 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1159 InitializationSequence Init(S, Entity, InitKind, StarThis);
1160 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1161 if (ER.isInvalid()) return nullptr;
1162 return ER.get();
1163 }
1164 return This;
1165}
1166
1167bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1168 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1169 const bool ByCopy) {
1170 // We don't need to capture this in an unevaluated context.
1171 if (isUnevaluatedContext() && !Explicit)
1172 return true;
1173
1174 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value")(((!ByCopy || Explicit) && "cannot implicitly capture *this by value"
) ? static_cast<void> (0) : __assert_fail ("(!ByCopy || Explicit) && \"cannot implicitly capture *this by value\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1174, __PRETTY_FUNCTION__))
;
1175
1176 const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt
1177 ? *FunctionScopeIndexToStopAt
1178 : FunctionScopes.size() - 1;
1179
1180 // Check that we can capture the *enclosing object* (referred to by '*this')
1181 // by the capturing-entity/closure (lambda/block/etc) at
1182 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1183
1184 // Note: The *enclosing object* can only be captured by-value by a
1185 // closure that is a lambda, using the explicit notation:
1186 // [*this] { ... }.
1187 // Every other capture of the *enclosing object* results in its by-reference
1188 // capture.
1189
1190 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1191 // stack), we can capture the *enclosing object* only if:
1192 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1193 // - or, 'L' has an implicit capture.
1194 // AND
1195 // -- there is no enclosing closure
1196 // -- or, there is some enclosing closure 'E' that has already captured the
1197 // *enclosing object*, and every intervening closure (if any) between 'E'
1198 // and 'L' can implicitly capture the *enclosing object*.
1199 // -- or, every enclosing closure can implicitly capture the
1200 // *enclosing object*
1201
1202
1203 unsigned NumCapturingClosures = 0;
1204 for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) {
1205 if (CapturingScopeInfo *CSI =
1206 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1207 if (CSI->CXXThisCaptureIndex != 0) {
1208 // 'this' is already being captured; there isn't anything more to do.
1209 CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose);
1210 break;
1211 }
1212 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1213 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1214 // This context can't implicitly capture 'this'; fail out.
1215 if (BuildAndDiagnose)
1216 Diag(Loc, diag::err_this_capture)
1217 << (Explicit && idx == MaxFunctionScopesIndex);
1218 return true;
1219 }
1220 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1221 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1222 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1223 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1224 (Explicit && idx == MaxFunctionScopesIndex)) {
1225 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1226 // iteration through can be an explicit capture, all enclosing closures,
1227 // if any, must perform implicit captures.
1228
1229 // This closure can capture 'this'; continue looking upwards.
1230 NumCapturingClosures++;
1231 continue;
1232 }
1233 // This context can't implicitly capture 'this'; fail out.
1234 if (BuildAndDiagnose)
1235 Diag(Loc, diag::err_this_capture)
1236 << (Explicit && idx == MaxFunctionScopesIndex);
1237 return true;
1238 }
1239 break;
1240 }
1241 if (!BuildAndDiagnose) return false;
1242
1243 // If we got here, then the closure at MaxFunctionScopesIndex on the
1244 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1245 // (including implicit by-reference captures in any enclosing closures).
1246
1247 // In the loop below, respect the ByCopy flag only for the closure requesting
1248 // the capture (i.e. first iteration through the loop below). Ignore it for
1249 // all enclosing closure's up to NumCapturingClosures (since they must be
1250 // implicitly capturing the *enclosing object* by reference (see loop
1251 // above)).
1252 assert((!ByCopy ||(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1255, __PRETTY_FUNCTION__))
1253 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1255, __PRETTY_FUNCTION__))
1254 "Only a lambda can capture the enclosing object (referred to by "(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1255, __PRETTY_FUNCTION__))
1255 "*this) by copy")(((!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[
MaxFunctionScopesIndex])) && "Only a lambda can capture the enclosing object (referred to by "
"*this) by copy") ? static_cast<void> (0) : __assert_fail
("(!ByCopy || dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && \"Only a lambda can capture the enclosing object (referred to by \" \"*this) by copy\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1255, __PRETTY_FUNCTION__))
;
1256 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1257 // contexts.
1258 QualType ThisTy = getCurrentThisType();
1259 for (int idx = MaxFunctionScopesIndex; NumCapturingClosures;
1260 --idx, --NumCapturingClosures) {
1261 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1262 Expr *ThisExpr = nullptr;
1263
1264 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1265 // For lambda expressions, build a field and an initializing expression,
1266 // and capture the *enclosing object* by copy only if this is the first
1267 // iteration.
1268 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1269 ByCopy && idx == MaxFunctionScopesIndex);
1270
1271 } else if (CapturedRegionScopeInfo *RSI
1272 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1273 ThisExpr =
1274 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1275 false/*ByCopy*/);
1276
1277 bool isNested = NumCapturingClosures > 1;
1278 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1279 }
1280 return false;
1281}
1282
1283ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1284 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1285 /// is a non-lvalue expression whose value is the address of the object for
1286 /// which the function is called.
1287
1288 QualType ThisTy = getCurrentThisType();
1289 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1290
1291 CheckCXXThisCapture(Loc);
1292 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1293}
1294
1295bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1296 // If we're outside the body of a member function, then we'll have a specified
1297 // type for 'this'.
1298 if (CXXThisTypeOverride.isNull())
1299 return false;
1300
1301 // Determine whether we're looking into a class that's currently being
1302 // defined.
1303 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1304 return Class && Class->isBeingDefined();
1305}
1306
1307/// Parse construction of a specified type.
1308/// Can be interpreted either as function-style casting ("int(x)")
1309/// or class type construction ("ClassType(x,y,z)")
1310/// or creation of a value-initialized type ("int()").
1311ExprResult
1312Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1313 SourceLocation LParenOrBraceLoc,
1314 MultiExprArg exprs,
1315 SourceLocation RParenOrBraceLoc,
1316 bool ListInitialization) {
1317 if (!TypeRep)
1318 return ExprError();
1319
1320 TypeSourceInfo *TInfo;
1321 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1322 if (!TInfo)
1323 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1324
1325 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs,
1326 RParenOrBraceLoc, ListInitialization);
1327 // Avoid creating a non-type-dependent expression that contains typos.
1328 // Non-type-dependent expressions are liable to be discarded without
1329 // checking for embedded typos.
1330 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1331 !Result.get()->isTypeDependent())
1332 Result = CorrectDelayedTyposInExpr(Result.get());
1333 return Result;
1334}
1335
1336ExprResult
1337Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1338 SourceLocation LParenOrBraceLoc,
1339 MultiExprArg Exprs,
1340 SourceLocation RParenOrBraceLoc,
1341 bool ListInitialization) {
1342 QualType Ty = TInfo->getType();
1343 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1344
1345 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1346 // FIXME: CXXUnresolvedConstructExpr does not model list-initialization
1347 // directly. We work around this by dropping the locations of the braces.
1348 SourceRange Locs = ListInitialization
1349 ? SourceRange()
1350 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1351 return CXXUnresolvedConstructExpr::Create(Context, TInfo, Locs.getBegin(),
1352 Exprs, Locs.getEnd());
1353 }
1354
1355 assert((!ListInitialization ||(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1357, __PRETTY_FUNCTION__))
1356 (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) &&(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1357, __PRETTY_FUNCTION__))
1357 "List initialization must have initializer list as expression.")(((!ListInitialization || (Exprs.size() == 1 && isa<
InitListExpr>(Exprs[0]))) && "List initialization must have initializer list as expression."
) ? static_cast<void> (0) : __assert_fail ("(!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0]))) && \"List initialization must have initializer list as expression.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1357, __PRETTY_FUNCTION__))
;
1358 SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc);
1359
1360 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1361 InitializationKind Kind =
1362 Exprs.size()
1363 ? ListInitialization
1364 ? InitializationKind::CreateDirectList(
1365 TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc)
1366 : InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc,
1367 RParenOrBraceLoc)
1368 : InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc,
1369 RParenOrBraceLoc);
1370
1371 // C++1z [expr.type.conv]p1:
1372 // If the type is a placeholder for a deduced class type, [...perform class
1373 // template argument deduction...]
1374 DeducedType *Deduced = Ty->getContainedDeducedType();
1375 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1376 Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity,
1377 Kind, Exprs);
1378 if (Ty.isNull())
1379 return ExprError();
1380 Entity = InitializedEntity::InitializeTemporary(TInfo, Ty);
1381 }
1382
1383 // C++ [expr.type.conv]p1:
1384 // If the expression list is a parenthesized single expression, the type
1385 // conversion expression is equivalent (in definedness, and if defined in
1386 // meaning) to the corresponding cast expression.
1387 if (Exprs.size() == 1 && !ListInitialization &&
1388 !isa<InitListExpr>(Exprs[0])) {
1389 Expr *Arg = Exprs[0];
1390 return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg,
1391 RParenOrBraceLoc);
1392 }
1393
1394 // For an expression of the form T(), T shall not be an array type.
1395 QualType ElemTy = Ty;
1396 if (Ty->isArrayType()) {
1397 if (!ListInitialization)
1398 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type)
1399 << FullRange);
1400 ElemTy = Context.getBaseElementType(Ty);
1401 }
1402
1403 // There doesn't seem to be an explicit rule against this but sanity demands
1404 // we only construct objects with object types.
1405 if (Ty->isFunctionType())
1406 return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type)
1407 << Ty << FullRange);
1408
1409 // C++17 [expr.type.conv]p2:
1410 // If the type is cv void and the initializer is (), the expression is a
1411 // prvalue of the specified type that performs no initialization.
1412 if (!Ty->isVoidType() &&
1413 RequireCompleteType(TyBeginLoc, ElemTy,
1414 diag::err_invalid_incomplete_type_use, FullRange))
1415 return ExprError();
1416
1417 // Otherwise, the expression is a prvalue of the specified type whose
1418 // result object is direct-initialized (11.6) with the initializer.
1419 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1420 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1421
1422 if (Result.isInvalid())
1423 return Result;
1424
1425 Expr *Inner = Result.get();
1426 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1427 Inner = BTE->getSubExpr();
1428 if (!isa<CXXTemporaryObjectExpr>(Inner) &&
1429 !isa<CXXScalarValueInitExpr>(Inner)) {
1430 // If we created a CXXTemporaryObjectExpr, that node also represents the
1431 // functional cast. Otherwise, create an explicit cast to represent
1432 // the syntactic form of a functional-style cast that was used here.
1433 //
1434 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1435 // would give a more consistent AST representation than using a
1436 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1437 // is sometimes handled by initialization and sometimes not.
1438 QualType ResultType = Result.get()->getType();
1439 SourceRange Locs = ListInitialization
1440 ? SourceRange()
1441 : SourceRange(LParenOrBraceLoc, RParenOrBraceLoc);
1442 Result = CXXFunctionalCastExpr::Create(
1443 Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp,
1444 Result.get(), /*Path=*/nullptr, Locs.getBegin(), Locs.getEnd());
1445 }
1446
1447 return Result;
1448}
1449
1450bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) {
1451 // [CUDA] Ignore this function, if we can't call it.
1452 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext);
1453 if (getLangOpts().CUDA &&
1454 IdentifyCUDAPreference(Caller, Method) <= CFP_WrongSide)
1455 return false;
1456
1457 SmallVector<const FunctionDecl*, 4> PreventedBy;
1458 bool Result = Method->isUsualDeallocationFunction(PreventedBy);
1459
1460 if (Result || !getLangOpts().CUDA || PreventedBy.empty())
1461 return Result;
1462
1463 // In case of CUDA, return true if none of the 1-argument deallocator
1464 // functions are actually callable.
1465 return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) {
1466 assert(FD->getNumParams() == 1 &&((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy"
) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1467, __PRETTY_FUNCTION__))
1467 "Only single-operand functions should be in PreventedBy")((FD->getNumParams() == 1 && "Only single-operand functions should be in PreventedBy"
) ? static_cast<void> (0) : __assert_fail ("FD->getNumParams() == 1 && \"Only single-operand functions should be in PreventedBy\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1467, __PRETTY_FUNCTION__))
;
1468 return IdentifyCUDAPreference(Caller, FD) >= CFP_HostDevice;
1469 });
1470}
1471
1472/// Determine whether the given function is a non-placement
1473/// deallocation function.
1474static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1475 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1476 return S.isUsualDeallocationFunction(Method);
1477
1478 if (FD->getOverloadedOperator() != OO_Delete &&
1479 FD->getOverloadedOperator() != OO_Array_Delete)
1480 return false;
1481
1482 unsigned UsualParams = 1;
1483
1484 if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() &&
1485 S.Context.hasSameUnqualifiedType(
1486 FD->getParamDecl(UsualParams)->getType(),
1487 S.Context.getSizeType()))
1488 ++UsualParams;
1489
1490 if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() &&
1491 S.Context.hasSameUnqualifiedType(
1492 FD->getParamDecl(UsualParams)->getType(),
1493 S.Context.getTypeDeclType(S.getStdAlignValT())))
1494 ++UsualParams;
1495
1496 return UsualParams == FD->getNumParams();
1497}
1498
1499namespace {
1500 struct UsualDeallocFnInfo {
1501 UsualDeallocFnInfo() : Found(), FD(nullptr) {}
1502 UsualDeallocFnInfo(Sema &S, DeclAccessPair Found)
1503 : Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())),
1504 Destroying(false), HasSizeT(false), HasAlignValT(false),
1505 CUDAPref(Sema::CFP_Native) {
1506 // A function template declaration is never a usual deallocation function.
1507 if (!FD)
1508 return;
1509 unsigned NumBaseParams = 1;
1510 if (FD->isDestroyingOperatorDelete()) {
1511 Destroying = true;
1512 ++NumBaseParams;
1513 }
1514 if (FD->getNumParams() == NumBaseParams + 2)
1515 HasAlignValT = HasSizeT = true;
1516 else if (FD->getNumParams() == NumBaseParams + 1) {
1517 HasSizeT = FD->getParamDecl(NumBaseParams)->getType()->isIntegerType();
1518 HasAlignValT = !HasSizeT;
1519 }
1520
1521 // In CUDA, determine how much we'd like / dislike to call this.
1522 if (S.getLangOpts().CUDA)
1523 if (auto *Caller = dyn_cast<FunctionDecl>(S.CurContext))
1524 CUDAPref = S.IdentifyCUDAPreference(Caller, FD);
1525 }
1526
1527 explicit operator bool() const { return FD; }
1528
1529 bool isBetterThan(const UsualDeallocFnInfo &Other, bool WantSize,
1530 bool WantAlign) const {
1531 // C++ P0722:
1532 // A destroying operator delete is preferred over a non-destroying
1533 // operator delete.
1534 if (Destroying != Other.Destroying)
1535 return Destroying;
1536
1537 // C++17 [expr.delete]p10:
1538 // If the type has new-extended alignment, a function with a parameter
1539 // of type std::align_val_t is preferred; otherwise a function without
1540 // such a parameter is preferred
1541 if (HasAlignValT != Other.HasAlignValT)
1542 return HasAlignValT == WantAlign;
1543
1544 if (HasSizeT != Other.HasSizeT)
1545 return HasSizeT == WantSize;
1546
1547 // Use CUDA call preference as a tiebreaker.
1548 return CUDAPref > Other.CUDAPref;
1549 }
1550
1551 DeclAccessPair Found;
1552 FunctionDecl *FD;
1553 bool Destroying, HasSizeT, HasAlignValT;
1554 Sema::CUDAFunctionPreference CUDAPref;
1555 };
1556}
1557
1558/// Determine whether a type has new-extended alignment. This may be called when
1559/// the type is incomplete (for a delete-expression with an incomplete pointee
1560/// type), in which case it will conservatively return false if the alignment is
1561/// not known.
1562static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) {
1563 return S.getLangOpts().AlignedAllocation &&
1564 S.getASTContext().getTypeAlignIfKnown(AllocType) >
1565 S.getASTContext().getTargetInfo().getNewAlign();
1566}
1567
1568/// Select the correct "usual" deallocation function to use from a selection of
1569/// deallocation functions (either global or class-scope).
1570static UsualDeallocFnInfo resolveDeallocationOverload(
1571 Sema &S, LookupResult &R, bool WantSize, bool WantAlign,
1572 llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) {
1573 UsualDeallocFnInfo Best;
1574
1575 for (auto I = R.begin(), E = R.end(); I != E; ++I) {
1576 UsualDeallocFnInfo Info(S, I.getPair());
1577 if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) ||
1578 Info.CUDAPref == Sema::CFP_Never)
1579 continue;
1580
1581 if (!Best) {
1582 Best = Info;
1583 if (BestFns)
1584 BestFns->push_back(Info);
1585 continue;
1586 }
1587
1588 if (Best.isBetterThan(Info, WantSize, WantAlign))
1589 continue;
1590
1591 // If more than one preferred function is found, all non-preferred
1592 // functions are eliminated from further consideration.
1593 if (BestFns && Info.isBetterThan(Best, WantSize, WantAlign))
1594 BestFns->clear();
1595
1596 Best = Info;
1597 if (BestFns)
1598 BestFns->push_back(Info);
1599 }
1600
1601 return Best;
1602}
1603
1604/// Determine whether a given type is a class for which 'delete[]' would call
1605/// a member 'operator delete[]' with a 'size_t' parameter. This implies that
1606/// we need to store the array size (even if the type is
1607/// trivially-destructible).
1608static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1609 QualType allocType) {
1610 const RecordType *record =
1611 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1612 if (!record) return false;
1613
1614 // Try to find an operator delete[] in class scope.
1615
1616 DeclarationName deleteName =
1617 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1618 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1619 S.LookupQualifiedName(ops, record->getDecl());
1620
1621 // We're just doing this for information.
1622 ops.suppressDiagnostics();
1623
1624 // Very likely: there's no operator delete[].
1625 if (ops.empty()) return false;
1626
1627 // If it's ambiguous, it should be illegal to call operator delete[]
1628 // on this thing, so it doesn't matter if we allocate extra space or not.
1629 if (ops.isAmbiguous()) return false;
1630
1631 // C++17 [expr.delete]p10:
1632 // If the deallocation functions have class scope, the one without a
1633 // parameter of type std::size_t is selected.
1634 auto Best = resolveDeallocationOverload(
1635 S, ops, /*WantSize*/false,
1636 /*WantAlign*/hasNewExtendedAlignment(S, allocType));
1637 return Best && Best.HasSizeT;
1638}
1639
1640/// Parsed a C++ 'new' expression (C++ 5.3.4).
1641///
1642/// E.g.:
1643/// @code new (memory) int[size][4] @endcode
1644/// or
1645/// @code ::new Foo(23, "hello") @endcode
1646///
1647/// \param StartLoc The first location of the expression.
1648/// \param UseGlobal True if 'new' was prefixed with '::'.
1649/// \param PlacementLParen Opening paren of the placement arguments.
1650/// \param PlacementArgs Placement new arguments.
1651/// \param PlacementRParen Closing paren of the placement arguments.
1652/// \param TypeIdParens If the type is in parens, the source range.
1653/// \param D The type to be allocated, as well as array dimensions.
1654/// \param Initializer The initializing expression or initializer-list, or null
1655/// if there is none.
1656ExprResult
1657Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1658 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1659 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1660 Declarator &D, Expr *Initializer) {
1661 Expr *ArraySize = nullptr;
1662 // If the specified type is an array, unwrap it and save the expression.
1663 if (D.getNumTypeObjects() > 0 &&
1664 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1665 DeclaratorChunk &Chunk = D.getTypeObject(0);
1666 if (D.getDeclSpec().hasAutoTypeSpec())
1667 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1668 << D.getSourceRange());
1669 if (Chunk.Arr.hasStatic)
1670 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1671 << D.getSourceRange());
1672 if (!Chunk.Arr.NumElts)
1673 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1674 << D.getSourceRange());
1675
1676 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1677 D.DropFirstTypeObject();
1678 }
1679
1680 // Every dimension shall be of constant size.
1681 if (ArraySize) {
1682 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1683 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1684 break;
1685
1686 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1687 if (Expr *NumElts = (Expr *)Array.NumElts) {
1688 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1689 if (getLangOpts().CPlusPlus14) {
1690 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1691 // shall be a converted constant expression (5.19) of type std::size_t
1692 // and shall evaluate to a strictly positive value.
1693 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1694 assert(IntWidth && "Builtin type of size 0?")((IntWidth && "Builtin type of size 0?") ? static_cast
<void> (0) : __assert_fail ("IntWidth && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1694, __PRETTY_FUNCTION__))
;
1695 llvm::APSInt Value(IntWidth);
1696 Array.NumElts
1697 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1698 CCEK_NewExpr)
1699 .get();
1700 } else {
1701 Array.NumElts
1702 = VerifyIntegerConstantExpression(NumElts, nullptr,
1703 diag::err_new_array_nonconst)
1704 .get();
1705 }
1706 if (!Array.NumElts)
1707 return ExprError();
1708 }
1709 }
1710 }
1711 }
1712
1713 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1714 QualType AllocType = TInfo->getType();
1715 if (D.isInvalidType())
1716 return ExprError();
1717
1718 SourceRange DirectInitRange;
1719 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1720 DirectInitRange = List->getSourceRange();
1721
1722 return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal,
1723 PlacementLParen, PlacementArgs, PlacementRParen,
1724 TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange,
1725 Initializer);
1726}
1727
1728static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1729 Expr *Init) {
1730 if (!Init)
1731 return true;
1732 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1733 return PLE->getNumExprs() == 0;
1734 if (isa<ImplicitValueInitExpr>(Init))
1735 return true;
1736 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1737 return !CCE->isListInitialization() &&
1738 CCE->getConstructor()->isDefaultConstructor();
1739 else if (Style == CXXNewExpr::ListInit) {
1740 assert(isa<InitListExpr>(Init) &&((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1741, __PRETTY_FUNCTION__))
1741 "Shouldn't create list CXXConstructExprs for arrays.")((isa<InitListExpr>(Init) && "Shouldn't create list CXXConstructExprs for arrays."
) ? static_cast<void> (0) : __assert_fail ("isa<InitListExpr>(Init) && \"Shouldn't create list CXXConstructExprs for arrays.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1741, __PRETTY_FUNCTION__))
;
1742 return true;
1743 }
1744 return false;
1745}
1746
1747bool
1748Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const {
1749 if (!getLangOpts().AlignedAllocationUnavailable)
1750 return false;
1751 if (FD.isDefined())
1752 return false;
1753 bool IsAligned = false;
1754 if (FD.isReplaceableGlobalAllocationFunction(&IsAligned) && IsAligned)
1755 return true;
1756 return false;
1757}
1758
1759// Emit a diagnostic if an aligned allocation/deallocation function that is not
1760// implemented in the standard library is selected.
1761void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD,
1762 SourceLocation Loc) {
1763 if (isUnavailableAlignedAllocationFunction(FD)) {
1764 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
1765 StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling(
1766 getASTContext().getTargetInfo().getPlatformName());
1767
1768 OverloadedOperatorKind Kind = FD.getDeclName().getCXXOverloadedOperator();
1769 bool IsDelete = Kind == OO_Delete || Kind == OO_Array_Delete;
1770 Diag(Loc, diag::err_aligned_allocation_unavailable)
1771 << IsDelete << FD.getType().getAsString() << OSName
1772 << alignedAllocMinVersion(T.getOS()).getAsString();
1773 Diag(Loc, diag::note_silence_aligned_allocation_unavailable);
1774 }
1775}
1776
1777ExprResult
1778Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1779 SourceLocation PlacementLParen,
1780 MultiExprArg PlacementArgs,
1781 SourceLocation PlacementRParen,
1782 SourceRange TypeIdParens,
1783 QualType AllocType,
1784 TypeSourceInfo *AllocTypeInfo,
1785 Expr *ArraySize,
1786 SourceRange DirectInitRange,
1787 Expr *Initializer) {
1788 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1789 SourceLocation StartLoc = Range.getBegin();
1790
1791 CXXNewExpr::InitializationStyle initStyle;
1792 if (DirectInitRange.isValid()) {
1793 assert(Initializer && "Have parens but no initializer.")((Initializer && "Have parens but no initializer.") ?
static_cast<void> (0) : __assert_fail ("Initializer && \"Have parens but no initializer.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1793, __PRETTY_FUNCTION__))
;
1794 initStyle = CXXNewExpr::CallInit;
1795 } else if (Initializer && isa<InitListExpr>(Initializer))
1796 initStyle = CXXNewExpr::ListInit;
1797 else {
1798 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1800, __PRETTY_FUNCTION__))
1799 isa<CXXConstructExpr>(Initializer)) &&(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1800, __PRETTY_FUNCTION__))
1800 "Initializer expression that cannot have been implicitly created.")(((!Initializer || isa<ImplicitValueInitExpr>(Initializer
) || isa<CXXConstructExpr>(Initializer)) && "Initializer expression that cannot have been implicitly created."
) ? static_cast<void> (0) : __assert_fail ("(!Initializer || isa<ImplicitValueInitExpr>(Initializer) || isa<CXXConstructExpr>(Initializer)) && \"Initializer expression that cannot have been implicitly created.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1800, __PRETTY_FUNCTION__))
;
1801 initStyle = CXXNewExpr::NoInit;
1802 }
1803
1804 Expr **Inits = &Initializer;
1805 unsigned NumInits = Initializer ? 1 : 0;
1806 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1807 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init")((initStyle == CXXNewExpr::CallInit && "paren init for non-call init"
) ? static_cast<void> (0) : __assert_fail ("initStyle == CXXNewExpr::CallInit && \"paren init for non-call init\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1807, __PRETTY_FUNCTION__))
;
1808 Inits = List->getExprs();
1809 NumInits = List->getNumExprs();
1810 }
1811
1812 // C++11 [expr.new]p15:
1813 // A new-expression that creates an object of type T initializes that
1814 // object as follows:
1815 InitializationKind Kind
1816 // - If the new-initializer is omitted, the object is default-
1817 // initialized (8.5); if no initialization is performed,
1818 // the object has indeterminate value
1819 = initStyle == CXXNewExpr::NoInit
1820 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1821 // - Otherwise, the new-initializer is interpreted according to
1822 // the
1823 // initialization rules of 8.5 for direct-initialization.
1824 : initStyle == CXXNewExpr::ListInit
1825 ? InitializationKind::CreateDirectList(
1826 TypeRange.getBegin(), Initializer->getBeginLoc(),
1827 Initializer->getEndLoc())
1828 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1829 DirectInitRange.getBegin(),
1830 DirectInitRange.getEnd());
1831
1832 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1833 auto *Deduced = AllocType->getContainedDeducedType();
1834 if (Deduced && isa<DeducedTemplateSpecializationType>(Deduced)) {
1835 if (ArraySize)
1836 return ExprError(Diag(ArraySize->getExprLoc(),
1837 diag::err_deduced_class_template_compound_type)
1838 << /*array*/ 2 << ArraySize->getSourceRange());
1839
1840 InitializedEntity Entity
1841 = InitializedEntity::InitializeNew(StartLoc, AllocType);
1842 AllocType = DeduceTemplateSpecializationFromInitializer(
1843 AllocTypeInfo, Entity, Kind, MultiExprArg(Inits, NumInits));
1844 if (AllocType.isNull())
1845 return ExprError();
1846 } else if (Deduced) {
1847 bool Braced = (initStyle == CXXNewExpr::ListInit);
1848 if (NumInits == 1) {
1849 if (auto p = dyn_cast_or_null<InitListExpr>(Inits[0])) {
1850 Inits = p->getInits();
1851 NumInits = p->getNumInits();
1852 Braced = true;
1853 }
1854 }
1855
1856 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1857 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1858 << AllocType << TypeRange);
1859 if (NumInits > 1) {
1860 Expr *FirstBad = Inits[1];
1861 return ExprError(Diag(FirstBad->getBeginLoc(),
1862 diag::err_auto_new_ctor_multiple_expressions)
1863 << AllocType << TypeRange);
1864 }
1865 if (Braced && !getLangOpts().CPlusPlus17)
1866 Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init)
1867 << AllocType << TypeRange;
1868 Expr *Deduce = Inits[0];
1869 QualType DeducedType;
1870 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1871 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1872 << AllocType << Deduce->getType()
1873 << TypeRange << Deduce->getSourceRange());
1874 if (DeducedType.isNull())
1875 return ExprError();
1876 AllocType = DeducedType;
1877 }
1878
1879 // Per C++0x [expr.new]p5, the type being constructed may be a
1880 // typedef of an array type.
1881 if (!ArraySize) {
1882 if (const ConstantArrayType *Array
1883 = Context.getAsConstantArrayType(AllocType)) {
1884 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1885 Context.getSizeType(),
1886 TypeRange.getEnd());
1887 AllocType = Array->getElementType();
1888 }
1889 }
1890
1891 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1892 return ExprError();
1893
1894 // In ARC, infer 'retaining' for the allocated
1895 if (getLangOpts().ObjCAutoRefCount &&
1896 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1897 AllocType->isObjCLifetimeType()) {
1898 AllocType = Context.getLifetimeQualifiedType(AllocType,
1899 AllocType->getObjCARCImplicitLifetime());
1900 }
1901
1902 QualType ResultType = Context.getPointerType(AllocType);
1903
1904 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1905 ExprResult result = CheckPlaceholderExpr(ArraySize);
1906 if (result.isInvalid()) return ExprError();
1907 ArraySize = result.get();
1908 }
1909 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1910 // integral or enumeration type with a non-negative value."
1911 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1912 // enumeration type, or a class type for which a single non-explicit
1913 // conversion function to integral or unscoped enumeration type exists.
1914 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1915 // std::size_t.
1916 llvm::Optional<uint64_t> KnownArraySize;
1917 if (ArraySize && !ArraySize->isTypeDependent()) {
1918 ExprResult ConvertedSize;
1919 if (getLangOpts().CPlusPlus14) {
1920 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?")((Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"
) ? static_cast<void> (0) : __assert_fail ("Context.getTargetInfo().getIntWidth() && \"Builtin type of size 0?\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 1920, __PRETTY_FUNCTION__))
;
1921
1922 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1923 AA_Converting);
1924
1925 if (!ConvertedSize.isInvalid() &&
1926 ArraySize->getType()->getAs<RecordType>())
1927 // Diagnose the compatibility of this conversion.
1928 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1929 << ArraySize->getType() << 0 << "'size_t'";
1930 } else {
1931 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1932 protected:
1933 Expr *ArraySize;
1934
1935 public:
1936 SizeConvertDiagnoser(Expr *ArraySize)
1937 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1938 ArraySize(ArraySize) {}
1939
1940 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1941 QualType T) override {
1942 return S.Diag(Loc, diag::err_array_size_not_integral)
1943 << S.getLangOpts().CPlusPlus11 << T;
1944 }
1945
1946 SemaDiagnosticBuilder diagnoseIncomplete(
1947 Sema &S, SourceLocation Loc, QualType T) override {
1948 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1949 << T << ArraySize->getSourceRange();
1950 }
1951
1952 SemaDiagnosticBuilder diagnoseExplicitConv(
1953 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1954 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1955 }
1956
1957 SemaDiagnosticBuilder noteExplicitConv(
1958 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1959 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1960 << ConvTy->isEnumeralType() << ConvTy;
1961 }
1962
1963 SemaDiagnosticBuilder diagnoseAmbiguous(
1964 Sema &S, SourceLocation Loc, QualType T) override {
1965 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1966 }
1967
1968 SemaDiagnosticBuilder noteAmbiguous(
1969 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1970 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1971 << ConvTy->isEnumeralType() << ConvTy;
1972 }
1973
1974 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1975 QualType T,
1976 QualType ConvTy) override {
1977 return S.Diag(Loc,
1978 S.getLangOpts().CPlusPlus11
1979 ? diag::warn_cxx98_compat_array_size_conversion
1980 : diag::ext_array_size_conversion)
1981 << T << ConvTy->isEnumeralType() << ConvTy;
1982 }
1983 } SizeDiagnoser(ArraySize);
1984
1985 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1986 SizeDiagnoser);
1987 }
1988 if (ConvertedSize.isInvalid())
1989 return ExprError();
1990
1991 ArraySize = ConvertedSize.get();
1992 QualType SizeType = ArraySize->getType();
1993
1994 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1995 return ExprError();
1996
1997 // C++98 [expr.new]p7:
1998 // The expression in a direct-new-declarator shall have integral type
1999 // with a non-negative value.
2000 //
2001 // Let's see if this is a constant < 0. If so, we reject it out of hand,
2002 // per CWG1464. Otherwise, if it's not a constant, we must have an
2003 // unparenthesized array type.
2004 if (!ArraySize->isValueDependent()) {
2005 llvm::APSInt Value;
2006 // We've already performed any required implicit conversion to integer or
2007 // unscoped enumeration type.
2008 // FIXME: Per CWG1464, we are required to check the value prior to
2009 // converting to size_t. This will never find a negative array size in
2010 // C++14 onwards, because Value is always unsigned here!
2011 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
2012 if (Value.isSigned() && Value.isNegative()) {
2013 return ExprError(Diag(ArraySize->getBeginLoc(),
2014 diag::err_typecheck_negative_array_size)
2015 << ArraySize->getSourceRange());
2016 }
2017
2018 if (!AllocType->isDependentType()) {
2019 unsigned ActiveSizeBits =
2020 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
2021 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
2022 return ExprError(
2023 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2024 << Value.toString(10) << ArraySize->getSourceRange());
2025 }
2026
2027 KnownArraySize = Value.getZExtValue();
2028 } else if (TypeIdParens.isValid()) {
2029 // Can't have dynamic array size when the type-id is in parentheses.
2030 Diag(ArraySize->getBeginLoc(), diag::ext_new_paren_array_nonconst)
2031 << ArraySize->getSourceRange()
2032 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
2033 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
2034
2035 TypeIdParens = SourceRange();
2036 }
2037 }
2038
2039 // Note that we do *not* convert the argument in any way. It can
2040 // be signed, larger than size_t, whatever.
2041 }
2042
2043 FunctionDecl *OperatorNew = nullptr;
2044 FunctionDecl *OperatorDelete = nullptr;
2045 unsigned Alignment =
2046 AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType);
2047 unsigned NewAlignment = Context.getTargetInfo().getNewAlign();
2048 bool PassAlignment = getLangOpts().AlignedAllocation &&
2049 Alignment > NewAlignment;
2050
2051 AllocationFunctionScope Scope = UseGlobal ? AFS_Global : AFS_Both;
2052 if (!AllocType->isDependentType() &&
2053 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
2054 FindAllocationFunctions(StartLoc,
2055 SourceRange(PlacementLParen, PlacementRParen),
2056 Scope, Scope, AllocType, ArraySize, PassAlignment,
2057 PlacementArgs, OperatorNew, OperatorDelete))
2058 return ExprError();
2059
2060 // If this is an array allocation, compute whether the usual array
2061 // deallocation function for the type has a size_t parameter.
2062 bool UsualArrayDeleteWantsSize = false;
2063 if (ArraySize && !AllocType->isDependentType())
2064 UsualArrayDeleteWantsSize =
2065 doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
2066
2067 SmallVector<Expr *, 8> AllPlaceArgs;
2068 if (OperatorNew) {
2069 const FunctionProtoType *Proto =
2070 OperatorNew->getType()->getAs<FunctionProtoType>();
2071 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
2072 : VariadicDoesNotApply;
2073
2074 // We've already converted the placement args, just fill in any default
2075 // arguments. Skip the first parameter because we don't have a corresponding
2076 // argument. Skip the second parameter too if we're passing in the
2077 // alignment; we've already filled it in.
2078 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto,
2079 PassAlignment ? 2 : 1, PlacementArgs,
2080 AllPlaceArgs, CallType))
2081 return ExprError();
2082
2083 if (!AllPlaceArgs.empty())
2084 PlacementArgs = AllPlaceArgs;
2085
2086 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
2087 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
2088
2089 // FIXME: Missing call to CheckFunctionCall or equivalent
2090
2091 // Warn if the type is over-aligned and is being allocated by (unaligned)
2092 // global operator new.
2093 if (PlacementArgs.empty() && !PassAlignment &&
2094 (OperatorNew->isImplicit() ||
2095 (OperatorNew->getBeginLoc().isValid() &&
2096 getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) {
2097 if (Alignment > NewAlignment)
2098 Diag(StartLoc, diag::warn_overaligned_type)
2099 << AllocType
2100 << unsigned(Alignment / Context.getCharWidth())
2101 << unsigned(NewAlignment / Context.getCharWidth());
2102 }
2103 }
2104
2105 // Array 'new' can't have any initializers except empty parentheses.
2106 // Initializer lists are also allowed, in C++11. Rely on the parser for the
2107 // dialect distinction.
2108 if (ArraySize && !isLegalArrayNewInitializer(initStyle, Initializer)) {
2109 SourceRange InitRange(Inits[0]->getBeginLoc(),
2110 Inits[NumInits - 1]->getEndLoc());
2111 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
2112 return ExprError();
2113 }
2114
2115 // If we can perform the initialization, and we've not already done so,
2116 // do it now.
2117 if (!AllocType->isDependentType() &&
2118 !Expr::hasAnyTypeDependentArguments(
2119 llvm::makeArrayRef(Inits, NumInits))) {
2120 // The type we initialize is the complete type, including the array bound.
2121 QualType InitType;
2122 if (KnownArraySize)
2123 InitType = Context.getConstantArrayType(
2124 AllocType, llvm::APInt(Context.getTypeSize(Context.getSizeType()),
2125 *KnownArraySize),
2126 ArrayType::Normal, 0);
2127 else if (ArraySize)
2128 InitType =
2129 Context.getIncompleteArrayType(AllocType, ArrayType::Normal, 0);
2130 else
2131 InitType = AllocType;
2132
2133 InitializedEntity Entity
2134 = InitializedEntity::InitializeNew(StartLoc, InitType);
2135 InitializationSequence InitSeq(*this, Entity, Kind,
2136 MultiExprArg(Inits, NumInits));
2137 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
2138 MultiExprArg(Inits, NumInits));
2139 if (FullInit.isInvalid())
2140 return ExprError();
2141
2142 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
2143 // we don't want the initialized object to be destructed.
2144 // FIXME: We should not create these in the first place.
2145 if (CXXBindTemporaryExpr *Binder =
2146 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
2147 FullInit = Binder->getSubExpr();
2148
2149 Initializer = FullInit.get();
2150 }
2151
2152 // Mark the new and delete operators as referenced.
2153 if (OperatorNew) {
2154 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
2155 return ExprError();
2156 MarkFunctionReferenced(StartLoc, OperatorNew);
2157 }
2158 if (OperatorDelete) {
2159 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
2160 return ExprError();
2161 MarkFunctionReferenced(StartLoc, OperatorDelete);
2162 }
2163
2164 // C++0x [expr.new]p17:
2165 // If the new expression creates an array of objects of class type,
2166 // access and ambiguity control are done for the destructor.
2167 QualType BaseAllocType = Context.getBaseElementType(AllocType);
2168 if (ArraySize && !BaseAllocType->isDependentType()) {
2169 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
2170 if (CXXDestructorDecl *dtor = LookupDestructor(
2171 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
2172 MarkFunctionReferenced(StartLoc, dtor);
2173 CheckDestructorAccess(StartLoc, dtor,
2174 PDiag(diag::err_access_dtor)
2175 << BaseAllocType);
2176 if (DiagnoseUseOfDecl(dtor, StartLoc))
2177 return ExprError();
2178 }
2179 }
2180 }
2181
2182 return new (Context)
2183 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete, PassAlignment,
2184 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
2185 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
2186 Range, DirectInitRange);
2187}
2188
2189/// Checks that a type is suitable as the allocated type
2190/// in a new-expression.
2191bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
2192 SourceRange R) {
2193 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
2194 // abstract class type or array thereof.
2195 if (AllocType->isFunctionType())
2196 return Diag(Loc, diag::err_bad_new_type)
2197 << AllocType << 0 << R;
2198 else if (AllocType->isReferenceType())
2199 return Diag(Loc, diag::err_bad_new_type)
2200 << AllocType << 1 << R;
2201 else if (!AllocType->isDependentType() &&
2202 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
2203 return true;
2204 else if (RequireNonAbstractType(Loc, AllocType,
2205 diag::err_allocation_of_abstract_type))
2206 return true;
2207 else if (AllocType->isVariablyModifiedType())
2208 return Diag(Loc, diag::err_variably_modified_new_type)
2209 << AllocType;
2210 else if (AllocType.getAddressSpace() != LangAS::Default &&
2211 !getLangOpts().OpenCLCPlusPlus)
2212 return Diag(Loc, diag::err_address_space_qualified_new)
2213 << AllocType.getUnqualifiedType()
2214 << AllocType.getQualifiers().getAddressSpaceAttributePrintValue();
2215 else if (getLangOpts().ObjCAutoRefCount) {
2216 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
2217 QualType BaseAllocType = Context.getBaseElementType(AT);
2218 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
2219 BaseAllocType->isObjCLifetimeType())
2220 return Diag(Loc, diag::err_arc_new_array_without_ownership)
2221 << BaseAllocType;
2222 }
2223 }
2224
2225 return false;
2226}
2227
2228static bool resolveAllocationOverload(
2229 Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args,
2230 bool &PassAlignment, FunctionDecl *&Operator,
2231 OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) {
2232 OverloadCandidateSet Candidates(R.getNameLoc(),
2233 OverloadCandidateSet::CSK_Normal);
2234 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2235 Alloc != AllocEnd; ++Alloc) {
2236 // Even member operator new/delete are implicitly treated as
2237 // static, so don't use AddMemberCandidate.
2238 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2239
2240 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2241 S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2242 /*ExplicitTemplateArgs=*/nullptr, Args,
2243 Candidates,
2244 /*SuppressUserConversions=*/false);
2245 continue;
2246 }
2247
2248 FunctionDecl *Fn = cast<FunctionDecl>(D);
2249 S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2250 /*SuppressUserConversions=*/false);
2251 }
2252
2253 // Do the resolution.
2254 OverloadCandidateSet::iterator Best;
2255 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
2256 case OR_Success: {
2257 // Got one!
2258 FunctionDecl *FnDecl = Best->Function;
2259 if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(),
2260 Best->FoundDecl) == Sema::AR_inaccessible)
2261 return true;
2262
2263 Operator = FnDecl;
2264 return false;
2265 }
2266
2267 case OR_No_Viable_Function:
2268 // C++17 [expr.new]p13:
2269 // If no matching function is found and the allocated object type has
2270 // new-extended alignment, the alignment argument is removed from the
2271 // argument list, and overload resolution is performed again.
2272 if (PassAlignment) {
2273 PassAlignment = false;
2274 AlignArg = Args[1];
2275 Args.erase(Args.begin() + 1);
2276 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2277 Operator, &Candidates, AlignArg,
2278 Diagnose);
2279 }
2280
2281 // MSVC will fall back on trying to find a matching global operator new
2282 // if operator new[] cannot be found. Also, MSVC will leak by not
2283 // generating a call to operator delete or operator delete[], but we
2284 // will not replicate that bug.
2285 // FIXME: Find out how this interacts with the std::align_val_t fallback
2286 // once MSVC implements it.
2287 if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New &&
2288 S.Context.getLangOpts().MSVCCompat) {
2289 R.clear();
2290 R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New));
2291 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
2292 // FIXME: This will give bad diagnostics pointing at the wrong functions.
2293 return resolveAllocationOverload(S, R, Range, Args, PassAlignment,
2294 Operator, /*Candidates=*/nullptr,
2295 /*AlignArg=*/nullptr, Diagnose);
2296 }
2297
2298 if (Diagnose) {
2299 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
2300 << R.getLookupName() << Range;
2301
2302 // If we have aligned candidates, only note the align_val_t candidates
2303 // from AlignedCandidates and the non-align_val_t candidates from
2304 // Candidates.
2305 if (AlignedCandidates) {
2306 auto IsAligned = [](OverloadCandidate &C) {
2307 return C.Function->getNumParams() > 1 &&
2308 C.Function->getParamDecl(1)->getType()->isAlignValT();
2309 };
2310 auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); };
2311
2312 // This was an overaligned allocation, so list the aligned candidates
2313 // first.
2314 Args.insert(Args.begin() + 1, AlignArg);
2315 AlignedCandidates->NoteCandidates(S, OCD_AllCandidates, Args, "",
2316 R.getNameLoc(), IsAligned);
2317 Args.erase(Args.begin() + 1);
2318 Candidates.NoteCandidates(S, OCD_AllCandidates, Args, "", R.getNameLoc(),
2319 IsUnaligned);
2320 } else {
2321 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2322 }
2323 }
2324 return true;
2325
2326 case OR_Ambiguous:
2327 if (Diagnose) {
2328 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
2329 << R.getLookupName() << Range;
2330 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
2331 }
2332 return true;
2333
2334 case OR_Deleted: {
2335 if (Diagnose) {
2336 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
2337 << Best->Function->isDeleted() << R.getLookupName()
2338 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
2339 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
2340 }
2341 return true;
2342 }
2343 }
2344 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2344)
;
2345}
2346
2347bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
2348 AllocationFunctionScope NewScope,
2349 AllocationFunctionScope DeleteScope,
2350 QualType AllocType, bool IsArray,
2351 bool &PassAlignment, MultiExprArg PlaceArgs,
2352 FunctionDecl *&OperatorNew,
2353 FunctionDecl *&OperatorDelete,
2354 bool Diagnose) {
2355 // --- Choosing an allocation function ---
2356 // C++ 5.3.4p8 - 14 & 18
2357 // 1) If looking in AFS_Global scope for allocation functions, only look in
2358 // the global scope. Else, if AFS_Class, only look in the scope of the
2359 // allocated class. If AFS_Both, look in both.
2360 // 2) If an array size is given, look for operator new[], else look for
2361 // operator new.
2362 // 3) The first argument is always size_t. Append the arguments from the
2363 // placement form.
2364
2365 SmallVector<Expr*, 8> AllocArgs;
2366 AllocArgs.reserve((PassAlignment ? 2 : 1) + PlaceArgs.size());
2367
2368 // We don't care about the actual value of these arguments.
2369 // FIXME: Should the Sema create the expression and embed it in the syntax
2370 // tree? Or should the consumer just recalculate the value?
2371 // FIXME: Using a dummy value will interact poorly with attribute enable_if.
2372 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
2373 Context.getTargetInfo().getPointerWidth(0)),
2374 Context.getSizeType(),
2375 SourceLocation());
2376 AllocArgs.push_back(&Size);
2377
2378 QualType AlignValT = Context.VoidTy;
2379 if (PassAlignment) {
2380 DeclareGlobalNewDelete();
2381 AlignValT = Context.getTypeDeclType(getStdAlignValT());
2382 }
2383 CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation());
2384 if (PassAlignment)
2385 AllocArgs.push_back(&Align);
2386
2387 AllocArgs.insert(AllocArgs.end(), PlaceArgs.begin(), PlaceArgs.end());
2388
2389 // C++ [expr.new]p8:
2390 // If the allocated type is a non-array type, the allocation
2391 // function's name is operator new and the deallocation function's
2392 // name is operator delete. If the allocated type is an array
2393 // type, the allocation function's name is operator new[] and the
2394 // deallocation function's name is operator delete[].
2395 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
2396 IsArray ? OO_Array_New : OO_New);
2397
2398 QualType AllocElemType = Context.getBaseElementType(AllocType);
2399
2400 // Find the allocation function.
2401 {
2402 LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName);
2403
2404 // C++1z [expr.new]p9:
2405 // If the new-expression begins with a unary :: operator, the allocation
2406 // function's name is looked up in the global scope. Otherwise, if the
2407 // allocated type is a class type T or array thereof, the allocation
2408 // function's name is looked up in the scope of T.
2409 if (AllocElemType->isRecordType() && NewScope != AFS_Global)
2410 LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl());
2411
2412 // We can see ambiguity here if the allocation function is found in
2413 // multiple base classes.
2414 if (R.isAmbiguous())
2415 return true;
2416
2417 // If this lookup fails to find the name, or if the allocated type is not
2418 // a class type, the allocation function's name is looked up in the
2419 // global scope.
2420 if (R.empty()) {
2421 if (NewScope == AFS_Class)
2422 return true;
2423
2424 LookupQualifiedName(R, Context.getTranslationUnitDecl());
2425 }
2426
2427 if (getLangOpts().OpenCLCPlusPlus && R.empty()) {
2428 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new";
2429 return true;
2430 }
2431
2432 assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2432, __PRETTY_FUNCTION__))
;
2433 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2433, __PRETTY_FUNCTION__))
;
2434
2435 // We do our own custom access checks below.
2436 R.suppressDiagnostics();
2437
2438 if (resolveAllocationOverload(*this, R, Range, AllocArgs, PassAlignment,
2439 OperatorNew, /*Candidates=*/nullptr,
2440 /*AlignArg=*/nullptr, Diagnose))
2441 return true;
2442 }
2443
2444 // We don't need an operator delete if we're running under -fno-exceptions.
2445 if (!getLangOpts().Exceptions) {
2446 OperatorDelete = nullptr;
2447 return false;
2448 }
2449
2450 // Note, the name of OperatorNew might have been changed from array to
2451 // non-array by resolveAllocationOverload.
2452 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2453 OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New
2454 ? OO_Array_Delete
2455 : OO_Delete);
2456
2457 // C++ [expr.new]p19:
2458 //
2459 // If the new-expression begins with a unary :: operator, the
2460 // deallocation function's name is looked up in the global
2461 // scope. Otherwise, if the allocated type is a class type T or an
2462 // array thereof, the deallocation function's name is looked up in
2463 // the scope of T. If this lookup fails to find the name, or if
2464 // the allocated type is not a class type or array thereof, the
2465 // deallocation function's name is looked up in the global scope.
2466 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2467 if (AllocElemType->isRecordType() && DeleteScope != AFS_Global) {
2468 CXXRecordDecl *RD
2469 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2470 LookupQualifiedName(FoundDelete, RD);
2471 }
2472 if (FoundDelete.isAmbiguous())
2473 return true; // FIXME: clean up expressions?
2474
2475 bool FoundGlobalDelete = FoundDelete.empty();
2476 if (FoundDelete.empty()) {
2477 if (DeleteScope == AFS_Class)
2478 return true;
2479
2480 DeclareGlobalNewDelete();
2481 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2482 }
2483
2484 FoundDelete.suppressDiagnostics();
2485
2486 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2487
2488 // Whether we're looking for a placement operator delete is dictated
2489 // by whether we selected a placement operator new, not by whether
2490 // we had explicit placement arguments. This matters for things like
2491 // struct A { void *operator new(size_t, int = 0); ... };
2492 // A *a = new A()
2493 //
2494 // We don't have any definition for what a "placement allocation function"
2495 // is, but we assume it's any allocation function whose
2496 // parameter-declaration-clause is anything other than (size_t).
2497 //
2498 // FIXME: Should (size_t, std::align_val_t) also be considered non-placement?
2499 // This affects whether an exception from the constructor of an overaligned
2500 // type uses the sized or non-sized form of aligned operator delete.
2501 bool isPlacementNew = !PlaceArgs.empty() || OperatorNew->param_size() != 1 ||
2502 OperatorNew->isVariadic();
2503
2504 if (isPlacementNew) {
2505 // C++ [expr.new]p20:
2506 // A declaration of a placement deallocation function matches the
2507 // declaration of a placement allocation function if it has the
2508 // same number of parameters and, after parameter transformations
2509 // (8.3.5), all parameter types except the first are
2510 // identical. [...]
2511 //
2512 // To perform this comparison, we compute the function type that
2513 // the deallocation function should have, and use that type both
2514 // for template argument deduction and for comparison purposes.
2515 QualType ExpectedFunctionType;
2516 {
2517 const FunctionProtoType *Proto
2518 = OperatorNew->getType()->getAs<FunctionProtoType>();
2519
2520 SmallVector<QualType, 4> ArgTypes;
2521 ArgTypes.push_back(Context.VoidPtrTy);
2522 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2523 ArgTypes.push_back(Proto->getParamType(I));
2524
2525 FunctionProtoType::ExtProtoInfo EPI;
2526 // FIXME: This is not part of the standard's rule.
2527 EPI.Variadic = Proto->isVariadic();
2528
2529 ExpectedFunctionType
2530 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2531 }
2532
2533 for (LookupResult::iterator D = FoundDelete.begin(),
2534 DEnd = FoundDelete.end();
2535 D != DEnd; ++D) {
2536 FunctionDecl *Fn = nullptr;
2537 if (FunctionTemplateDecl *FnTmpl =
2538 dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2539 // Perform template argument deduction to try to match the
2540 // expected function type.
2541 TemplateDeductionInfo Info(StartLoc);
2542 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2543 Info))
2544 continue;
2545 } else
2546 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2547
2548 if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(),
2549 ExpectedFunctionType,
2550 /*AdjustExcpetionSpec*/true),
2551 ExpectedFunctionType))
2552 Matches.push_back(std::make_pair(D.getPair(), Fn));
2553 }
2554
2555 if (getLangOpts().CUDA)
2556 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2557 } else {
2558 // C++1y [expr.new]p22:
2559 // For a non-placement allocation function, the normal deallocation
2560 // function lookup is used
2561 //
2562 // Per [expr.delete]p10, this lookup prefers a member operator delete
2563 // without a size_t argument, but prefers a non-member operator delete
2564 // with a size_t where possible (which it always is in this case).
2565 llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns;
2566 UsualDeallocFnInfo Selected = resolveDeallocationOverload(
2567 *this, FoundDelete, /*WantSize*/ FoundGlobalDelete,
2568 /*WantAlign*/ hasNewExtendedAlignment(*this, AllocElemType),
2569 &BestDeallocFns);
2570 if (Selected)
2571 Matches.push_back(std::make_pair(Selected.Found, Selected.FD));
2572 else {
2573 // If we failed to select an operator, all remaining functions are viable
2574 // but ambiguous.
2575 for (auto Fn : BestDeallocFns)
2576 Matches.push_back(std::make_pair(Fn.Found, Fn.FD));
2577 }
2578 }
2579
2580 // C++ [expr.new]p20:
2581 // [...] If the lookup finds a single matching deallocation
2582 // function, that function will be called; otherwise, no
2583 // deallocation function will be called.
2584 if (Matches.size() == 1) {
2585 OperatorDelete = Matches[0].second;
2586
2587 // C++1z [expr.new]p23:
2588 // If the lookup finds a usual deallocation function (3.7.4.2)
2589 // with a parameter of type std::size_t and that function, considered
2590 // as a placement deallocation function, would have been
2591 // selected as a match for the allocation function, the program
2592 // is ill-formed.
2593 if (getLangOpts().CPlusPlus11 && isPlacementNew &&
2594 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2595 UsualDeallocFnInfo Info(*this,
2596 DeclAccessPair::make(OperatorDelete, AS_public));
2597 // Core issue, per mail to core reflector, 2016-10-09:
2598 // If this is a member operator delete, and there is a corresponding
2599 // non-sized member operator delete, this isn't /really/ a sized
2600 // deallocation function, it just happens to have a size_t parameter.
2601 bool IsSizedDelete = Info.HasSizeT;
2602 if (IsSizedDelete && !FoundGlobalDelete) {
2603 auto NonSizedDelete =
2604 resolveDeallocationOverload(*this, FoundDelete, /*WantSize*/false,
2605 /*WantAlign*/Info.HasAlignValT);
2606 if (NonSizedDelete && !NonSizedDelete.HasSizeT &&
2607 NonSizedDelete.HasAlignValT == Info.HasAlignValT)
2608 IsSizedDelete = false;
2609 }
2610
2611 if (IsSizedDelete) {
2612 SourceRange R = PlaceArgs.empty()
2613 ? SourceRange()
2614 : SourceRange(PlaceArgs.front()->getBeginLoc(),
2615 PlaceArgs.back()->getEndLoc());
2616 Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R;
2617 if (!OperatorDelete->isImplicit())
2618 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2619 << DeleteName;
2620 }
2621 }
2622
2623 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2624 Matches[0].first);
2625 } else if (!Matches.empty()) {
2626 // We found multiple suitable operators. Per [expr.new]p20, that means we
2627 // call no 'operator delete' function, but we should at least warn the user.
2628 // FIXME: Suppress this warning if the construction cannot throw.
2629 Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found)
2630 << DeleteName << AllocElemType;
2631
2632 for (auto &Match : Matches)
2633 Diag(Match.second->getLocation(),
2634 diag::note_member_declared_here) << DeleteName;
2635 }
2636
2637 return false;
2638}
2639
2640/// DeclareGlobalNewDelete - Declare the global forms of operator new and
2641/// delete. These are:
2642/// @code
2643/// // C++03:
2644/// void* operator new(std::size_t) throw(std::bad_alloc);
2645/// void* operator new[](std::size_t) throw(std::bad_alloc);
2646/// void operator delete(void *) throw();
2647/// void operator delete[](void *) throw();
2648/// // C++11:
2649/// void* operator new(std::size_t);
2650/// void* operator new[](std::size_t);
2651/// void operator delete(void *) noexcept;
2652/// void operator delete[](void *) noexcept;
2653/// // C++1y:
2654/// void* operator new(std::size_t);
2655/// void* operator new[](std::size_t);
2656/// void operator delete(void *) noexcept;
2657/// void operator delete[](void *) noexcept;
2658/// void operator delete(void *, std::size_t) noexcept;
2659/// void operator delete[](void *, std::size_t) noexcept;
2660/// @endcode
2661/// Note that the placement and nothrow forms of new are *not* implicitly
2662/// declared. Their use requires including \<new\>.
2663void Sema::DeclareGlobalNewDelete() {
2664 if (GlobalNewDeleteDeclared)
2665 return;
2666
2667 // OpenCL C++ 1.0 s2.9: the implicitly declared new and delete operators
2668 // are not supported.
2669 if (getLangOpts().OpenCLCPlusPlus)
2670 return;
2671
2672 // C++ [basic.std.dynamic]p2:
2673 // [...] The following allocation and deallocation functions (18.4) are
2674 // implicitly declared in global scope in each translation unit of a
2675 // program
2676 //
2677 // C++03:
2678 // void* operator new(std::size_t) throw(std::bad_alloc);
2679 // void* operator new[](std::size_t) throw(std::bad_alloc);
2680 // void operator delete(void*) throw();
2681 // void operator delete[](void*) throw();
2682 // C++11:
2683 // void* operator new(std::size_t);
2684 // void* operator new[](std::size_t);
2685 // void operator delete(void*) noexcept;
2686 // void operator delete[](void*) noexcept;
2687 // C++1y:
2688 // void* operator new(std::size_t);
2689 // void* operator new[](std::size_t);
2690 // void operator delete(void*) noexcept;
2691 // void operator delete[](void*) noexcept;
2692 // void operator delete(void*, std::size_t) noexcept;
2693 // void operator delete[](void*, std::size_t) noexcept;
2694 //
2695 // These implicit declarations introduce only the function names operator
2696 // new, operator new[], operator delete, operator delete[].
2697 //
2698 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2699 // "std" or "bad_alloc" as necessary to form the exception specification.
2700 // However, we do not make these implicit declarations visible to name
2701 // lookup.
2702 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2703 // The "std::bad_alloc" class has not yet been declared, so build it
2704 // implicitly.
2705 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2706 getOrCreateStdNamespace(),
2707 SourceLocation(), SourceLocation(),
2708 &PP.getIdentifierTable().get("bad_alloc"),
2709 nullptr);
2710 getStdBadAlloc()->setImplicit(true);
2711 }
2712 if (!StdAlignValT && getLangOpts().AlignedAllocation) {
2713 // The "std::align_val_t" enum class has not yet been declared, so build it
2714 // implicitly.
2715 auto *AlignValT = EnumDecl::Create(
2716 Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(),
2717 &PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true);
2718 AlignValT->setIntegerType(Context.getSizeType());
2719 AlignValT->setPromotionType(Context.getSizeType());
2720 AlignValT->setImplicit(true);
2721 StdAlignValT = AlignValT;
2722 }
2723
2724 GlobalNewDeleteDeclared = true;
2725
2726 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2727 QualType SizeT = Context.getSizeType();
2728
2729 auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind,
2730 QualType Return, QualType Param) {
2731 llvm::SmallVector<QualType, 3> Params;
2732 Params.push_back(Param);
2733
2734 // Create up to four variants of the function (sized/aligned).
2735 bool HasSizedVariant = getLangOpts().SizedDeallocation &&
2736 (Kind == OO_Delete || Kind == OO_Array_Delete);
2737 bool HasAlignedVariant = getLangOpts().AlignedAllocation;
2738
2739 int NumSizeVariants = (HasSizedVariant ? 2 : 1);
2740 int NumAlignVariants = (HasAlignedVariant ? 2 : 1);
2741 for (int Sized = 0; Sized < NumSizeVariants; ++Sized) {
2742 if (Sized)
2743 Params.push_back(SizeT);
2744
2745 for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) {
2746 if (Aligned)
2747 Params.push_back(Context.getTypeDeclType(getStdAlignValT()));
2748
2749 DeclareGlobalAllocationFunction(
2750 Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params);
2751
2752 if (Aligned)
2753 Params.pop_back();
2754 }
2755 }
2756 };
2757
2758 DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT);
2759 DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT);
2760 DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr);
2761 DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr);
2762}
2763
2764/// DeclareGlobalAllocationFunction - Declares a single implicit global
2765/// allocation function if it doesn't already exist.
2766void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2767 QualType Return,
2768 ArrayRef<QualType> Params) {
2769 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2770
2771 // Check if this function is already declared.
2772 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2773 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2774 Alloc != AllocEnd; ++Alloc) {
2775 // Only look at non-template functions, as it is the predefined,
2776 // non-templated allocation function we are trying to declare here.
2777 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2778 if (Func->getNumParams() == Params.size()) {
2779 llvm::SmallVector<QualType, 3> FuncParams;
2780 for (auto *P : Func->parameters())
2781 FuncParams.push_back(
2782 Context.getCanonicalType(P->getType().getUnqualifiedType()));
2783 if (llvm::makeArrayRef(FuncParams) == Params) {
2784 // Make the function visible to name lookup, even if we found it in
2785 // an unimported module. It either is an implicitly-declared global
2786 // allocation function, or is suppressing that function.
2787 Func->setVisibleDespiteOwningModule();
2788 return;
2789 }
2790 }
2791 }
2792 }
2793
2794 FunctionProtoType::ExtProtoInfo EPI;
2795
2796 QualType BadAllocType;
2797 bool HasBadAllocExceptionSpec
2798 = (Name.getCXXOverloadedOperator() == OO_New ||
2799 Name.getCXXOverloadedOperator() == OO_Array_New);
2800 if (HasBadAllocExceptionSpec) {
2801 if (!getLangOpts().CPlusPlus11) {
2802 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2803 assert(StdBadAlloc && "Must have std::bad_alloc declared")((StdBadAlloc && "Must have std::bad_alloc declared")
? static_cast<void> (0) : __assert_fail ("StdBadAlloc && \"Must have std::bad_alloc declared\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2803, __PRETTY_FUNCTION__))
;
2804 EPI.ExceptionSpec.Type = EST_Dynamic;
2805 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2806 }
2807 } else {
2808 EPI.ExceptionSpec =
2809 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2810 }
2811
2812 auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) {
2813 QualType FnType = Context.getFunctionType(Return, Params, EPI);
2814 FunctionDecl *Alloc = FunctionDecl::Create(
2815 Context, GlobalCtx, SourceLocation(), SourceLocation(), Name,
2816 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2817 Alloc->setImplicit();
2818 // Global allocation functions should always be visible.
2819 Alloc->setVisibleDespiteOwningModule();
2820
2821 Alloc->addAttr(VisibilityAttr::CreateImplicit(
2822 Context, LangOpts.GlobalAllocationFunctionVisibilityHidden
2823 ? VisibilityAttr::Hidden
2824 : VisibilityAttr::Default));
2825
2826 llvm::SmallVector<ParmVarDecl *, 3> ParamDecls;
2827 for (QualType T : Params) {
2828 ParamDecls.push_back(ParmVarDecl::Create(
2829 Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T,
2830 /*TInfo=*/nullptr, SC_None, nullptr));
2831 ParamDecls.back()->setImplicit();
2832 }
2833 Alloc->setParams(ParamDecls);
2834 if (ExtraAttr)
2835 Alloc->addAttr(ExtraAttr);
2836 Context.getTranslationUnitDecl()->addDecl(Alloc);
2837 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2838 };
2839
2840 if (!LangOpts.CUDA)
2841 CreateAllocationFunctionDecl(nullptr);
2842 else {
2843 // Host and device get their own declaration so each can be
2844 // defined or re-declared independently.
2845 CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context));
2846 CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context));
2847 }
2848}
2849
2850FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2851 bool CanProvideSize,
2852 bool Overaligned,
2853 DeclarationName Name) {
2854 DeclareGlobalNewDelete();
2855
2856 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2857 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2858
2859 // FIXME: It's possible for this to result in ambiguity, through a
2860 // user-declared variadic operator delete or the enable_if attribute. We
2861 // should probably not consider those cases to be usual deallocation
2862 // functions. But for now we just make an arbitrary choice in that case.
2863 auto Result = resolveDeallocationOverload(*this, FoundDelete, CanProvideSize,
2864 Overaligned);
2865 assert(Result.FD && "operator delete missing from global scope?")((Result.FD && "operator delete missing from global scope?"
) ? static_cast<void> (0) : __assert_fail ("Result.FD && \"operator delete missing from global scope?\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 2865, __PRETTY_FUNCTION__))
;
2866 return Result.FD;
2867}
2868
2869FunctionDecl *Sema::FindDeallocationFunctionForDestructor(SourceLocation Loc,
2870 CXXRecordDecl *RD) {
2871 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2872
2873 FunctionDecl *OperatorDelete = nullptr;
2874 if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete))
2875 return nullptr;
2876 if (OperatorDelete)
2877 return OperatorDelete;
2878
2879 // If there's no class-specific operator delete, look up the global
2880 // non-array delete.
2881 return FindUsualDeallocationFunction(
2882 Loc, true, hasNewExtendedAlignment(*this, Context.getRecordType(RD)),
2883 Name);
2884}
2885
2886bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2887 DeclarationName Name,
2888 FunctionDecl *&Operator, bool Diagnose) {
2889 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2890 // Try to find operator delete/operator delete[] in class scope.
2891 LookupQualifiedName(Found, RD);
2892
2893 if (Found.isAmbiguous())
2894 return true;
2895
2896 Found.suppressDiagnostics();
2897
2898 bool Overaligned = hasNewExtendedAlignment(*this, Context.getRecordType(RD));
2899
2900 // C++17 [expr.delete]p10:
2901 // If the deallocation functions have class scope, the one without a
2902 // parameter of type std::size_t is selected.
2903 llvm::SmallVector<UsualDeallocFnInfo, 4> Matches;
2904 resolveDeallocationOverload(*this, Found, /*WantSize*/ false,
2905 /*WantAlign*/ Overaligned, &Matches);
2906
2907 // If we could find an overload, use it.
2908 if (Matches.size() == 1) {
2909 Operator = cast<CXXMethodDecl>(Matches[0].FD);
2910
2911 // FIXME: DiagnoseUseOfDecl?
2912 if (Operator->isDeleted()) {
2913 if (Diagnose) {
2914 Diag(StartLoc, diag::err_deleted_function_use);
2915 NoteDeletedFunction(Operator);
2916 }
2917 return true;
2918 }
2919
2920 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2921 Matches[0].Found, Diagnose) == AR_inaccessible)
2922 return true;
2923
2924 return false;
2925 }
2926
2927 // We found multiple suitable operators; complain about the ambiguity.
2928 // FIXME: The standard doesn't say to do this; it appears that the intent
2929 // is that this should never happen.
2930 if (!Matches.empty()) {
2931 if (Diagnose) {
2932 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2933 << Name << RD;
2934 for (auto &Match : Matches)
2935 Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name;
2936 }
2937 return true;
2938 }
2939
2940 // We did find operator delete/operator delete[] declarations, but
2941 // none of them were suitable.
2942 if (!Found.empty()) {
2943 if (Diagnose) {
2944 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2945 << Name << RD;
2946
2947 for (NamedDecl *D : Found)
2948 Diag(D->getUnderlyingDecl()->getLocation(),
2949 diag::note_member_declared_here) << Name;
2950 }
2951 return true;
2952 }
2953
2954 Operator = nullptr;
2955 return false;
2956}
2957
2958namespace {
2959/// Checks whether delete-expression, and new-expression used for
2960/// initializing deletee have the same array form.
2961class MismatchingNewDeleteDetector {
2962public:
2963 enum MismatchResult {
2964 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2965 NoMismatch,
2966 /// Indicates that variable is initialized with mismatching form of \a new.
2967 VarInitMismatches,
2968 /// Indicates that member is initialized with mismatching form of \a new.
2969 MemberInitMismatches,
2970 /// Indicates that 1 or more constructors' definitions could not been
2971 /// analyzed, and they will be checked again at the end of translation unit.
2972 AnalyzeLater
2973 };
2974
2975 /// \param EndOfTU True, if this is the final analysis at the end of
2976 /// translation unit. False, if this is the initial analysis at the point
2977 /// delete-expression was encountered.
2978 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2979 : Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU),
2980 HasUndefinedConstructors(false) {}
2981
2982 /// Checks whether pointee of a delete-expression is initialized with
2983 /// matching form of new-expression.
2984 ///
2985 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2986 /// point where delete-expression is encountered, then a warning will be
2987 /// issued immediately. If return value is \c AnalyzeLater at the point where
2988 /// delete-expression is seen, then member will be analyzed at the end of
2989 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2990 /// couldn't be analyzed. If at least one constructor initializes the member
2991 /// with matching type of new, the return value is \c NoMismatch.
2992 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2993 /// Analyzes a class member.
2994 /// \param Field Class member to analyze.
2995 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2996 /// for deleting the \p Field.
2997 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2998 FieldDecl *Field;
2999 /// List of mismatching new-expressions used for initialization of the pointee
3000 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
3001 /// Indicates whether delete-expression was in array form.
3002 bool IsArrayForm;
3003
3004private:
3005 const bool EndOfTU;
3006 /// Indicates that there is at least one constructor without body.
3007 bool HasUndefinedConstructors;
3008 /// Returns \c CXXNewExpr from given initialization expression.
3009 /// \param E Expression used for initializing pointee in delete-expression.
3010 /// E can be a single-element \c InitListExpr consisting of new-expression.
3011 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
3012 /// Returns whether member is initialized with mismatching form of
3013 /// \c new either by the member initializer or in-class initialization.
3014 ///
3015 /// If bodies of all constructors are not visible at the end of translation
3016 /// unit or at least one constructor initializes member with the matching
3017 /// form of \c new, mismatch cannot be proven, and this function will return
3018 /// \c NoMismatch.
3019 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
3020 /// Returns whether variable is initialized with mismatching form of
3021 /// \c new.
3022 ///
3023 /// If variable is initialized with matching form of \c new or variable is not
3024 /// initialized with a \c new expression, this function will return true.
3025 /// If variable is initialized with mismatching form of \c new, returns false.
3026 /// \param D Variable to analyze.
3027 bool hasMatchingVarInit(const DeclRefExpr *D);
3028 /// Checks whether the constructor initializes pointee with mismatching
3029 /// form of \c new.
3030 ///
3031 /// Returns true, if member is initialized with matching form of \c new in
3032 /// member initializer list. Returns false, if member is initialized with the
3033 /// matching form of \c new in this constructor's initializer or given
3034 /// constructor isn't defined at the point where delete-expression is seen, or
3035 /// member isn't initialized by the constructor.
3036 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
3037 /// Checks whether member is initialized with matching form of
3038 /// \c new in member initializer list.
3039 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
3040 /// Checks whether member is initialized with mismatching form of \c new by
3041 /// in-class initializer.
3042 MismatchResult analyzeInClassInitializer();
3043};
3044}
3045
3046MismatchingNewDeleteDetector::MismatchResult
3047MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
3048 NewExprs.clear();
3049 assert(DE && "Expected delete-expression")((DE && "Expected delete-expression") ? static_cast<
void> (0) : __assert_fail ("DE && \"Expected delete-expression\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3049, __PRETTY_FUNCTION__))
;
3050 IsArrayForm = DE->isArrayForm();
3051 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
3052 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
3053 return analyzeMemberExpr(ME);
3054 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
3055 if (!hasMatchingVarInit(D))
3056 return VarInitMismatches;
3057 }
3058 return NoMismatch;
3059}
3060
3061const CXXNewExpr *
3062MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
3063 assert(E != nullptr && "Expected a valid initializer expression")((E != nullptr && "Expected a valid initializer expression"
) ? static_cast<void> (0) : __assert_fail ("E != nullptr && \"Expected a valid initializer expression\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3063, __PRETTY_FUNCTION__))
;
3064 E = E->IgnoreParenImpCasts();
3065 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
3066 if (ILE->getNumInits() == 1)
3067 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
3068 }
3069
3070 return dyn_cast_or_null<const CXXNewExpr>(E);
3071}
3072
3073bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
3074 const CXXCtorInitializer *CI) {
3075 const CXXNewExpr *NE = nullptr;
3076 if (Field == CI->getMember() &&
3077 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
3078 if (NE->isArray() == IsArrayForm)
3079 return true;
3080 else
3081 NewExprs.push_back(NE);
3082 }
3083 return false;
3084}
3085
3086bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
3087 const CXXConstructorDecl *CD) {
3088 if (CD->isImplicit())
3089 return false;
3090 const FunctionDecl *Definition = CD;
3091 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
3092 HasUndefinedConstructors = true;
3093 return EndOfTU;
3094 }
3095 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
3096 if (hasMatchingNewInCtorInit(CI))
3097 return true;
3098 }
3099 return false;
3100}
3101
3102MismatchingNewDeleteDetector::MismatchResult
3103MismatchingNewDeleteDetector::analyzeInClassInitializer() {
3104 assert(Field != nullptr && "This should be called only for members")((Field != nullptr && "This should be called only for members"
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"This should be called only for members\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3104, __PRETTY_FUNCTION__))
;
3105 const Expr *InitExpr = Field->getInClassInitializer();
3106 if (!InitExpr)
3107 return EndOfTU ? NoMismatch : AnalyzeLater;
3108 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
3109 if (NE->isArray() != IsArrayForm) {
3110 NewExprs.push_back(NE);
3111 return MemberInitMismatches;
3112 }
3113 }
3114 return NoMismatch;
3115}
3116
3117MismatchingNewDeleteDetector::MismatchResult
3118MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
3119 bool DeleteWasArrayForm) {
3120 assert(Field != nullptr && "Analysis requires a valid class member.")((Field != nullptr && "Analysis requires a valid class member."
) ? static_cast<void> (0) : __assert_fail ("Field != nullptr && \"Analysis requires a valid class member.\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3120, __PRETTY_FUNCTION__))
;
3121 this->Field = Field;
3122 IsArrayForm = DeleteWasArrayForm;
3123 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
3124 for (const auto *CD : RD->ctors()) {
3125 if (hasMatchingNewInCtor(CD))
3126 return NoMismatch;
3127 }
3128 if (HasUndefinedConstructors)
3129 return EndOfTU ? NoMismatch : AnalyzeLater;
3130 if (!NewExprs.empty())
3131 return MemberInitMismatches;
3132 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
3133 : NoMismatch;
3134}
3135
3136MismatchingNewDeleteDetector::MismatchResult
3137MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
3138 assert(ME != nullptr && "Expected a member expression")((ME != nullptr && "Expected a member expression") ? static_cast
<void> (0) : __assert_fail ("ME != nullptr && \"Expected a member expression\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3138, __PRETTY_FUNCTION__))
;
3139 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3140 return analyzeField(F, IsArrayForm);
3141 return NoMismatch;
3142}
3143
3144bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
3145 const CXXNewExpr *NE = nullptr;
3146 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
3147 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
3148 NE->isArray() != IsArrayForm) {
3149 NewExprs.push_back(NE);
3150 }
3151 }
3152 return NewExprs.empty();
3153}
3154
3155static void
3156DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
3157 const MismatchingNewDeleteDetector &Detector) {
3158 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
3159 FixItHint H;
3160 if (!Detector.IsArrayForm)
3161 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
3162 else {
3163 SourceLocation RSquare = Lexer::findLocationAfterToken(
3164 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
3165 SemaRef.getLangOpts(), true);
3166 if (RSquare.isValid())
3167 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
3168 }
3169 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
3170 << Detector.IsArrayForm << H;
3171
3172 for (const auto *NE : Detector.NewExprs)
3173 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
3174 << Detector.IsArrayForm;
3175}
3176
3177void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
3178 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
3179 return;
3180 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
3181 switch (Detector.analyzeDeleteExpr(DE)) {
3182 case MismatchingNewDeleteDetector::VarInitMismatches:
3183 case MismatchingNewDeleteDetector::MemberInitMismatches: {
3184 DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector);
3185 break;
3186 }
3187 case MismatchingNewDeleteDetector::AnalyzeLater: {
3188 DeleteExprs[Detector.Field].push_back(
3189 std::make_pair(DE->getBeginLoc(), DE->isArrayForm()));
3190 break;
3191 }
3192 case MismatchingNewDeleteDetector::NoMismatch:
3193 break;
3194 }
3195}
3196
3197void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
3198 bool DeleteWasArrayForm) {
3199 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
3200 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
3201 case MismatchingNewDeleteDetector::VarInitMismatches:
3202 llvm_unreachable("This analysis should have been done for class members.")::llvm::llvm_unreachable_internal("This analysis should have been done for class members."
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3202)
;
3203 case MismatchingNewDeleteDetector::AnalyzeLater:
3204 llvm_unreachable("Analysis cannot be postponed any point beyond end of "::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3205)
3205 "translation unit.")::llvm::llvm_unreachable_internal("Analysis cannot be postponed any point beyond end of "
"translation unit.", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3205)
;
3206 case MismatchingNewDeleteDetector::MemberInitMismatches:
3207 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
3208 break;
3209 case MismatchingNewDeleteDetector::NoMismatch:
3210 break;
3211 }
3212}
3213
3214/// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
3215/// @code ::delete ptr; @endcode
3216/// or
3217/// @code delete [] ptr; @endcode
3218ExprResult
3219Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
3220 bool ArrayForm, Expr *ExE) {
3221 // C++ [expr.delete]p1:
3222 // The operand shall have a pointer type, or a class type having a single
3223 // non-explicit conversion function to a pointer type. The result has type
3224 // void.
3225 //
3226 // DR599 amends "pointer type" to "pointer to object type" in both cases.
3227
3228 ExprResult Ex = ExE;
3229 FunctionDecl *OperatorDelete = nullptr;
3230 bool ArrayFormAsWritten = ArrayForm;
3231 bool UsualArrayDeleteWantsSize = false;
3232
3233 if (!Ex.get()->isTypeDependent()) {
3234 // Perform lvalue-to-rvalue cast, if needed.
3235 Ex = DefaultLvalueConversion(Ex.get());
3236 if (Ex.isInvalid())
3237 return ExprError();
3238
3239 QualType Type = Ex.get()->getType();
3240
3241 class DeleteConverter : public ContextualImplicitConverter {
3242 public:
3243 DeleteConverter() : ContextualImplicitConverter(false, true) {}
3244
3245 bool match(QualType ConvType) override {
3246 // FIXME: If we have an operator T* and an operator void*, we must pick
3247 // the operator T*.
3248 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
3249 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
3250 return true;
3251 return false;
3252 }
3253
3254 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
3255 QualType T) override {
3256 return S.Diag(Loc, diag::err_delete_operand) << T;
3257 }
3258
3259 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
3260 QualType T) override {
3261 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
3262 }
3263
3264 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
3265 QualType T,
3266 QualType ConvTy) override {
3267 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
3268 }
3269
3270 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
3271 QualType ConvTy) override {
3272 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3273 << ConvTy;
3274 }
3275
3276 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
3277 QualType T) override {
3278 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
3279 }
3280
3281 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
3282 QualType ConvTy) override {
3283 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
3284 << ConvTy;
3285 }
3286
3287 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
3288 QualType T,
3289 QualType ConvTy) override {
3290 llvm_unreachable("conversion functions are permitted")::llvm::llvm_unreachable_internal("conversion functions are permitted"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3290)
;
3291 }
3292 } Converter;
3293
3294 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
3295 if (Ex.isInvalid())
3296 return ExprError();
3297 Type = Ex.get()->getType();
3298 if (!Converter.match(Type))
3299 // FIXME: PerformContextualImplicitConversion should return ExprError
3300 // itself in this case.
3301 return ExprError();
3302
3303 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
3304 QualType PointeeElem = Context.getBaseElementType(Pointee);
3305
3306 if (Pointee.getAddressSpace() != LangAS::Default &&
3307 !getLangOpts().OpenCLCPlusPlus)
3308 return Diag(Ex.get()->getBeginLoc(),
3309 diag::err_address_space_qualified_delete)
3310 << Pointee.getUnqualifiedType()
3311 << Pointee.getQualifiers().getAddressSpaceAttributePrintValue();
3312
3313 CXXRecordDecl *PointeeRD = nullptr;
3314 if (Pointee->isVoidType() && !isSFINAEContext()) {
3315 // The C++ standard bans deleting a pointer to a non-object type, which
3316 // effectively bans deletion of "void*". However, most compilers support
3317 // this, so we treat it as a warning unless we're in a SFINAE context.
3318 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
3319 << Type << Ex.get()->getSourceRange();
3320 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
3321 return ExprError(Diag(StartLoc, diag::err_delete_operand)
3322 << Type << Ex.get()->getSourceRange());
3323 } else if (!Pointee->isDependentType()) {
3324 // FIXME: This can result in errors if the definition was imported from a
3325 // module but is hidden.
3326 if (!RequireCompleteType(StartLoc, Pointee,
3327 diag::warn_delete_incomplete, Ex.get())) {
3328 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
3329 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
3330 }
3331 }
3332
3333 if (Pointee->isArrayType() && !ArrayForm) {
3334 Diag(StartLoc, diag::warn_delete_array_type)
3335 << Type << Ex.get()->getSourceRange()
3336 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
3337 ArrayForm = true;
3338 }
3339
3340 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
3341 ArrayForm ? OO_Array_Delete : OO_Delete);
3342
3343 if (PointeeRD) {
3344 if (!UseGlobal &&
3345 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
3346 OperatorDelete))
3347 return ExprError();
3348
3349 // If we're allocating an array of records, check whether the
3350 // usual operator delete[] has a size_t parameter.
3351 if (ArrayForm) {
3352 // If the user specifically asked to use the global allocator,
3353 // we'll need to do the lookup into the class.
3354 if (UseGlobal)
3355 UsualArrayDeleteWantsSize =
3356 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
3357
3358 // Otherwise, the usual operator delete[] should be the
3359 // function we just found.
3360 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
3361 UsualArrayDeleteWantsSize =
3362 UsualDeallocFnInfo(*this,
3363 DeclAccessPair::make(OperatorDelete, AS_public))
3364 .HasSizeT;
3365 }
3366
3367 if (!PointeeRD->hasIrrelevantDestructor())
3368 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3369 MarkFunctionReferenced(StartLoc,
3370 const_cast<CXXDestructorDecl*>(Dtor));
3371 if (DiagnoseUseOfDecl(Dtor, StartLoc))
3372 return ExprError();
3373 }
3374
3375 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
3376 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
3377 /*WarnOnNonAbstractTypes=*/!ArrayForm,
3378 SourceLocation());
3379 }
3380
3381 if (!OperatorDelete) {
3382 if (getLangOpts().OpenCLCPlusPlus) {
3383 Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete";
3384 return ExprError();
3385 }
3386
3387 bool IsComplete = isCompleteType(StartLoc, Pointee);
3388 bool CanProvideSize =
3389 IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize ||
3390 Pointee.isDestructedType());
3391 bool Overaligned = hasNewExtendedAlignment(*this, Pointee);
3392
3393 // Look for a global declaration.
3394 OperatorDelete = FindUsualDeallocationFunction(StartLoc, CanProvideSize,
3395 Overaligned, DeleteName);
3396 }
3397
3398 MarkFunctionReferenced(StartLoc, OperatorDelete);
3399
3400 // Check access and ambiguity of destructor if we're going to call it.
3401 // Note that this is required even for a virtual delete.
3402 bool IsVirtualDelete = false;
3403 if (PointeeRD) {
3404 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3405 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3406 PDiag(diag::err_access_dtor) << PointeeElem);
3407 IsVirtualDelete = Dtor->isVirtual();
3408 }
3409 }
3410
3411 DiagnoseUseOfDecl(OperatorDelete, StartLoc);
3412
3413 // Convert the operand to the type of the first parameter of operator
3414 // delete. This is only necessary if we selected a destroying operator
3415 // delete that we are going to call (non-virtually); converting to void*
3416 // is trivial and left to AST consumers to handle.
3417 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
3418 if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) {
3419 Qualifiers Qs = Pointee.getQualifiers();
3420 if (Qs.hasCVRQualifiers()) {
3421 // Qualifiers are irrelevant to this conversion; we're only looking
3422 // for access and ambiguity.
3423 Qs.removeCVRQualifiers();
3424 QualType Unqual = Context.getPointerType(
3425 Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs));
3426 Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp);
3427 }
3428 Ex = PerformImplicitConversion(Ex.get(), ParamType, AA_Passing);
3429 if (Ex.isInvalid())
3430 return ExprError();
3431 }
3432 }
3433
3434 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3435 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3436 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3437 AnalyzeDeleteExprMismatch(Result);
3438 return Result;
3439}
3440
3441static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall,
3442 bool IsDelete,
3443 FunctionDecl *&Operator) {
3444
3445 DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName(
3446 IsDelete ? OO_Delete : OO_New);
3447
3448 LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName);
3449 S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl());
3450 assert(!R.empty() && "implicitly declared allocation functions not found")((!R.empty() && "implicitly declared allocation functions not found"
) ? static_cast<void> (0) : __assert_fail ("!R.empty() && \"implicitly declared allocation functions not found\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3450, __PRETTY_FUNCTION__))
;
3451 assert(!R.isAmbiguous() && "global allocation functions are ambiguous")((!R.isAmbiguous() && "global allocation functions are ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!R.isAmbiguous() && \"global allocation functions are ambiguous\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3451, __PRETTY_FUNCTION__))
;
3452
3453 // We do our own custom access checks below.
3454 R.suppressDiagnostics();
3455
3456 SmallVector<Expr *, 8> Args(TheCall->arg_begin(), TheCall->arg_end());
3457 OverloadCandidateSet Candidates(R.getNameLoc(),
3458 OverloadCandidateSet::CSK_Normal);
3459 for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end();
3460 FnOvl != FnOvlEnd; ++FnOvl) {
3461 // Even member operator new/delete are implicitly treated as
3462 // static, so don't use AddMemberCandidate.
3463 NamedDecl *D = (*FnOvl)->getUnderlyingDecl();
3464
3465 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
3466 S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(),
3467 /*ExplicitTemplateArgs=*/nullptr, Args,
3468 Candidates,
3469 /*SuppressUserConversions=*/false);
3470 continue;
3471 }
3472
3473 FunctionDecl *Fn = cast<FunctionDecl>(D);
3474 S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates,
3475 /*SuppressUserConversions=*/false);
3476 }
3477
3478 SourceRange Range = TheCall->getSourceRange();
3479
3480 // Do the resolution.
3481 OverloadCandidateSet::iterator Best;
3482 switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) {
3483 case OR_Success: {
3484 // Got one!
3485 FunctionDecl *FnDecl = Best->Function;
3486 assert(R.getNamingClass() == nullptr &&((R.getNamingClass() == nullptr && "class members should not be considered"
) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3487, __PRETTY_FUNCTION__))
3487 "class members should not be considered")((R.getNamingClass() == nullptr && "class members should not be considered"
) ? static_cast<void> (0) : __assert_fail ("R.getNamingClass() == nullptr && \"class members should not be considered\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3487, __PRETTY_FUNCTION__))
;
3488
3489 if (!FnDecl->isReplaceableGlobalAllocationFunction()) {
3490 S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual)
3491 << (IsDelete ? 1 : 0) << Range;
3492 S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here)
3493 << R.getLookupName() << FnDecl->getSourceRange();
3494 return true;
3495 }
3496
3497 Operator = FnDecl;
3498 return false;
3499 }
3500
3501 case OR_No_Viable_Function:
3502 S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call)
3503 << R.getLookupName() << Range;
3504 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3505 return true;
3506
3507 case OR_Ambiguous:
3508 S.Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call)
3509 << R.getLookupName() << Range;
3510 Candidates.NoteCandidates(S, OCD_ViableCandidates, Args);
3511 return true;
3512
3513 case OR_Deleted: {
3514 S.Diag(R.getNameLoc(), diag::err_ovl_deleted_call)
3515 << Best->Function->isDeleted() << R.getLookupName()
3516 << S.getDeletedOrUnavailableSuffix(Best->Function) << Range;
3517 Candidates.NoteCandidates(S, OCD_AllCandidates, Args);
3518 return true;
3519 }
3520 }
3521 llvm_unreachable("Unreachable, bad result from BestViableFunction")::llvm::llvm_unreachable_internal("Unreachable, bad result from BestViableFunction"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3521)
;
3522}
3523
3524ExprResult
3525Sema::SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult,
3526 bool IsDelete) {
3527 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
3528 if (!getLangOpts().CPlusPlus) {
3529 Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language)
3530 << (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new")
3531 << "C++";
3532 return ExprError();
3533 }
3534 // CodeGen assumes it can find the global new and delete to call,
3535 // so ensure that they are declared.
3536 DeclareGlobalNewDelete();
3537
3538 FunctionDecl *OperatorNewOrDelete = nullptr;
3539 if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete,
3540 OperatorNewOrDelete))
3541 return ExprError();
3542 assert(OperatorNewOrDelete && "should be found")((OperatorNewOrDelete && "should be found") ? static_cast
<void> (0) : __assert_fail ("OperatorNewOrDelete && \"should be found\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3542, __PRETTY_FUNCTION__))
;
3543
3544 DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc());
3545 MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete);
3546
3547 TheCall->setType(OperatorNewOrDelete->getReturnType());
3548 for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) {
3549 QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType();
3550 InitializedEntity Entity =
3551 InitializedEntity::InitializeParameter(Context, ParamTy, false);
3552 ExprResult Arg = PerformCopyInitialization(
3553 Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i));
3554 if (Arg.isInvalid())
3555 return ExprError();
3556 TheCall->setArg(i, Arg.get());
3557 }
3558 auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee());
3559 assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr &&((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr
&& "Callee expected to be implicit cast to a builtin function pointer"
) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3560, __PRETTY_FUNCTION__))
3560 "Callee expected to be implicit cast to a builtin function pointer")((Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr
&& "Callee expected to be implicit cast to a builtin function pointer"
) ? static_cast<void> (0) : __assert_fail ("Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && \"Callee expected to be implicit cast to a builtin function pointer\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3560, __PRETTY_FUNCTION__))
;
3561 Callee->setType(OperatorNewOrDelete->getType());
3562
3563 return TheCallResult;
3564}
3565
3566void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3567 bool IsDelete, bool CallCanBeVirtual,
3568 bool WarnOnNonAbstractTypes,
3569 SourceLocation DtorLoc) {
3570 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext())
3571 return;
3572
3573 // C++ [expr.delete]p3:
3574 // In the first alternative (delete object), if the static type of the
3575 // object to be deleted is different from its dynamic type, the static
3576 // type shall be a base class of the dynamic type of the object to be
3577 // deleted and the static type shall have a virtual destructor or the
3578 // behavior is undefined.
3579 //
3580 const CXXRecordDecl *PointeeRD = dtor->getParent();
3581 // Note: a final class cannot be derived from, no issue there
3582 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3583 return;
3584
3585 // If the superclass is in a system header, there's nothing that can be done.
3586 // The `delete` (where we emit the warning) can be in a system header,
3587 // what matters for this warning is where the deleted type is defined.
3588 if (getSourceManager().isInSystemHeader(PointeeRD->getLocation()))
3589 return;
3590
3591 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3592 if (PointeeRD->isAbstract()) {
3593 // If the class is abstract, we warn by default, because we're
3594 // sure the code has undefined behavior.
3595 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3596 << ClassType;
3597 } else if (WarnOnNonAbstractTypes) {
3598 // Otherwise, if this is not an array delete, it's a bit suspect,
3599 // but not necessarily wrong.
3600 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3601 << ClassType;
3602 }
3603 if (!IsDelete) {
3604 std::string TypeStr;
3605 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3606 Diag(DtorLoc, diag::note_delete_non_virtual)
3607 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3608 }
3609}
3610
3611Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3612 SourceLocation StmtLoc,
3613 ConditionKind CK) {
3614 ExprResult E =
3615 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3616 if (E.isInvalid())
3617 return ConditionError();
3618 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3619 CK == ConditionKind::ConstexprIf);
3620}
3621
3622/// Check the use of the given variable as a C++ condition in an if,
3623/// while, do-while, or switch statement.
3624ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3625 SourceLocation StmtLoc,
3626 ConditionKind CK) {
3627 if (ConditionVar->isInvalidDecl())
3628 return ExprError();
3629
3630 QualType T = ConditionVar->getType();
3631
3632 // C++ [stmt.select]p2:
3633 // The declarator shall not specify a function or an array.
3634 if (T->isFunctionType())
3635 return ExprError(Diag(ConditionVar->getLocation(),
3636 diag::err_invalid_use_of_function_type)
3637 << ConditionVar->getSourceRange());
3638 else if (T->isArrayType())
3639 return ExprError(Diag(ConditionVar->getLocation(),
3640 diag::err_invalid_use_of_array_type)
3641 << ConditionVar->getSourceRange());
3642
3643 ExprResult Condition = DeclRefExpr::Create(
3644 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3645 /*enclosing*/ false, ConditionVar->getLocation(),
3646 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3647
3648 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3649
3650 switch (CK) {
3651 case ConditionKind::Boolean:
3652 return CheckBooleanCondition(StmtLoc, Condition.get());
3653
3654 case ConditionKind::ConstexprIf:
3655 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3656
3657 case ConditionKind::Switch:
3658 return CheckSwitchCondition(StmtLoc, Condition.get());
3659 }
3660
3661 llvm_unreachable("unexpected condition kind")::llvm::llvm_unreachable_internal("unexpected condition kind"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3661)
;
3662}
3663
3664/// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
3665ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3666 // C++ 6.4p4:
3667 // The value of a condition that is an initialized declaration in a statement
3668 // other than a switch statement is the value of the declared variable
3669 // implicitly converted to type bool. If that conversion is ill-formed, the
3670 // program is ill-formed.
3671 // The value of a condition that is an expression is the value of the
3672 // expression, implicitly converted to bool.
3673 //
3674 // FIXME: Return this value to the caller so they don't need to recompute it.
3675 llvm::APSInt Value(/*BitWidth*/1);
3676 return (IsConstexpr && !CondExpr->isValueDependent())
3677 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3678 CCEK_ConstexprIf)
3679 : PerformContextuallyConvertToBool(CondExpr);
3680}
3681
3682/// Helper function to determine whether this is the (deprecated) C++
3683/// conversion from a string literal to a pointer to non-const char or
3684/// non-const wchar_t (for narrow and wide string literals,
3685/// respectively).
3686bool
3687Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3688 // Look inside the implicit cast, if it exists.
3689 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3690 From = Cast->getSubExpr();
3691
3692 // A string literal (2.13.4) that is not a wide string literal can
3693 // be converted to an rvalue of type "pointer to char"; a wide
3694 // string literal can be converted to an rvalue of type "pointer
3695 // to wchar_t" (C++ 4.2p2).
3696 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3697 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3698 if (const BuiltinType *ToPointeeType
3699 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3700 // This conversion is considered only when there is an
3701 // explicit appropriate pointer target type (C++ 4.2p2).
3702 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3703 switch (StrLit->getKind()) {
3704 case StringLiteral::UTF8:
3705 case StringLiteral::UTF16:
3706 case StringLiteral::UTF32:
3707 // We don't allow UTF literals to be implicitly converted
3708 break;
3709 case StringLiteral::Ascii:
3710 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3711 ToPointeeType->getKind() == BuiltinType::Char_S);
3712 case StringLiteral::Wide:
3713 return Context.typesAreCompatible(Context.getWideCharType(),
3714 QualType(ToPointeeType, 0));
3715 }
3716 }
3717 }
3718
3719 return false;
3720}
3721
3722static ExprResult BuildCXXCastArgument(Sema &S,
3723 SourceLocation CastLoc,
3724 QualType Ty,
3725 CastKind Kind,
3726 CXXMethodDecl *Method,
3727 DeclAccessPair FoundDecl,
3728 bool HadMultipleCandidates,
3729 Expr *From) {
3730 switch (Kind) {
3731 default: llvm_unreachable("Unhandled cast kind!")::llvm::llvm_unreachable_internal("Unhandled cast kind!", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3731)
;
3732 case CK_ConstructorConversion: {
3733 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3734 SmallVector<Expr*, 8> ConstructorArgs;
3735
3736 if (S.RequireNonAbstractType(CastLoc, Ty,
3737 diag::err_allocation_of_abstract_type))
3738 return ExprError();
3739
3740 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3741 return ExprError();
3742
3743 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3744 InitializedEntity::InitializeTemporary(Ty));
3745 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3746 return ExprError();
3747
3748 ExprResult Result = S.BuildCXXConstructExpr(
3749 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3750 ConstructorArgs, HadMultipleCandidates,
3751 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3752 CXXConstructExpr::CK_Complete, SourceRange());
3753 if (Result.isInvalid())
3754 return ExprError();
3755
3756 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3757 }
3758
3759 case CK_UserDefinedConversion: {
3760 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!")((!From->getType()->isPointerType() && "Arg can't have pointer type!"
) ? static_cast<void> (0) : __assert_fail ("!From->getType()->isPointerType() && \"Arg can't have pointer type!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3760, __PRETTY_FUNCTION__))
;
3761
3762 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3763 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3764 return ExprError();
3765
3766 // Create an implicit call expr that calls it.
3767 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3768 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3769 HadMultipleCandidates);
3770 if (Result.isInvalid())
3771 return ExprError();
3772 // Record usage of conversion in an implicit cast.
3773 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3774 CK_UserDefinedConversion, Result.get(),
3775 nullptr, Result.get()->getValueKind());
3776
3777 return S.MaybeBindToTemporary(Result.get());
3778 }
3779 }
3780}
3781
3782/// PerformImplicitConversion - Perform an implicit conversion of the
3783/// expression From to the type ToType using the pre-computed implicit
3784/// conversion sequence ICS. Returns the converted
3785/// expression. Action is the kind of conversion we're performing,
3786/// used in the error message.
3787ExprResult
3788Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3789 const ImplicitConversionSequence &ICS,
3790 AssignmentAction Action,
3791 CheckedConversionKind CCK) {
3792 // C++ [over.match.oper]p7: [...] operands of class type are converted [...]
3793 if (CCK == CCK_ForBuiltinOverloadedOp && !From->getType()->isRecordType())
3794 return From;
3795
3796 switch (ICS.getKind()) {
3797 case ImplicitConversionSequence::StandardConversion: {
3798 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3799 Action, CCK);
3800 if (Res.isInvalid())
3801 return ExprError();
3802 From = Res.get();
3803 break;
3804 }
3805
3806 case ImplicitConversionSequence::UserDefinedConversion: {
3807
3808 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3809 CastKind CastKind;
3810 QualType BeforeToType;
3811 assert(FD && "no conversion function for user-defined conversion seq")((FD && "no conversion function for user-defined conversion seq"
) ? static_cast<void> (0) : __assert_fail ("FD && \"no conversion function for user-defined conversion seq\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3811, __PRETTY_FUNCTION__))
;
3812 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3813 CastKind = CK_UserDefinedConversion;
3814
3815 // If the user-defined conversion is specified by a conversion function,
3816 // the initial standard conversion sequence converts the source type to
3817 // the implicit object parameter of the conversion function.
3818 BeforeToType = Context.getTagDeclType(Conv->getParent());
3819 } else {
3820 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3821 CastKind = CK_ConstructorConversion;
3822 // Do no conversion if dealing with ... for the first conversion.
3823 if (!ICS.UserDefined.EllipsisConversion) {
3824 // If the user-defined conversion is specified by a constructor, the
3825 // initial standard conversion sequence converts the source type to
3826 // the type required by the argument of the constructor
3827 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3828 }
3829 }
3830 // Watch out for ellipsis conversion.
3831 if (!ICS.UserDefined.EllipsisConversion) {
3832 ExprResult Res =
3833 PerformImplicitConversion(From, BeforeToType,
3834 ICS.UserDefined.Before, AA_Converting,
3835 CCK);
3836 if (Res.isInvalid())
3837 return ExprError();
3838 From = Res.get();
3839 }
3840
3841 ExprResult CastArg = BuildCXXCastArgument(
3842 *this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind,
3843 cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction,
3844 ICS.UserDefined.HadMultipleCandidates, From);
3845
3846 if (CastArg.isInvalid())
3847 return ExprError();
3848
3849 From = CastArg.get();
3850
3851 // C++ [over.match.oper]p7:
3852 // [...] the second standard conversion sequence of a user-defined
3853 // conversion sequence is not applied.
3854 if (CCK == CCK_ForBuiltinOverloadedOp)
3855 return From;
3856
3857 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3858 AA_Converting, CCK);
3859 }
3860
3861 case ImplicitConversionSequence::AmbiguousConversion:
3862 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3863 PDiag(diag::err_typecheck_ambiguous_condition)
3864 << From->getSourceRange());
3865 return ExprError();
3866
3867 case ImplicitConversionSequence::EllipsisConversion:
3868 llvm_unreachable("Cannot perform an ellipsis conversion")::llvm::llvm_unreachable_internal("Cannot perform an ellipsis conversion"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3868)
;
3869
3870 case ImplicitConversionSequence::BadConversion:
3871 bool Diagnosed =
3872 DiagnoseAssignmentResult(Incompatible, From->getExprLoc(), ToType,
3873 From->getType(), From, Action);
3874 assert(Diagnosed && "failed to diagnose bad conversion")((Diagnosed && "failed to diagnose bad conversion") ?
static_cast<void> (0) : __assert_fail ("Diagnosed && \"failed to diagnose bad conversion\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3874, __PRETTY_FUNCTION__))
; (void)Diagnosed;
3875 return ExprError();
3876 }
3877
3878 // Everything went well.
3879 return From;
3880}
3881
3882/// PerformImplicitConversion - Perform an implicit conversion of the
3883/// expression From to the type ToType by following the standard
3884/// conversion sequence SCS. Returns the converted
3885/// expression. Flavor is the context in which we're performing this
3886/// conversion, for use in error messages.
3887ExprResult
3888Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3889 const StandardConversionSequence& SCS,
3890 AssignmentAction Action,
3891 CheckedConversionKind CCK) {
3892 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3893
3894 // Overall FIXME: we are recomputing too many types here and doing far too
3895 // much extra work. What this means is that we need to keep track of more
3896 // information that is computed when we try the implicit conversion initially,
3897 // so that we don't need to recompute anything here.
3898 QualType FromType = From->getType();
3899
3900 if (SCS.CopyConstructor) {
3901 // FIXME: When can ToType be a reference type?
3902 assert(!ToType->isReferenceType())((!ToType->isReferenceType()) ? static_cast<void> (0
) : __assert_fail ("!ToType->isReferenceType()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3902, __PRETTY_FUNCTION__))
;
3903 if (SCS.Second == ICK_Derived_To_Base) {
3904 SmallVector<Expr*, 8> ConstructorArgs;
3905 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3906 From, /*FIXME:ConstructLoc*/SourceLocation(),
3907 ConstructorArgs))
3908 return ExprError();
3909 return BuildCXXConstructExpr(
3910 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3911 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3912 ConstructorArgs, /*HadMultipleCandidates*/ false,
3913 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3914 CXXConstructExpr::CK_Complete, SourceRange());
3915 }
3916 return BuildCXXConstructExpr(
3917 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3918 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3919 From, /*HadMultipleCandidates*/ false,
3920 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3921 CXXConstructExpr::CK_Complete, SourceRange());
3922 }
3923
3924 // Resolve overloaded function references.
3925 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3926 DeclAccessPair Found;
3927 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3928 true, Found);
3929 if (!Fn)
3930 return ExprError();
3931
3932 if (DiagnoseUseOfDecl(Fn, From->getBeginLoc()))
3933 return ExprError();
3934
3935 From = FixOverloadedFunctionReference(From, Found, Fn);
3936 FromType = From->getType();
3937 }
3938
3939 // If we're converting to an atomic type, first convert to the corresponding
3940 // non-atomic type.
3941 QualType ToAtomicType;
3942 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3943 ToAtomicType = ToType;
3944 ToType = ToAtomic->getValueType();
3945 }
3946
3947 QualType InitialFromType = FromType;
3948 // Perform the first implicit conversion.
3949 switch (SCS.First) {
3950 case ICK_Identity:
3951 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3952 FromType = FromAtomic->getValueType().getUnqualifiedType();
3953 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3954 From, /*BasePath=*/nullptr, VK_RValue);
3955 }
3956 break;
3957
3958 case ICK_Lvalue_To_Rvalue: {
3959 assert(From->getObjectKind() != OK_ObjCProperty)((From->getObjectKind() != OK_ObjCProperty) ? static_cast<
void> (0) : __assert_fail ("From->getObjectKind() != OK_ObjCProperty"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3959, __PRETTY_FUNCTION__))
;
3960 ExprResult FromRes = DefaultLvalueConversion(From);
3961 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!")((!FromRes.isInvalid() && "Can't perform deduced conversion?!"
) ? static_cast<void> (0) : __assert_fail ("!FromRes.isInvalid() && \"Can't perform deduced conversion?!\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3961, __PRETTY_FUNCTION__))
;
3962 From = FromRes.get();
3963 FromType = From->getType();
3964 break;
3965 }
3966
3967 case ICK_Array_To_Pointer:
3968 FromType = Context.getArrayDecayedType(FromType);
3969 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3970 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3971 break;
3972
3973 case ICK_Function_To_Pointer:
3974 FromType = Context.getPointerType(FromType);
3975 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3976 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3977 break;
3978
3979 default:
3980 llvm_unreachable("Improper first standard conversion")::llvm::llvm_unreachable_internal("Improper first standard conversion"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 3980)
;
3981 }
3982
3983 // Perform the second implicit conversion
3984 switch (SCS.Second) {
3985 case ICK_Identity:
3986 // C++ [except.spec]p5:
3987 // [For] assignment to and initialization of pointers to functions,
3988 // pointers to member functions, and references to functions: the
3989 // target entity shall allow at least the exceptions allowed by the
3990 // source value in the assignment or initialization.
3991 switch (Action) {
3992 case AA_Assigning:
3993 case AA_Initializing:
3994 // Note, function argument passing and returning are initialization.
3995 case AA_Passing:
3996 case AA_Returning:
3997 case AA_Sending:
3998 case AA_Passing_CFAudited:
3999 if (CheckExceptionSpecCompatibility(From, ToType))
4000 return ExprError();
4001 break;
4002
4003 case AA_Casting:
4004 case AA_Converting:
4005 // Casts and implicit conversions are not initialization, so are not
4006 // checked for exception specification mismatches.
4007 break;
4008 }
4009 // Nothing else to do.
4010 break;
4011
4012 case ICK_Integral_Promotion:
4013 case ICK_Integral_Conversion:
4014 if (ToType->isBooleanType()) {
4015 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4017, __PRETTY_FUNCTION__))
4016 SCS.Second == ICK_Integral_Promotion &&((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4017, __PRETTY_FUNCTION__))
4017 "only enums with fixed underlying type can promote to bool")((FromType->castAs<EnumType>()->getDecl()->isFixed
() && SCS.Second == ICK_Integral_Promotion &&
"only enums with fixed underlying type can promote to bool")
? static_cast<void> (0) : __assert_fail ("FromType->castAs<EnumType>()->getDecl()->isFixed() && SCS.Second == ICK_Integral_Promotion && \"only enums with fixed underlying type can promote to bool\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4017, __PRETTY_FUNCTION__))
;
4018 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
4019 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4020 } else {
4021 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
4022 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4023 }
4024 break;
4025
4026 case ICK_Floating_Promotion:
4027 case ICK_Floating_Conversion:
4028 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
4029 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4030 break;
4031
4032 case ICK_Complex_Promotion:
4033 case ICK_Complex_Conversion: {
4034 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
4035 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
4036 CastKind CK;
4037 if (FromEl->isRealFloatingType()) {
4038 if (ToEl->isRealFloatingType())
4039 CK = CK_FloatingComplexCast;
4040 else
4041 CK = CK_FloatingComplexToIntegralComplex;
4042 } else if (ToEl->isRealFloatingType()) {
4043 CK = CK_IntegralComplexToFloatingComplex;
4044 } else {
4045 CK = CK_IntegralComplexCast;
4046 }
4047 From = ImpCastExprToType(From, ToType, CK,
4048 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4049 break;
4050 }
4051
4052 case ICK_Floating_Integral:
4053 if (ToType->isRealFloatingType())
4054 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
4055 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4056 else
4057 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
4058 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4059 break;
4060
4061 case ICK_Compatible_Conversion:
4062 From = ImpCastExprToType(From, ToType, CK_NoOp,
4063 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4064 break;
4065
4066 case ICK_Writeback_Conversion:
4067 case ICK_Pointer_Conversion: {
4068 if (SCS.IncompatibleObjC && Action != AA_Casting) {
4069 // Diagnose incompatible Objective-C conversions
4070 if (Action == AA_Initializing || Action == AA_Assigning)
4071 Diag(From->getBeginLoc(),
4072 diag::ext_typecheck_convert_incompatible_pointer)
4073 << ToType << From->getType() << Action << From->getSourceRange()
4074 << 0;
4075 else
4076 Diag(From->getBeginLoc(),
4077 diag::ext_typecheck_convert_incompatible_pointer)
4078 << From->getType() << ToType << Action << From->getSourceRange()
4079 << 0;
4080
4081 if (From->getType()->isObjCObjectPointerType() &&
4082 ToType->isObjCObjectPointerType())
4083 EmitRelatedResultTypeNote(From);
4084 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
4085 !CheckObjCARCUnavailableWeakConversion(ToType,
4086 From->getType())) {
4087 if (Action == AA_Initializing)
4088 Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign);
4089 else
4090 Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable)
4091 << (Action == AA_Casting) << From->getType() << ToType
4092 << From->getSourceRange();
4093 }
4094
4095 CastKind Kind;
4096 CXXCastPath BasePath;
4097 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
4098 return ExprError();
4099
4100 // Make sure we extend blocks if necessary.
4101 // FIXME: doing this here is really ugly.
4102 if (Kind == CK_BlockPointerToObjCPointerCast) {
4103 ExprResult E = From;
4104 (void) PrepareCastToObjCObjectPointer(E);
4105 From = E.get();
4106 }
4107 if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
4108 CheckObjCConversion(SourceRange(), ToType, From, CCK);
4109 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4110 .get();
4111 break;
4112 }
4113
4114 case ICK_Pointer_Member: {
4115 CastKind Kind;
4116 CXXCastPath BasePath;
4117 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
4118 return ExprError();
4119 if (CheckExceptionSpecCompatibility(From, ToType))
4120 return ExprError();
4121
4122 // We may not have been able to figure out what this member pointer resolved
4123 // to up until this exact point. Attempt to lock-in it's inheritance model.
4124 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4125 (void)isCompleteType(From->getExprLoc(), From->getType());
4126 (void)isCompleteType(From->getExprLoc(), ToType);
4127 }
4128
4129 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
4130 .get();
4131 break;
4132 }
4133
4134 case ICK_Boolean_Conversion:
4135 // Perform half-to-boolean conversion via float.
4136 if (From->getType()->isHalfType()) {
4137 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
4138 FromType = Context.FloatTy;
4139 }
4140
4141 From = ImpCastExprToType(From, Context.BoolTy,
4142 ScalarTypeToBooleanCastKind(FromType),
4143 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4144 break;
4145
4146 case ICK_Derived_To_Base: {
4147 CXXCastPath BasePath;
4148 if (CheckDerivedToBaseConversion(
4149 From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(),
4150 From->getSourceRange(), &BasePath, CStyle))
4151 return ExprError();
4152
4153 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
4154 CK_DerivedToBase, From->getValueKind(),
4155 &BasePath, CCK).get();
4156 break;
4157 }
4158
4159 case ICK_Vector_Conversion:
4160 From = ImpCastExprToType(From, ToType, CK_BitCast,
4161 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4162 break;
4163
4164 case ICK_Vector_Splat: {
4165 // Vector splat from any arithmetic type to a vector.
4166 Expr *Elem = prepareVectorSplat(ToType, From).get();
4167 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
4168 /*BasePath=*/nullptr, CCK).get();
4169 break;
4170 }
4171
4172 case ICK_Complex_Real:
4173 // Case 1. x -> _Complex y
4174 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
4175 QualType ElType = ToComplex->getElementType();
4176 bool isFloatingComplex = ElType->isRealFloatingType();
4177
4178 // x -> y
4179 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
4180 // do nothing
4181 } else if (From->getType()->isRealFloatingType()) {
4182 From = ImpCastExprToType(From, ElType,
4183 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
4184 } else {
4185 assert(From->getType()->isIntegerType())((From->getType()->isIntegerType()) ? static_cast<void
> (0) : __assert_fail ("From->getType()->isIntegerType()"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4185, __PRETTY_FUNCTION__))
;
4186 From = ImpCastExprToType(From, ElType,
4187 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
4188 }
4189 // y -> _Complex y
4190 From = ImpCastExprToType(From, ToType,
4191 isFloatingComplex ? CK_FloatingRealToComplex
4192 : CK_IntegralRealToComplex).get();
4193
4194 // Case 2. _Complex x -> y
4195 } else {
4196 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
4197 assert(FromComplex)((FromComplex) ? static_cast<void> (0) : __assert_fail (
"FromComplex", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4197, __PRETTY_FUNCTION__))
;
4198
4199 QualType ElType = FromComplex->getElementType();
4200 bool isFloatingComplex = ElType->isRealFloatingType();
4201
4202 // _Complex x -> x
4203 From = ImpCastExprToType(From, ElType,
4204 isFloatingComplex ? CK_FloatingComplexToReal
4205 : CK_IntegralComplexToReal,
4206 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4207
4208 // x -> y
4209 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
4210 // do nothing
4211 } else if (ToType->isRealFloatingType()) {
4212 From = ImpCastExprToType(From, ToType,
4213 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
4214 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4215 } else {
4216 assert(ToType->isIntegerType())((ToType->isIntegerType()) ? static_cast<void> (0) :
__assert_fail ("ToType->isIntegerType()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4216, __PRETTY_FUNCTION__))
;
4217 From = ImpCastExprToType(From, ToType,
4218 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
4219 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4220 }
4221 }
4222 break;
4223
4224 case ICK_Block_Pointer_Conversion: {
4225 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
4226 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4227 break;
4228 }
4229
4230 case ICK_TransparentUnionConversion: {
4231 ExprResult FromRes = From;
4232 Sema::AssignConvertType ConvTy =
4233 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
4234 if (FromRes.isInvalid())
4235 return ExprError();
4236 From = FromRes.get();
4237 assert ((ConvTy == Sema::Compatible) &&(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4238, __PRETTY_FUNCTION__))
4238 "Improper transparent union conversion")(((ConvTy == Sema::Compatible) && "Improper transparent union conversion"
) ? static_cast<void> (0) : __assert_fail ("(ConvTy == Sema::Compatible) && \"Improper transparent union conversion\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4238, __PRETTY_FUNCTION__))
;
4239 (void)ConvTy;
4240 break;
4241 }
4242
4243 case ICK_Zero_Event_Conversion:
4244 case ICK_Zero_Queue_Conversion:
4245 From = ImpCastExprToType(From, ToType,
4246 CK_ZeroToOCLOpaqueType,
4247 From->getValueKind()).get();
4248 break;
4249
4250 case ICK_Lvalue_To_Rvalue:
4251 case ICK_Array_To_Pointer:
4252 case ICK_Function_To_Pointer:
4253 case ICK_Function_Conversion:
4254 case ICK_Qualification:
4255 case ICK_Num_Conversion_Kinds:
4256 case ICK_C_Only_Conversion:
4257 case ICK_Incompatible_Pointer_Conversion:
4258 llvm_unreachable("Improper second standard conversion")::llvm::llvm_unreachable_internal("Improper second standard conversion"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4258)
;
4259 }
4260
4261 switch (SCS.Third) {
4262 case ICK_Identity:
4263 // Nothing to do.
4264 break;
4265
4266 case ICK_Function_Conversion:
4267 // If both sides are functions (or pointers/references to them), there could
4268 // be incompatible exception declarations.
4269 if (CheckExceptionSpecCompatibility(From, ToType))
4270 return ExprError();
4271
4272 From = ImpCastExprToType(From, ToType, CK_NoOp,
4273 VK_RValue, /*BasePath=*/nullptr, CCK).get();
4274 break;
4275
4276 case ICK_Qualification: {
4277 // The qualification keeps the category of the inner expression, unless the
4278 // target type isn't a reference.
4279 ExprValueKind VK =
4280 ToType->isReferenceType() ? From->getValueKind() : VK_RValue;
4281
4282 CastKind CK = CK_NoOp;
4283
4284 if (ToType->isReferenceType() &&
4285 ToType->getPointeeType().getAddressSpace() !=
4286 From->getType().getAddressSpace())
4287 CK = CK_AddressSpaceConversion;
4288
4289 if (ToType->isPointerType() &&
4290 ToType->getPointeeType().getAddressSpace() !=
4291 From->getType()->getPointeeType().getAddressSpace())
4292 CK = CK_AddressSpaceConversion;
4293
4294 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK,
4295 /*BasePath=*/nullptr, CCK)
4296 .get();
4297
4298 if (SCS.DeprecatedStringLiteralToCharPtr &&
4299 !getLangOpts().WritableStrings) {
4300 Diag(From->getBeginLoc(),
4301 getLangOpts().CPlusPlus11
4302 ? diag::ext_deprecated_string_literal_conversion
4303 : diag::warn_deprecated_string_literal_conversion)
4304 << ToType.getNonReferenceType();
4305 }
4306
4307 break;
4308 }
4309
4310 default:
4311 llvm_unreachable("Improper third standard conversion")::llvm::llvm_unreachable_internal("Improper third standard conversion"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4311)
;
4312 }
4313
4314 // If this conversion sequence involved a scalar -> atomic conversion, perform
4315 // that conversion now.
4316 if (!ToAtomicType.isNull()) {
4317 assert(Context.hasSameType(((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4318, __PRETTY_FUNCTION__))
4318 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()))((Context.hasSameType( ToAtomicType->castAs<AtomicType>
()->getValueType(), From->getType())) ? static_cast<
void> (0) : __assert_fail ("Context.hasSameType( ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4318, __PRETTY_FUNCTION__))
;
4319 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
4320 VK_RValue, nullptr, CCK).get();
4321 }
4322
4323 // If this conversion sequence succeeded and involved implicitly converting a
4324 // _Nullable type to a _Nonnull one, complain.
4325 if (!isCast(CCK))
4326 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
4327 From->getBeginLoc());
4328
4329 return From;
4330}
4331
4332/// Check the completeness of a type in a unary type trait.
4333///
4334/// If the particular type trait requires a complete type, tries to complete
4335/// it. If completing the type fails, a diagnostic is emitted and false
4336/// returned. If completing the type succeeds or no completion was required,
4337/// returns true.
4338static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
4339 SourceLocation Loc,
4340 QualType ArgTy) {
4341 // C++0x [meta.unary.prop]p3:
4342 // For all of the class templates X declared in this Clause, instantiating
4343 // that template with a template argument that is a class template
4344 // specialization may result in the implicit instantiation of the template
4345 // argument if and only if the semantics of X require that the argument
4346 // must be a complete type.
4347 // We apply this rule to all the type trait expressions used to implement
4348 // these class templates. We also try to follow any GCC documented behavior
4349 // in these expressions to ensure portability of standard libraries.
4350 switch (UTT) {
4351 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4351)
;
4352 // is_complete_type somewhat obviously cannot require a complete type.
4353 case UTT_IsCompleteType:
4354 // Fall-through
4355
4356 // These traits are modeled on the type predicates in C++0x
4357 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
4358 // requiring a complete type, as whether or not they return true cannot be
4359 // impacted by the completeness of the type.
4360 case UTT_IsVoid:
4361 case UTT_IsIntegral:
4362 case UTT_IsFloatingPoint:
4363 case UTT_IsArray:
4364 case UTT_IsPointer:
4365 case UTT_IsLvalueReference:
4366 case UTT_IsRvalueReference:
4367 case UTT_IsMemberFunctionPointer:
4368 case UTT_IsMemberObjectPointer:
4369 case UTT_IsEnum:
4370 case UTT_IsUnion:
4371 case UTT_IsClass:
4372 case UTT_IsFunction:
4373 case UTT_IsReference:
4374 case UTT_IsArithmetic:
4375 case UTT_IsFundamental:
4376 case UTT_IsObject:
4377 case UTT_IsScalar:
4378 case UTT_IsCompound:
4379 case UTT_IsMemberPointer:
4380 // Fall-through
4381
4382 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
4383 // which requires some of its traits to have the complete type. However,
4384 // the completeness of the type cannot impact these traits' semantics, and
4385 // so they don't require it. This matches the comments on these traits in
4386 // Table 49.
4387 case UTT_IsConst:
4388 case UTT_IsVolatile:
4389 case UTT_IsSigned:
4390 case UTT_IsUnsigned:
4391
4392 // This type trait always returns false, checking the type is moot.
4393 case UTT_IsInterfaceClass:
4394 return true;
4395
4396 // C++14 [meta.unary.prop]:
4397 // If T is a non-union class type, T shall be a complete type.
4398 case UTT_IsEmpty:
4399 case UTT_IsPolymorphic:
4400 case UTT_IsAbstract:
4401 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
4402 if (!RD->isUnion())
4403 return !S.RequireCompleteType(
4404 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4405 return true;
4406
4407 // C++14 [meta.unary.prop]:
4408 // If T is a class type, T shall be a complete type.
4409 case UTT_IsFinal:
4410 case UTT_IsSealed:
4411 if (ArgTy->getAsCXXRecordDecl())
4412 return !S.RequireCompleteType(
4413 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4414 return true;
4415
4416 // C++1z [meta.unary.prop]:
4417 // remove_all_extents_t<T> shall be a complete type or cv void.
4418 case UTT_IsAggregate:
4419 case UTT_IsTrivial:
4420 case UTT_IsTriviallyCopyable:
4421 case UTT_IsStandardLayout:
4422 case UTT_IsPOD:
4423 case UTT_IsLiteral:
4424 // Per the GCC type traits documentation, T shall be a complete type, cv void,
4425 // or an array of unknown bound. But GCC actually imposes the same constraints
4426 // as above.
4427 case UTT_HasNothrowAssign:
4428 case UTT_HasNothrowMoveAssign:
4429 case UTT_HasNothrowConstructor:
4430 case UTT_HasNothrowCopy:
4431 case UTT_HasTrivialAssign:
4432 case UTT_HasTrivialMoveAssign:
4433 case UTT_HasTrivialDefaultConstructor:
4434 case UTT_HasTrivialMoveConstructor:
4435 case UTT_HasTrivialCopy:
4436 case UTT_HasTrivialDestructor:
4437 case UTT_HasVirtualDestructor:
4438 ArgTy = QualType(ArgTy->getBaseElementTypeUnsafe(), 0);
4439 LLVM_FALLTHROUGH[[clang::fallthrough]];
4440
4441 // C++1z [meta.unary.prop]:
4442 // T shall be a complete type, cv void, or an array of unknown bound.
4443 case UTT_IsDestructible:
4444 case UTT_IsNothrowDestructible:
4445 case UTT_IsTriviallyDestructible:
4446 case UTT_HasUniqueObjectRepresentations:
4447 if (ArgTy->isIncompleteArrayType() || ArgTy->isVoidType())
4448 return true;
4449
4450 return !S.RequireCompleteType(
4451 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
4452 }
4453}
4454
4455static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
4456 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
4457 bool (CXXRecordDecl::*HasTrivial)() const,
4458 bool (CXXRecordDecl::*HasNonTrivial)() const,
4459 bool (CXXMethodDecl::*IsDesiredOp)() const)
4460{
4461 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4462 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
4463 return true;
4464
4465 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
4466 DeclarationNameInfo NameInfo(Name, KeyLoc);
4467 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
4468 if (Self.LookupQualifiedName(Res, RD)) {
4469 bool FoundOperator = false;
4470 Res.suppressDiagnostics();
4471 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
4472 Op != OpEnd; ++Op) {
4473 if (isa<FunctionTemplateDecl>(*Op))
4474 continue;
4475
4476 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
4477 if((Operator->*IsDesiredOp)()) {
4478 FoundOperator = true;
4479 const FunctionProtoType *CPT =
4480 Operator->getType()->getAs<FunctionProtoType>();
4481 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4482 if (!CPT || !CPT->isNothrow())
4483 return false;
4484 }
4485 }
4486 return FoundOperator;
4487 }
4488 return false;
4489}
4490
4491static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
4492 SourceLocation KeyLoc, QualType T) {
4493 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4493, __PRETTY_FUNCTION__))
;
4494
4495 ASTContext &C = Self.Context;
4496 switch(UTT) {
4497 default: llvm_unreachable("not a UTT")::llvm::llvm_unreachable_internal("not a UTT", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4497)
;
4498 // Type trait expressions corresponding to the primary type category
4499 // predicates in C++0x [meta.unary.cat].
4500 case UTT_IsVoid:
4501 return T->isVoidType();
4502 case UTT_IsIntegral:
4503 return T->isIntegralType(C);
4504 case UTT_IsFloatingPoint:
4505 return T->isFloatingType();
4506 case UTT_IsArray:
4507 return T->isArrayType();
4508 case UTT_IsPointer:
4509 return T->isPointerType();
4510 case UTT_IsLvalueReference:
4511 return T->isLValueReferenceType();
4512 case UTT_IsRvalueReference:
4513 return T->isRValueReferenceType();
4514 case UTT_IsMemberFunctionPointer:
4515 return T->isMemberFunctionPointerType();
4516 case UTT_IsMemberObjectPointer:
4517 return T->isMemberDataPointerType();
4518 case UTT_IsEnum:
4519 return T->isEnumeralType();
4520 case UTT_IsUnion:
4521 return T->isUnionType();
4522 case UTT_IsClass:
4523 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
4524 case UTT_IsFunction:
4525 return T->isFunctionType();
4526
4527 // Type trait expressions which correspond to the convenient composition
4528 // predicates in C++0x [meta.unary.comp].
4529 case UTT_IsReference:
4530 return T->isReferenceType();
4531 case UTT_IsArithmetic:
4532 return T->isArithmeticType() && !T->isEnumeralType();
4533 case UTT_IsFundamental:
4534 return T->isFundamentalType();
4535 case UTT_IsObject:
4536 return T->isObjectType();
4537 case UTT_IsScalar:
4538 // Note: semantic analysis depends on Objective-C lifetime types to be
4539 // considered scalar types. However, such types do not actually behave
4540 // like scalar types at run time (since they may require retain/release
4541 // operations), so we report them as non-scalar.
4542 if (T->isObjCLifetimeType()) {
4543 switch (T.getObjCLifetime()) {
4544 case Qualifiers::OCL_None:
4545 case Qualifiers::OCL_ExplicitNone:
4546 return true;
4547
4548 case Qualifiers::OCL_Strong:
4549 case Qualifiers::OCL_Weak:
4550 case Qualifiers::OCL_Autoreleasing:
4551 return false;
4552 }
4553 }
4554
4555 return T->isScalarType();
4556 case UTT_IsCompound:
4557 return T->isCompoundType();
4558 case UTT_IsMemberPointer:
4559 return T->isMemberPointerType();
4560
4561 // Type trait expressions which correspond to the type property predicates
4562 // in C++0x [meta.unary.prop].
4563 case UTT_IsConst:
4564 return T.isConstQualified();
4565 case UTT_IsVolatile:
4566 return T.isVolatileQualified();
4567 case UTT_IsTrivial:
4568 return T.isTrivialType(C);
4569 case UTT_IsTriviallyCopyable:
4570 return T.isTriviallyCopyableType(C);
4571 case UTT_IsStandardLayout:
4572 return T->isStandardLayoutType();
4573 case UTT_IsPOD:
4574 return T.isPODType(C);
4575 case UTT_IsLiteral:
4576 return T->isLiteralType(C);
4577 case UTT_IsEmpty:
4578 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4579 return !RD->isUnion() && RD->isEmpty();
4580 return false;
4581 case UTT_IsPolymorphic:
4582 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4583 return !RD->isUnion() && RD->isPolymorphic();
4584 return false;
4585 case UTT_IsAbstract:
4586 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4587 return !RD->isUnion() && RD->isAbstract();
4588 return false;
4589 case UTT_IsAggregate:
4590 // Report vector extensions and complex types as aggregates because they
4591 // support aggregate initialization. GCC mirrors this behavior for vectors
4592 // but not _Complex.
4593 return T->isAggregateType() || T->isVectorType() || T->isExtVectorType() ||
4594 T->isAnyComplexType();
4595 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4596 // even then only when it is used with the 'interface struct ...' syntax
4597 // Clang doesn't support /CLR which makes this type trait moot.
4598 case UTT_IsInterfaceClass:
4599 return false;
4600 case UTT_IsFinal:
4601 case UTT_IsSealed:
4602 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4603 return RD->hasAttr<FinalAttr>();
4604 return false;
4605 case UTT_IsSigned:
4606 return T->isSignedIntegerType();
4607 case UTT_IsUnsigned:
4608 return T->isUnsignedIntegerType();
4609
4610 // Type trait expressions which query classes regarding their construction,
4611 // destruction, and copying. Rather than being based directly on the
4612 // related type predicates in the standard, they are specified by both
4613 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4614 // specifications.
4615 //
4616 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4617 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4618 //
4619 // Note that these builtins do not behave as documented in g++: if a class
4620 // has both a trivial and a non-trivial special member of a particular kind,
4621 // they return false! For now, we emulate this behavior.
4622 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4623 // does not correctly compute triviality in the presence of multiple special
4624 // members of the same kind. Revisit this once the g++ bug is fixed.
4625 case UTT_HasTrivialDefaultConstructor:
4626 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4627 // If __is_pod (type) is true then the trait is true, else if type is
4628 // a cv class or union type (or array thereof) with a trivial default
4629 // constructor ([class.ctor]) then the trait is true, else it is false.
4630 if (T.isPODType(C))
4631 return true;
4632 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4633 return RD->hasTrivialDefaultConstructor() &&
4634 !RD->hasNonTrivialDefaultConstructor();
4635 return false;
4636 case UTT_HasTrivialMoveConstructor:
4637 // This trait is implemented by MSVC 2012 and needed to parse the
4638 // standard library headers. Specifically this is used as the logic
4639 // behind std::is_trivially_move_constructible (20.9.4.3).
4640 if (T.isPODType(C))
4641 return true;
4642 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4643 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4644 return false;
4645 case UTT_HasTrivialCopy:
4646 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4647 // If __is_pod (type) is true or type is a reference type then
4648 // the trait is true, else if type is a cv class or union type
4649 // with a trivial copy constructor ([class.copy]) then the trait
4650 // is true, else it is false.
4651 if (T.isPODType(C) || T->isReferenceType())
4652 return true;
4653 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4654 return RD->hasTrivialCopyConstructor() &&
4655 !RD->hasNonTrivialCopyConstructor();
4656 return false;
4657 case UTT_HasTrivialMoveAssign:
4658 // This trait is implemented by MSVC 2012 and needed to parse the
4659 // standard library headers. Specifically it is used as the logic
4660 // behind std::is_trivially_move_assignable (20.9.4.3)
4661 if (T.isPODType(C))
4662 return true;
4663 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4664 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4665 return false;
4666 case UTT_HasTrivialAssign:
4667 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4668 // If type is const qualified or is a reference type then the
4669 // trait is false. Otherwise if __is_pod (type) is true then the
4670 // trait is true, else if type is a cv class or union type with
4671 // a trivial copy assignment ([class.copy]) then the trait is
4672 // true, else it is false.
4673 // Note: the const and reference restrictions are interesting,
4674 // given that const and reference members don't prevent a class
4675 // from having a trivial copy assignment operator (but do cause
4676 // errors if the copy assignment operator is actually used, q.v.
4677 // [class.copy]p12).
4678
4679 if (T.isConstQualified())
4680 return false;
4681 if (T.isPODType(C))
4682 return true;
4683 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4684 return RD->hasTrivialCopyAssignment() &&
4685 !RD->hasNonTrivialCopyAssignment();
4686 return false;
4687 case UTT_IsDestructible:
4688 case UTT_IsTriviallyDestructible:
4689 case UTT_IsNothrowDestructible:
4690 // C++14 [meta.unary.prop]:
4691 // For reference types, is_destructible<T>::value is true.
4692 if (T->isReferenceType())
4693 return true;
4694
4695 // Objective-C++ ARC: autorelease types don't require destruction.
4696 if (T->isObjCLifetimeType() &&
4697 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4698 return true;
4699
4700 // C++14 [meta.unary.prop]:
4701 // For incomplete types and function types, is_destructible<T>::value is
4702 // false.
4703 if (T->isIncompleteType() || T->isFunctionType())
4704 return false;
4705
4706 // A type that requires destruction (via a non-trivial destructor or ARC
4707 // lifetime semantics) is not trivially-destructible.
4708 if (UTT == UTT_IsTriviallyDestructible && T.isDestructedType())
4709 return false;
4710
4711 // C++14 [meta.unary.prop]:
4712 // For object types and given U equal to remove_all_extents_t<T>, if the
4713 // expression std::declval<U&>().~U() is well-formed when treated as an
4714 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4715 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4716 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4717 if (!Destructor)
4718 return false;
4719 // C++14 [dcl.fct.def.delete]p2:
4720 // A program that refers to a deleted function implicitly or
4721 // explicitly, other than to declare it, is ill-formed.
4722 if (Destructor->isDeleted())
4723 return false;
4724 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4725 return false;
4726 if (UTT == UTT_IsNothrowDestructible) {
4727 const FunctionProtoType *CPT =
4728 Destructor->getType()->getAs<FunctionProtoType>();
4729 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4730 if (!CPT || !CPT->isNothrow())
4731 return false;
4732 }
4733 }
4734 return true;
4735
4736 case UTT_HasTrivialDestructor:
4737 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4738 // If __is_pod (type) is true or type is a reference type
4739 // then the trait is true, else if type is a cv class or union
4740 // type (or array thereof) with a trivial destructor
4741 // ([class.dtor]) then the trait is true, else it is
4742 // false.
4743 if (T.isPODType(C) || T->isReferenceType())
4744 return true;
4745
4746 // Objective-C++ ARC: autorelease types don't require destruction.
4747 if (T->isObjCLifetimeType() &&
4748 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4749 return true;
4750
4751 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4752 return RD->hasTrivialDestructor();
4753 return false;
4754 // TODO: Propagate nothrowness for implicitly declared special members.
4755 case UTT_HasNothrowAssign:
4756 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4757 // If type is const qualified or is a reference type then the
4758 // trait is false. Otherwise if __has_trivial_assign (type)
4759 // is true then the trait is true, else if type is a cv class
4760 // or union type with copy assignment operators that are known
4761 // not to throw an exception then the trait is true, else it is
4762 // false.
4763 if (C.getBaseElementType(T).isConstQualified())
4764 return false;
4765 if (T->isReferenceType())
4766 return false;
4767 if (T.isPODType(C) || T->isObjCLifetimeType())
4768 return true;
4769
4770 if (const RecordType *RT = T->getAs<RecordType>())
4771 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4772 &CXXRecordDecl::hasTrivialCopyAssignment,
4773 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4774 &CXXMethodDecl::isCopyAssignmentOperator);
4775 return false;
4776 case UTT_HasNothrowMoveAssign:
4777 // This trait is implemented by MSVC 2012 and needed to parse the
4778 // standard library headers. Specifically this is used as the logic
4779 // behind std::is_nothrow_move_assignable (20.9.4.3).
4780 if (T.isPODType(C))
4781 return true;
4782
4783 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4784 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4785 &CXXRecordDecl::hasTrivialMoveAssignment,
4786 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4787 &CXXMethodDecl::isMoveAssignmentOperator);
4788 return false;
4789 case UTT_HasNothrowCopy:
4790 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4791 // If __has_trivial_copy (type) is true then the trait is true, else
4792 // if type is a cv class or union type with copy constructors that are
4793 // known not to throw an exception then the trait is true, else it is
4794 // false.
4795 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4796 return true;
4797 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4798 if (RD->hasTrivialCopyConstructor() &&
4799 !RD->hasNonTrivialCopyConstructor())
4800 return true;
4801
4802 bool FoundConstructor = false;
4803 unsigned FoundTQs;
4804 for (const auto *ND : Self.LookupConstructors(RD)) {
4805 // A template constructor is never a copy constructor.
4806 // FIXME: However, it may actually be selected at the actual overload
4807 // resolution point.
4808 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4809 continue;
4810 // UsingDecl itself is not a constructor
4811 if (isa<UsingDecl>(ND))
4812 continue;
4813 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4814 if (Constructor->isCopyConstructor(FoundTQs)) {
4815 FoundConstructor = true;
4816 const FunctionProtoType *CPT
4817 = Constructor->getType()->getAs<FunctionProtoType>();
4818 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4819 if (!CPT)
4820 return false;
4821 // TODO: check whether evaluating default arguments can throw.
4822 // For now, we'll be conservative and assume that they can throw.
4823 if (!CPT->isNothrow() || CPT->getNumParams() > 1)
4824 return false;
4825 }
4826 }
4827
4828 return FoundConstructor;
4829 }
4830 return false;
4831 case UTT_HasNothrowConstructor:
4832 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4833 // If __has_trivial_constructor (type) is true then the trait is
4834 // true, else if type is a cv class or union type (or array
4835 // thereof) with a default constructor that is known not to
4836 // throw an exception then the trait is true, else it is false.
4837 if (T.isPODType(C) || T->isObjCLifetimeType())
4838 return true;
4839 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4840 if (RD->hasTrivialDefaultConstructor() &&
4841 !RD->hasNonTrivialDefaultConstructor())
4842 return true;
4843
4844 bool FoundConstructor = false;
4845 for (const auto *ND : Self.LookupConstructors(RD)) {
4846 // FIXME: In C++0x, a constructor template can be a default constructor.
4847 if (isa<FunctionTemplateDecl>(ND->getUnderlyingDecl()))
4848 continue;
4849 // UsingDecl itself is not a constructor
4850 if (isa<UsingDecl>(ND))
4851 continue;
4852 auto *Constructor = cast<CXXConstructorDecl>(ND->getUnderlyingDecl());
4853 if (Constructor->isDefaultConstructor()) {
4854 FoundConstructor = true;
4855 const FunctionProtoType *CPT
4856 = Constructor->getType()->getAs<FunctionProtoType>();
4857 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4858 if (!CPT)
4859 return false;
4860 // FIXME: check whether evaluating default arguments can throw.
4861 // For now, we'll be conservative and assume that they can throw.
4862 if (!CPT->isNothrow() || CPT->getNumParams() > 0)
4863 return false;
4864 }
4865 }
4866 return FoundConstructor;
4867 }
4868 return false;
4869 case UTT_HasVirtualDestructor:
4870 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4871 // If type is a class type with a virtual destructor ([class.dtor])
4872 // then the trait is true, else it is false.
4873 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4874 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4875 return Destructor->isVirtual();
4876 return false;
4877
4878 // These type trait expressions are modeled on the specifications for the
4879 // Embarcadero C++0x type trait functions:
4880 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4881 case UTT_IsCompleteType:
4882 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4883 // Returns True if and only if T is a complete type at the point of the
4884 // function call.
4885 return !T->isIncompleteType();
4886 case UTT_HasUniqueObjectRepresentations:
4887 return C.hasUniqueObjectRepresentations(T);
4888 }
4889}
4890
4891static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4892 QualType RhsT, SourceLocation KeyLoc);
4893
4894static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4895 ArrayRef<TypeSourceInfo *> Args,
4896 SourceLocation RParenLoc) {
4897 if (Kind <= UTT_Last)
4898 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4899
4900 // Evaluate BTT_ReferenceBindsToTemporary alongside the IsConstructible
4901 // traits to avoid duplication.
4902 if (Kind <= BTT_Last && Kind != BTT_ReferenceBindsToTemporary)
4903 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4904 Args[1]->getType(), RParenLoc);
4905
4906 switch (Kind) {
4907 case clang::BTT_ReferenceBindsToTemporary:
4908 case clang::TT_IsConstructible:
4909 case clang::TT_IsNothrowConstructible:
4910 case clang::TT_IsTriviallyConstructible: {
4911 // C++11 [meta.unary.prop]:
4912 // is_trivially_constructible is defined as:
4913 //
4914 // is_constructible<T, Args...>::value is true and the variable
4915 // definition for is_constructible, as defined below, is known to call
4916 // no operation that is not trivial.
4917 //
4918 // The predicate condition for a template specialization
4919 // is_constructible<T, Args...> shall be satisfied if and only if the
4920 // following variable definition would be well-formed for some invented
4921 // variable t:
4922 //
4923 // T t(create<Args>()...);
4924 assert(!Args.empty())((!Args.empty()) ? static_cast<void> (0) : __assert_fail
("!Args.empty()", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 4924, __PRETTY_FUNCTION__))
;
4925
4926 // Precondition: T and all types in the parameter pack Args shall be
4927 // complete types, (possibly cv-qualified) void, or arrays of
4928 // unknown bound.
4929 for (const auto *TSI : Args) {
4930 QualType ArgTy = TSI->getType();
4931 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4932 continue;
4933
4934 if (S.RequireCompleteType(KWLoc, ArgTy,
4935 diag::err_incomplete_type_used_in_type_trait_expr))
4936 return false;
4937 }
4938
4939 // Make sure the first argument is not incomplete nor a function type.
4940 QualType T = Args[0]->getType();
4941 if (T->isIncompleteType() || T->isFunctionType())
4942 return false;
4943
4944 // Make sure the first argument is not an abstract type.
4945 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4946 if (RD && RD->isAbstract())
4947 return false;
4948
4949 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4950 SmallVector<Expr *, 2> ArgExprs;
4951 ArgExprs.reserve(Args.size() - 1);
4952 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4953 QualType ArgTy = Args[I]->getType();
4954 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4955 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4956 OpaqueArgExprs.push_back(
4957 OpaqueValueExpr(Args[I]->getTypeLoc().getBeginLoc(),
4958 ArgTy.getNonLValueExprType(S.Context),
4959 Expr::getValueKindForType(ArgTy)));
4960 }
4961 for (Expr &E : OpaqueArgExprs)
4962 ArgExprs.push_back(&E);
4963
4964 // Perform the initialization in an unevaluated context within a SFINAE
4965 // trap at translation unit scope.
4966 EnterExpressionEvaluationContext Unevaluated(
4967 S, Sema::ExpressionEvaluationContext::Unevaluated);
4968 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4969 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4970 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4971 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4972 RParenLoc));
4973 InitializationSequence Init(S, To, InitKind, ArgExprs);
4974 if (Init.Failed())
4975 return false;
4976
4977 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4978 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4979 return false;
4980
4981 if (Kind == clang::TT_IsConstructible)
4982 return true;
4983
4984 if (Kind == clang::BTT_ReferenceBindsToTemporary) {
4985 if (!T->isReferenceType())
4986 return false;
4987
4988 return !Init.isDirectReferenceBinding();
4989 }
4990
4991 if (Kind == clang::TT_IsNothrowConstructible)
4992 return S.canThrow(Result.get()) == CT_Cannot;
4993
4994 if (Kind == clang::TT_IsTriviallyConstructible) {
4995 // Under Objective-C ARC and Weak, if the destination has non-trivial
4996 // Objective-C lifetime, this is a non-trivial construction.
4997 if (T.getNonReferenceType().hasNonTrivialObjCLifetime())
4998 return false;
4999
5000 // The initialization succeeded; now make sure there are no non-trivial
5001 // calls.
5002 return !Result.get()->hasNonTrivialCall(S.Context);
5003 }
5004
5005 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5005)
;
5006 return false;
5007 }
5008 default: llvm_unreachable("not a TT")::llvm::llvm_unreachable_internal("not a TT", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5008)
;
5009 }
5010
5011 return false;
5012}
5013
5014ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5015 ArrayRef<TypeSourceInfo *> Args,
5016 SourceLocation RParenLoc) {
5017 QualType ResultType = Context.getLogicalOperationType();
5018
5019 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
5020 *this, Kind, KWLoc, Args[0]->getType()))
5021 return ExprError();
5022
5023 bool Dependent = false;
5024 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5025 if (Args[I]->getType()->isDependentType()) {
5026 Dependent = true;
5027 break;
5028 }
5029 }
5030
5031 bool Result = false;
5032 if (!Dependent)
5033 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
5034
5035 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
5036 RParenLoc, Result);
5037}
5038
5039ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
5040 ArrayRef<ParsedType> Args,
5041 SourceLocation RParenLoc) {
5042 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
5043 ConvertedArgs.reserve(Args.size());
5044
5045 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
5046 TypeSourceInfo *TInfo;
5047 QualType T = GetTypeFromParser(Args[I], &TInfo);
5048 if (!TInfo)
5049 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
5050
5051 ConvertedArgs.push_back(TInfo);
5052 }
5053
5054 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
5055}
5056
5057static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
5058 QualType RhsT, SourceLocation KeyLoc) {
5059 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5060, __PRETTY_FUNCTION__))
5060 "Cannot evaluate traits of dependent types")((!LhsT->isDependentType() && !RhsT->isDependentType
() && "Cannot evaluate traits of dependent types") ? static_cast
<void> (0) : __assert_fail ("!LhsT->isDependentType() && !RhsT->isDependentType() && \"Cannot evaluate traits of dependent types\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5060, __PRETTY_FUNCTION__))
;
5061
5062 switch(BTT) {
5063 case BTT_IsBaseOf: {
5064 // C++0x [meta.rel]p2
5065 // Base is a base class of Derived without regard to cv-qualifiers or
5066 // Base and Derived are not unions and name the same class type without
5067 // regard to cv-qualifiers.
5068
5069 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
5070 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
5071 if (!rhsRecord || !lhsRecord) {
5072 const ObjCObjectType *LHSObjTy = LhsT->getAs<ObjCObjectType>();
5073 const ObjCObjectType *RHSObjTy = RhsT->getAs<ObjCObjectType>();
5074 if (!LHSObjTy || !RHSObjTy)
5075 return false;
5076
5077 ObjCInterfaceDecl *BaseInterface = LHSObjTy->getInterface();
5078 ObjCInterfaceDecl *DerivedInterface = RHSObjTy->getInterface();
5079 if (!BaseInterface || !DerivedInterface)
5080 return false;
5081
5082 if (Self.RequireCompleteType(
5083 KeyLoc, RhsT, diag::err_incomplete_type_used_in_type_trait_expr))
5084 return false;
5085
5086 return BaseInterface->isSuperClassOf(DerivedInterface);
5087 }
5088
5089 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5090, __PRETTY_FUNCTION__))
5090 == (lhsRecord == rhsRecord))((Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord
== rhsRecord)) ? static_cast<void> (0) : __assert_fail
("Self.Context.hasSameUnqualifiedType(LhsT, RhsT) == (lhsRecord == rhsRecord)"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5090, __PRETTY_FUNCTION__))
;
5091
5092 if (lhsRecord == rhsRecord)
5093 return !lhsRecord->getDecl()->isUnion();
5094
5095 // C++0x [meta.rel]p2:
5096 // If Base and Derived are class types and are different types
5097 // (ignoring possible cv-qualifiers) then Derived shall be a
5098 // complete type.
5099 if (Self.RequireCompleteType(KeyLoc, RhsT,
5100 diag::err_incomplete_type_used_in_type_trait_expr))
5101 return false;
5102
5103 return cast<CXXRecordDecl>(rhsRecord->getDecl())
5104 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
5105 }
5106 case BTT_IsSame:
5107 return Self.Context.hasSameType(LhsT, RhsT);
5108 case BTT_TypeCompatible: {
5109 // GCC ignores cv-qualifiers on arrays for this builtin.
5110 Qualifiers LhsQuals, RhsQuals;
5111 QualType Lhs = Self.getASTContext().getUnqualifiedArrayType(LhsT, LhsQuals);
5112 QualType Rhs = Self.getASTContext().getUnqualifiedArrayType(RhsT, RhsQuals);
5113 return Self.Context.typesAreCompatible(Lhs, Rhs);
5114 }
5115 case BTT_IsConvertible:
5116 case BTT_IsConvertibleTo: {
5117 // C++0x [meta.rel]p4:
5118 // Given the following function prototype:
5119 //
5120 // template <class T>
5121 // typename add_rvalue_reference<T>::type create();
5122 //
5123 // the predicate condition for a template specialization
5124 // is_convertible<From, To> shall be satisfied if and only if
5125 // the return expression in the following code would be
5126 // well-formed, including any implicit conversions to the return
5127 // type of the function:
5128 //
5129 // To test() {
5130 // return create<From>();
5131 // }
5132 //
5133 // Access checking is performed as if in a context unrelated to To and
5134 // From. Only the validity of the immediate context of the expression
5135 // of the return-statement (including conversions to the return type)
5136 // is considered.
5137 //
5138 // We model the initialization as a copy-initialization of a temporary
5139 // of the appropriate type, which for this expression is identical to the
5140 // return statement (since NRVO doesn't apply).
5141
5142 // Functions aren't allowed to return function or array types.
5143 if (RhsT->isFunctionType() || RhsT->isArrayType())
5144 return false;
5145
5146 // A return statement in a void function must have void type.
5147 if (RhsT->isVoidType())
5148 return LhsT->isVoidType();
5149
5150 // A function definition requires a complete, non-abstract return type.
5151 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
5152 return false;
5153
5154 // Compute the result of add_rvalue_reference.
5155 if (LhsT->isObjectType() || LhsT->isFunctionType())
5156 LhsT = Self.Context.getRValueReferenceType(LhsT);
5157
5158 // Build a fake source and destination for initialization.
5159 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
5160 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5161 Expr::getValueKindForType(LhsT));
5162 Expr *FromPtr = &From;
5163 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
5164 SourceLocation()));
5165
5166 // Perform the initialization in an unevaluated context within a SFINAE
5167 // trap at translation unit scope.
5168 EnterExpressionEvaluationContext Unevaluated(
5169 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5170 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5171 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5172 InitializationSequence Init(Self, To, Kind, FromPtr);
5173 if (Init.Failed())
5174 return false;
5175
5176 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
5177 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
5178 }
5179
5180 case BTT_IsAssignable:
5181 case BTT_IsNothrowAssignable:
5182 case BTT_IsTriviallyAssignable: {
5183 // C++11 [meta.unary.prop]p3:
5184 // is_trivially_assignable is defined as:
5185 // is_assignable<T, U>::value is true and the assignment, as defined by
5186 // is_assignable, is known to call no operation that is not trivial
5187 //
5188 // is_assignable is defined as:
5189 // The expression declval<T>() = declval<U>() is well-formed when
5190 // treated as an unevaluated operand (Clause 5).
5191 //
5192 // For both, T and U shall be complete types, (possibly cv-qualified)
5193 // void, or arrays of unknown bound.
5194 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
5195 Self.RequireCompleteType(KeyLoc, LhsT,
5196 diag::err_incomplete_type_used_in_type_trait_expr))
5197 return false;
5198 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
5199 Self.RequireCompleteType(KeyLoc, RhsT,
5200 diag::err_incomplete_type_used_in_type_trait_expr))
5201 return false;
5202
5203 // cv void is never assignable.
5204 if (LhsT->isVoidType() || RhsT->isVoidType())
5205 return false;
5206
5207 // Build expressions that emulate the effect of declval<T>() and
5208 // declval<U>().
5209 if (LhsT->isObjectType() || LhsT->isFunctionType())
5210 LhsT = Self.Context.getRValueReferenceType(LhsT);
5211 if (RhsT->isObjectType() || RhsT->isFunctionType())
5212 RhsT = Self.Context.getRValueReferenceType(RhsT);
5213 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
5214 Expr::getValueKindForType(LhsT));
5215 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
5216 Expr::getValueKindForType(RhsT));
5217
5218 // Attempt the assignment in an unevaluated context within a SFINAE
5219 // trap at translation unit scope.
5220 EnterExpressionEvaluationContext Unevaluated(
5221 Self, Sema::ExpressionEvaluationContext::Unevaluated);
5222 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
5223 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
5224 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
5225 &Rhs);
5226 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
5227 return false;
5228
5229 if (BTT == BTT_IsAssignable)
5230 return true;
5231
5232 if (BTT == BTT_IsNothrowAssignable)
5233 return Self.canThrow(Result.get()) == CT_Cannot;
5234
5235 if (BTT == BTT_IsTriviallyAssignable) {
5236 // Under Objective-C ARC and Weak, if the destination has non-trivial
5237 // Objective-C lifetime, this is a non-trivial assignment.
5238 if (LhsT.getNonReferenceType().hasNonTrivialObjCLifetime())
5239 return false;
5240
5241 return !Result.get()->hasNonTrivialCall(Self.Context);
5242 }
5243
5244 llvm_unreachable("unhandled type trait")::llvm::llvm_unreachable_internal("unhandled type trait", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5244)
;
5245 return false;
5246 }
5247 default: llvm_unreachable("not a BTT")::llvm::llvm_unreachable_internal("not a BTT", "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5247)
;
5248 }
5249 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5249)
;
5250}
5251
5252ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
5253 SourceLocation KWLoc,
5254 ParsedType Ty,
5255 Expr* DimExpr,
5256 SourceLocation RParen) {
5257 TypeSourceInfo *TSInfo;
5258 QualType T = GetTypeFromParser(Ty, &TSInfo);
5259 if (!TSInfo)
5260 TSInfo = Context.getTrivialTypeSourceInfo(T);
5261
5262 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
5263}
5264
5265static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
5266 QualType T, Expr *DimExpr,
5267 SourceLocation KeyLoc) {
5268 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type")((!T->isDependentType() && "Cannot evaluate traits of dependent type"
) ? static_cast<void> (0) : __assert_fail ("!T->isDependentType() && \"Cannot evaluate traits of dependent type\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5268, __PRETTY_FUNCTION__))
;
5269
5270 switch(ATT) {
5271 case ATT_ArrayRank:
5272 if (T->isArrayType()) {
5273 unsigned Dim = 0;
5274 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5275 ++Dim;
5276 T = AT->getElementType();
5277 }
5278 return Dim;
5279 }
5280 return 0;
5281
5282 case ATT_ArrayExtent: {
5283 llvm::APSInt Value;
5284 uint64_t Dim;
5285 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
5286 diag::err_dimension_expr_not_constant_integer,
5287 false).isInvalid())
5288 return 0;
5289 if (Value.isSigned() && Value.isNegative()) {
5290 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
5291 << DimExpr->getSourceRange();
5292 return 0;
5293 }
5294 Dim = Value.getLimitedValue();
5295
5296 if (T->isArrayType()) {
5297 unsigned D = 0;
5298 bool Matched = false;
5299 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
5300 if (Dim == D) {
5301 Matched = true;
5302 break;
5303 }
5304 ++D;
5305 T = AT->getElementType();
5306 }
5307
5308 if (Matched && T->isArrayType()) {
5309 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
5310 return CAT->getSize().getLimitedValue();
5311 }
5312 }
5313 return 0;
5314 }
5315 }
5316 llvm_unreachable("Unknown type trait or not implemented")::llvm::llvm_unreachable_internal("Unknown type trait or not implemented"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5316)
;
5317}
5318
5319ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
5320 SourceLocation KWLoc,
5321 TypeSourceInfo *TSInfo,
5322 Expr* DimExpr,
5323 SourceLocation RParen) {
5324 QualType T = TSInfo->getType();
5325
5326 // FIXME: This should likely be tracked as an APInt to remove any host
5327 // assumptions about the width of size_t on the target.
5328 uint64_t Value = 0;
5329 if (!T->isDependentType())
5330 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
5331
5332 // While the specification for these traits from the Embarcadero C++
5333 // compiler's documentation says the return type is 'unsigned int', Clang
5334 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
5335 // compiler, there is no difference. On several other platforms this is an
5336 // important distinction.
5337 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
5338 RParen, Context.getSizeType());
5339}
5340
5341ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
5342 SourceLocation KWLoc,
5343 Expr *Queried,
5344 SourceLocation RParen) {
5345 // If error parsing the expression, ignore.
5346 if (!Queried)
5347 return ExprError();
5348
5349 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
5350
5351 return Result;
5352}
5353
5354static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
5355 switch (ET) {
5356 case ET_IsLValueExpr: return E->isLValue();
5357 case ET_IsRValueExpr: return E->isRValue();
5358 }
5359 llvm_unreachable("Expression trait not covered by switch")::llvm::llvm_unreachable_internal("Expression trait not covered by switch"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5359)
;
5360}
5361
5362ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
5363 SourceLocation KWLoc,
5364 Expr *Queried,
5365 SourceLocation RParen) {
5366 if (Queried->isTypeDependent()) {
5367 // Delay type-checking for type-dependent expressions.
5368 } else if (Queried->getType()->isPlaceholderType()) {
5369 ExprResult PE = CheckPlaceholderExpr(Queried);
5370 if (PE.isInvalid()) return ExprError();
5371 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
5372 }
5373
5374 bool Value = EvaluateExpressionTrait(ET, Queried);
5375
5376 return new (Context)
5377 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
5378}
5379
5380QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
5381 ExprValueKind &VK,
5382 SourceLocation Loc,
5383 bool isIndirect) {
5384 assert(!LHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5386, __PRETTY_FUNCTION__))
5385 !RHS.get()->getType()->isPlaceholderType() &&((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5386, __PRETTY_FUNCTION__))
5386 "placeholders should have been weeded out by now")((!LHS.get()->getType()->isPlaceholderType() &&
!RHS.get()->getType()->isPlaceholderType() && "placeholders should have been weeded out by now"
) ? static_cast<void> (0) : __assert_fail ("!LHS.get()->getType()->isPlaceholderType() && !RHS.get()->getType()->isPlaceholderType() && \"placeholders should have been weeded out by now\""
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5386, __PRETTY_FUNCTION__))
;
5387
5388 // The LHS undergoes lvalue conversions if this is ->*, and undergoes the
5389 // temporary materialization conversion otherwise.
5390 if (isIndirect)
5391 LHS = DefaultLvalueConversion(LHS.get());
5392 else if (LHS.get()->isRValue())
5393 LHS = TemporaryMaterializationConversion(LHS.get());
5394 if (LHS.isInvalid())
5395 return QualType();
5396
5397 // The RHS always undergoes lvalue conversions.
5398 RHS = DefaultLvalueConversion(RHS.get());
5399 if (RHS.isInvalid()) return QualType();
5400
5401 const char *OpSpelling = isIndirect ? "->*" : ".*";
5402 // C++ 5.5p2
5403 // The binary operator .* [p3: ->*] binds its second operand, which shall
5404 // be of type "pointer to member of T" (where T is a completely-defined
5405 // class type) [...]
5406 QualType RHSType = RHS.get()->getType();
5407 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
5408 if (!MemPtr) {
5409 Diag(Loc, diag::err_bad_memptr_rhs)
5410 << OpSpelling << RHSType << RHS.get()->getSourceRange();
5411 return QualType();
5412 }
5413
5414 QualType Class(MemPtr->getClass(), 0);
5415
5416 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
5417 // member pointer points must be completely-defined. However, there is no
5418 // reason for this semantic distinction, and the rule is not enforced by
5419 // other compilers. Therefore, we do not check this property, as it is
5420 // likely to be considered a defect.
5421
5422 // C++ 5.5p2
5423 // [...] to its first operand, which shall be of class T or of a class of
5424 // which T is an unambiguous and accessible base class. [p3: a pointer to
5425 // such a class]
5426 QualType LHSType = LHS.get()->getType();
5427 if (isIndirect) {
5428 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
5429 LHSType = Ptr->getPointeeType();
5430 else {
5431 Diag(Loc, diag::err_bad_memptr_lhs)
5432 << OpSpelling << 1 << LHSType
5433 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
5434 return QualType();
5435 }
5436 }
5437
5438 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
5439 // If we want to check the hierarchy, we need a complete type.
5440 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
5441 OpSpelling, (int)isIndirect)) {
5442 return QualType();
5443 }
5444
5445 if (!IsDerivedFrom(Loc, LHSType, Class)) {
5446 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
5447 << (int)isIndirect << LHS.get()->getType();
5448 return QualType();
5449 }
5450
5451 CXXCastPath BasePath;
5452 if (CheckDerivedToBaseConversion(
5453 LHSType, Class, Loc,
5454 SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()),
5455 &BasePath))
5456 return QualType();
5457
5458 // Cast LHS to type of use.
5459 QualType UseType = Context.getQualifiedType(Class, LHSType.getQualifiers());
5460 if (isIndirect)
5461 UseType = Context.getPointerType(UseType);
5462 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
5463 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
5464 &BasePath);
5465 }
5466
5467 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
5468 // Diagnose use of pointer-to-member type which when used as
5469 // the functional cast in a pointer-to-member expression.
5470 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
5471 return QualType();
5472 }
5473
5474 // C++ 5.5p2
5475 // The result is an object or a function of the type specified by the
5476 // second operand.
5477 // The cv qualifiers are the union of those in the pointer and the left side,
5478 // in accordance with 5.5p5 and 5.2.5.
5479 QualType Result = MemPtr->getPointeeType();
5480 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
5481
5482 // C++0x [expr.mptr.oper]p6:
5483 // In a .* expression whose object expression is an rvalue, the program is
5484 // ill-formed if the second operand is a pointer to member function with
5485 // ref-qualifier &. In a ->* expression or in a .* expression whose object
5486 // expression is an lvalue, the program is ill-formed if the second operand
5487 // is a pointer to member function with ref-qualifier &&.
5488 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
5489 switch (Proto->getRefQualifier()) {
5490 case RQ_None:
5491 // Do nothing
5492 break;
5493
5494 case RQ_LValue:
5495 if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) {
5496 // C++2a allows functions with ref-qualifier & if their cv-qualifier-seq
5497 // is (exactly) 'const'.
5498 if (Proto->isConst() && !Proto->isVolatile())
5499 Diag(Loc, getLangOpts().CPlusPlus2a
5500 ? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue
5501 : diag::ext_pointer_to_const_ref_member_on_rvalue);
5502 else
5503 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5504 << RHSType << 1 << LHS.get()->getSourceRange();
5505 }
5506 break;
5507
5508 case RQ_RValue:
5509 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
5510 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
5511 << RHSType << 0 << LHS.get()->getSourceRange();
5512 break;
5513 }
5514 }
5515
5516 // C++ [expr.mptr.oper]p6:
5517 // The result of a .* expression whose second operand is a pointer
5518 // to a data member is of the same value category as its
5519 // first operand. The result of a .* expression whose second
5520 // operand is a pointer to a member function is a prvalue. The
5521 // result of an ->* expression is an lvalue if its second operand
5522 // is a pointer to data member and a prvalue otherwise.
5523 if (Result->isFunctionType()) {
5524 VK = VK_RValue;
5525 return Context.BoundMemberTy;
5526 } else if (isIndirect) {
5527 VK = VK_LValue;
5528 } else {
5529 VK = LHS.get()->getValueKind();
5530 }
5531
5532 return Result;
5533}
5534
5535/// Try to convert a type to another according to C++11 5.16p3.
5536///
5537/// This is part of the parameter validation for the ? operator. If either
5538/// value operand is a class type, the two operands are attempted to be
5539/// converted to each other. This function does the conversion in one direction.
5540/// It returns true if the program is ill-formed and has already been diagnosed
5541/// as such.
5542static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
5543 SourceLocation QuestionLoc,
5544 bool &HaveConversion,
5545 QualType &ToType) {
5546 HaveConversion = false;
5547 ToType = To->getType();
5548
5549 InitializationKind Kind =
5550 InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation());
5551 // C++11 5.16p3
5552 // The process for determining whether an operand expression E1 of type T1
5553 // can be converted to match an operand expression E2 of type T2 is defined
5554 // as follows:
5555 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
5556 // implicitly converted to type "lvalue reference to T2", subject to the
5557 // constraint that in the conversion the reference must bind directly to
5558 // an lvalue.
5559 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
5560 // implicitly converted to the type "rvalue reference to R2", subject to
5561 // the constraint that the reference must bind directly.
5562 if (To->isLValue() || To->isXValue()) {
5563 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
5564 : Self.Context.getRValueReferenceType(ToType);
5565
5566 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5567
5568 InitializationSequence InitSeq(Self, Entity, Kind, From);
5569 if (InitSeq.isDirectReferenceBinding()) {
5570 ToType = T;
5571 HaveConversion = true;
5572 return false;
5573 }
5574
5575 if (InitSeq.isAmbiguous())
5576 return InitSeq.Diagnose(Self, Entity, Kind, From);
5577 }
5578
5579 // -- If E2 is an rvalue, or if the conversion above cannot be done:
5580 // -- if E1 and E2 have class type, and the underlying class types are
5581 // the same or one is a base class of the other:
5582 QualType FTy = From->getType();
5583 QualType TTy = To->getType();
5584 const RecordType *FRec = FTy->getAs<RecordType>();
5585 const RecordType *TRec = TTy->getAs<RecordType>();
5586 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
5587 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
5588 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
5589 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
5590 // E1 can be converted to match E2 if the class of T2 is the
5591 // same type as, or a base class of, the class of T1, and
5592 // [cv2 > cv1].
5593 if (FRec == TRec || FDerivedFromT) {
5594 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
5595 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5596 InitializationSequence InitSeq(Self, Entity, Kind, From);
5597 if (InitSeq) {
5598 HaveConversion = true;
5599 return false;
5600 }
5601
5602 if (InitSeq.isAmbiguous())
5603 return InitSeq.Diagnose(Self, Entity, Kind, From);
5604 }
5605 }
5606
5607 return false;
5608 }
5609
5610 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5611 // implicitly converted to the type that expression E2 would have
5612 // if E2 were converted to an rvalue (or the type it has, if E2 is
5613 // an rvalue).
5614 //
5615 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5616 // to the array-to-pointer or function-to-pointer conversions.
5617 TTy = TTy.getNonLValueExprType(Self.Context);
5618
5619 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5620 InitializationSequence InitSeq(Self, Entity, Kind, From);
5621 HaveConversion = !InitSeq.Failed();
5622 ToType = TTy;
5623 if (InitSeq.isAmbiguous())
5624 return InitSeq.Diagnose(Self, Entity, Kind, From);
5625
5626 return false;
5627}
5628
5629/// Try to find a common type for two according to C++0x 5.16p5.
5630///
5631/// This is part of the parameter validation for the ? operator. If either
5632/// value operand is a class type, overload resolution is used to find a
5633/// conversion to a common type.
5634static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5635 SourceLocation QuestionLoc) {
5636 Expr *Args[2] = { LHS.get(), RHS.get() };
5637 OverloadCandidateSet CandidateSet(QuestionLoc,
5638 OverloadCandidateSet::CSK_Operator);
5639 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5640 CandidateSet);
5641
5642 OverloadCandidateSet::iterator Best;
5643 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5644 case OR_Success: {
5645 // We found a match. Perform the conversions on the arguments and move on.
5646 ExprResult LHSRes = Self.PerformImplicitConversion(
5647 LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0],
5648 Sema::AA_Converting);
5649 if (LHSRes.isInvalid())
5650 break;
5651 LHS = LHSRes;
5652
5653 ExprResult RHSRes = Self.PerformImplicitConversion(
5654 RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1],
5655 Sema::AA_Converting);
5656 if (RHSRes.isInvalid())
5657 break;
5658 RHS = RHSRes;
5659 if (Best->Function)
5660 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5661 return false;
5662 }
5663
5664 case OR_No_Viable_Function:
5665
5666 // Emit a better diagnostic if one of the expressions is a null pointer
5667 // constant and the other is a pointer type. In this case, the user most
5668 // likely forgot to take the address of the other expression.
5669 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5670 return true;
5671
5672 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5673 << LHS.get()->getType() << RHS.get()->getType()
5674 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5675 return true;
5676
5677 case OR_Ambiguous:
5678 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5679 << LHS.get()->getType() << RHS.get()->getType()
5680 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5681 // FIXME: Print the possible common types by printing the return types of
5682 // the viable candidates.
5683 break;
5684
5685 case OR_Deleted:
5686 llvm_unreachable("Conditional operator has only built-in overloads")::llvm::llvm_unreachable_internal("Conditional operator has only built-in overloads"
, "/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/Sema/SemaExprCXX.cpp"
, 5686)
;
5687 }
5688 return true;
5689}
5690
5691/// Perform an "extended" implicit conversion as returned by
5692/// TryClassUnification.
5693static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5694 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5695 InitializationKind Kind =
5696 InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation());
5697 Expr *Arg = E.get();
5698 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5699 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5700 if (Result.isInvalid())
5701 return true;
5702
5703 E = Result;
5704 return false;
5705}
5706
5707/// Check the operands of ?: under C++ semantics.
5708///
5709/// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5710/// extension. In this case, LHS == Cond. (But they're not aliases.)
5711QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5712 ExprResult &RHS, ExprValueKind &VK,
5713 ExprObjectKind &OK,
5714 SourceLocation QuestionLoc) {
5715 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5716 // interface pointers.
5717
5718 // C++11 [expr.cond]p1
5719 // The first expression is contextually converted to bool.
5720 //
5721 // FIXME; GCC's vector extension permits the use of a?b:c where the type of
5722 // a is that of a integer vector with the same number of elements and
5723 // size as the vectors of b and c. If one of either b or c is a scalar
5724 // it is implicitly converted to match the type of the vector.
5725 // Otherwise the expression is ill-formed. If both b and c are scalars,
5726 // then b and c are checked and converted to the type of a if possible.
5727 // Unlike the OpenCL ?: operator, the expression is evaluated as
5728 // (a[0] != 0 ? b[0] : c[0], .. , a[n] != 0 ? b[n] : c[n]).
5729 if (!Cond.get()->isTypeDependent()) {
5730 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5731 if (CondRes.isInvalid())
5732 return QualType();
5733 Cond = CondRes;
5734 }
5735
5736 // Assume r-value.
5737 VK = VK_RValue;
5738 OK = OK_Ordinary;
5739
5740 // Either of the arguments dependent?
5741 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5742 return Context.DependentTy;
5743
5744 // C++11 [expr.cond]p2
5745 // If either the second or the third operand has type (cv) void, ...
5746 QualType LTy = LHS.get()->getType();
5747 QualType RTy = RHS.get()->getType();
5748 bool LVoid = LTy->isVoidType();
5749 bool RVoid = RTy->isVoidType();
5750 if (LVoid || RVoid) {
5751 // ... one of the following shall hold:
5752 // -- The second or the third operand (but not both) is a (possibly
5753 // parenthesized) throw-expression; the result is of the type
5754 // and value category of the other.
5755 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5756 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5757 if (LThrow != RThrow) {
5758 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5759 VK = NonThrow->getValueKind();
5760 // DR (no number yet): the result is a bit-field if the
5761 // non-throw-expression operand is a bit-field.
5762 OK = NonThrow->getObjectKind();
5763 return NonThrow->getType();
5764 }
5765
5766 // -- Both the second and third operands have type void; the result is of
5767 // type void and is a prvalue.
5768 if (LVoid && RVoid)
5769 return Context.VoidTy;
5770
5771 // Neither holds, error.
5772 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5773 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5774 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5775 return QualType();
5776 }
5777
5778 // Neither is void.
5779
5780 // C++11 [expr.cond]p3
5781 // Otherwise, if the second and third operand have different types, and
5782 // either has (cv) class type [...] an attempt is made to convert each of
5783 // those operands to the type of the other.
5784 if (!Context.hasSameType(LTy, RTy) &&
5785 (LTy->isRecordType() || RTy->isRecordType())) {
5786 // These return true if a single direction is already ambiguous.
5787 QualType L2RType, R2LType;
5788 bool HaveL2R, HaveR2L;
5789 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5790 return QualType();
5791 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5792 return QualType();
5793
5794 // If both can be converted, [...] the program is ill-formed.
5795 if (HaveL2R && HaveR2L) {
5796 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5797 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5798 return QualType();
5799 }
5800
5801 // If exactly one conversion is possible, that conversion is applied to
5802 // the chosen operand and the converted operands are used in place of the
5803 // original operands for the remainder of this section.
5804 if (HaveL2R) {
5805 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5806 return QualType();
5807 LTy = LHS.get()->getType();
5808 } else if (HaveR2L) {
5809 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5810 return QualType();
5811 RTy = RHS.get()->getType();
5812 }
5813 }
5814
5815 // C++11 [expr.cond]p3
5816 // if both are glvalues of the same value category and the same type except
5817 // for cv-qualification, an attempt is made to convert each of those
5818 // operands to the type of the other.
5819 // FIXME:
5820 // Resolving a defect in P0012R1: we extend this to cover all cases where
5821 // one of the operands is reference-compatible with the other, in order
5822 // to support conditionals between functions differing in noexcept.
5823 ExprValueKind LVK = LHS.get()->getValueKind();
5824 ExprValueKind RVK = RHS.get()->getValueKind();
5825 if (!Context.hasSameType(LTy, RTy) &&
5826 LVK == RVK && LVK != VK_RValue) {
5827 // DerivedToBase was already handled by the class-specific case above.
5828 // FIXME: Should we allow ObjC conversions here?
5829 bool DerivedToBase, ObjCConversion, ObjCLifetimeConversion;
5830 if (CompareReferenceRelationship(
5831 QuestionLoc, LTy, RTy, DerivedToBase,
5832 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5833 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5834 // [...] subject to the constraint that the reference must bind
5835 // directly [...]
5836 !RHS.get()->refersToBitField() &&
5837 !RHS.get()->refersToVectorElement()) {
5838 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5839 RTy = RHS.get()->getType();
5840 } else if (CompareReferenceRelationship(
5841 QuestionLoc, RTy, LTy, DerivedToBase,
5842 ObjCConversion, ObjCLifetimeConversion) == Ref_Compatible &&
5843 !DerivedToBase && !ObjCConversion && !ObjCLifetimeConversion &&
5844 !LHS.get()->refersToBitField() &&
5845 !LHS.get()->refersToVectorElement()) {
5846 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5847 LTy = LHS.get()->getType();
5848 }
5849 }
5850
5851 // C++11 [expr.cond]p4
5852 // If the second and third operands are glvalues of the same value
5853 // category and have the same type, the result is of that type and
5854 // value category and it is a bit-field if the second or the third
5855 // operand is a bit-field, or if both are bit-fields.
5856 // We only extend this to bitfields, not to the crazy other kinds of
5857 // l-values.
5858 bool Same = Context.hasSameType(LTy, RTy);
5859 if (Same && LVK == RVK && LVK != VK_RValue &&
5860 LHS.get()->isOrdinaryOrBitFieldObject() &&
5861 RHS.get()->isOrdinaryOrBitFieldObject()) {
5862 VK = LHS.get()->getValueKind();
5863 if (LHS.get()->getObjectKind() == OK_BitField ||
5864 RHS.get()->getObjectKind() == OK_BitField)
5865 OK = OK_BitField;
5866