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 /// \brief 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/PartialDiagnostic.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/Initialization.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/Scope.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaLambda.h"
37 #include "clang/Sema/TemplateDeduction.h"
38 #include "llvm/ADT/APInt.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/Support/ErrorHandling.h"
41 using namespace clang;
42 using namespace sema;
43
44 /// \brief Handle the result of the special case name lookup for inheriting
45 /// constructor declarations. 'NS::X::X' and 'NS::X<...>::X' are treated as
46 /// constructor names in member using declarations, even if 'X' is not the
47 /// name of the corresponding type.
getInheritingConstructorName(CXXScopeSpec & SS,SourceLocation NameLoc,IdentifierInfo & Name)48 ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS,
49 SourceLocation NameLoc,
50 IdentifierInfo &Name) {
51 NestedNameSpecifier *NNS = SS.getScopeRep();
52
53 // Convert the nested-name-specifier into a type.
54 QualType Type;
55 switch (NNS->getKind()) {
56 case NestedNameSpecifier::TypeSpec:
57 case NestedNameSpecifier::TypeSpecWithTemplate:
58 Type = QualType(NNS->getAsType(), 0);
59 break;
60
61 case NestedNameSpecifier::Identifier:
62 // Strip off the last layer of the nested-name-specifier and build a
63 // typename type for it.
64 assert(NNS->getAsIdentifier() == &Name && "not a constructor name");
65 Type = Context.getDependentNameType(ETK_None, NNS->getPrefix(),
66 NNS->getAsIdentifier());
67 break;
68
69 case NestedNameSpecifier::Global:
70 case NestedNameSpecifier::Super:
71 case NestedNameSpecifier::Namespace:
72 case NestedNameSpecifier::NamespaceAlias:
73 llvm_unreachable("Nested name specifier is not a type for inheriting ctor");
74 }
75
76 // This reference to the type is located entirely at the location of the
77 // final identifier in the qualified-id.
78 return CreateParsedType(Type,
79 Context.getTrivialTypeSourceInfo(Type, NameLoc));
80 }
81
getDestructorName(SourceLocation TildeLoc,IdentifierInfo & II,SourceLocation NameLoc,Scope * S,CXXScopeSpec & SS,ParsedType ObjectTypePtr,bool EnteringContext)82 ParsedType Sema::getDestructorName(SourceLocation TildeLoc,
83 IdentifierInfo &II,
84 SourceLocation NameLoc,
85 Scope *S, CXXScopeSpec &SS,
86 ParsedType ObjectTypePtr,
87 bool EnteringContext) {
88 // Determine where to perform name lookup.
89
90 // FIXME: This area of the standard is very messy, and the current
91 // wording is rather unclear about which scopes we search for the
92 // destructor name; see core issues 399 and 555. Issue 399 in
93 // particular shows where the current description of destructor name
94 // lookup is completely out of line with existing practice, e.g.,
95 // this appears to be ill-formed:
96 //
97 // namespace N {
98 // template <typename T> struct S {
99 // ~S();
100 // };
101 // }
102 //
103 // void f(N::S<int>* s) {
104 // s->N::S<int>::~S();
105 // }
106 //
107 // See also PR6358 and PR6359.
108 // For this reason, we're currently only doing the C++03 version of this
109 // code; the C++0x version has to wait until we get a proper spec.
110 QualType SearchType;
111 DeclContext *LookupCtx = nullptr;
112 bool isDependent = false;
113 bool LookInScope = false;
114
115 if (SS.isInvalid())
116 return nullptr;
117
118 // If we have an object type, it's because we are in a
119 // pseudo-destructor-expression or a member access expression, and
120 // we know what type we're looking for.
121 if (ObjectTypePtr)
122 SearchType = GetTypeFromParser(ObjectTypePtr);
123
124 if (SS.isSet()) {
125 NestedNameSpecifier *NNS = SS.getScopeRep();
126
127 bool AlreadySearched = false;
128 bool LookAtPrefix = true;
129 // C++11 [basic.lookup.qual]p6:
130 // If a pseudo-destructor-name (5.2.4) contains a nested-name-specifier,
131 // the type-names are looked up as types in the scope designated by the
132 // nested-name-specifier. Similarly, in a qualified-id of the form:
133 //
134 // nested-name-specifier[opt] class-name :: ~ class-name
135 //
136 // the second class-name is looked up in the same scope as the first.
137 //
138 // Here, we determine whether the code below is permitted to look at the
139 // prefix of the nested-name-specifier.
140 DeclContext *DC = computeDeclContext(SS, EnteringContext);
141 if (DC && DC->isFileContext()) {
142 AlreadySearched = true;
143 LookupCtx = DC;
144 isDependent = false;
145 } else if (DC && isa<CXXRecordDecl>(DC)) {
146 LookAtPrefix = false;
147 LookInScope = true;
148 }
149
150 // The second case from the C++03 rules quoted further above.
151 NestedNameSpecifier *Prefix = nullptr;
152 if (AlreadySearched) {
153 // Nothing left to do.
154 } else if (LookAtPrefix && (Prefix = NNS->getPrefix())) {
155 CXXScopeSpec PrefixSS;
156 PrefixSS.Adopt(NestedNameSpecifierLoc(Prefix, SS.location_data()));
157 LookupCtx = computeDeclContext(PrefixSS, EnteringContext);
158 isDependent = isDependentScopeSpecifier(PrefixSS);
159 } else if (ObjectTypePtr) {
160 LookupCtx = computeDeclContext(SearchType);
161 isDependent = SearchType->isDependentType();
162 } else {
163 LookupCtx = computeDeclContext(SS, EnteringContext);
164 isDependent = LookupCtx && LookupCtx->isDependentContext();
165 }
166 } else if (ObjectTypePtr) {
167 // C++ [basic.lookup.classref]p3:
168 // If the unqualified-id is ~type-name, the type-name is looked up
169 // in the context of the entire postfix-expression. If the type T
170 // of the object expression is of a class type C, the type-name is
171 // also looked up in the scope of class C. At least one of the
172 // lookups shall find a name that refers to (possibly
173 // cv-qualified) T.
174 LookupCtx = computeDeclContext(SearchType);
175 isDependent = SearchType->isDependentType();
176 assert((isDependent || !SearchType->isIncompleteType()) &&
177 "Caller should have completed object type");
178
179 LookInScope = true;
180 } else {
181 // Perform lookup into the current scope (only).
182 LookInScope = true;
183 }
184
185 TypeDecl *NonMatchingTypeDecl = nullptr;
186 LookupResult Found(*this, &II, NameLoc, LookupOrdinaryName);
187 for (unsigned Step = 0; Step != 2; ++Step) {
188 // Look for the name first in the computed lookup context (if we
189 // have one) and, if that fails to find a match, in the scope (if
190 // we're allowed to look there).
191 Found.clear();
192 if (Step == 0 && LookupCtx)
193 LookupQualifiedName(Found, LookupCtx);
194 else if (Step == 1 && LookInScope && S)
195 LookupName(Found, S);
196 else
197 continue;
198
199 // FIXME: Should we be suppressing ambiguities here?
200 if (Found.isAmbiguous())
201 return nullptr;
202
203 if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) {
204 QualType T = Context.getTypeDeclType(Type);
205 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
206
207 if (SearchType.isNull() || SearchType->isDependentType() ||
208 Context.hasSameUnqualifiedType(T, SearchType)) {
209 // We found our type!
210
211 return CreateParsedType(T,
212 Context.getTrivialTypeSourceInfo(T, NameLoc));
213 }
214
215 if (!SearchType.isNull())
216 NonMatchingTypeDecl = Type;
217 }
218
219 // If the name that we found is a class template name, and it is
220 // the same name as the template name in the last part of the
221 // nested-name-specifier (if present) or the object type, then
222 // this is the destructor for that class.
223 // FIXME: This is a workaround until we get real drafting for core
224 // issue 399, for which there isn't even an obvious direction.
225 if (ClassTemplateDecl *Template = Found.getAsSingle<ClassTemplateDecl>()) {
226 QualType MemberOfType;
227 if (SS.isSet()) {
228 if (DeclContext *Ctx = computeDeclContext(SS, EnteringContext)) {
229 // Figure out the type of the context, if it has one.
230 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx))
231 MemberOfType = Context.getTypeDeclType(Record);
232 }
233 }
234 if (MemberOfType.isNull())
235 MemberOfType = SearchType;
236
237 if (MemberOfType.isNull())
238 continue;
239
240 // We're referring into a class template specialization. If the
241 // class template we found is the same as the template being
242 // specialized, we found what we are looking for.
243 if (const RecordType *Record = MemberOfType->getAs<RecordType>()) {
244 if (ClassTemplateSpecializationDecl *Spec
245 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
246 if (Spec->getSpecializedTemplate()->getCanonicalDecl() ==
247 Template->getCanonicalDecl())
248 return CreateParsedType(
249 MemberOfType,
250 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
251 }
252
253 continue;
254 }
255
256 // We're referring to an unresolved class template
257 // specialization. Determine whether we class template we found
258 // is the same as the template being specialized or, if we don't
259 // know which template is being specialized, that it at least
260 // has the same name.
261 if (const TemplateSpecializationType *SpecType
262 = MemberOfType->getAs<TemplateSpecializationType>()) {
263 TemplateName SpecName = SpecType->getTemplateName();
264
265 // The class template we found is the same template being
266 // specialized.
267 if (TemplateDecl *SpecTemplate = SpecName.getAsTemplateDecl()) {
268 if (SpecTemplate->getCanonicalDecl() == Template->getCanonicalDecl())
269 return CreateParsedType(
270 MemberOfType,
271 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
272
273 continue;
274 }
275
276 // The class template we found has the same name as the
277 // (dependent) template name being specialized.
278 if (DependentTemplateName *DepTemplate
279 = SpecName.getAsDependentTemplateName()) {
280 if (DepTemplate->isIdentifier() &&
281 DepTemplate->getIdentifier() == Template->getIdentifier())
282 return CreateParsedType(
283 MemberOfType,
284 Context.getTrivialTypeSourceInfo(MemberOfType, NameLoc));
285
286 continue;
287 }
288 }
289 }
290 }
291
292 if (isDependent) {
293 // We didn't find our type, but that's okay: it's dependent
294 // anyway.
295
296 // FIXME: What if we have no nested-name-specifier?
297 QualType T = CheckTypenameType(ETK_None, SourceLocation(),
298 SS.getWithLocInContext(Context),
299 II, NameLoc);
300 return ParsedType::make(T);
301 }
302
303 if (NonMatchingTypeDecl) {
304 QualType T = Context.getTypeDeclType(NonMatchingTypeDecl);
305 Diag(NameLoc, diag::err_destructor_expr_type_mismatch)
306 << T << SearchType;
307 Diag(NonMatchingTypeDecl->getLocation(), diag::note_destructor_type_here)
308 << T;
309 } else if (ObjectTypePtr)
310 Diag(NameLoc, diag::err_ident_in_dtor_not_a_type)
311 << &II;
312 else {
313 SemaDiagnosticBuilder DtorDiag = Diag(NameLoc,
314 diag::err_destructor_class_name);
315 if (S) {
316 const DeclContext *Ctx = S->getEntity();
317 if (const CXXRecordDecl *Class = dyn_cast_or_null<CXXRecordDecl>(Ctx))
318 DtorDiag << FixItHint::CreateReplacement(SourceRange(NameLoc),
319 Class->getNameAsString());
320 }
321 }
322
323 return nullptr;
324 }
325
getDestructorType(const DeclSpec & DS,ParsedType ObjectType)326 ParsedType Sema::getDestructorType(const DeclSpec& DS, ParsedType ObjectType) {
327 if (DS.getTypeSpecType() == DeclSpec::TST_error || !ObjectType)
328 return nullptr;
329 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype
330 && "only get destructor types from declspecs");
331 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
332 QualType SearchType = GetTypeFromParser(ObjectType);
333 if (SearchType->isDependentType() || Context.hasSameUnqualifiedType(SearchType, T)) {
334 return ParsedType::make(T);
335 }
336
337 Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch)
338 << T << SearchType;
339 return nullptr;
340 }
341
checkLiteralOperatorId(const CXXScopeSpec & SS,const UnqualifiedId & Name)342 bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS,
343 const UnqualifiedId &Name) {
344 assert(Name.getKind() == UnqualifiedId::IK_LiteralOperatorId);
345
346 if (!SS.isValid())
347 return false;
348
349 switch (SS.getScopeRep()->getKind()) {
350 case NestedNameSpecifier::Identifier:
351 case NestedNameSpecifier::TypeSpec:
352 case NestedNameSpecifier::TypeSpecWithTemplate:
353 // Per C++11 [over.literal]p2, literal operators can only be declared at
354 // namespace scope. Therefore, this unqualified-id cannot name anything.
355 // Reject it early, because we have no AST representation for this in the
356 // case where the scope is dependent.
357 Diag(Name.getLocStart(), diag::err_literal_operator_id_outside_namespace)
358 << SS.getScopeRep();
359 return true;
360
361 case NestedNameSpecifier::Global:
362 case NestedNameSpecifier::Super:
363 case NestedNameSpecifier::Namespace:
364 case NestedNameSpecifier::NamespaceAlias:
365 return false;
366 }
367
368 llvm_unreachable("unknown nested name specifier kind");
369 }
370
371 /// \brief Build a C++ typeid expression with a type operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)372 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
373 SourceLocation TypeidLoc,
374 TypeSourceInfo *Operand,
375 SourceLocation RParenLoc) {
376 // C++ [expr.typeid]p4:
377 // The top-level cv-qualifiers of the lvalue expression or the type-id
378 // that is the operand of typeid are always ignored.
379 // If the type of the type-id is a class type or a reference to a class
380 // type, the class shall be completely-defined.
381 Qualifiers Quals;
382 QualType T
383 = Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(),
384 Quals);
385 if (T->getAs<RecordType>() &&
386 RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
387 return ExprError();
388
389 if (T->isVariablyModifiedType())
390 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T);
391
392 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand,
393 SourceRange(TypeidLoc, RParenLoc));
394 }
395
396 /// \brief Build a C++ typeid expression with an expression operand.
BuildCXXTypeId(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)397 ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType,
398 SourceLocation TypeidLoc,
399 Expr *E,
400 SourceLocation RParenLoc) {
401 bool WasEvaluated = false;
402 if (E && !E->isTypeDependent()) {
403 if (E->getType()->isPlaceholderType()) {
404 ExprResult result = CheckPlaceholderExpr(E);
405 if (result.isInvalid()) return ExprError();
406 E = result.get();
407 }
408
409 QualType T = E->getType();
410 if (const RecordType *RecordT = T->getAs<RecordType>()) {
411 CXXRecordDecl *RecordD = cast<CXXRecordDecl>(RecordT->getDecl());
412 // C++ [expr.typeid]p3:
413 // [...] If the type of the expression is a class type, the class
414 // shall be completely-defined.
415 if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid))
416 return ExprError();
417
418 // C++ [expr.typeid]p3:
419 // When typeid is applied to an expression other than an glvalue of a
420 // polymorphic class type [...] [the] expression is an unevaluated
421 // operand. [...]
422 if (RecordD->isPolymorphic() && E->isGLValue()) {
423 // The subexpression is potentially evaluated; switch the context
424 // and recheck the subexpression.
425 ExprResult Result = TransformToPotentiallyEvaluated(E);
426 if (Result.isInvalid()) return ExprError();
427 E = Result.get();
428
429 // We require a vtable to query the type at run time.
430 MarkVTableUsed(TypeidLoc, RecordD);
431 WasEvaluated = true;
432 }
433 }
434
435 // C++ [expr.typeid]p4:
436 // [...] If the type of the type-id is a reference to a possibly
437 // cv-qualified type, the result of the typeid expression refers to a
438 // std::type_info object representing the cv-unqualified referenced
439 // type.
440 Qualifiers Quals;
441 QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals);
442 if (!Context.hasSameType(T, UnqualT)) {
443 T = UnqualT;
444 E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get();
445 }
446 }
447
448 if (E->getType()->isVariablyModifiedType())
449 return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid)
450 << E->getType());
451 else if (ActiveTemplateInstantiations.empty() &&
452 E->HasSideEffects(Context, WasEvaluated)) {
453 // The expression operand for typeid is in an unevaluated expression
454 // context, so side effects could result in unintended consequences.
455 Diag(E->getExprLoc(), WasEvaluated
456 ? diag::warn_side_effects_typeid
457 : diag::warn_side_effects_unevaluated_context);
458 }
459
460 return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E,
461 SourceRange(TypeidLoc, RParenLoc));
462 }
463
464 /// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression);
465 ExprResult
ActOnCXXTypeid(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)466 Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc,
467 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
468 // Find the std::type_info type.
469 if (!getStdNamespace())
470 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
471
472 if (!CXXTypeInfoDecl) {
473 IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info");
474 LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName);
475 LookupQualifiedName(R, getStdNamespace());
476 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
477 // Microsoft's typeinfo doesn't have type_info in std but in the global
478 // namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153.
479 if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) {
480 LookupQualifiedName(R, Context.getTranslationUnitDecl());
481 CXXTypeInfoDecl = R.getAsSingle<RecordDecl>();
482 }
483 if (!CXXTypeInfoDecl)
484 return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid));
485 }
486
487 if (!getLangOpts().RTTI) {
488 return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti));
489 }
490
491 QualType TypeInfoType = Context.getTypeDeclType(CXXTypeInfoDecl);
492
493 if (isType) {
494 // The operand is a type; handle it as such.
495 TypeSourceInfo *TInfo = nullptr;
496 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
497 &TInfo);
498 if (T.isNull())
499 return ExprError();
500
501 if (!TInfo)
502 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
503
504 return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc);
505 }
506
507 // The operand is an expression.
508 return BuildCXXTypeId(TypeInfoType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
509 }
510
511 /// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to
512 /// a single GUID.
513 static void
getUuidAttrOfType(Sema & SemaRef,QualType QT,llvm::SmallSetVector<const UuidAttr *,1> & UuidAttrs)514 getUuidAttrOfType(Sema &SemaRef, QualType QT,
515 llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) {
516 // Optionally remove one level of pointer, reference or array indirection.
517 const Type *Ty = QT.getTypePtr();
518 if (QT->isPointerType() || QT->isReferenceType())
519 Ty = QT->getPointeeType().getTypePtr();
520 else if (QT->isArrayType())
521 Ty = Ty->getBaseElementTypeUnsafe();
522
523 const auto *RD = Ty->getAsCXXRecordDecl();
524 if (!RD)
525 return;
526
527 if (const auto *Uuid = RD->getMostRecentDecl()->getAttr<UuidAttr>()) {
528 UuidAttrs.insert(Uuid);
529 return;
530 }
531
532 // __uuidof can grab UUIDs from template arguments.
533 if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
534 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
535 for (const TemplateArgument &TA : TAL.asArray()) {
536 const UuidAttr *UuidForTA = nullptr;
537 if (TA.getKind() == TemplateArgument::Type)
538 getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs);
539 else if (TA.getKind() == TemplateArgument::Declaration)
540 getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs);
541
542 if (UuidForTA)
543 UuidAttrs.insert(UuidForTA);
544 }
545 }
546 }
547
548 /// \brief Build a Microsoft __uuidof expression with a type operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,TypeSourceInfo * Operand,SourceLocation RParenLoc)549 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
550 SourceLocation TypeidLoc,
551 TypeSourceInfo *Operand,
552 SourceLocation RParenLoc) {
553 StringRef UuidStr;
554 if (!Operand->getType()->isDependentType()) {
555 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
556 getUuidAttrOfType(*this, Operand->getType(), UuidAttrs);
557 if (UuidAttrs.empty())
558 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
559 if (UuidAttrs.size() > 1)
560 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
561 UuidStr = UuidAttrs.back()->getGuid();
562 }
563
564 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), Operand, UuidStr,
565 SourceRange(TypeidLoc, RParenLoc));
566 }
567
568 /// \brief Build a Microsoft __uuidof expression with an expression operand.
BuildCXXUuidof(QualType TypeInfoType,SourceLocation TypeidLoc,Expr * E,SourceLocation RParenLoc)569 ExprResult Sema::BuildCXXUuidof(QualType TypeInfoType,
570 SourceLocation TypeidLoc,
571 Expr *E,
572 SourceLocation RParenLoc) {
573 StringRef UuidStr;
574 if (!E->getType()->isDependentType()) {
575 if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
576 UuidStr = "00000000-0000-0000-0000-000000000000";
577 } else {
578 llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs;
579 getUuidAttrOfType(*this, E->getType(), UuidAttrs);
580 if (UuidAttrs.empty())
581 return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid));
582 if (UuidAttrs.size() > 1)
583 return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids));
584 UuidStr = UuidAttrs.back()->getGuid();
585 }
586 }
587
588 return new (Context) CXXUuidofExpr(TypeInfoType.withConst(), E, UuidStr,
589 SourceRange(TypeidLoc, RParenLoc));
590 }
591
592 /// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression);
593 ExprResult
ActOnCXXUuidof(SourceLocation OpLoc,SourceLocation LParenLoc,bool isType,void * TyOrExpr,SourceLocation RParenLoc)594 Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc,
595 bool isType, void *TyOrExpr, SourceLocation RParenLoc) {
596 // If MSVCGuidDecl has not been cached, do the lookup.
597 if (!MSVCGuidDecl) {
598 IdentifierInfo *GuidII = &PP.getIdentifierTable().get("_GUID");
599 LookupResult R(*this, GuidII, SourceLocation(), LookupTagName);
600 LookupQualifiedName(R, Context.getTranslationUnitDecl());
601 MSVCGuidDecl = R.getAsSingle<RecordDecl>();
602 if (!MSVCGuidDecl)
603 return ExprError(Diag(OpLoc, diag::err_need_header_before_ms_uuidof));
604 }
605
606 QualType GuidType = Context.getTypeDeclType(MSVCGuidDecl);
607
608 if (isType) {
609 // The operand is a type; handle it as such.
610 TypeSourceInfo *TInfo = nullptr;
611 QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr),
612 &TInfo);
613 if (T.isNull())
614 return ExprError();
615
616 if (!TInfo)
617 TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc);
618
619 return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc);
620 }
621
622 // The operand is an expression.
623 return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc);
624 }
625
626 /// ActOnCXXBoolLiteral - Parse {true,false} literals.
627 ExprResult
ActOnCXXBoolLiteral(SourceLocation OpLoc,tok::TokenKind Kind)628 Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) {
629 assert((Kind == tok::kw_true || Kind == tok::kw_false) &&
630 "Unknown C++ Boolean value!");
631 return new (Context)
632 CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc);
633 }
634
635 /// ActOnCXXNullPtrLiteral - Parse 'nullptr'.
636 ExprResult
ActOnCXXNullPtrLiteral(SourceLocation Loc)637 Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) {
638 return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc);
639 }
640
641 /// ActOnCXXThrow - Parse throw expressions.
642 ExprResult
ActOnCXXThrow(Scope * S,SourceLocation OpLoc,Expr * Ex)643 Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) {
644 bool IsThrownVarInScope = false;
645 if (Ex) {
646 // C++0x [class.copymove]p31:
647 // When certain criteria are met, an implementation is allowed to omit the
648 // copy/move construction of a class object [...]
649 //
650 // - in a throw-expression, when the operand is the name of a
651 // non-volatile automatic object (other than a function or catch-
652 // clause parameter) whose scope does not extend beyond the end of the
653 // innermost enclosing try-block (if there is one), the copy/move
654 // operation from the operand to the exception object (15.1) can be
655 // omitted by constructing the automatic object directly into the
656 // exception object
657 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens()))
658 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
659 if (Var->hasLocalStorage() && !Var->getType().isVolatileQualified()) {
660 for( ; S; S = S->getParent()) {
661 if (S->isDeclScope(Var)) {
662 IsThrownVarInScope = true;
663 break;
664 }
665
666 if (S->getFlags() &
667 (Scope::FnScope | Scope::ClassScope | Scope::BlockScope |
668 Scope::FunctionPrototypeScope | Scope::ObjCMethodScope |
669 Scope::TryScope))
670 break;
671 }
672 }
673 }
674 }
675
676 return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope);
677 }
678
BuildCXXThrow(SourceLocation OpLoc,Expr * Ex,bool IsThrownVarInScope)679 ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex,
680 bool IsThrownVarInScope) {
681 // Don't report an error if 'throw' is used in system headers.
682 if (!getLangOpts().CXXExceptions &&
683 !getSourceManager().isInSystemHeader(OpLoc))
684 Diag(OpLoc, diag::err_exceptions_disabled) << "throw";
685
686 if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope())
687 Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw";
688
689 if (Ex && !Ex->isTypeDependent()) {
690 QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType());
691 if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex))
692 return ExprError();
693
694 // Initialize the exception result. This implicitly weeds out
695 // abstract types or types with inaccessible copy constructors.
696
697 // C++0x [class.copymove]p31:
698 // When certain criteria are met, an implementation is allowed to omit the
699 // copy/move construction of a class object [...]
700 //
701 // - in a throw-expression, when the operand is the name of a
702 // non-volatile automatic object (other than a function or
703 // catch-clause
704 // parameter) whose scope does not extend beyond the end of the
705 // innermost enclosing try-block (if there is one), the copy/move
706 // operation from the operand to the exception object (15.1) can be
707 // omitted by constructing the automatic object directly into the
708 // exception object
709 const VarDecl *NRVOVariable = nullptr;
710 if (IsThrownVarInScope)
711 NRVOVariable = getCopyElisionCandidate(QualType(), Ex, false);
712
713 InitializedEntity Entity = InitializedEntity::InitializeException(
714 OpLoc, ExceptionObjectTy,
715 /*NRVO=*/NRVOVariable != nullptr);
716 ExprResult Res = PerformMoveOrCopyInitialization(
717 Entity, NRVOVariable, QualType(), Ex, IsThrownVarInScope);
718 if (Res.isInvalid())
719 return ExprError();
720 Ex = Res.get();
721 }
722
723 return new (Context)
724 CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope);
725 }
726
727 static void
collectPublicBases(CXXRecordDecl * RD,llvm::DenseMap<CXXRecordDecl *,unsigned> & SubobjectsSeen,llvm::SmallPtrSetImpl<CXXRecordDecl * > & VBases,llvm::SetVector<CXXRecordDecl * > & PublicSubobjectsSeen,bool ParentIsPublic)728 collectPublicBases(CXXRecordDecl *RD,
729 llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen,
730 llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases,
731 llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen,
732 bool ParentIsPublic) {
733 for (const CXXBaseSpecifier &BS : RD->bases()) {
734 CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
735 bool NewSubobject;
736 // Virtual bases constitute the same subobject. Non-virtual bases are
737 // always distinct subobjects.
738 if (BS.isVirtual())
739 NewSubobject = VBases.insert(BaseDecl).second;
740 else
741 NewSubobject = true;
742
743 if (NewSubobject)
744 ++SubobjectsSeen[BaseDecl];
745
746 // Only add subobjects which have public access throughout the entire chain.
747 bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public;
748 if (PublicPath)
749 PublicSubobjectsSeen.insert(BaseDecl);
750
751 // Recurse on to each base subobject.
752 collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen,
753 PublicPath);
754 }
755 }
756
getUnambiguousPublicSubobjects(CXXRecordDecl * RD,llvm::SmallVectorImpl<CXXRecordDecl * > & Objects)757 static void getUnambiguousPublicSubobjects(
758 CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) {
759 llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen;
760 llvm::SmallSet<CXXRecordDecl *, 2> VBases;
761 llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen;
762 SubobjectsSeen[RD] = 1;
763 PublicSubobjectsSeen.insert(RD);
764 collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen,
765 /*ParentIsPublic=*/true);
766
767 for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) {
768 // Skip ambiguous objects.
769 if (SubobjectsSeen[PublicSubobject] > 1)
770 continue;
771
772 Objects.push_back(PublicSubobject);
773 }
774 }
775
776 /// CheckCXXThrowOperand - Validate the operand of a throw.
CheckCXXThrowOperand(SourceLocation ThrowLoc,QualType ExceptionObjectTy,Expr * E)777 bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc,
778 QualType ExceptionObjectTy, Expr *E) {
779 // If the type of the exception would be an incomplete type or a pointer
780 // to an incomplete type other than (cv) void the program is ill-formed.
781 QualType Ty = ExceptionObjectTy;
782 bool isPointer = false;
783 if (const PointerType* Ptr = Ty->getAs<PointerType>()) {
784 Ty = Ptr->getPointeeType();
785 isPointer = true;
786 }
787 if (!isPointer || !Ty->isVoidType()) {
788 if (RequireCompleteType(ThrowLoc, Ty,
789 isPointer ? diag::err_throw_incomplete_ptr
790 : diag::err_throw_incomplete,
791 E->getSourceRange()))
792 return true;
793
794 if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy,
795 diag::err_throw_abstract_type, E))
796 return true;
797 }
798
799 // If the exception has class type, we need additional handling.
800 CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
801 if (!RD)
802 return false;
803
804 // If we are throwing a polymorphic class type or pointer thereof,
805 // exception handling will make use of the vtable.
806 MarkVTableUsed(ThrowLoc, RD);
807
808 // If a pointer is thrown, the referenced object will not be destroyed.
809 if (isPointer)
810 return false;
811
812 // If the class has a destructor, we must be able to call it.
813 if (!RD->hasIrrelevantDestructor()) {
814 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
815 MarkFunctionReferenced(E->getExprLoc(), Destructor);
816 CheckDestructorAccess(E->getExprLoc(), Destructor,
817 PDiag(diag::err_access_dtor_exception) << Ty);
818 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
819 return true;
820 }
821 }
822
823 // The MSVC ABI creates a list of all types which can catch the exception
824 // object. This list also references the appropriate copy constructor to call
825 // if the object is caught by value and has a non-trivial copy constructor.
826 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
827 // We are only interested in the public, unambiguous bases contained within
828 // the exception object. Bases which are ambiguous or otherwise
829 // inaccessible are not catchable types.
830 llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects;
831 getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects);
832
833 for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) {
834 // Attempt to lookup the copy constructor. Various pieces of machinery
835 // will spring into action, like template instantiation, which means this
836 // cannot be a simple walk of the class's decls. Instead, we must perform
837 // lookup and overload resolution.
838 CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0);
839 if (!CD)
840 continue;
841
842 // Mark the constructor referenced as it is used by this throw expression.
843 MarkFunctionReferenced(E->getExprLoc(), CD);
844
845 // Skip this copy constructor if it is trivial, we don't need to record it
846 // in the catchable type data.
847 if (CD->isTrivial())
848 continue;
849
850 // The copy constructor is non-trivial, create a mapping from this class
851 // type to this constructor.
852 // N.B. The selection of copy constructor is not sensitive to this
853 // particular throw-site. Lookup will be performed at the catch-site to
854 // ensure that the copy constructor is, in fact, accessible (via
855 // friendship or any other means).
856 Context.addCopyConstructorForExceptionObject(Subobject, CD);
857
858 // We don't keep the instantiated default argument expressions around so
859 // we must rebuild them here.
860 for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) {
861 // Skip any default arguments that we've already instantiated.
862 if (Context.getDefaultArgExprForConstructor(CD, I))
863 continue;
864
865 Expr *DefaultArg =
866 BuildCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I)).get();
867 Context.addDefaultArgExprForConstructor(CD, I, DefaultArg);
868 }
869 }
870 }
871
872 return false;
873 }
874
adjustCVQualifiersForCXXThisWithinLambda(ArrayRef<FunctionScopeInfo * > FunctionScopes,QualType ThisTy,DeclContext * CurSemaContext,ASTContext & ASTCtx)875 static QualType adjustCVQualifiersForCXXThisWithinLambda(
876 ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy,
877 DeclContext *CurSemaContext, ASTContext &ASTCtx) {
878
879 QualType ClassType = ThisTy->getPointeeType();
880 LambdaScopeInfo *CurLSI = nullptr;
881 DeclContext *CurDC = CurSemaContext;
882
883 // Iterate through the stack of lambdas starting from the innermost lambda to
884 // the outermost lambda, checking if '*this' is ever captured by copy - since
885 // that could change the cv-qualifiers of the '*this' object.
886 // The object referred to by '*this' starts out with the cv-qualifiers of its
887 // member function. We then start with the innermost lambda and iterate
888 // outward checking to see if any lambda performs a by-copy capture of '*this'
889 // - and if so, any nested lambda must respect the 'constness' of that
890 // capturing lamdbda's call operator.
891 //
892
893 // The issue is that we cannot rely entirely on the FunctionScopeInfo stack
894 // since ScopeInfos are pushed on during parsing and treetransforming. But
895 // since a generic lambda's call operator can be instantiated anywhere (even
896 // end of the TU) we need to be able to examine its enclosing lambdas and so
897 // we use the DeclContext to get a hold of the closure-class and query it for
898 // capture information. The reason we don't just resort to always using the
899 // DeclContext chain is that it is only mature for lambda expressions
900 // enclosing generic lambda's call operators that are being instantiated.
901
902 for (int I = FunctionScopes.size();
903 I-- && isa<LambdaScopeInfo>(FunctionScopes[I]);
904 CurDC = getLambdaAwareParentOfDeclContext(CurDC)) {
905 CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]);
906
907 if (!CurLSI->isCXXThisCaptured())
908 continue;
909
910 auto C = CurLSI->getCXXThisCapture();
911
912 if (C.isCopyCapture()) {
913 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
914 if (CurLSI->CallOperator->isConst())
915 ClassType.addConst();
916 return ASTCtx.getPointerType(ClassType);
917 }
918 }
919 // We've run out of ScopeInfos but check if CurDC is a lambda (which can
920 // happen during instantiation of generic lambdas)
921 if (isLambdaCallOperator(CurDC)) {
922 assert(CurLSI);
923 assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator));
924 assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator));
925
926 auto IsThisCaptured =
927 [](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) {
928 IsConst = false;
929 IsByCopy = false;
930 for (auto &&C : Closure->captures()) {
931 if (C.capturesThis()) {
932 if (C.getCaptureKind() == LCK_StarThis)
933 IsByCopy = true;
934 if (Closure->getLambdaCallOperator()->isConst())
935 IsConst = true;
936 return true;
937 }
938 }
939 return false;
940 };
941
942 bool IsByCopyCapture = false;
943 bool IsConstCapture = false;
944 CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent());
945 while (Closure &&
946 IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) {
947 if (IsByCopyCapture) {
948 ClassType.removeLocalCVRQualifiers(Qualifiers::CVRMask);
949 if (IsConstCapture)
950 ClassType.addConst();
951 return ASTCtx.getPointerType(ClassType);
952 }
953 Closure = isLambdaCallOperator(Closure->getParent())
954 ? cast<CXXRecordDecl>(Closure->getParent()->getParent())
955 : nullptr;
956 }
957 }
958 return ASTCtx.getPointerType(ClassType);
959 }
960
getCurrentThisType()961 QualType Sema::getCurrentThisType() {
962 DeclContext *DC = getFunctionLevelDeclContext();
963 QualType ThisTy = CXXThisTypeOverride;
964 if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) {
965 if (method && method->isInstance())
966 ThisTy = method->getThisType(Context);
967 }
968 if (ThisTy.isNull()) {
969 if (isGenericLambdaCallOperatorSpecialization(CurContext) &&
970 CurContext->getParent()->getParent()->isRecord()) {
971 // This is a generic lambda call operator that is being instantiated
972 // within a default initializer - so use the enclosing class as 'this'.
973 // There is no enclosing member function to retrieve the 'this' pointer
974 // from.
975
976 // FIXME: This looks wrong. If we're in a lambda within a lambda within a
977 // default member initializer, we need to recurse up more parents to find
978 // the right context. Looks like we should be walking up to the parent of
979 // the closure type, checking whether that is itself a lambda, and if so,
980 // recursing, until we reach a class or a function that isn't a lambda
981 // call operator. And we should accumulate the constness of *this on the
982 // way.
983
984 QualType ClassTy = Context.getTypeDeclType(
985 cast<CXXRecordDecl>(CurContext->getParent()->getParent()));
986 // There are no cv-qualifiers for 'this' within default initializers,
987 // per [expr.prim.general]p4.
988 ThisTy = Context.getPointerType(ClassTy);
989 }
990 }
991
992 // If we are within a lambda's call operator, the cv-qualifiers of 'this'
993 // might need to be adjusted if the lambda or any of its enclosing lambda's
994 // captures '*this' by copy.
995 if (!ThisTy.isNull() && isLambdaCallOperator(CurContext))
996 return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy,
997 CurContext, Context);
998 return ThisTy;
999 }
1000
CXXThisScopeRAII(Sema & S,Decl * ContextDecl,unsigned CXXThisTypeQuals,bool Enabled)1001 Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S,
1002 Decl *ContextDecl,
1003 unsigned CXXThisTypeQuals,
1004 bool Enabled)
1005 : S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false)
1006 {
1007 if (!Enabled || !ContextDecl)
1008 return;
1009
1010 CXXRecordDecl *Record = nullptr;
1011 if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl))
1012 Record = Template->getTemplatedDecl();
1013 else
1014 Record = cast<CXXRecordDecl>(ContextDecl);
1015
1016 // We care only for CVR qualifiers here, so cut everything else.
1017 CXXThisTypeQuals &= Qualifiers::FastMask;
1018 S.CXXThisTypeOverride
1019 = S.Context.getPointerType(
1020 S.Context.getRecordType(Record).withCVRQualifiers(CXXThisTypeQuals));
1021
1022 this->Enabled = true;
1023 }
1024
1025
~CXXThisScopeRAII()1026 Sema::CXXThisScopeRAII::~CXXThisScopeRAII() {
1027 if (Enabled) {
1028 S.CXXThisTypeOverride = OldCXXThisTypeOverride;
1029 }
1030 }
1031
captureThis(Sema & S,ASTContext & Context,RecordDecl * RD,QualType ThisTy,SourceLocation Loc,const bool ByCopy)1032 static Expr *captureThis(Sema &S, ASTContext &Context, RecordDecl *RD,
1033 QualType ThisTy, SourceLocation Loc,
1034 const bool ByCopy) {
1035
1036 QualType AdjustedThisTy = ThisTy;
1037 // The type of the corresponding data member (not a 'this' pointer if 'by
1038 // copy').
1039 QualType CaptureThisFieldTy = ThisTy;
1040 if (ByCopy) {
1041 // If we are capturing the object referred to by '*this' by copy, ignore any
1042 // cv qualifiers inherited from the type of the member function for the type
1043 // of the closure-type's corresponding data member and any use of 'this'.
1044 CaptureThisFieldTy = ThisTy->getPointeeType();
1045 CaptureThisFieldTy.removeLocalCVRQualifiers(Qualifiers::CVRMask);
1046 AdjustedThisTy = Context.getPointerType(CaptureThisFieldTy);
1047 }
1048
1049 FieldDecl *Field = FieldDecl::Create(
1050 Context, RD, Loc, Loc, nullptr, CaptureThisFieldTy,
1051 Context.getTrivialTypeSourceInfo(CaptureThisFieldTy, Loc), nullptr, false,
1052 ICIS_NoInit);
1053
1054 Field->setImplicit(true);
1055 Field->setAccess(AS_private);
1056 RD->addDecl(Field);
1057 Expr *This =
1058 new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit*/ true);
1059 if (ByCopy) {
1060 Expr *StarThis = S.CreateBuiltinUnaryOp(Loc,
1061 UO_Deref,
1062 This).get();
1063 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1064 nullptr, CaptureThisFieldTy, Loc);
1065 InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1066 InitializationSequence Init(S, Entity, InitKind, StarThis);
1067 ExprResult ER = Init.Perform(S, Entity, InitKind, StarThis);
1068 if (ER.isInvalid()) return nullptr;
1069 return ER.get();
1070 }
1071 return This;
1072 }
1073
CheckCXXThisCapture(SourceLocation Loc,const bool Explicit,bool BuildAndDiagnose,const unsigned * const FunctionScopeIndexToStopAt,const bool ByCopy)1074 bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
1075 bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt,
1076 const bool ByCopy) {
1077 // We don't need to capture this in an unevaluated context.
1078 if (isUnevaluatedContext() && !Explicit)
1079 return true;
1080
1081 assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value");
1082
1083 const unsigned MaxFunctionScopesIndex = FunctionScopeIndexToStopAt ?
1084 *FunctionScopeIndexToStopAt : FunctionScopes.size() - 1;
1085
1086 // Check that we can capture the *enclosing object* (referred to by '*this')
1087 // by the capturing-entity/closure (lambda/block/etc) at
1088 // MaxFunctionScopesIndex-deep on the FunctionScopes stack.
1089
1090 // Note: The *enclosing object* can only be captured by-value by a
1091 // closure that is a lambda, using the explicit notation:
1092 // [*this] { ... }.
1093 // Every other capture of the *enclosing object* results in its by-reference
1094 // capture.
1095
1096 // For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes
1097 // stack), we can capture the *enclosing object* only if:
1098 // - 'L' has an explicit byref or byval capture of the *enclosing object*
1099 // - or, 'L' has an implicit capture.
1100 // AND
1101 // -- there is no enclosing closure
1102 // -- or, there is some enclosing closure 'E' that has already captured the
1103 // *enclosing object*, and every intervening closure (if any) between 'E'
1104 // and 'L' can implicitly capture the *enclosing object*.
1105 // -- or, every enclosing closure can implicitly capture the
1106 // *enclosing object*
1107
1108
1109 unsigned NumCapturingClosures = 0;
1110 for (unsigned idx = MaxFunctionScopesIndex; idx != 0; idx--) {
1111 if (CapturingScopeInfo *CSI =
1112 dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) {
1113 if (CSI->CXXThisCaptureIndex != 0) {
1114 // 'this' is already being captured; there isn't anything more to do.
1115 break;
1116 }
1117 LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI);
1118 if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) {
1119 // This context can't implicitly capture 'this'; fail out.
1120 if (BuildAndDiagnose)
1121 Diag(Loc, diag::err_this_capture)
1122 << (Explicit && idx == MaxFunctionScopesIndex);
1123 return true;
1124 }
1125 if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref ||
1126 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval ||
1127 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block ||
1128 CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion ||
1129 (Explicit && idx == MaxFunctionScopesIndex)) {
1130 // Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first
1131 // iteration through can be an explicit capture, all enclosing closures,
1132 // if any, must perform implicit captures.
1133
1134 // This closure can capture 'this'; continue looking upwards.
1135 NumCapturingClosures++;
1136 continue;
1137 }
1138 // This context can't implicitly capture 'this'; fail out.
1139 if (BuildAndDiagnose)
1140 Diag(Loc, diag::err_this_capture)
1141 << (Explicit && idx == MaxFunctionScopesIndex);
1142 return true;
1143 }
1144 break;
1145 }
1146 if (!BuildAndDiagnose) return false;
1147
1148 // If we got here, then the closure at MaxFunctionScopesIndex on the
1149 // FunctionScopes stack, can capture the *enclosing object*, so capture it
1150 // (including implicit by-reference captures in any enclosing closures).
1151
1152 // In the loop below, respect the ByCopy flag only for the closure requesting
1153 // the capture (i.e. first iteration through the loop below). Ignore it for
1154 // all enclosing closure's upto NumCapturingClosures (since they must be
1155 // implicitly capturing the *enclosing object* by reference (see loop
1156 // above)).
1157 assert((!ByCopy ||
1158 dyn_cast<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) &&
1159 "Only a lambda can capture the enclosing object (referred to by "
1160 "*this) by copy");
1161 // FIXME: We need to delay this marking in PotentiallyPotentiallyEvaluated
1162 // contexts.
1163 QualType ThisTy = getCurrentThisType();
1164 for (unsigned idx = MaxFunctionScopesIndex; NumCapturingClosures;
1165 --idx, --NumCapturingClosures) {
1166 CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]);
1167 Expr *ThisExpr = nullptr;
1168
1169 if (LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI)) {
1170 // For lambda expressions, build a field and an initializing expression,
1171 // and capture the *enclosing object* by copy only if this is the first
1172 // iteration.
1173 ThisExpr = captureThis(*this, Context, LSI->Lambda, ThisTy, Loc,
1174 ByCopy && idx == MaxFunctionScopesIndex);
1175
1176 } else if (CapturedRegionScopeInfo *RSI
1177 = dyn_cast<CapturedRegionScopeInfo>(FunctionScopes[idx]))
1178 ThisExpr =
1179 captureThis(*this, Context, RSI->TheRecordDecl, ThisTy, Loc,
1180 false/*ByCopy*/);
1181
1182 bool isNested = NumCapturingClosures > 1;
1183 CSI->addThisCapture(isNested, Loc, ThisExpr, ByCopy);
1184 }
1185 return false;
1186 }
1187
ActOnCXXThis(SourceLocation Loc)1188 ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1189 /// C++ 9.3.2: In the body of a non-static member function, the keyword this
1190 /// is a non-lvalue expression whose value is the address of the object for
1191 /// which the function is called.
1192
1193 QualType ThisTy = getCurrentThisType();
1194 if (ThisTy.isNull()) return Diag(Loc, diag::err_invalid_this_use);
1195
1196 CheckCXXThisCapture(Loc);
1197 return new (Context) CXXThisExpr(Loc, ThisTy, /*isImplicit=*/false);
1198 }
1199
isThisOutsideMemberFunctionBody(QualType BaseType)1200 bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) {
1201 // If we're outside the body of a member function, then we'll have a specified
1202 // type for 'this'.
1203 if (CXXThisTypeOverride.isNull())
1204 return false;
1205
1206 // Determine whether we're looking into a class that's currently being
1207 // defined.
1208 CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl();
1209 return Class && Class->isBeingDefined();
1210 }
1211
1212 ExprResult
ActOnCXXTypeConstructExpr(ParsedType TypeRep,SourceLocation LParenLoc,MultiExprArg exprs,SourceLocation RParenLoc)1213 Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep,
1214 SourceLocation LParenLoc,
1215 MultiExprArg exprs,
1216 SourceLocation RParenLoc) {
1217 if (!TypeRep)
1218 return ExprError();
1219
1220 TypeSourceInfo *TInfo;
1221 QualType Ty = GetTypeFromParser(TypeRep, &TInfo);
1222 if (!TInfo)
1223 TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation());
1224
1225 auto Result = BuildCXXTypeConstructExpr(TInfo, LParenLoc, exprs, RParenLoc);
1226 // Avoid creating a non-type-dependent expression that contains typos.
1227 // Non-type-dependent expressions are liable to be discarded without
1228 // checking for embedded typos.
1229 if (!Result.isInvalid() && Result.get()->isInstantiationDependent() &&
1230 !Result.get()->isTypeDependent())
1231 Result = CorrectDelayedTyposInExpr(Result.get());
1232 return Result;
1233 }
1234
1235 /// ActOnCXXTypeConstructExpr - Parse construction of a specified type.
1236 /// Can be interpreted either as function-style casting ("int(x)")
1237 /// or class type construction ("ClassType(x,y,z)")
1238 /// or creation of a value-initialized type ("int()").
1239 ExprResult
BuildCXXTypeConstructExpr(TypeSourceInfo * TInfo,SourceLocation LParenLoc,MultiExprArg Exprs,SourceLocation RParenLoc)1240 Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo,
1241 SourceLocation LParenLoc,
1242 MultiExprArg Exprs,
1243 SourceLocation RParenLoc) {
1244 QualType Ty = TInfo->getType();
1245 SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc();
1246
1247 if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) {
1248 return CXXUnresolvedConstructExpr::Create(Context, TInfo, LParenLoc, Exprs,
1249 RParenLoc);
1250 }
1251
1252 bool ListInitialization = LParenLoc.isInvalid();
1253 assert((!ListInitialization || (Exprs.size() == 1 && isa<InitListExpr>(Exprs[0])))
1254 && "List initialization must have initializer list as expression.");
1255 SourceRange FullRange = SourceRange(TyBeginLoc,
1256 ListInitialization ? Exprs[0]->getSourceRange().getEnd() : RParenLoc);
1257
1258 // C++ [expr.type.conv]p1:
1259 // If the expression list is a single expression, the type conversion
1260 // expression is equivalent (in definedness, and if defined in meaning) to the
1261 // corresponding cast expression.
1262 if (Exprs.size() == 1 && !ListInitialization) {
1263 Expr *Arg = Exprs[0];
1264 return BuildCXXFunctionalCastExpr(TInfo, LParenLoc, Arg, RParenLoc);
1265 }
1266
1267 // C++14 [expr.type.conv]p2: The expression T(), where T is a
1268 // simple-type-specifier or typename-specifier for a non-array complete
1269 // object type or the (possibly cv-qualified) void type, creates a prvalue
1270 // of the specified type, whose value is that produced by value-initializing
1271 // an object of type T.
1272 QualType ElemTy = Ty;
1273 if (Ty->isArrayType()) {
1274 if (!ListInitialization)
1275 return ExprError(Diag(TyBeginLoc,
1276 diag::err_value_init_for_array_type) << FullRange);
1277 ElemTy = Context.getBaseElementType(Ty);
1278 }
1279
1280 if (!ListInitialization && Ty->isFunctionType())
1281 return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_function_type)
1282 << FullRange);
1283
1284 if (!Ty->isVoidType() &&
1285 RequireCompleteType(TyBeginLoc, ElemTy,
1286 diag::err_invalid_incomplete_type_use, FullRange))
1287 return ExprError();
1288
1289 if (RequireNonAbstractType(TyBeginLoc, Ty,
1290 diag::err_allocation_of_abstract_type))
1291 return ExprError();
1292
1293 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TInfo);
1294 InitializationKind Kind =
1295 Exprs.size() ? ListInitialization
1296 ? InitializationKind::CreateDirectList(TyBeginLoc)
1297 : InitializationKind::CreateDirect(TyBeginLoc, LParenLoc, RParenLoc)
1298 : InitializationKind::CreateValue(TyBeginLoc, LParenLoc, RParenLoc);
1299 InitializationSequence InitSeq(*this, Entity, Kind, Exprs);
1300 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs);
1301
1302 if (Result.isInvalid() || !ListInitialization)
1303 return Result;
1304
1305 Expr *Inner = Result.get();
1306 if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner))
1307 Inner = BTE->getSubExpr();
1308 if (!isa<CXXTemporaryObjectExpr>(Inner)) {
1309 // If we created a CXXTemporaryObjectExpr, that node also represents the
1310 // functional cast. Otherwise, create an explicit cast to represent
1311 // the syntactic form of a functional-style cast that was used here.
1312 //
1313 // FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr
1314 // would give a more consistent AST representation than using a
1315 // CXXTemporaryObjectExpr. It's also weird that the functional cast
1316 // is sometimes handled by initialization and sometimes not.
1317 QualType ResultType = Result.get()->getType();
1318 Result = CXXFunctionalCastExpr::Create(
1319 Context, ResultType, Expr::getValueKindForType(TInfo->getType()), TInfo,
1320 CK_NoOp, Result.get(), /*Path=*/nullptr, LParenLoc, RParenLoc);
1321 }
1322
1323 return Result;
1324 }
1325
1326 /// doesUsualArrayDeleteWantSize - Answers whether the usual
1327 /// operator delete[] for the given type has a size_t parameter.
doesUsualArrayDeleteWantSize(Sema & S,SourceLocation loc,QualType allocType)1328 static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc,
1329 QualType allocType) {
1330 const RecordType *record =
1331 allocType->getBaseElementTypeUnsafe()->getAs<RecordType>();
1332 if (!record) return false;
1333
1334 // Try to find an operator delete[] in class scope.
1335
1336 DeclarationName deleteName =
1337 S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete);
1338 LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName);
1339 S.LookupQualifiedName(ops, record->getDecl());
1340
1341 // We're just doing this for information.
1342 ops.suppressDiagnostics();
1343
1344 // Very likely: there's no operator delete[].
1345 if (ops.empty()) return false;
1346
1347 // If it's ambiguous, it should be illegal to call operator delete[]
1348 // on this thing, so it doesn't matter if we allocate extra space or not.
1349 if (ops.isAmbiguous()) return false;
1350
1351 LookupResult::Filter filter = ops.makeFilter();
1352 while (filter.hasNext()) {
1353 NamedDecl *del = filter.next()->getUnderlyingDecl();
1354
1355 // C++0x [basic.stc.dynamic.deallocation]p2:
1356 // A template instance is never a usual deallocation function,
1357 // regardless of its signature.
1358 if (isa<FunctionTemplateDecl>(del)) {
1359 filter.erase();
1360 continue;
1361 }
1362
1363 // C++0x [basic.stc.dynamic.deallocation]p2:
1364 // If class T does not declare [an operator delete[] with one
1365 // parameter] but does declare a member deallocation function
1366 // named operator delete[] with exactly two parameters, the
1367 // second of which has type std::size_t, then this function
1368 // is a usual deallocation function.
1369 if (!cast<CXXMethodDecl>(del)->isUsualDeallocationFunction()) {
1370 filter.erase();
1371 continue;
1372 }
1373 }
1374 filter.done();
1375
1376 if (!ops.isSingleResult()) return false;
1377
1378 const FunctionDecl *del = cast<FunctionDecl>(ops.getFoundDecl());
1379 return (del->getNumParams() == 2);
1380 }
1381
1382 /// \brief Parsed a C++ 'new' expression (C++ 5.3.4).
1383 ///
1384 /// E.g.:
1385 /// @code new (memory) int[size][4] @endcode
1386 /// or
1387 /// @code ::new Foo(23, "hello") @endcode
1388 ///
1389 /// \param StartLoc The first location of the expression.
1390 /// \param UseGlobal True if 'new' was prefixed with '::'.
1391 /// \param PlacementLParen Opening paren of the placement arguments.
1392 /// \param PlacementArgs Placement new arguments.
1393 /// \param PlacementRParen Closing paren of the placement arguments.
1394 /// \param TypeIdParens If the type is in parens, the source range.
1395 /// \param D The type to be allocated, as well as array dimensions.
1396 /// \param Initializer The initializing expression or initializer-list, or null
1397 /// if there is none.
1398 ExprResult
ActOnCXXNew(SourceLocation StartLoc,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,Declarator & D,Expr * Initializer)1399 Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal,
1400 SourceLocation PlacementLParen, MultiExprArg PlacementArgs,
1401 SourceLocation PlacementRParen, SourceRange TypeIdParens,
1402 Declarator &D, Expr *Initializer) {
1403 bool TypeContainsAuto = D.getDeclSpec().containsPlaceholderType();
1404
1405 Expr *ArraySize = nullptr;
1406 // If the specified type is an array, unwrap it and save the expression.
1407 if (D.getNumTypeObjects() > 0 &&
1408 D.getTypeObject(0).Kind == DeclaratorChunk::Array) {
1409 DeclaratorChunk &Chunk = D.getTypeObject(0);
1410 if (TypeContainsAuto)
1411 return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto)
1412 << D.getSourceRange());
1413 if (Chunk.Arr.hasStatic)
1414 return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new)
1415 << D.getSourceRange());
1416 if (!Chunk.Arr.NumElts)
1417 return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size)
1418 << D.getSourceRange());
1419
1420 ArraySize = static_cast<Expr*>(Chunk.Arr.NumElts);
1421 D.DropFirstTypeObject();
1422 }
1423
1424 // Every dimension shall be of constant size.
1425 if (ArraySize) {
1426 for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) {
1427 if (D.getTypeObject(I).Kind != DeclaratorChunk::Array)
1428 break;
1429
1430 DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr;
1431 if (Expr *NumElts = (Expr *)Array.NumElts) {
1432 if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) {
1433 if (getLangOpts().CPlusPlus14) {
1434 // C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator
1435 // shall be a converted constant expression (5.19) of type std::size_t
1436 // and shall evaluate to a strictly positive value.
1437 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
1438 assert(IntWidth && "Builtin type of size 0?");
1439 llvm::APSInt Value(IntWidth);
1440 Array.NumElts
1441 = CheckConvertedConstantExpression(NumElts, Context.getSizeType(), Value,
1442 CCEK_NewExpr)
1443 .get();
1444 } else {
1445 Array.NumElts
1446 = VerifyIntegerConstantExpression(NumElts, nullptr,
1447 diag::err_new_array_nonconst)
1448 .get();
1449 }
1450 if (!Array.NumElts)
1451 return ExprError();
1452 }
1453 }
1454 }
1455 }
1456
1457 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, /*Scope=*/nullptr);
1458 QualType AllocType = TInfo->getType();
1459 if (D.isInvalidType())
1460 return ExprError();
1461
1462 SourceRange DirectInitRange;
1463 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer))
1464 DirectInitRange = List->getSourceRange();
1465
1466 return BuildCXXNew(SourceRange(StartLoc, D.getLocEnd()), UseGlobal,
1467 PlacementLParen,
1468 PlacementArgs,
1469 PlacementRParen,
1470 TypeIdParens,
1471 AllocType,
1472 TInfo,
1473 ArraySize,
1474 DirectInitRange,
1475 Initializer,
1476 TypeContainsAuto);
1477 }
1478
isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,Expr * Init)1479 static bool isLegalArrayNewInitializer(CXXNewExpr::InitializationStyle Style,
1480 Expr *Init) {
1481 if (!Init)
1482 return true;
1483 if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init))
1484 return PLE->getNumExprs() == 0;
1485 if (isa<ImplicitValueInitExpr>(Init))
1486 return true;
1487 else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init))
1488 return !CCE->isListInitialization() &&
1489 CCE->getConstructor()->isDefaultConstructor();
1490 else if (Style == CXXNewExpr::ListInit) {
1491 assert(isa<InitListExpr>(Init) &&
1492 "Shouldn't create list CXXConstructExprs for arrays.");
1493 return true;
1494 }
1495 return false;
1496 }
1497
1498 ExprResult
BuildCXXNew(SourceRange Range,bool UseGlobal,SourceLocation PlacementLParen,MultiExprArg PlacementArgs,SourceLocation PlacementRParen,SourceRange TypeIdParens,QualType AllocType,TypeSourceInfo * AllocTypeInfo,Expr * ArraySize,SourceRange DirectInitRange,Expr * Initializer,bool TypeMayContainAuto)1499 Sema::BuildCXXNew(SourceRange Range, bool UseGlobal,
1500 SourceLocation PlacementLParen,
1501 MultiExprArg PlacementArgs,
1502 SourceLocation PlacementRParen,
1503 SourceRange TypeIdParens,
1504 QualType AllocType,
1505 TypeSourceInfo *AllocTypeInfo,
1506 Expr *ArraySize,
1507 SourceRange DirectInitRange,
1508 Expr *Initializer,
1509 bool TypeMayContainAuto) {
1510 SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange();
1511 SourceLocation StartLoc = Range.getBegin();
1512
1513 CXXNewExpr::InitializationStyle initStyle;
1514 if (DirectInitRange.isValid()) {
1515 assert(Initializer && "Have parens but no initializer.");
1516 initStyle = CXXNewExpr::CallInit;
1517 } else if (Initializer && isa<InitListExpr>(Initializer))
1518 initStyle = CXXNewExpr::ListInit;
1519 else {
1520 assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) ||
1521 isa<CXXConstructExpr>(Initializer)) &&
1522 "Initializer expression that cannot have been implicitly created.");
1523 initStyle = CXXNewExpr::NoInit;
1524 }
1525
1526 Expr **Inits = &Initializer;
1527 unsigned NumInits = Initializer ? 1 : 0;
1528 if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) {
1529 assert(initStyle == CXXNewExpr::CallInit && "paren init for non-call init");
1530 Inits = List->getExprs();
1531 NumInits = List->getNumExprs();
1532 }
1533
1534 // C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for.
1535 if (TypeMayContainAuto && AllocType->isUndeducedType()) {
1536 if (initStyle == CXXNewExpr::NoInit || NumInits == 0)
1537 return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg)
1538 << AllocType << TypeRange);
1539 if (initStyle == CXXNewExpr::ListInit ||
1540 (NumInits == 1 && isa<InitListExpr>(Inits[0])))
1541 return ExprError(Diag(Inits[0]->getLocStart(),
1542 diag::err_auto_new_list_init)
1543 << AllocType << TypeRange);
1544 if (NumInits > 1) {
1545 Expr *FirstBad = Inits[1];
1546 return ExprError(Diag(FirstBad->getLocStart(),
1547 diag::err_auto_new_ctor_multiple_expressions)
1548 << AllocType << TypeRange);
1549 }
1550 Expr *Deduce = Inits[0];
1551 QualType DeducedType;
1552 if (DeduceAutoType(AllocTypeInfo, Deduce, DeducedType) == DAR_Failed)
1553 return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure)
1554 << AllocType << Deduce->getType()
1555 << TypeRange << Deduce->getSourceRange());
1556 if (DeducedType.isNull())
1557 return ExprError();
1558 AllocType = DeducedType;
1559 }
1560
1561 // Per C++0x [expr.new]p5, the type being constructed may be a
1562 // typedef of an array type.
1563 if (!ArraySize) {
1564 if (const ConstantArrayType *Array
1565 = Context.getAsConstantArrayType(AllocType)) {
1566 ArraySize = IntegerLiteral::Create(Context, Array->getSize(),
1567 Context.getSizeType(),
1568 TypeRange.getEnd());
1569 AllocType = Array->getElementType();
1570 }
1571 }
1572
1573 if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange))
1574 return ExprError();
1575
1576 if (initStyle == CXXNewExpr::ListInit &&
1577 isStdInitializerList(AllocType, nullptr)) {
1578 Diag(AllocTypeInfo->getTypeLoc().getBeginLoc(),
1579 diag::warn_dangling_std_initializer_list)
1580 << /*at end of FE*/0 << Inits[0]->getSourceRange();
1581 }
1582
1583 // In ARC, infer 'retaining' for the allocated
1584 if (getLangOpts().ObjCAutoRefCount &&
1585 AllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1586 AllocType->isObjCLifetimeType()) {
1587 AllocType = Context.getLifetimeQualifiedType(AllocType,
1588 AllocType->getObjCARCImplicitLifetime());
1589 }
1590
1591 QualType ResultType = Context.getPointerType(AllocType);
1592
1593 if (ArraySize && ArraySize->getType()->isNonOverloadPlaceholderType()) {
1594 ExprResult result = CheckPlaceholderExpr(ArraySize);
1595 if (result.isInvalid()) return ExprError();
1596 ArraySize = result.get();
1597 }
1598 // C++98 5.3.4p6: "The expression in a direct-new-declarator shall have
1599 // integral or enumeration type with a non-negative value."
1600 // C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped
1601 // enumeration type, or a class type for which a single non-explicit
1602 // conversion function to integral or unscoped enumeration type exists.
1603 // C++1y [expr.new]p6: The expression [...] is implicitly converted to
1604 // std::size_t.
1605 if (ArraySize && !ArraySize->isTypeDependent()) {
1606 ExprResult ConvertedSize;
1607 if (getLangOpts().CPlusPlus14) {
1608 assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?");
1609
1610 ConvertedSize = PerformImplicitConversion(ArraySize, Context.getSizeType(),
1611 AA_Converting);
1612
1613 if (!ConvertedSize.isInvalid() &&
1614 ArraySize->getType()->getAs<RecordType>())
1615 // Diagnose the compatibility of this conversion.
1616 Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion)
1617 << ArraySize->getType() << 0 << "'size_t'";
1618 } else {
1619 class SizeConvertDiagnoser : public ICEConvertDiagnoser {
1620 protected:
1621 Expr *ArraySize;
1622
1623 public:
1624 SizeConvertDiagnoser(Expr *ArraySize)
1625 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false),
1626 ArraySize(ArraySize) {}
1627
1628 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
1629 QualType T) override {
1630 return S.Diag(Loc, diag::err_array_size_not_integral)
1631 << S.getLangOpts().CPlusPlus11 << T;
1632 }
1633
1634 SemaDiagnosticBuilder diagnoseIncomplete(
1635 Sema &S, SourceLocation Loc, QualType T) override {
1636 return S.Diag(Loc, diag::err_array_size_incomplete_type)
1637 << T << ArraySize->getSourceRange();
1638 }
1639
1640 SemaDiagnosticBuilder diagnoseExplicitConv(
1641 Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override {
1642 return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy;
1643 }
1644
1645 SemaDiagnosticBuilder noteExplicitConv(
1646 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1647 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1648 << ConvTy->isEnumeralType() << ConvTy;
1649 }
1650
1651 SemaDiagnosticBuilder diagnoseAmbiguous(
1652 Sema &S, SourceLocation Loc, QualType T) override {
1653 return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T;
1654 }
1655
1656 SemaDiagnosticBuilder noteAmbiguous(
1657 Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override {
1658 return S.Diag(Conv->getLocation(), diag::note_array_size_conversion)
1659 << ConvTy->isEnumeralType() << ConvTy;
1660 }
1661
1662 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
1663 QualType T,
1664 QualType ConvTy) override {
1665 return S.Diag(Loc,
1666 S.getLangOpts().CPlusPlus11
1667 ? diag::warn_cxx98_compat_array_size_conversion
1668 : diag::ext_array_size_conversion)
1669 << T << ConvTy->isEnumeralType() << ConvTy;
1670 }
1671 } SizeDiagnoser(ArraySize);
1672
1673 ConvertedSize = PerformContextualImplicitConversion(StartLoc, ArraySize,
1674 SizeDiagnoser);
1675 }
1676 if (ConvertedSize.isInvalid())
1677 return ExprError();
1678
1679 ArraySize = ConvertedSize.get();
1680 QualType SizeType = ArraySize->getType();
1681
1682 if (!SizeType->isIntegralOrUnscopedEnumerationType())
1683 return ExprError();
1684
1685 // C++98 [expr.new]p7:
1686 // The expression in a direct-new-declarator shall have integral type
1687 // with a non-negative value.
1688 //
1689 // Let's see if this is a constant < 0. If so, we reject it out of
1690 // hand. Otherwise, if it's not a constant, we must have an unparenthesized
1691 // array type.
1692 //
1693 // Note: such a construct has well-defined semantics in C++11: it throws
1694 // std::bad_array_new_length.
1695 if (!ArraySize->isValueDependent()) {
1696 llvm::APSInt Value;
1697 // We've already performed any required implicit conversion to integer or
1698 // unscoped enumeration type.
1699 if (ArraySize->isIntegerConstantExpr(Value, Context)) {
1700 if (Value < llvm::APSInt(
1701 llvm::APInt::getNullValue(Value.getBitWidth()),
1702 Value.isUnsigned())) {
1703 if (getLangOpts().CPlusPlus11)
1704 Diag(ArraySize->getLocStart(),
1705 diag::warn_typecheck_negative_array_new_size)
1706 << ArraySize->getSourceRange();
1707 else
1708 return ExprError(Diag(ArraySize->getLocStart(),
1709 diag::err_typecheck_negative_array_size)
1710 << ArraySize->getSourceRange());
1711 } else if (!AllocType->isDependentType()) {
1712 unsigned ActiveSizeBits =
1713 ConstantArrayType::getNumAddressingBits(Context, AllocType, Value);
1714 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1715 if (getLangOpts().CPlusPlus11)
1716 Diag(ArraySize->getLocStart(),
1717 diag::warn_array_new_too_large)
1718 << Value.toString(10)
1719 << ArraySize->getSourceRange();
1720 else
1721 return ExprError(Diag(ArraySize->getLocStart(),
1722 diag::err_array_too_large)
1723 << Value.toString(10)
1724 << ArraySize->getSourceRange());
1725 }
1726 }
1727 } else if (TypeIdParens.isValid()) {
1728 // Can't have dynamic array size when the type-id is in parentheses.
1729 Diag(ArraySize->getLocStart(), diag::ext_new_paren_array_nonconst)
1730 << ArraySize->getSourceRange()
1731 << FixItHint::CreateRemoval(TypeIdParens.getBegin())
1732 << FixItHint::CreateRemoval(TypeIdParens.getEnd());
1733
1734 TypeIdParens = SourceRange();
1735 }
1736 }
1737
1738 // Note that we do *not* convert the argument in any way. It can
1739 // be signed, larger than size_t, whatever.
1740 }
1741
1742 FunctionDecl *OperatorNew = nullptr;
1743 FunctionDecl *OperatorDelete = nullptr;
1744
1745 if (!AllocType->isDependentType() &&
1746 !Expr::hasAnyTypeDependentArguments(PlacementArgs) &&
1747 FindAllocationFunctions(StartLoc,
1748 SourceRange(PlacementLParen, PlacementRParen),
1749 UseGlobal, AllocType, ArraySize, PlacementArgs,
1750 OperatorNew, OperatorDelete))
1751 return ExprError();
1752
1753 // If this is an array allocation, compute whether the usual array
1754 // deallocation function for the type has a size_t parameter.
1755 bool UsualArrayDeleteWantsSize = false;
1756 if (ArraySize && !AllocType->isDependentType())
1757 UsualArrayDeleteWantsSize
1758 = doesUsualArrayDeleteWantSize(*this, StartLoc, AllocType);
1759
1760 SmallVector<Expr *, 8> AllPlaceArgs;
1761 if (OperatorNew) {
1762 const FunctionProtoType *Proto =
1763 OperatorNew->getType()->getAs<FunctionProtoType>();
1764 VariadicCallType CallType = Proto->isVariadic() ? VariadicFunction
1765 : VariadicDoesNotApply;
1766
1767 // We've already converted the placement args, just fill in any default
1768 // arguments. Skip the first parameter because we don't have a corresponding
1769 // argument.
1770 if (GatherArgumentsForCall(PlacementLParen, OperatorNew, Proto, 1,
1771 PlacementArgs, AllPlaceArgs, CallType))
1772 return ExprError();
1773
1774 if (!AllPlaceArgs.empty())
1775 PlacementArgs = AllPlaceArgs;
1776
1777 // FIXME: This is wrong: PlacementArgs misses out the first (size) argument.
1778 DiagnoseSentinelCalls(OperatorNew, PlacementLParen, PlacementArgs);
1779
1780 // FIXME: Missing call to CheckFunctionCall or equivalent
1781 }
1782
1783 // Warn if the type is over-aligned and is being allocated by global operator
1784 // new.
1785 if (PlacementArgs.empty() && OperatorNew &&
1786 (OperatorNew->isImplicit() ||
1787 (OperatorNew->getLocStart().isValid() &&
1788 getSourceManager().isInSystemHeader(OperatorNew->getLocStart())))) {
1789 if (unsigned Align = Context.getPreferredTypeAlign(AllocType.getTypePtr())){
1790 unsigned SuitableAlign = Context.getTargetInfo().getSuitableAlign();
1791 if (Align > SuitableAlign)
1792 Diag(StartLoc, diag::warn_overaligned_type)
1793 << AllocType
1794 << unsigned(Align / Context.getCharWidth())
1795 << unsigned(SuitableAlign / Context.getCharWidth());
1796 }
1797 }
1798
1799 QualType InitType = AllocType;
1800 // Array 'new' can't have any initializers except empty parentheses.
1801 // Initializer lists are also allowed, in C++11. Rely on the parser for the
1802 // dialect distinction.
1803 if (ResultType->isArrayType() || ArraySize) {
1804 if (!isLegalArrayNewInitializer(initStyle, Initializer)) {
1805 SourceRange InitRange(Inits[0]->getLocStart(),
1806 Inits[NumInits - 1]->getLocEnd());
1807 Diag(StartLoc, diag::err_new_array_init_args) << InitRange;
1808 return ExprError();
1809 }
1810 if (InitListExpr *ILE = dyn_cast_or_null<InitListExpr>(Initializer)) {
1811 // We do the initialization typechecking against the array type
1812 // corresponding to the number of initializers + 1 (to also check
1813 // default-initialization).
1814 unsigned NumElements = ILE->getNumInits() + 1;
1815 InitType = Context.getConstantArrayType(AllocType,
1816 llvm::APInt(Context.getTypeSize(Context.getSizeType()), NumElements),
1817 ArrayType::Normal, 0);
1818 }
1819 }
1820
1821 // If we can perform the initialization, and we've not already done so,
1822 // do it now.
1823 if (!AllocType->isDependentType() &&
1824 !Expr::hasAnyTypeDependentArguments(
1825 llvm::makeArrayRef(Inits, NumInits))) {
1826 // C++11 [expr.new]p15:
1827 // A new-expression that creates an object of type T initializes that
1828 // object as follows:
1829 InitializationKind Kind
1830 // - If the new-initializer is omitted, the object is default-
1831 // initialized (8.5); if no initialization is performed,
1832 // the object has indeterminate value
1833 = initStyle == CXXNewExpr::NoInit
1834 ? InitializationKind::CreateDefault(TypeRange.getBegin())
1835 // - Otherwise, the new-initializer is interpreted according to the
1836 // initialization rules of 8.5 for direct-initialization.
1837 : initStyle == CXXNewExpr::ListInit
1838 ? InitializationKind::CreateDirectList(TypeRange.getBegin())
1839 : InitializationKind::CreateDirect(TypeRange.getBegin(),
1840 DirectInitRange.getBegin(),
1841 DirectInitRange.getEnd());
1842
1843 InitializedEntity Entity
1844 = InitializedEntity::InitializeNew(StartLoc, InitType);
1845 InitializationSequence InitSeq(*this, Entity, Kind, MultiExprArg(Inits, NumInits));
1846 ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind,
1847 MultiExprArg(Inits, NumInits));
1848 if (FullInit.isInvalid())
1849 return ExprError();
1850
1851 // FullInit is our initializer; strip off CXXBindTemporaryExprs, because
1852 // we don't want the initialized object to be destructed.
1853 if (CXXBindTemporaryExpr *Binder =
1854 dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get()))
1855 FullInit = Binder->getSubExpr();
1856
1857 Initializer = FullInit.get();
1858 }
1859
1860 // Mark the new and delete operators as referenced.
1861 if (OperatorNew) {
1862 if (DiagnoseUseOfDecl(OperatorNew, StartLoc))
1863 return ExprError();
1864 MarkFunctionReferenced(StartLoc, OperatorNew);
1865 }
1866 if (OperatorDelete) {
1867 if (DiagnoseUseOfDecl(OperatorDelete, StartLoc))
1868 return ExprError();
1869 MarkFunctionReferenced(StartLoc, OperatorDelete);
1870 }
1871
1872 // C++0x [expr.new]p17:
1873 // If the new expression creates an array of objects of class type,
1874 // access and ambiguity control are done for the destructor.
1875 QualType BaseAllocType = Context.getBaseElementType(AllocType);
1876 if (ArraySize && !BaseAllocType->isDependentType()) {
1877 if (const RecordType *BaseRecordType = BaseAllocType->getAs<RecordType>()) {
1878 if (CXXDestructorDecl *dtor = LookupDestructor(
1879 cast<CXXRecordDecl>(BaseRecordType->getDecl()))) {
1880 MarkFunctionReferenced(StartLoc, dtor);
1881 CheckDestructorAccess(StartLoc, dtor,
1882 PDiag(diag::err_access_dtor)
1883 << BaseAllocType);
1884 if (DiagnoseUseOfDecl(dtor, StartLoc))
1885 return ExprError();
1886 }
1887 }
1888 }
1889
1890 return new (Context)
1891 CXXNewExpr(Context, UseGlobal, OperatorNew, OperatorDelete,
1892 UsualArrayDeleteWantsSize, PlacementArgs, TypeIdParens,
1893 ArraySize, initStyle, Initializer, ResultType, AllocTypeInfo,
1894 Range, DirectInitRange);
1895 }
1896
1897 /// \brief Checks that a type is suitable as the allocated type
1898 /// in a new-expression.
CheckAllocatedType(QualType AllocType,SourceLocation Loc,SourceRange R)1899 bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc,
1900 SourceRange R) {
1901 // C++ 5.3.4p1: "[The] type shall be a complete object type, but not an
1902 // abstract class type or array thereof.
1903 if (AllocType->isFunctionType())
1904 return Diag(Loc, diag::err_bad_new_type)
1905 << AllocType << 0 << R;
1906 else if (AllocType->isReferenceType())
1907 return Diag(Loc, diag::err_bad_new_type)
1908 << AllocType << 1 << R;
1909 else if (!AllocType->isDependentType() &&
1910 RequireCompleteType(Loc, AllocType, diag::err_new_incomplete_type,R))
1911 return true;
1912 else if (RequireNonAbstractType(Loc, AllocType,
1913 diag::err_allocation_of_abstract_type))
1914 return true;
1915 else if (AllocType->isVariablyModifiedType())
1916 return Diag(Loc, diag::err_variably_modified_new_type)
1917 << AllocType;
1918 else if (unsigned AddressSpace = AllocType.getAddressSpace())
1919 return Diag(Loc, diag::err_address_space_qualified_new)
1920 << AllocType.getUnqualifiedType() << AddressSpace;
1921 else if (getLangOpts().ObjCAutoRefCount) {
1922 if (const ArrayType *AT = Context.getAsArrayType(AllocType)) {
1923 QualType BaseAllocType = Context.getBaseElementType(AT);
1924 if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None &&
1925 BaseAllocType->isObjCLifetimeType())
1926 return Diag(Loc, diag::err_arc_new_array_without_ownership)
1927 << BaseAllocType;
1928 }
1929 }
1930
1931 return false;
1932 }
1933
1934 /// \brief Determine whether the given function is a non-placement
1935 /// deallocation function.
isNonPlacementDeallocationFunction(Sema & S,FunctionDecl * FD)1936 static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) {
1937 if (FD->isInvalidDecl())
1938 return false;
1939
1940 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD))
1941 return Method->isUsualDeallocationFunction();
1942
1943 if (FD->getOverloadedOperator() != OO_Delete &&
1944 FD->getOverloadedOperator() != OO_Array_Delete)
1945 return false;
1946
1947 if (FD->getNumParams() == 1)
1948 return true;
1949
1950 return S.getLangOpts().SizedDeallocation && FD->getNumParams() == 2 &&
1951 S.Context.hasSameUnqualifiedType(FD->getParamDecl(1)->getType(),
1952 S.Context.getSizeType());
1953 }
1954
1955 /// FindAllocationFunctions - Finds the overloads of operator new and delete
1956 /// that are appropriate for the allocation.
FindAllocationFunctions(SourceLocation StartLoc,SourceRange Range,bool UseGlobal,QualType AllocType,bool IsArray,MultiExprArg PlaceArgs,FunctionDecl * & OperatorNew,FunctionDecl * & OperatorDelete)1957 bool Sema::FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range,
1958 bool UseGlobal, QualType AllocType,
1959 bool IsArray, MultiExprArg PlaceArgs,
1960 FunctionDecl *&OperatorNew,
1961 FunctionDecl *&OperatorDelete) {
1962 // --- Choosing an allocation function ---
1963 // C++ 5.3.4p8 - 14 & 18
1964 // 1) If UseGlobal is true, only look in the global scope. Else, also look
1965 // in the scope of the allocated class.
1966 // 2) If an array size is given, look for operator new[], else look for
1967 // operator new.
1968 // 3) The first argument is always size_t. Append the arguments from the
1969 // placement form.
1970
1971 SmallVector<Expr*, 8> AllocArgs(1 + PlaceArgs.size());
1972 // We don't care about the actual value of this argument.
1973 // FIXME: Should the Sema create the expression and embed it in the syntax
1974 // tree? Or should the consumer just recalculate the value?
1975 IntegerLiteral Size(Context, llvm::APInt::getNullValue(
1976 Context.getTargetInfo().getPointerWidth(0)),
1977 Context.getSizeType(),
1978 SourceLocation());
1979 AllocArgs[0] = &Size;
1980 std::copy(PlaceArgs.begin(), PlaceArgs.end(), AllocArgs.begin() + 1);
1981
1982 // C++ [expr.new]p8:
1983 // If the allocated type is a non-array type, the allocation
1984 // function's name is operator new and the deallocation function's
1985 // name is operator delete. If the allocated type is an array
1986 // type, the allocation function's name is operator new[] and the
1987 // deallocation function's name is operator delete[].
1988 DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName(
1989 IsArray ? OO_Array_New : OO_New);
1990 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
1991 IsArray ? OO_Array_Delete : OO_Delete);
1992
1993 QualType AllocElemType = Context.getBaseElementType(AllocType);
1994
1995 if (AllocElemType->isRecordType() && !UseGlobal) {
1996 CXXRecordDecl *Record
1997 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
1998 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, Record,
1999 /*AllowMissing=*/true, OperatorNew))
2000 return true;
2001 }
2002
2003 if (!OperatorNew) {
2004 // Didn't find a member overload. Look for a global one.
2005 DeclareGlobalNewDelete();
2006 DeclContext *TUDecl = Context.getTranslationUnitDecl();
2007 bool FallbackEnabled = IsArray && Context.getLangOpts().MSVCCompat;
2008 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
2009 /*AllowMissing=*/FallbackEnabled, OperatorNew,
2010 /*Diagnose=*/!FallbackEnabled)) {
2011 if (!FallbackEnabled)
2012 return true;
2013
2014 // MSVC will fall back on trying to find a matching global operator new
2015 // if operator new[] cannot be found. Also, MSVC will leak by not
2016 // generating a call to operator delete or operator delete[], but we
2017 // will not replicate that bug.
2018 NewName = Context.DeclarationNames.getCXXOperatorName(OO_New);
2019 DeleteName = Context.DeclarationNames.getCXXOperatorName(OO_Delete);
2020 if (FindAllocationOverload(StartLoc, Range, NewName, AllocArgs, TUDecl,
2021 /*AllowMissing=*/false, OperatorNew))
2022 return true;
2023 }
2024 }
2025
2026 // We don't need an operator delete if we're running under
2027 // -fno-exceptions.
2028 if (!getLangOpts().Exceptions) {
2029 OperatorDelete = nullptr;
2030 return false;
2031 }
2032
2033 // C++ [expr.new]p19:
2034 //
2035 // If the new-expression begins with a unary :: operator, the
2036 // deallocation function's name is looked up in the global
2037 // scope. Otherwise, if the allocated type is a class type T or an
2038 // array thereof, the deallocation function's name is looked up in
2039 // the scope of T. If this lookup fails to find the name, or if
2040 // the allocated type is not a class type or array thereof, the
2041 // deallocation function's name is looked up in the global scope.
2042 LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName);
2043 if (AllocElemType->isRecordType() && !UseGlobal) {
2044 CXXRecordDecl *RD
2045 = cast<CXXRecordDecl>(AllocElemType->getAs<RecordType>()->getDecl());
2046 LookupQualifiedName(FoundDelete, RD);
2047 }
2048 if (FoundDelete.isAmbiguous())
2049 return true; // FIXME: clean up expressions?
2050
2051 if (FoundDelete.empty()) {
2052 DeclareGlobalNewDelete();
2053 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2054 }
2055
2056 FoundDelete.suppressDiagnostics();
2057
2058 SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches;
2059
2060 // Whether we're looking for a placement operator delete is dictated
2061 // by whether we selected a placement operator new, not by whether
2062 // we had explicit placement arguments. This matters for things like
2063 // struct A { void *operator new(size_t, int = 0); ... };
2064 // A *a = new A()
2065 bool isPlacementNew = (!PlaceArgs.empty() || OperatorNew->param_size() != 1);
2066
2067 if (isPlacementNew) {
2068 // C++ [expr.new]p20:
2069 // A declaration of a placement deallocation function matches the
2070 // declaration of a placement allocation function if it has the
2071 // same number of parameters and, after parameter transformations
2072 // (8.3.5), all parameter types except the first are
2073 // identical. [...]
2074 //
2075 // To perform this comparison, we compute the function type that
2076 // the deallocation function should have, and use that type both
2077 // for template argument deduction and for comparison purposes.
2078 //
2079 // FIXME: this comparison should ignore CC and the like.
2080 QualType ExpectedFunctionType;
2081 {
2082 const FunctionProtoType *Proto
2083 = OperatorNew->getType()->getAs<FunctionProtoType>();
2084
2085 SmallVector<QualType, 4> ArgTypes;
2086 ArgTypes.push_back(Context.VoidPtrTy);
2087 for (unsigned I = 1, N = Proto->getNumParams(); I < N; ++I)
2088 ArgTypes.push_back(Proto->getParamType(I));
2089
2090 FunctionProtoType::ExtProtoInfo EPI;
2091 EPI.Variadic = Proto->isVariadic();
2092
2093 ExpectedFunctionType
2094 = Context.getFunctionType(Context.VoidTy, ArgTypes, EPI);
2095 }
2096
2097 for (LookupResult::iterator D = FoundDelete.begin(),
2098 DEnd = FoundDelete.end();
2099 D != DEnd; ++D) {
2100 FunctionDecl *Fn = nullptr;
2101 if (FunctionTemplateDecl *FnTmpl
2102 = dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) {
2103 // Perform template argument deduction to try to match the
2104 // expected function type.
2105 TemplateDeductionInfo Info(StartLoc);
2106 if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn,
2107 Info))
2108 continue;
2109 } else
2110 Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl());
2111
2112 if (Context.hasSameType(Fn->getType(), ExpectedFunctionType))
2113 Matches.push_back(std::make_pair(D.getPair(), Fn));
2114 }
2115 } else {
2116 // C++ [expr.new]p20:
2117 // [...] Any non-placement deallocation function matches a
2118 // non-placement allocation function. [...]
2119 for (LookupResult::iterator D = FoundDelete.begin(),
2120 DEnd = FoundDelete.end();
2121 D != DEnd; ++D) {
2122 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>((*D)->getUnderlyingDecl()))
2123 if (isNonPlacementDeallocationFunction(*this, Fn))
2124 Matches.push_back(std::make_pair(D.getPair(), Fn));
2125 }
2126
2127 // C++1y [expr.new]p22:
2128 // For a non-placement allocation function, the normal deallocation
2129 // function lookup is used
2130 // C++1y [expr.delete]p?:
2131 // If [...] deallocation function lookup finds both a usual deallocation
2132 // function with only a pointer parameter and a usual deallocation
2133 // function with both a pointer parameter and a size parameter, then the
2134 // selected deallocation function shall be the one with two parameters.
2135 // Otherwise, the selected deallocation function shall be the function
2136 // with one parameter.
2137 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2138 if (Matches[0].second->getNumParams() == 1)
2139 Matches.erase(Matches.begin());
2140 else
2141 Matches.erase(Matches.begin() + 1);
2142 assert(Matches[0].second->getNumParams() == 2 &&
2143 "found an unexpected usual deallocation function");
2144 }
2145 }
2146
2147 // C++ [expr.new]p20:
2148 // [...] If the lookup finds a single matching deallocation
2149 // function, that function will be called; otherwise, no
2150 // deallocation function will be called.
2151 if (Matches.size() == 1) {
2152 OperatorDelete = Matches[0].second;
2153
2154 // C++0x [expr.new]p20:
2155 // If the lookup finds the two-parameter form of a usual
2156 // deallocation function (3.7.4.2) and that function, considered
2157 // as a placement deallocation function, would have been
2158 // selected as a match for the allocation function, the program
2159 // is ill-formed.
2160 if (!PlaceArgs.empty() && getLangOpts().CPlusPlus11 &&
2161 isNonPlacementDeallocationFunction(*this, OperatorDelete)) {
2162 Diag(StartLoc, diag::err_placement_new_non_placement_delete)
2163 << SourceRange(PlaceArgs.front()->getLocStart(),
2164 PlaceArgs.back()->getLocEnd());
2165 if (!OperatorDelete->isImplicit())
2166 Diag(OperatorDelete->getLocation(), diag::note_previous_decl)
2167 << DeleteName;
2168 } else {
2169 CheckAllocationAccess(StartLoc, Range, FoundDelete.getNamingClass(),
2170 Matches[0].first);
2171 }
2172 }
2173
2174 return false;
2175 }
2176
2177 /// \brief Find an fitting overload for the allocation function
2178 /// in the specified scope.
2179 ///
2180 /// \param StartLoc The location of the 'new' token.
2181 /// \param Range The range of the placement arguments.
2182 /// \param Name The name of the function ('operator new' or 'operator new[]').
2183 /// \param Args The placement arguments specified.
2184 /// \param Ctx The scope in which we should search; either a class scope or the
2185 /// translation unit.
2186 /// \param AllowMissing If \c true, report an error if we can't find any
2187 /// allocation functions. Otherwise, succeed but don't fill in \p
2188 /// Operator.
2189 /// \param Operator Filled in with the found allocation function. Unchanged if
2190 /// no allocation function was found.
2191 /// \param Diagnose If \c true, issue errors if the allocation function is not
2192 /// usable.
FindAllocationOverload(SourceLocation StartLoc,SourceRange Range,DeclarationName Name,MultiExprArg Args,DeclContext * Ctx,bool AllowMissing,FunctionDecl * & Operator,bool Diagnose)2193 bool Sema::FindAllocationOverload(SourceLocation StartLoc, SourceRange Range,
2194 DeclarationName Name, MultiExprArg Args,
2195 DeclContext *Ctx,
2196 bool AllowMissing, FunctionDecl *&Operator,
2197 bool Diagnose) {
2198 LookupResult R(*this, Name, StartLoc, LookupOrdinaryName);
2199 LookupQualifiedName(R, Ctx);
2200 if (R.empty()) {
2201 if (AllowMissing || !Diagnose)
2202 return false;
2203 return Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
2204 << Name << Range;
2205 }
2206
2207 if (R.isAmbiguous())
2208 return true;
2209
2210 R.suppressDiagnostics();
2211
2212 OverloadCandidateSet Candidates(StartLoc, OverloadCandidateSet::CSK_Normal);
2213 for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end();
2214 Alloc != AllocEnd; ++Alloc) {
2215 // Even member operator new/delete are implicitly treated as
2216 // static, so don't use AddMemberCandidate.
2217 NamedDecl *D = (*Alloc)->getUnderlyingDecl();
2218
2219 if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
2220 AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(),
2221 /*ExplicitTemplateArgs=*/nullptr,
2222 Args, Candidates,
2223 /*SuppressUserConversions=*/false);
2224 continue;
2225 }
2226
2227 FunctionDecl *Fn = cast<FunctionDecl>(D);
2228 AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates,
2229 /*SuppressUserConversions=*/false);
2230 }
2231
2232 // Do the resolution.
2233 OverloadCandidateSet::iterator Best;
2234 switch (Candidates.BestViableFunction(*this, StartLoc, Best)) {
2235 case OR_Success: {
2236 // Got one!
2237 FunctionDecl *FnDecl = Best->Function;
2238 if (CheckAllocationAccess(StartLoc, Range, R.getNamingClass(),
2239 Best->FoundDecl, Diagnose) == AR_inaccessible)
2240 return true;
2241
2242 Operator = FnDecl;
2243 return false;
2244 }
2245
2246 case OR_No_Viable_Function:
2247 if (Diagnose) {
2248 Diag(StartLoc, diag::err_ovl_no_viable_function_in_call)
2249 << Name << Range;
2250 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
2251 }
2252 return true;
2253
2254 case OR_Ambiguous:
2255 if (Diagnose) {
2256 Diag(StartLoc, diag::err_ovl_ambiguous_call)
2257 << Name << Range;
2258 Candidates.NoteCandidates(*this, OCD_ViableCandidates, Args);
2259 }
2260 return true;
2261
2262 case OR_Deleted: {
2263 if (Diagnose) {
2264 Diag(StartLoc, diag::err_ovl_deleted_call)
2265 << Best->Function->isDeleted()
2266 << Name
2267 << getDeletedOrUnavailableSuffix(Best->Function)
2268 << Range;
2269 Candidates.NoteCandidates(*this, OCD_AllCandidates, Args);
2270 }
2271 return true;
2272 }
2273 }
2274 llvm_unreachable("Unreachable, bad result from BestViableFunction");
2275 }
2276
2277
2278 /// DeclareGlobalNewDelete - Declare the global forms of operator new and
2279 /// delete. These are:
2280 /// @code
2281 /// // C++03:
2282 /// void* operator new(std::size_t) throw(std::bad_alloc);
2283 /// void* operator new[](std::size_t) throw(std::bad_alloc);
2284 /// void operator delete(void *) throw();
2285 /// void operator delete[](void *) throw();
2286 /// // C++11:
2287 /// void* operator new(std::size_t);
2288 /// void* operator new[](std::size_t);
2289 /// void operator delete(void *) noexcept;
2290 /// void operator delete[](void *) noexcept;
2291 /// // C++1y:
2292 /// void* operator new(std::size_t);
2293 /// void* operator new[](std::size_t);
2294 /// void operator delete(void *) noexcept;
2295 /// void operator delete[](void *) noexcept;
2296 /// void operator delete(void *, std::size_t) noexcept;
2297 /// void operator delete[](void *, std::size_t) noexcept;
2298 /// @endcode
2299 /// Note that the placement and nothrow forms of new are *not* implicitly
2300 /// declared. Their use requires including \<new\>.
DeclareGlobalNewDelete()2301 void Sema::DeclareGlobalNewDelete() {
2302 if (GlobalNewDeleteDeclared)
2303 return;
2304
2305 // C++ [basic.std.dynamic]p2:
2306 // [...] The following allocation and deallocation functions (18.4) are
2307 // implicitly declared in global scope in each translation unit of a
2308 // program
2309 //
2310 // C++03:
2311 // void* operator new(std::size_t) throw(std::bad_alloc);
2312 // void* operator new[](std::size_t) throw(std::bad_alloc);
2313 // void operator delete(void*) throw();
2314 // void operator delete[](void*) throw();
2315 // C++11:
2316 // void* operator new(std::size_t);
2317 // void* operator new[](std::size_t);
2318 // void operator delete(void*) noexcept;
2319 // void operator delete[](void*) noexcept;
2320 // C++1y:
2321 // void* operator new(std::size_t);
2322 // void* operator new[](std::size_t);
2323 // void operator delete(void*) noexcept;
2324 // void operator delete[](void*) noexcept;
2325 // void operator delete(void*, std::size_t) noexcept;
2326 // void operator delete[](void*, std::size_t) noexcept;
2327 //
2328 // These implicit declarations introduce only the function names operator
2329 // new, operator new[], operator delete, operator delete[].
2330 //
2331 // Here, we need to refer to std::bad_alloc, so we will implicitly declare
2332 // "std" or "bad_alloc" as necessary to form the exception specification.
2333 // However, we do not make these implicit declarations visible to name
2334 // lookup.
2335 if (!StdBadAlloc && !getLangOpts().CPlusPlus11) {
2336 // The "std::bad_alloc" class has not yet been declared, so build it
2337 // implicitly.
2338 StdBadAlloc = CXXRecordDecl::Create(Context, TTK_Class,
2339 getOrCreateStdNamespace(),
2340 SourceLocation(), SourceLocation(),
2341 &PP.getIdentifierTable().get("bad_alloc"),
2342 nullptr);
2343 getStdBadAlloc()->setImplicit(true);
2344 }
2345
2346 GlobalNewDeleteDeclared = true;
2347
2348 QualType VoidPtr = Context.getPointerType(Context.VoidTy);
2349 QualType SizeT = Context.getSizeType();
2350
2351 DeclareGlobalAllocationFunction(
2352 Context.DeclarationNames.getCXXOperatorName(OO_New),
2353 VoidPtr, SizeT, QualType());
2354 DeclareGlobalAllocationFunction(
2355 Context.DeclarationNames.getCXXOperatorName(OO_Array_New),
2356 VoidPtr, SizeT, QualType());
2357 DeclareGlobalAllocationFunction(
2358 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2359 Context.VoidTy, VoidPtr);
2360 DeclareGlobalAllocationFunction(
2361 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2362 Context.VoidTy, VoidPtr);
2363 if (getLangOpts().SizedDeallocation) {
2364 DeclareGlobalAllocationFunction(
2365 Context.DeclarationNames.getCXXOperatorName(OO_Delete),
2366 Context.VoidTy, VoidPtr, Context.getSizeType());
2367 DeclareGlobalAllocationFunction(
2368 Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete),
2369 Context.VoidTy, VoidPtr, Context.getSizeType());
2370 }
2371 }
2372
2373 /// DeclareGlobalAllocationFunction - Declares a single implicit global
2374 /// allocation function if it doesn't already exist.
DeclareGlobalAllocationFunction(DeclarationName Name,QualType Return,QualType Param1,QualType Param2)2375 void Sema::DeclareGlobalAllocationFunction(DeclarationName Name,
2376 QualType Return,
2377 QualType Param1, QualType Param2) {
2378 DeclContext *GlobalCtx = Context.getTranslationUnitDecl();
2379 unsigned NumParams = Param2.isNull() ? 1 : 2;
2380
2381 // Check if this function is already declared.
2382 DeclContext::lookup_result R = GlobalCtx->lookup(Name);
2383 for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end();
2384 Alloc != AllocEnd; ++Alloc) {
2385 // Only look at non-template functions, as it is the predefined,
2386 // non-templated allocation function we are trying to declare here.
2387 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) {
2388 if (Func->getNumParams() == NumParams) {
2389 QualType InitialParam1Type =
2390 Context.getCanonicalType(Func->getParamDecl(0)
2391 ->getType().getUnqualifiedType());
2392 QualType InitialParam2Type =
2393 NumParams == 2
2394 ? Context.getCanonicalType(Func->getParamDecl(1)
2395 ->getType().getUnqualifiedType())
2396 : QualType();
2397 // FIXME: Do we need to check for default arguments here?
2398 if (InitialParam1Type == Param1 &&
2399 (NumParams == 1 || InitialParam2Type == Param2)) {
2400 // Make the function visible to name lookup, even if we found it in
2401 // an unimported module. It either is an implicitly-declared global
2402 // allocation function, or is suppressing that function.
2403 Func->setHidden(false);
2404 return;
2405 }
2406 }
2407 }
2408 }
2409
2410 FunctionProtoType::ExtProtoInfo EPI;
2411
2412 QualType BadAllocType;
2413 bool HasBadAllocExceptionSpec
2414 = (Name.getCXXOverloadedOperator() == OO_New ||
2415 Name.getCXXOverloadedOperator() == OO_Array_New);
2416 if (HasBadAllocExceptionSpec) {
2417 if (!getLangOpts().CPlusPlus11) {
2418 BadAllocType = Context.getTypeDeclType(getStdBadAlloc());
2419 assert(StdBadAlloc && "Must have std::bad_alloc declared");
2420 EPI.ExceptionSpec.Type = EST_Dynamic;
2421 EPI.ExceptionSpec.Exceptions = llvm::makeArrayRef(BadAllocType);
2422 }
2423 } else {
2424 EPI.ExceptionSpec =
2425 getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone;
2426 }
2427
2428 QualType Params[] = { Param1, Param2 };
2429
2430 QualType FnType = Context.getFunctionType(
2431 Return, llvm::makeArrayRef(Params, NumParams), EPI);
2432 FunctionDecl *Alloc =
2433 FunctionDecl::Create(Context, GlobalCtx, SourceLocation(),
2434 SourceLocation(), Name,
2435 FnType, /*TInfo=*/nullptr, SC_None, false, true);
2436 Alloc->setImplicit();
2437
2438 // Implicit sized deallocation functions always have default visibility.
2439 Alloc->addAttr(VisibilityAttr::CreateImplicit(Context,
2440 VisibilityAttr::Default));
2441
2442 ParmVarDecl *ParamDecls[2];
2443 for (unsigned I = 0; I != NumParams; ++I) {
2444 ParamDecls[I] = ParmVarDecl::Create(Context, Alloc, SourceLocation(),
2445 SourceLocation(), nullptr,
2446 Params[I], /*TInfo=*/nullptr,
2447 SC_None, nullptr);
2448 ParamDecls[I]->setImplicit();
2449 }
2450 Alloc->setParams(llvm::makeArrayRef(ParamDecls, NumParams));
2451
2452 Context.getTranslationUnitDecl()->addDecl(Alloc);
2453 IdResolver.tryAddTopLevelDecl(Alloc, Name);
2454 }
2455
FindUsualDeallocationFunction(SourceLocation StartLoc,bool CanProvideSize,DeclarationName Name)2456 FunctionDecl *Sema::FindUsualDeallocationFunction(SourceLocation StartLoc,
2457 bool CanProvideSize,
2458 DeclarationName Name) {
2459 DeclareGlobalNewDelete();
2460
2461 LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName);
2462 LookupQualifiedName(FoundDelete, Context.getTranslationUnitDecl());
2463
2464 // C++ [expr.new]p20:
2465 // [...] Any non-placement deallocation function matches a
2466 // non-placement allocation function. [...]
2467 llvm::SmallVector<FunctionDecl*, 2> Matches;
2468 for (LookupResult::iterator D = FoundDelete.begin(),
2469 DEnd = FoundDelete.end();
2470 D != DEnd; ++D) {
2471 if (FunctionDecl *Fn = dyn_cast<FunctionDecl>(*D))
2472 if (isNonPlacementDeallocationFunction(*this, Fn))
2473 Matches.push_back(Fn);
2474 }
2475
2476 // C++1y [expr.delete]p?:
2477 // If the type is complete and deallocation function lookup finds both a
2478 // usual deallocation function with only a pointer parameter and a usual
2479 // deallocation function with both a pointer parameter and a size
2480 // parameter, then the selected deallocation function shall be the one
2481 // with two parameters. Otherwise, the selected deallocation function
2482 // shall be the function with one parameter.
2483 if (getLangOpts().SizedDeallocation && Matches.size() == 2) {
2484 unsigned NumArgs = CanProvideSize ? 2 : 1;
2485 if (Matches[0]->getNumParams() != NumArgs)
2486 Matches.erase(Matches.begin());
2487 else
2488 Matches.erase(Matches.begin() + 1);
2489 assert(Matches[0]->getNumParams() == NumArgs &&
2490 "found an unexpected usual deallocation function");
2491 }
2492
2493 if (getLangOpts().CUDA)
2494 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2495
2496 assert(Matches.size() == 1 &&
2497 "unexpectedly have multiple usual deallocation functions");
2498 return Matches.front();
2499 }
2500
FindDeallocationFunction(SourceLocation StartLoc,CXXRecordDecl * RD,DeclarationName Name,FunctionDecl * & Operator,bool Diagnose)2501 bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD,
2502 DeclarationName Name,
2503 FunctionDecl* &Operator, bool Diagnose) {
2504 LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName);
2505 // Try to find operator delete/operator delete[] in class scope.
2506 LookupQualifiedName(Found, RD);
2507
2508 if (Found.isAmbiguous())
2509 return true;
2510
2511 Found.suppressDiagnostics();
2512
2513 SmallVector<DeclAccessPair,4> Matches;
2514 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2515 F != FEnd; ++F) {
2516 NamedDecl *ND = (*F)->getUnderlyingDecl();
2517
2518 // Ignore template operator delete members from the check for a usual
2519 // deallocation function.
2520 if (isa<FunctionTemplateDecl>(ND))
2521 continue;
2522
2523 if (cast<CXXMethodDecl>(ND)->isUsualDeallocationFunction())
2524 Matches.push_back(F.getPair());
2525 }
2526
2527 if (getLangOpts().CUDA)
2528 EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(CurContext), Matches);
2529
2530 // There's exactly one suitable operator; pick it.
2531 if (Matches.size() == 1) {
2532 Operator = cast<CXXMethodDecl>(Matches[0]->getUnderlyingDecl());
2533
2534 if (Operator->isDeleted()) {
2535 if (Diagnose) {
2536 Diag(StartLoc, diag::err_deleted_function_use);
2537 NoteDeletedFunction(Operator);
2538 }
2539 return true;
2540 }
2541
2542 if (CheckAllocationAccess(StartLoc, SourceRange(), Found.getNamingClass(),
2543 Matches[0], Diagnose) == AR_inaccessible)
2544 return true;
2545
2546 return false;
2547
2548 // We found multiple suitable operators; complain about the ambiguity.
2549 } else if (!Matches.empty()) {
2550 if (Diagnose) {
2551 Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found)
2552 << Name << RD;
2553
2554 for (SmallVectorImpl<DeclAccessPair>::iterator
2555 F = Matches.begin(), FEnd = Matches.end(); F != FEnd; ++F)
2556 Diag((*F)->getUnderlyingDecl()->getLocation(),
2557 diag::note_member_declared_here) << Name;
2558 }
2559 return true;
2560 }
2561
2562 // We did find operator delete/operator delete[] declarations, but
2563 // none of them were suitable.
2564 if (!Found.empty()) {
2565 if (Diagnose) {
2566 Diag(StartLoc, diag::err_no_suitable_delete_member_function_found)
2567 << Name << RD;
2568
2569 for (LookupResult::iterator F = Found.begin(), FEnd = Found.end();
2570 F != FEnd; ++F)
2571 Diag((*F)->getUnderlyingDecl()->getLocation(),
2572 diag::note_member_declared_here) << Name;
2573 }
2574 return true;
2575 }
2576
2577 Operator = nullptr;
2578 return false;
2579 }
2580
2581 namespace {
2582 /// \brief Checks whether delete-expression, and new-expression used for
2583 /// initializing deletee have the same array form.
2584 class MismatchingNewDeleteDetector {
2585 public:
2586 enum MismatchResult {
2587 /// Indicates that there is no mismatch or a mismatch cannot be proven.
2588 NoMismatch,
2589 /// Indicates that variable is initialized with mismatching form of \a new.
2590 VarInitMismatches,
2591 /// Indicates that member is initialized with mismatching form of \a new.
2592 MemberInitMismatches,
2593 /// Indicates that 1 or more constructors' definitions could not been
2594 /// analyzed, and they will be checked again at the end of translation unit.
2595 AnalyzeLater
2596 };
2597
2598 /// \param EndOfTU True, if this is the final analysis at the end of
2599 /// translation unit. False, if this is the initial analysis at the point
2600 /// delete-expression was encountered.
MismatchingNewDeleteDetector(bool EndOfTU)2601 explicit MismatchingNewDeleteDetector(bool EndOfTU)
2602 : IsArrayForm(false), Field(nullptr), EndOfTU(EndOfTU),
2603 HasUndefinedConstructors(false) {}
2604
2605 /// \brief Checks whether pointee of a delete-expression is initialized with
2606 /// matching form of new-expression.
2607 ///
2608 /// If return value is \c VarInitMismatches or \c MemberInitMismatches at the
2609 /// point where delete-expression is encountered, then a warning will be
2610 /// issued immediately. If return value is \c AnalyzeLater at the point where
2611 /// delete-expression is seen, then member will be analyzed at the end of
2612 /// translation unit. \c AnalyzeLater is returned iff at least one constructor
2613 /// couldn't be analyzed. If at least one constructor initializes the member
2614 /// with matching type of new, the return value is \c NoMismatch.
2615 MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE);
2616 /// \brief Analyzes a class member.
2617 /// \param Field Class member to analyze.
2618 /// \param DeleteWasArrayForm Array form-ness of the delete-expression used
2619 /// for deleting the \p Field.
2620 MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm);
2621 /// List of mismatching new-expressions used for initialization of the pointee
2622 llvm::SmallVector<const CXXNewExpr *, 4> NewExprs;
2623 /// Indicates whether delete-expression was in array form.
2624 bool IsArrayForm;
2625 FieldDecl *Field;
2626
2627 private:
2628 const bool EndOfTU;
2629 /// \brief Indicates that there is at least one constructor without body.
2630 bool HasUndefinedConstructors;
2631 /// \brief Returns \c CXXNewExpr from given initialization expression.
2632 /// \param E Expression used for initializing pointee in delete-expression.
2633 /// E can be a single-element \c InitListExpr consisting of new-expression.
2634 const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E);
2635 /// \brief Returns whether member is initialized with mismatching form of
2636 /// \c new either by the member initializer or in-class initialization.
2637 ///
2638 /// If bodies of all constructors are not visible at the end of translation
2639 /// unit or at least one constructor initializes member with the matching
2640 /// form of \c new, mismatch cannot be proven, and this function will return
2641 /// \c NoMismatch.
2642 MismatchResult analyzeMemberExpr(const MemberExpr *ME);
2643 /// \brief Returns whether variable is initialized with mismatching form of
2644 /// \c new.
2645 ///
2646 /// If variable is initialized with matching form of \c new or variable is not
2647 /// initialized with a \c new expression, this function will return true.
2648 /// If variable is initialized with mismatching form of \c new, returns false.
2649 /// \param D Variable to analyze.
2650 bool hasMatchingVarInit(const DeclRefExpr *D);
2651 /// \brief Checks whether the constructor initializes pointee with mismatching
2652 /// form of \c new.
2653 ///
2654 /// Returns true, if member is initialized with matching form of \c new in
2655 /// member initializer list. Returns false, if member is initialized with the
2656 /// matching form of \c new in this constructor's initializer or given
2657 /// constructor isn't defined at the point where delete-expression is seen, or
2658 /// member isn't initialized by the constructor.
2659 bool hasMatchingNewInCtor(const CXXConstructorDecl *CD);
2660 /// \brief Checks whether member is initialized with matching form of
2661 /// \c new in member initializer list.
2662 bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI);
2663 /// Checks whether member is initialized with mismatching form of \c new by
2664 /// in-class initializer.
2665 MismatchResult analyzeInClassInitializer();
2666 };
2667 }
2668
2669 MismatchingNewDeleteDetector::MismatchResult
analyzeDeleteExpr(const CXXDeleteExpr * DE)2670 MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) {
2671 NewExprs.clear();
2672 assert(DE && "Expected delete-expression");
2673 IsArrayForm = DE->isArrayForm();
2674 const Expr *E = DE->getArgument()->IgnoreParenImpCasts();
2675 if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) {
2676 return analyzeMemberExpr(ME);
2677 } else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) {
2678 if (!hasMatchingVarInit(D))
2679 return VarInitMismatches;
2680 }
2681 return NoMismatch;
2682 }
2683
2684 const CXXNewExpr *
getNewExprFromInitListOrExpr(const Expr * E)2685 MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) {
2686 assert(E != nullptr && "Expected a valid initializer expression");
2687 E = E->IgnoreParenImpCasts();
2688 if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) {
2689 if (ILE->getNumInits() == 1)
2690 E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts());
2691 }
2692
2693 return dyn_cast_or_null<const CXXNewExpr>(E);
2694 }
2695
hasMatchingNewInCtorInit(const CXXCtorInitializer * CI)2696 bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit(
2697 const CXXCtorInitializer *CI) {
2698 const CXXNewExpr *NE = nullptr;
2699 if (Field == CI->getMember() &&
2700 (NE = getNewExprFromInitListOrExpr(CI->getInit()))) {
2701 if (NE->isArray() == IsArrayForm)
2702 return true;
2703 else
2704 NewExprs.push_back(NE);
2705 }
2706 return false;
2707 }
2708
hasMatchingNewInCtor(const CXXConstructorDecl * CD)2709 bool MismatchingNewDeleteDetector::hasMatchingNewInCtor(
2710 const CXXConstructorDecl *CD) {
2711 if (CD->isImplicit())
2712 return false;
2713 const FunctionDecl *Definition = CD;
2714 if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) {
2715 HasUndefinedConstructors = true;
2716 return EndOfTU;
2717 }
2718 for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) {
2719 if (hasMatchingNewInCtorInit(CI))
2720 return true;
2721 }
2722 return false;
2723 }
2724
2725 MismatchingNewDeleteDetector::MismatchResult
analyzeInClassInitializer()2726 MismatchingNewDeleteDetector::analyzeInClassInitializer() {
2727 assert(Field != nullptr && "This should be called only for members");
2728 const Expr *InitExpr = Field->getInClassInitializer();
2729 if (!InitExpr)
2730 return EndOfTU ? NoMismatch : AnalyzeLater;
2731 if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) {
2732 if (NE->isArray() != IsArrayForm) {
2733 NewExprs.push_back(NE);
2734 return MemberInitMismatches;
2735 }
2736 }
2737 return NoMismatch;
2738 }
2739
2740 MismatchingNewDeleteDetector::MismatchResult
analyzeField(FieldDecl * Field,bool DeleteWasArrayForm)2741 MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field,
2742 bool DeleteWasArrayForm) {
2743 assert(Field != nullptr && "Analysis requires a valid class member.");
2744 this->Field = Field;
2745 IsArrayForm = DeleteWasArrayForm;
2746 const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent());
2747 for (const auto *CD : RD->ctors()) {
2748 if (hasMatchingNewInCtor(CD))
2749 return NoMismatch;
2750 }
2751 if (HasUndefinedConstructors)
2752 return EndOfTU ? NoMismatch : AnalyzeLater;
2753 if (!NewExprs.empty())
2754 return MemberInitMismatches;
2755 return Field->hasInClassInitializer() ? analyzeInClassInitializer()
2756 : NoMismatch;
2757 }
2758
2759 MismatchingNewDeleteDetector::MismatchResult
analyzeMemberExpr(const MemberExpr * ME)2760 MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) {
2761 assert(ME != nullptr && "Expected a member expression");
2762 if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl()))
2763 return analyzeField(F, IsArrayForm);
2764 return NoMismatch;
2765 }
2766
hasMatchingVarInit(const DeclRefExpr * D)2767 bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) {
2768 const CXXNewExpr *NE = nullptr;
2769 if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) {
2770 if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) &&
2771 NE->isArray() != IsArrayForm) {
2772 NewExprs.push_back(NE);
2773 }
2774 }
2775 return NewExprs.empty();
2776 }
2777
2778 static void
DiagnoseMismatchedNewDelete(Sema & SemaRef,SourceLocation DeleteLoc,const MismatchingNewDeleteDetector & Detector)2779 DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc,
2780 const MismatchingNewDeleteDetector &Detector) {
2781 SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc);
2782 FixItHint H;
2783 if (!Detector.IsArrayForm)
2784 H = FixItHint::CreateInsertion(EndOfDelete, "[]");
2785 else {
2786 SourceLocation RSquare = Lexer::findLocationAfterToken(
2787 DeleteLoc, tok::l_square, SemaRef.getSourceManager(),
2788 SemaRef.getLangOpts(), true);
2789 if (RSquare.isValid())
2790 H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare));
2791 }
2792 SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new)
2793 << Detector.IsArrayForm << H;
2794
2795 for (const auto *NE : Detector.NewExprs)
2796 SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here)
2797 << Detector.IsArrayForm;
2798 }
2799
AnalyzeDeleteExprMismatch(const CXXDeleteExpr * DE)2800 void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) {
2801 if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation()))
2802 return;
2803 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false);
2804 switch (Detector.analyzeDeleteExpr(DE)) {
2805 case MismatchingNewDeleteDetector::VarInitMismatches:
2806 case MismatchingNewDeleteDetector::MemberInitMismatches: {
2807 DiagnoseMismatchedNewDelete(*this, DE->getLocStart(), Detector);
2808 break;
2809 }
2810 case MismatchingNewDeleteDetector::AnalyzeLater: {
2811 DeleteExprs[Detector.Field].push_back(
2812 std::make_pair(DE->getLocStart(), DE->isArrayForm()));
2813 break;
2814 }
2815 case MismatchingNewDeleteDetector::NoMismatch:
2816 break;
2817 }
2818 }
2819
AnalyzeDeleteExprMismatch(FieldDecl * Field,SourceLocation DeleteLoc,bool DeleteWasArrayForm)2820 void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc,
2821 bool DeleteWasArrayForm) {
2822 MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true);
2823 switch (Detector.analyzeField(Field, DeleteWasArrayForm)) {
2824 case MismatchingNewDeleteDetector::VarInitMismatches:
2825 llvm_unreachable("This analysis should have been done for class members.");
2826 case MismatchingNewDeleteDetector::AnalyzeLater:
2827 llvm_unreachable("Analysis cannot be postponed any point beyond end of "
2828 "translation unit.");
2829 case MismatchingNewDeleteDetector::MemberInitMismatches:
2830 DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector);
2831 break;
2832 case MismatchingNewDeleteDetector::NoMismatch:
2833 break;
2834 }
2835 }
2836
2837 /// ActOnCXXDelete - Parsed a C++ 'delete' expression (C++ 5.3.5), as in:
2838 /// @code ::delete ptr; @endcode
2839 /// or
2840 /// @code delete [] ptr; @endcode
2841 ExprResult
ActOnCXXDelete(SourceLocation StartLoc,bool UseGlobal,bool ArrayForm,Expr * ExE)2842 Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal,
2843 bool ArrayForm, Expr *ExE) {
2844 // C++ [expr.delete]p1:
2845 // The operand shall have a pointer type, or a class type having a single
2846 // non-explicit conversion function to a pointer type. The result has type
2847 // void.
2848 //
2849 // DR599 amends "pointer type" to "pointer to object type" in both cases.
2850
2851 ExprResult Ex = ExE;
2852 FunctionDecl *OperatorDelete = nullptr;
2853 bool ArrayFormAsWritten = ArrayForm;
2854 bool UsualArrayDeleteWantsSize = false;
2855
2856 if (!Ex.get()->isTypeDependent()) {
2857 // Perform lvalue-to-rvalue cast, if needed.
2858 Ex = DefaultLvalueConversion(Ex.get());
2859 if (Ex.isInvalid())
2860 return ExprError();
2861
2862 QualType Type = Ex.get()->getType();
2863
2864 class DeleteConverter : public ContextualImplicitConverter {
2865 public:
2866 DeleteConverter() : ContextualImplicitConverter(false, true) {}
2867
2868 bool match(QualType ConvType) override {
2869 // FIXME: If we have an operator T* and an operator void*, we must pick
2870 // the operator T*.
2871 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
2872 if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType())
2873 return true;
2874 return false;
2875 }
2876
2877 SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc,
2878 QualType T) override {
2879 return S.Diag(Loc, diag::err_delete_operand) << T;
2880 }
2881
2882 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
2883 QualType T) override {
2884 return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T;
2885 }
2886
2887 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
2888 QualType T,
2889 QualType ConvTy) override {
2890 return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy;
2891 }
2892
2893 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
2894 QualType ConvTy) override {
2895 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2896 << ConvTy;
2897 }
2898
2899 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
2900 QualType T) override {
2901 return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T;
2902 }
2903
2904 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
2905 QualType ConvTy) override {
2906 return S.Diag(Conv->getLocation(), diag::note_delete_conversion)
2907 << ConvTy;
2908 }
2909
2910 SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc,
2911 QualType T,
2912 QualType ConvTy) override {
2913 llvm_unreachable("conversion functions are permitted");
2914 }
2915 } Converter;
2916
2917 Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter);
2918 if (Ex.isInvalid())
2919 return ExprError();
2920 Type = Ex.get()->getType();
2921 if (!Converter.match(Type))
2922 // FIXME: PerformContextualImplicitConversion should return ExprError
2923 // itself in this case.
2924 return ExprError();
2925
2926 QualType Pointee = Type->getAs<PointerType>()->getPointeeType();
2927 QualType PointeeElem = Context.getBaseElementType(Pointee);
2928
2929 if (unsigned AddressSpace = Pointee.getAddressSpace())
2930 return Diag(Ex.get()->getLocStart(),
2931 diag::err_address_space_qualified_delete)
2932 << Pointee.getUnqualifiedType() << AddressSpace;
2933
2934 CXXRecordDecl *PointeeRD = nullptr;
2935 if (Pointee->isVoidType() && !isSFINAEContext()) {
2936 // The C++ standard bans deleting a pointer to a non-object type, which
2937 // effectively bans deletion of "void*". However, most compilers support
2938 // this, so we treat it as a warning unless we're in a SFINAE context.
2939 Diag(StartLoc, diag::ext_delete_void_ptr_operand)
2940 << Type << Ex.get()->getSourceRange();
2941 } else if (Pointee->isFunctionType() || Pointee->isVoidType()) {
2942 return ExprError(Diag(StartLoc, diag::err_delete_operand)
2943 << Type << Ex.get()->getSourceRange());
2944 } else if (!Pointee->isDependentType()) {
2945 // FIXME: This can result in errors if the definition was imported from a
2946 // module but is hidden.
2947 if (!RequireCompleteType(StartLoc, Pointee,
2948 diag::warn_delete_incomplete, Ex.get())) {
2949 if (const RecordType *RT = PointeeElem->getAs<RecordType>())
2950 PointeeRD = cast<CXXRecordDecl>(RT->getDecl());
2951 }
2952 }
2953
2954 if (Pointee->isArrayType() && !ArrayForm) {
2955 Diag(StartLoc, diag::warn_delete_array_type)
2956 << Type << Ex.get()->getSourceRange()
2957 << FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]");
2958 ArrayForm = true;
2959 }
2960
2961 DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName(
2962 ArrayForm ? OO_Array_Delete : OO_Delete);
2963
2964 if (PointeeRD) {
2965 if (!UseGlobal &&
2966 FindDeallocationFunction(StartLoc, PointeeRD, DeleteName,
2967 OperatorDelete))
2968 return ExprError();
2969
2970 // If we're allocating an array of records, check whether the
2971 // usual operator delete[] has a size_t parameter.
2972 if (ArrayForm) {
2973 // If the user specifically asked to use the global allocator,
2974 // we'll need to do the lookup into the class.
2975 if (UseGlobal)
2976 UsualArrayDeleteWantsSize =
2977 doesUsualArrayDeleteWantSize(*this, StartLoc, PointeeElem);
2978
2979 // Otherwise, the usual operator delete[] should be the
2980 // function we just found.
2981 else if (OperatorDelete && isa<CXXMethodDecl>(OperatorDelete))
2982 UsualArrayDeleteWantsSize = (OperatorDelete->getNumParams() == 2);
2983 }
2984
2985 if (!PointeeRD->hasIrrelevantDestructor())
2986 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
2987 MarkFunctionReferenced(StartLoc,
2988 const_cast<CXXDestructorDecl*>(Dtor));
2989 if (DiagnoseUseOfDecl(Dtor, StartLoc))
2990 return ExprError();
2991 }
2992
2993 CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc,
2994 /*IsDelete=*/true, /*CallCanBeVirtual=*/true,
2995 /*WarnOnNonAbstractTypes=*/!ArrayForm,
2996 SourceLocation());
2997 }
2998
2999 if (!OperatorDelete)
3000 // Look for a global declaration.
3001 OperatorDelete = FindUsualDeallocationFunction(
3002 StartLoc, isCompleteType(StartLoc, Pointee) &&
3003 (!ArrayForm || UsualArrayDeleteWantsSize ||
3004 Pointee.isDestructedType()),
3005 DeleteName);
3006
3007 MarkFunctionReferenced(StartLoc, OperatorDelete);
3008
3009 // Check access and ambiguity of operator delete and destructor.
3010 if (PointeeRD) {
3011 if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) {
3012 CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor,
3013 PDiag(diag::err_access_dtor) << PointeeElem);
3014 }
3015 }
3016 }
3017
3018 CXXDeleteExpr *Result = new (Context) CXXDeleteExpr(
3019 Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten,
3020 UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc);
3021 AnalyzeDeleteExprMismatch(Result);
3022 return Result;
3023 }
3024
CheckVirtualDtorCall(CXXDestructorDecl * dtor,SourceLocation Loc,bool IsDelete,bool CallCanBeVirtual,bool WarnOnNonAbstractTypes,SourceLocation DtorLoc)3025 void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc,
3026 bool IsDelete, bool CallCanBeVirtual,
3027 bool WarnOnNonAbstractTypes,
3028 SourceLocation DtorLoc) {
3029 if (!dtor || dtor->isVirtual() || !CallCanBeVirtual)
3030 return;
3031
3032 // C++ [expr.delete]p3:
3033 // In the first alternative (delete object), if the static type of the
3034 // object to be deleted is different from its dynamic type, the static
3035 // type shall be a base class of the dynamic type of the object to be
3036 // deleted and the static type shall have a virtual destructor or the
3037 // behavior is undefined.
3038 //
3039 const CXXRecordDecl *PointeeRD = dtor->getParent();
3040 // Note: a final class cannot be derived from, no issue there
3041 if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>())
3042 return;
3043
3044 QualType ClassType = dtor->getThisType(Context)->getPointeeType();
3045 if (PointeeRD->isAbstract()) {
3046 // If the class is abstract, we warn by default, because we're
3047 // sure the code has undefined behavior.
3048 Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1)
3049 << ClassType;
3050 } else if (WarnOnNonAbstractTypes) {
3051 // Otherwise, if this is not an array delete, it's a bit suspect,
3052 // but not necessarily wrong.
3053 Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1)
3054 << ClassType;
3055 }
3056 if (!IsDelete) {
3057 std::string TypeStr;
3058 ClassType.getAsStringInternal(TypeStr, getPrintingPolicy());
3059 Diag(DtorLoc, diag::note_delete_non_virtual)
3060 << FixItHint::CreateInsertion(DtorLoc, TypeStr + "::");
3061 }
3062 }
3063
ActOnConditionVariable(Decl * ConditionVar,SourceLocation StmtLoc,ConditionKind CK)3064 Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar,
3065 SourceLocation StmtLoc,
3066 ConditionKind CK) {
3067 ExprResult E =
3068 CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK);
3069 if (E.isInvalid())
3070 return ConditionError();
3071 return ConditionResult(*this, ConditionVar, MakeFullExpr(E.get(), StmtLoc),
3072 CK == ConditionKind::ConstexprIf);
3073 }
3074
3075 /// \brief Check the use of the given variable as a C++ condition in an if,
3076 /// while, do-while, or switch statement.
CheckConditionVariable(VarDecl * ConditionVar,SourceLocation StmtLoc,ConditionKind CK)3077 ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar,
3078 SourceLocation StmtLoc,
3079 ConditionKind CK) {
3080 if (ConditionVar->isInvalidDecl())
3081 return ExprError();
3082
3083 QualType T = ConditionVar->getType();
3084
3085 // C++ [stmt.select]p2:
3086 // The declarator shall not specify a function or an array.
3087 if (T->isFunctionType())
3088 return ExprError(Diag(ConditionVar->getLocation(),
3089 diag::err_invalid_use_of_function_type)
3090 << ConditionVar->getSourceRange());
3091 else if (T->isArrayType())
3092 return ExprError(Diag(ConditionVar->getLocation(),
3093 diag::err_invalid_use_of_array_type)
3094 << ConditionVar->getSourceRange());
3095
3096 ExprResult Condition = DeclRefExpr::Create(
3097 Context, NestedNameSpecifierLoc(), SourceLocation(), ConditionVar,
3098 /*enclosing*/ false, ConditionVar->getLocation(),
3099 ConditionVar->getType().getNonReferenceType(), VK_LValue);
3100
3101 MarkDeclRefReferenced(cast<DeclRefExpr>(Condition.get()));
3102
3103 switch (CK) {
3104 case ConditionKind::Boolean:
3105 return CheckBooleanCondition(StmtLoc, Condition.get());
3106
3107 case ConditionKind::ConstexprIf:
3108 return CheckBooleanCondition(StmtLoc, Condition.get(), true);
3109
3110 case ConditionKind::Switch:
3111 return CheckSwitchCondition(StmtLoc, Condition.get());
3112 }
3113
3114 llvm_unreachable("unexpected condition kind");
3115 }
3116
3117 /// CheckCXXBooleanCondition - Returns true if a conversion to bool is invalid.
CheckCXXBooleanCondition(Expr * CondExpr,bool IsConstexpr)3118 ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) {
3119 // C++ 6.4p4:
3120 // The value of a condition that is an initialized declaration in a statement
3121 // other than a switch statement is the value of the declared variable
3122 // implicitly converted to type bool. If that conversion is ill-formed, the
3123 // program is ill-formed.
3124 // The value of a condition that is an expression is the value of the
3125 // expression, implicitly converted to bool.
3126 //
3127 // FIXME: Return this value to the caller so they don't need to recompute it.
3128 llvm::APSInt Value(/*BitWidth*/1);
3129 return (IsConstexpr && !CondExpr->isValueDependent())
3130 ? CheckConvertedConstantExpression(CondExpr, Context.BoolTy, Value,
3131 CCEK_ConstexprIf)
3132 : PerformContextuallyConvertToBool(CondExpr);
3133 }
3134
3135 /// Helper function to determine whether this is the (deprecated) C++
3136 /// conversion from a string literal to a pointer to non-const char or
3137 /// non-const wchar_t (for narrow and wide string literals,
3138 /// respectively).
3139 bool
IsStringLiteralToNonConstPointerConversion(Expr * From,QualType ToType)3140 Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) {
3141 // Look inside the implicit cast, if it exists.
3142 if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From))
3143 From = Cast->getSubExpr();
3144
3145 // A string literal (2.13.4) that is not a wide string literal can
3146 // be converted to an rvalue of type "pointer to char"; a wide
3147 // string literal can be converted to an rvalue of type "pointer
3148 // to wchar_t" (C++ 4.2p2).
3149 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens()))
3150 if (const PointerType *ToPtrType = ToType->getAs<PointerType>())
3151 if (const BuiltinType *ToPointeeType
3152 = ToPtrType->getPointeeType()->getAs<BuiltinType>()) {
3153 // This conversion is considered only when there is an
3154 // explicit appropriate pointer target type (C++ 4.2p2).
3155 if (!ToPtrType->getPointeeType().hasQualifiers()) {
3156 switch (StrLit->getKind()) {
3157 case StringLiteral::UTF8:
3158 case StringLiteral::UTF16:
3159 case StringLiteral::UTF32:
3160 // We don't allow UTF literals to be implicitly converted
3161 break;
3162 case StringLiteral::Ascii:
3163 return (ToPointeeType->getKind() == BuiltinType::Char_U ||
3164 ToPointeeType->getKind() == BuiltinType::Char_S);
3165 case StringLiteral::Wide:
3166 return Context.typesAreCompatible(Context.getWideCharType(),
3167 QualType(ToPointeeType, 0));
3168 }
3169 }
3170 }
3171
3172 return false;
3173 }
3174
BuildCXXCastArgument(Sema & S,SourceLocation CastLoc,QualType Ty,CastKind Kind,CXXMethodDecl * Method,DeclAccessPair FoundDecl,bool HadMultipleCandidates,Expr * From)3175 static ExprResult BuildCXXCastArgument(Sema &S,
3176 SourceLocation CastLoc,
3177 QualType Ty,
3178 CastKind Kind,
3179 CXXMethodDecl *Method,
3180 DeclAccessPair FoundDecl,
3181 bool HadMultipleCandidates,
3182 Expr *From) {
3183 switch (Kind) {
3184 default: llvm_unreachable("Unhandled cast kind!");
3185 case CK_ConstructorConversion: {
3186 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method);
3187 SmallVector<Expr*, 8> ConstructorArgs;
3188
3189 if (S.RequireNonAbstractType(CastLoc, Ty,
3190 diag::err_allocation_of_abstract_type))
3191 return ExprError();
3192
3193 if (S.CompleteConstructorCall(Constructor, From, CastLoc, ConstructorArgs))
3194 return ExprError();
3195
3196 S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl,
3197 InitializedEntity::InitializeTemporary(Ty));
3198 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3199 return ExprError();
3200
3201 ExprResult Result = S.BuildCXXConstructExpr(
3202 CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method),
3203 ConstructorArgs, HadMultipleCandidates,
3204 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3205 CXXConstructExpr::CK_Complete, SourceRange());
3206 if (Result.isInvalid())
3207 return ExprError();
3208
3209 return S.MaybeBindToTemporary(Result.getAs<Expr>());
3210 }
3211
3212 case CK_UserDefinedConversion: {
3213 assert(!From->getType()->isPointerType() && "Arg can't have pointer type!");
3214
3215 S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl);
3216 if (S.DiagnoseUseOfDecl(Method, CastLoc))
3217 return ExprError();
3218
3219 // Create an implicit call expr that calls it.
3220 CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method);
3221 ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv,
3222 HadMultipleCandidates);
3223 if (Result.isInvalid())
3224 return ExprError();
3225 // Record usage of conversion in an implicit cast.
3226 Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(),
3227 CK_UserDefinedConversion, Result.get(),
3228 nullptr, Result.get()->getValueKind());
3229
3230 return S.MaybeBindToTemporary(Result.get());
3231 }
3232 }
3233 }
3234
3235 /// PerformImplicitConversion - Perform an implicit conversion of the
3236 /// expression From to the type ToType using the pre-computed implicit
3237 /// conversion sequence ICS. Returns the converted
3238 /// expression. Action is the kind of conversion we're performing,
3239 /// used in the error message.
3240 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const ImplicitConversionSequence & ICS,AssignmentAction Action,CheckedConversionKind CCK)3241 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3242 const ImplicitConversionSequence &ICS,
3243 AssignmentAction Action,
3244 CheckedConversionKind CCK) {
3245 switch (ICS.getKind()) {
3246 case ImplicitConversionSequence::StandardConversion: {
3247 ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard,
3248 Action, CCK);
3249 if (Res.isInvalid())
3250 return ExprError();
3251 From = Res.get();
3252 break;
3253 }
3254
3255 case ImplicitConversionSequence::UserDefinedConversion: {
3256
3257 FunctionDecl *FD = ICS.UserDefined.ConversionFunction;
3258 CastKind CastKind;
3259 QualType BeforeToType;
3260 assert(FD && "no conversion function for user-defined conversion seq");
3261 if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) {
3262 CastKind = CK_UserDefinedConversion;
3263
3264 // If the user-defined conversion is specified by a conversion function,
3265 // the initial standard conversion sequence converts the source type to
3266 // the implicit object parameter of the conversion function.
3267 BeforeToType = Context.getTagDeclType(Conv->getParent());
3268 } else {
3269 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD);
3270 CastKind = CK_ConstructorConversion;
3271 // Do no conversion if dealing with ... for the first conversion.
3272 if (!ICS.UserDefined.EllipsisConversion) {
3273 // If the user-defined conversion is specified by a constructor, the
3274 // initial standard conversion sequence converts the source type to
3275 // the type required by the argument of the constructor
3276 BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType();
3277 }
3278 }
3279 // Watch out for ellipsis conversion.
3280 if (!ICS.UserDefined.EllipsisConversion) {
3281 ExprResult Res =
3282 PerformImplicitConversion(From, BeforeToType,
3283 ICS.UserDefined.Before, AA_Converting,
3284 CCK);
3285 if (Res.isInvalid())
3286 return ExprError();
3287 From = Res.get();
3288 }
3289
3290 ExprResult CastArg
3291 = BuildCXXCastArgument(*this,
3292 From->getLocStart(),
3293 ToType.getNonReferenceType(),
3294 CastKind, cast<CXXMethodDecl>(FD),
3295 ICS.UserDefined.FoundConversionFunction,
3296 ICS.UserDefined.HadMultipleCandidates,
3297 From);
3298
3299 if (CastArg.isInvalid())
3300 return ExprError();
3301
3302 From = CastArg.get();
3303
3304 return PerformImplicitConversion(From, ToType, ICS.UserDefined.After,
3305 AA_Converting, CCK);
3306 }
3307
3308 case ImplicitConversionSequence::AmbiguousConversion:
3309 ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(),
3310 PDiag(diag::err_typecheck_ambiguous_condition)
3311 << From->getSourceRange());
3312 return ExprError();
3313
3314 case ImplicitConversionSequence::EllipsisConversion:
3315 llvm_unreachable("Cannot perform an ellipsis conversion");
3316
3317 case ImplicitConversionSequence::BadConversion:
3318 return ExprError();
3319 }
3320
3321 // Everything went well.
3322 return From;
3323 }
3324
3325 /// PerformImplicitConversion - Perform an implicit conversion of the
3326 /// expression From to the type ToType by following the standard
3327 /// conversion sequence SCS. Returns the converted
3328 /// expression. Flavor is the context in which we're performing this
3329 /// conversion, for use in error messages.
3330 ExprResult
PerformImplicitConversion(Expr * From,QualType ToType,const StandardConversionSequence & SCS,AssignmentAction Action,CheckedConversionKind CCK)3331 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
3332 const StandardConversionSequence& SCS,
3333 AssignmentAction Action,
3334 CheckedConversionKind CCK) {
3335 bool CStyle = (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast);
3336
3337 // Overall FIXME: we are recomputing too many types here and doing far too
3338 // much extra work. What this means is that we need to keep track of more
3339 // information that is computed when we try the implicit conversion initially,
3340 // so that we don't need to recompute anything here.
3341 QualType FromType = From->getType();
3342
3343 if (SCS.CopyConstructor) {
3344 // FIXME: When can ToType be a reference type?
3345 assert(!ToType->isReferenceType());
3346 if (SCS.Second == ICK_Derived_To_Base) {
3347 SmallVector<Expr*, 8> ConstructorArgs;
3348 if (CompleteConstructorCall(cast<CXXConstructorDecl>(SCS.CopyConstructor),
3349 From, /*FIXME:ConstructLoc*/SourceLocation(),
3350 ConstructorArgs))
3351 return ExprError();
3352 return BuildCXXConstructExpr(
3353 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3354 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3355 ConstructorArgs, /*HadMultipleCandidates*/ false,
3356 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3357 CXXConstructExpr::CK_Complete, SourceRange());
3358 }
3359 return BuildCXXConstructExpr(
3360 /*FIXME:ConstructLoc*/ SourceLocation(), ToType,
3361 SCS.FoundCopyConstructor, SCS.CopyConstructor,
3362 From, /*HadMultipleCandidates*/ false,
3363 /*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false,
3364 CXXConstructExpr::CK_Complete, SourceRange());
3365 }
3366
3367 // Resolve overloaded function references.
3368 if (Context.hasSameType(FromType, Context.OverloadTy)) {
3369 DeclAccessPair Found;
3370 FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType,
3371 true, Found);
3372 if (!Fn)
3373 return ExprError();
3374
3375 if (DiagnoseUseOfDecl(Fn, From->getLocStart()))
3376 return ExprError();
3377
3378 From = FixOverloadedFunctionReference(From, Found, Fn);
3379 FromType = From->getType();
3380 }
3381
3382 // If we're converting to an atomic type, first convert to the corresponding
3383 // non-atomic type.
3384 QualType ToAtomicType;
3385 if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) {
3386 ToAtomicType = ToType;
3387 ToType = ToAtomic->getValueType();
3388 }
3389
3390 QualType InitialFromType = FromType;
3391 // Perform the first implicit conversion.
3392 switch (SCS.First) {
3393 case ICK_Identity:
3394 if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) {
3395 FromType = FromAtomic->getValueType().getUnqualifiedType();
3396 From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic,
3397 From, /*BasePath=*/nullptr, VK_RValue);
3398 }
3399 break;
3400
3401 case ICK_Lvalue_To_Rvalue: {
3402 assert(From->getObjectKind() != OK_ObjCProperty);
3403 ExprResult FromRes = DefaultLvalueConversion(From);
3404 assert(!FromRes.isInvalid() && "Can't perform deduced conversion?!");
3405 From = FromRes.get();
3406 FromType = From->getType();
3407 break;
3408 }
3409
3410 case ICK_Array_To_Pointer:
3411 FromType = Context.getArrayDecayedType(FromType);
3412 From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay,
3413 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3414 break;
3415
3416 case ICK_Function_To_Pointer:
3417 FromType = Context.getPointerType(FromType);
3418 From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay,
3419 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3420 break;
3421
3422 default:
3423 llvm_unreachable("Improper first standard conversion");
3424 }
3425
3426 // Perform the second implicit conversion
3427 switch (SCS.Second) {
3428 case ICK_Identity:
3429 // C++ [except.spec]p5:
3430 // [For] assignment to and initialization of pointers to functions,
3431 // pointers to member functions, and references to functions: the
3432 // target entity shall allow at least the exceptions allowed by the
3433 // source value in the assignment or initialization.
3434 switch (Action) {
3435 case AA_Assigning:
3436 case AA_Initializing:
3437 // Note, function argument passing and returning are initialization.
3438 case AA_Passing:
3439 case AA_Returning:
3440 case AA_Sending:
3441 case AA_Passing_CFAudited:
3442 if (CheckExceptionSpecCompatibility(From, ToType))
3443 return ExprError();
3444 break;
3445
3446 case AA_Casting:
3447 case AA_Converting:
3448 // Casts and implicit conversions are not initialization, so are not
3449 // checked for exception specification mismatches.
3450 break;
3451 }
3452 // Nothing else to do.
3453 break;
3454
3455 case ICK_NoReturn_Adjustment:
3456 // If both sides are functions (or pointers/references to them), there could
3457 // be incompatible exception declarations.
3458 if (CheckExceptionSpecCompatibility(From, ToType))
3459 return ExprError();
3460
3461 From = ImpCastExprToType(From, ToType, CK_NoOp,
3462 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3463 break;
3464
3465 case ICK_Integral_Promotion:
3466 case ICK_Integral_Conversion:
3467 if (ToType->isBooleanType()) {
3468 assert(FromType->castAs<EnumType>()->getDecl()->isFixed() &&
3469 SCS.Second == ICK_Integral_Promotion &&
3470 "only enums with fixed underlying type can promote to bool");
3471 From = ImpCastExprToType(From, ToType, CK_IntegralToBoolean,
3472 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3473 } else {
3474 From = ImpCastExprToType(From, ToType, CK_IntegralCast,
3475 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3476 }
3477 break;
3478
3479 case ICK_Floating_Promotion:
3480 case ICK_Floating_Conversion:
3481 From = ImpCastExprToType(From, ToType, CK_FloatingCast,
3482 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3483 break;
3484
3485 case ICK_Complex_Promotion:
3486 case ICK_Complex_Conversion: {
3487 QualType FromEl = From->getType()->getAs<ComplexType>()->getElementType();
3488 QualType ToEl = ToType->getAs<ComplexType>()->getElementType();
3489 CastKind CK;
3490 if (FromEl->isRealFloatingType()) {
3491 if (ToEl->isRealFloatingType())
3492 CK = CK_FloatingComplexCast;
3493 else
3494 CK = CK_FloatingComplexToIntegralComplex;
3495 } else if (ToEl->isRealFloatingType()) {
3496 CK = CK_IntegralComplexToFloatingComplex;
3497 } else {
3498 CK = CK_IntegralComplexCast;
3499 }
3500 From = ImpCastExprToType(From, ToType, CK,
3501 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3502 break;
3503 }
3504
3505 case ICK_Floating_Integral:
3506 if (ToType->isRealFloatingType())
3507 From = ImpCastExprToType(From, ToType, CK_IntegralToFloating,
3508 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3509 else
3510 From = ImpCastExprToType(From, ToType, CK_FloatingToIntegral,
3511 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3512 break;
3513
3514 case ICK_Compatible_Conversion:
3515 From = ImpCastExprToType(From, ToType, CK_NoOp,
3516 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3517 break;
3518
3519 case ICK_Writeback_Conversion:
3520 case ICK_Pointer_Conversion: {
3521 if (SCS.IncompatibleObjC && Action != AA_Casting) {
3522 // Diagnose incompatible Objective-C conversions
3523 if (Action == AA_Initializing || Action == AA_Assigning)
3524 Diag(From->getLocStart(),
3525 diag::ext_typecheck_convert_incompatible_pointer)
3526 << ToType << From->getType() << Action
3527 << From->getSourceRange() << 0;
3528 else
3529 Diag(From->getLocStart(),
3530 diag::ext_typecheck_convert_incompatible_pointer)
3531 << From->getType() << ToType << Action
3532 << From->getSourceRange() << 0;
3533
3534 if (From->getType()->isObjCObjectPointerType() &&
3535 ToType->isObjCObjectPointerType())
3536 EmitRelatedResultTypeNote(From);
3537 }
3538 else if (getLangOpts().ObjCAutoRefCount &&
3539 !CheckObjCARCUnavailableWeakConversion(ToType,
3540 From->getType())) {
3541 if (Action == AA_Initializing)
3542 Diag(From->getLocStart(),
3543 diag::err_arc_weak_unavailable_assign);
3544 else
3545 Diag(From->getLocStart(),
3546 diag::err_arc_convesion_of_weak_unavailable)
3547 << (Action == AA_Casting) << From->getType() << ToType
3548 << From->getSourceRange();
3549 }
3550
3551 CastKind Kind = CK_Invalid;
3552 CXXCastPath BasePath;
3553 if (CheckPointerConversion(From, ToType, Kind, BasePath, CStyle))
3554 return ExprError();
3555
3556 // Make sure we extend blocks if necessary.
3557 // FIXME: doing this here is really ugly.
3558 if (Kind == CK_BlockPointerToObjCPointerCast) {
3559 ExprResult E = From;
3560 (void) PrepareCastToObjCObjectPointer(E);
3561 From = E.get();
3562 }
3563 if (getLangOpts().ObjCAutoRefCount)
3564 CheckObjCARCConversion(SourceRange(), ToType, From, CCK);
3565 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3566 .get();
3567 break;
3568 }
3569
3570 case ICK_Pointer_Member: {
3571 CastKind Kind = CK_Invalid;
3572 CXXCastPath BasePath;
3573 if (CheckMemberPointerConversion(From, ToType, Kind, BasePath, CStyle))
3574 return ExprError();
3575 if (CheckExceptionSpecCompatibility(From, ToType))
3576 return ExprError();
3577
3578 // We may not have been able to figure out what this member pointer resolved
3579 // to up until this exact point. Attempt to lock-in it's inheritance model.
3580 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3581 (void)isCompleteType(From->getExprLoc(), From->getType());
3582 (void)isCompleteType(From->getExprLoc(), ToType);
3583 }
3584
3585 From = ImpCastExprToType(From, ToType, Kind, VK_RValue, &BasePath, CCK)
3586 .get();
3587 break;
3588 }
3589
3590 case ICK_Boolean_Conversion:
3591 // Perform half-to-boolean conversion via float.
3592 if (From->getType()->isHalfType()) {
3593 From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get();
3594 FromType = Context.FloatTy;
3595 }
3596
3597 From = ImpCastExprToType(From, Context.BoolTy,
3598 ScalarTypeToBooleanCastKind(FromType),
3599 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3600 break;
3601
3602 case ICK_Derived_To_Base: {
3603 CXXCastPath BasePath;
3604 if (CheckDerivedToBaseConversion(From->getType(),
3605 ToType.getNonReferenceType(),
3606 From->getLocStart(),
3607 From->getSourceRange(),
3608 &BasePath,
3609 CStyle))
3610 return ExprError();
3611
3612 From = ImpCastExprToType(From, ToType.getNonReferenceType(),
3613 CK_DerivedToBase, From->getValueKind(),
3614 &BasePath, CCK).get();
3615 break;
3616 }
3617
3618 case ICK_Vector_Conversion:
3619 From = ImpCastExprToType(From, ToType, CK_BitCast,
3620 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3621 break;
3622
3623 case ICK_Vector_Splat: {
3624 // Vector splat from any arithmetic type to a vector.
3625 Expr *Elem = prepareVectorSplat(ToType, From).get();
3626 From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_RValue,
3627 /*BasePath=*/nullptr, CCK).get();
3628 break;
3629 }
3630
3631 case ICK_Complex_Real:
3632 // Case 1. x -> _Complex y
3633 if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) {
3634 QualType ElType = ToComplex->getElementType();
3635 bool isFloatingComplex = ElType->isRealFloatingType();
3636
3637 // x -> y
3638 if (Context.hasSameUnqualifiedType(ElType, From->getType())) {
3639 // do nothing
3640 } else if (From->getType()->isRealFloatingType()) {
3641 From = ImpCastExprToType(From, ElType,
3642 isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get();
3643 } else {
3644 assert(From->getType()->isIntegerType());
3645 From = ImpCastExprToType(From, ElType,
3646 isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get();
3647 }
3648 // y -> _Complex y
3649 From = ImpCastExprToType(From, ToType,
3650 isFloatingComplex ? CK_FloatingRealToComplex
3651 : CK_IntegralRealToComplex).get();
3652
3653 // Case 2. _Complex x -> y
3654 } else {
3655 const ComplexType *FromComplex = From->getType()->getAs<ComplexType>();
3656 assert(FromComplex);
3657
3658 QualType ElType = FromComplex->getElementType();
3659 bool isFloatingComplex = ElType->isRealFloatingType();
3660
3661 // _Complex x -> x
3662 From = ImpCastExprToType(From, ElType,
3663 isFloatingComplex ? CK_FloatingComplexToReal
3664 : CK_IntegralComplexToReal,
3665 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3666
3667 // x -> y
3668 if (Context.hasSameUnqualifiedType(ElType, ToType)) {
3669 // do nothing
3670 } else if (ToType->isRealFloatingType()) {
3671 From = ImpCastExprToType(From, ToType,
3672 isFloatingComplex ? CK_FloatingCast : CK_IntegralToFloating,
3673 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3674 } else {
3675 assert(ToType->isIntegerType());
3676 From = ImpCastExprToType(From, ToType,
3677 isFloatingComplex ? CK_FloatingToIntegral : CK_IntegralCast,
3678 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3679 }
3680 }
3681 break;
3682
3683 case ICK_Block_Pointer_Conversion: {
3684 From = ImpCastExprToType(From, ToType.getUnqualifiedType(), CK_BitCast,
3685 VK_RValue, /*BasePath=*/nullptr, CCK).get();
3686 break;
3687 }
3688
3689 case ICK_TransparentUnionConversion: {
3690 ExprResult FromRes = From;
3691 Sema::AssignConvertType ConvTy =
3692 CheckTransparentUnionArgumentConstraints(ToType, FromRes);
3693 if (FromRes.isInvalid())
3694 return ExprError();
3695 From = FromRes.get();
3696 assert ((ConvTy == Sema::Compatible) &&
3697 "Improper transparent union conversion");
3698 (void)ConvTy;
3699 break;
3700 }
3701
3702 case ICK_Zero_Event_Conversion:
3703 From = ImpCastExprToType(From, ToType,
3704 CK_ZeroToOCLEvent,
3705 From->getValueKind()).get();
3706 break;
3707
3708 case ICK_Lvalue_To_Rvalue:
3709 case ICK_Array_To_Pointer:
3710 case ICK_Function_To_Pointer:
3711 case ICK_Qualification:
3712 case ICK_Num_Conversion_Kinds:
3713 case ICK_C_Only_Conversion:
3714 llvm_unreachable("Improper second standard conversion");
3715 }
3716
3717 switch (SCS.Third) {
3718 case ICK_Identity:
3719 // Nothing to do.
3720 break;
3721
3722 case ICK_Qualification: {
3723 // The qualification keeps the category of the inner expression, unless the
3724 // target type isn't a reference.
3725 ExprValueKind VK = ToType->isReferenceType() ?
3726 From->getValueKind() : VK_RValue;
3727 From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context),
3728 CK_NoOp, VK, /*BasePath=*/nullptr, CCK).get();
3729
3730 if (SCS.DeprecatedStringLiteralToCharPtr &&
3731 !getLangOpts().WritableStrings) {
3732 Diag(From->getLocStart(), getLangOpts().CPlusPlus11
3733 ? diag::ext_deprecated_string_literal_conversion
3734 : diag::warn_deprecated_string_literal_conversion)
3735 << ToType.getNonReferenceType();
3736 }
3737
3738 break;
3739 }
3740
3741 default:
3742 llvm_unreachable("Improper third standard conversion");
3743 }
3744
3745 // If this conversion sequence involved a scalar -> atomic conversion, perform
3746 // that conversion now.
3747 if (!ToAtomicType.isNull()) {
3748 assert(Context.hasSameType(
3749 ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType()));
3750 From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic,
3751 VK_RValue, nullptr, CCK).get();
3752 }
3753
3754 // If this conversion sequence succeeded and involved implicitly converting a
3755 // _Nullable type to a _Nonnull one, complain.
3756 if (CCK == CCK_ImplicitConversion)
3757 diagnoseNullableToNonnullConversion(ToType, InitialFromType,
3758 From->getLocStart());
3759
3760 return From;
3761 }
3762
3763 /// \brief Check the completeness of a type in a unary type trait.
3764 ///
3765 /// If the particular type trait requires a complete type, tries to complete
3766 /// it. If completing the type fails, a diagnostic is emitted and false
3767 /// returned. If completing the type succeeds or no completion was required,
3768 /// returns true.
CheckUnaryTypeTraitTypeCompleteness(Sema & S,TypeTrait UTT,SourceLocation Loc,QualType ArgTy)3769 static bool CheckUnaryTypeTraitTypeCompleteness(Sema &S, TypeTrait UTT,
3770 SourceLocation Loc,
3771 QualType ArgTy) {
3772 // C++0x [meta.unary.prop]p3:
3773 // For all of the class templates X declared in this Clause, instantiating
3774 // that template with a template argument that is a class template
3775 // specialization may result in the implicit instantiation of the template
3776 // argument if and only if the semantics of X require that the argument
3777 // must be a complete type.
3778 // We apply this rule to all the type trait expressions used to implement
3779 // these class templates. We also try to follow any GCC documented behavior
3780 // in these expressions to ensure portability of standard libraries.
3781 switch (UTT) {
3782 default: llvm_unreachable("not a UTT");
3783 // is_complete_type somewhat obviously cannot require a complete type.
3784 case UTT_IsCompleteType:
3785 // Fall-through
3786
3787 // These traits are modeled on the type predicates in C++0x
3788 // [meta.unary.cat] and [meta.unary.comp]. They are not specified as
3789 // requiring a complete type, as whether or not they return true cannot be
3790 // impacted by the completeness of the type.
3791 case UTT_IsVoid:
3792 case UTT_IsIntegral:
3793 case UTT_IsFloatingPoint:
3794 case UTT_IsArray:
3795 case UTT_IsPointer:
3796 case UTT_IsLvalueReference:
3797 case UTT_IsRvalueReference:
3798 case UTT_IsMemberFunctionPointer:
3799 case UTT_IsMemberObjectPointer:
3800 case UTT_IsEnum:
3801 case UTT_IsUnion:
3802 case UTT_IsClass:
3803 case UTT_IsFunction:
3804 case UTT_IsReference:
3805 case UTT_IsArithmetic:
3806 case UTT_IsFundamental:
3807 case UTT_IsObject:
3808 case UTT_IsScalar:
3809 case UTT_IsCompound:
3810 case UTT_IsMemberPointer:
3811 // Fall-through
3812
3813 // These traits are modeled on type predicates in C++0x [meta.unary.prop]
3814 // which requires some of its traits to have the complete type. However,
3815 // the completeness of the type cannot impact these traits' semantics, and
3816 // so they don't require it. This matches the comments on these traits in
3817 // Table 49.
3818 case UTT_IsConst:
3819 case UTT_IsVolatile:
3820 case UTT_IsSigned:
3821 case UTT_IsUnsigned:
3822
3823 // This type trait always returns false, checking the type is moot.
3824 case UTT_IsInterfaceClass:
3825 return true;
3826
3827 // C++14 [meta.unary.prop]:
3828 // If T is a non-union class type, T shall be a complete type.
3829 case UTT_IsEmpty:
3830 case UTT_IsPolymorphic:
3831 case UTT_IsAbstract:
3832 if (const auto *RD = ArgTy->getAsCXXRecordDecl())
3833 if (!RD->isUnion())
3834 return !S.RequireCompleteType(
3835 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3836 return true;
3837
3838 // C++14 [meta.unary.prop]:
3839 // If T is a class type, T shall be a complete type.
3840 case UTT_IsFinal:
3841 case UTT_IsSealed:
3842 if (ArgTy->getAsCXXRecordDecl())
3843 return !S.RequireCompleteType(
3844 Loc, ArgTy, diag::err_incomplete_type_used_in_type_trait_expr);
3845 return true;
3846
3847 // C++0x [meta.unary.prop] Table 49 requires the following traits to be
3848 // applied to a complete type.
3849 case UTT_IsTrivial:
3850 case UTT_IsTriviallyCopyable:
3851 case UTT_IsStandardLayout:
3852 case UTT_IsPOD:
3853 case UTT_IsLiteral:
3854
3855 case UTT_IsDestructible:
3856 case UTT_IsNothrowDestructible:
3857 // Fall-through
3858
3859 // These trait expressions are designed to help implement predicates in
3860 // [meta.unary.prop] despite not being named the same. They are specified
3861 // by both GCC and the Embarcadero C++ compiler, and require the complete
3862 // type due to the overarching C++0x type predicates being implemented
3863 // requiring the complete type.
3864 case UTT_HasNothrowAssign:
3865 case UTT_HasNothrowMoveAssign:
3866 case UTT_HasNothrowConstructor:
3867 case UTT_HasNothrowCopy:
3868 case UTT_HasTrivialAssign:
3869 case UTT_HasTrivialMoveAssign:
3870 case UTT_HasTrivialDefaultConstructor:
3871 case UTT_HasTrivialMoveConstructor:
3872 case UTT_HasTrivialCopy:
3873 case UTT_HasTrivialDestructor:
3874 case UTT_HasVirtualDestructor:
3875 // Arrays of unknown bound are expressly allowed.
3876 QualType ElTy = ArgTy;
3877 if (ArgTy->isIncompleteArrayType())
3878 ElTy = S.Context.getAsArrayType(ArgTy)->getElementType();
3879
3880 // The void type is expressly allowed.
3881 if (ElTy->isVoidType())
3882 return true;
3883
3884 return !S.RequireCompleteType(
3885 Loc, ElTy, diag::err_incomplete_type_used_in_type_trait_expr);
3886 }
3887 }
3888
HasNoThrowOperator(const RecordType * RT,OverloadedOperatorKind Op,Sema & Self,SourceLocation KeyLoc,ASTContext & C,bool (CXXRecordDecl::* HasTrivial)()const,bool (CXXRecordDecl::* HasNonTrivial)()const,bool (CXXMethodDecl::* IsDesiredOp)()const)3889 static bool HasNoThrowOperator(const RecordType *RT, OverloadedOperatorKind Op,
3890 Sema &Self, SourceLocation KeyLoc, ASTContext &C,
3891 bool (CXXRecordDecl::*HasTrivial)() const,
3892 bool (CXXRecordDecl::*HasNonTrivial)() const,
3893 bool (CXXMethodDecl::*IsDesiredOp)() const)
3894 {
3895 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
3896 if ((RD->*HasTrivial)() && !(RD->*HasNonTrivial)())
3897 return true;
3898
3899 DeclarationName Name = C.DeclarationNames.getCXXOperatorName(Op);
3900 DeclarationNameInfo NameInfo(Name, KeyLoc);
3901 LookupResult Res(Self, NameInfo, Sema::LookupOrdinaryName);
3902 if (Self.LookupQualifiedName(Res, RD)) {
3903 bool FoundOperator = false;
3904 Res.suppressDiagnostics();
3905 for (LookupResult::iterator Op = Res.begin(), OpEnd = Res.end();
3906 Op != OpEnd; ++Op) {
3907 if (isa<FunctionTemplateDecl>(*Op))
3908 continue;
3909
3910 CXXMethodDecl *Operator = cast<CXXMethodDecl>(*Op);
3911 if((Operator->*IsDesiredOp)()) {
3912 FoundOperator = true;
3913 const FunctionProtoType *CPT =
3914 Operator->getType()->getAs<FunctionProtoType>();
3915 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
3916 if (!CPT || !CPT->isNothrow(C))
3917 return false;
3918 }
3919 }
3920 return FoundOperator;
3921 }
3922 return false;
3923 }
3924
EvaluateUnaryTypeTrait(Sema & Self,TypeTrait UTT,SourceLocation KeyLoc,QualType T)3925 static bool EvaluateUnaryTypeTrait(Sema &Self, TypeTrait UTT,
3926 SourceLocation KeyLoc, QualType T) {
3927 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
3928
3929 ASTContext &C = Self.Context;
3930 switch(UTT) {
3931 default: llvm_unreachable("not a UTT");
3932 // Type trait expressions corresponding to the primary type category
3933 // predicates in C++0x [meta.unary.cat].
3934 case UTT_IsVoid:
3935 return T->isVoidType();
3936 case UTT_IsIntegral:
3937 return T->isIntegralType(C);
3938 case UTT_IsFloatingPoint:
3939 return T->isFloatingType();
3940 case UTT_IsArray:
3941 return T->isArrayType();
3942 case UTT_IsPointer:
3943 return T->isPointerType();
3944 case UTT_IsLvalueReference:
3945 return T->isLValueReferenceType();
3946 case UTT_IsRvalueReference:
3947 return T->isRValueReferenceType();
3948 case UTT_IsMemberFunctionPointer:
3949 return T->isMemberFunctionPointerType();
3950 case UTT_IsMemberObjectPointer:
3951 return T->isMemberDataPointerType();
3952 case UTT_IsEnum:
3953 return T->isEnumeralType();
3954 case UTT_IsUnion:
3955 return T->isUnionType();
3956 case UTT_IsClass:
3957 return T->isClassType() || T->isStructureType() || T->isInterfaceType();
3958 case UTT_IsFunction:
3959 return T->isFunctionType();
3960
3961 // Type trait expressions which correspond to the convenient composition
3962 // predicates in C++0x [meta.unary.comp].
3963 case UTT_IsReference:
3964 return T->isReferenceType();
3965 case UTT_IsArithmetic:
3966 return T->isArithmeticType() && !T->isEnumeralType();
3967 case UTT_IsFundamental:
3968 return T->isFundamentalType();
3969 case UTT_IsObject:
3970 return T->isObjectType();
3971 case UTT_IsScalar:
3972 // Note: semantic analysis depends on Objective-C lifetime types to be
3973 // considered scalar types. However, such types do not actually behave
3974 // like scalar types at run time (since they may require retain/release
3975 // operations), so we report them as non-scalar.
3976 if (T->isObjCLifetimeType()) {
3977 switch (T.getObjCLifetime()) {
3978 case Qualifiers::OCL_None:
3979 case Qualifiers::OCL_ExplicitNone:
3980 return true;
3981
3982 case Qualifiers::OCL_Strong:
3983 case Qualifiers::OCL_Weak:
3984 case Qualifiers::OCL_Autoreleasing:
3985 return false;
3986 }
3987 }
3988
3989 return T->isScalarType();
3990 case UTT_IsCompound:
3991 return T->isCompoundType();
3992 case UTT_IsMemberPointer:
3993 return T->isMemberPointerType();
3994
3995 // Type trait expressions which correspond to the type property predicates
3996 // in C++0x [meta.unary.prop].
3997 case UTT_IsConst:
3998 return T.isConstQualified();
3999 case UTT_IsVolatile:
4000 return T.isVolatileQualified();
4001 case UTT_IsTrivial:
4002 return T.isTrivialType(C);
4003 case UTT_IsTriviallyCopyable:
4004 return T.isTriviallyCopyableType(C);
4005 case UTT_IsStandardLayout:
4006 return T->isStandardLayoutType();
4007 case UTT_IsPOD:
4008 return T.isPODType(C);
4009 case UTT_IsLiteral:
4010 return T->isLiteralType(C);
4011 case UTT_IsEmpty:
4012 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4013 return !RD->isUnion() && RD->isEmpty();
4014 return false;
4015 case UTT_IsPolymorphic:
4016 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4017 return !RD->isUnion() && RD->isPolymorphic();
4018 return false;
4019 case UTT_IsAbstract:
4020 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4021 return !RD->isUnion() && RD->isAbstract();
4022 return false;
4023 // __is_interface_class only returns true when CL is invoked in /CLR mode and
4024 // even then only when it is used with the 'interface struct ...' syntax
4025 // Clang doesn't support /CLR which makes this type trait moot.
4026 case UTT_IsInterfaceClass:
4027 return false;
4028 case UTT_IsFinal:
4029 case UTT_IsSealed:
4030 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4031 return RD->hasAttr<FinalAttr>();
4032 return false;
4033 case UTT_IsSigned:
4034 return T->isSignedIntegerType();
4035 case UTT_IsUnsigned:
4036 return T->isUnsignedIntegerType();
4037
4038 // Type trait expressions which query classes regarding their construction,
4039 // destruction, and copying. Rather than being based directly on the
4040 // related type predicates in the standard, they are specified by both
4041 // GCC[1] and the Embarcadero C++ compiler[2], and Clang implements those
4042 // specifications.
4043 //
4044 // 1: http://gcc.gnu/.org/onlinedocs/gcc/Type-Traits.html
4045 // 2: http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4046 //
4047 // Note that these builtins do not behave as documented in g++: if a class
4048 // has both a trivial and a non-trivial special member of a particular kind,
4049 // they return false! For now, we emulate this behavior.
4050 // FIXME: This appears to be a g++ bug: more complex cases reveal that it
4051 // does not correctly compute triviality in the presence of multiple special
4052 // members of the same kind. Revisit this once the g++ bug is fixed.
4053 case UTT_HasTrivialDefaultConstructor:
4054 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4055 // If __is_pod (type) is true then the trait is true, else if type is
4056 // a cv class or union type (or array thereof) with a trivial default
4057 // constructor ([class.ctor]) then the trait is true, else it is false.
4058 if (T.isPODType(C))
4059 return true;
4060 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4061 return RD->hasTrivialDefaultConstructor() &&
4062 !RD->hasNonTrivialDefaultConstructor();
4063 return false;
4064 case UTT_HasTrivialMoveConstructor:
4065 // This trait is implemented by MSVC 2012 and needed to parse the
4066 // standard library headers. Specifically this is used as the logic
4067 // behind std::is_trivially_move_constructible (20.9.4.3).
4068 if (T.isPODType(C))
4069 return true;
4070 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4071 return RD->hasTrivialMoveConstructor() && !RD->hasNonTrivialMoveConstructor();
4072 return false;
4073 case UTT_HasTrivialCopy:
4074 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4075 // If __is_pod (type) is true or type is a reference type then
4076 // the trait is true, else if type is a cv class or union type
4077 // with a trivial copy constructor ([class.copy]) then the trait
4078 // is true, else it is false.
4079 if (T.isPODType(C) || T->isReferenceType())
4080 return true;
4081 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4082 return RD->hasTrivialCopyConstructor() &&
4083 !RD->hasNonTrivialCopyConstructor();
4084 return false;
4085 case UTT_HasTrivialMoveAssign:
4086 // This trait is implemented by MSVC 2012 and needed to parse the
4087 // standard library headers. Specifically it is used as the logic
4088 // behind std::is_trivially_move_assignable (20.9.4.3)
4089 if (T.isPODType(C))
4090 return true;
4091 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4092 return RD->hasTrivialMoveAssignment() && !RD->hasNonTrivialMoveAssignment();
4093 return false;
4094 case UTT_HasTrivialAssign:
4095 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4096 // If type is const qualified or is a reference type then the
4097 // trait is false. Otherwise if __is_pod (type) is true then the
4098 // trait is true, else if type is a cv class or union type with
4099 // a trivial copy assignment ([class.copy]) then the trait is
4100 // true, else it is false.
4101 // Note: the const and reference restrictions are interesting,
4102 // given that const and reference members don't prevent a class
4103 // from having a trivial copy assignment operator (but do cause
4104 // errors if the copy assignment operator is actually used, q.v.
4105 // [class.copy]p12).
4106
4107 if (T.isConstQualified())
4108 return false;
4109 if (T.isPODType(C))
4110 return true;
4111 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4112 return RD->hasTrivialCopyAssignment() &&
4113 !RD->hasNonTrivialCopyAssignment();
4114 return false;
4115 case UTT_IsDestructible:
4116 case UTT_IsNothrowDestructible:
4117 // C++14 [meta.unary.prop]:
4118 // For reference types, is_destructible<T>::value is true.
4119 if (T->isReferenceType())
4120 return true;
4121
4122 // Objective-C++ ARC: autorelease types don't require destruction.
4123 if (T->isObjCLifetimeType() &&
4124 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4125 return true;
4126
4127 // C++14 [meta.unary.prop]:
4128 // For incomplete types and function types, is_destructible<T>::value is
4129 // false.
4130 if (T->isIncompleteType() || T->isFunctionType())
4131 return false;
4132
4133 // C++14 [meta.unary.prop]:
4134 // For object types and given U equal to remove_all_extents_t<T>, if the
4135 // expression std::declval<U&>().~U() is well-formed when treated as an
4136 // unevaluated operand (Clause 5), then is_destructible<T>::value is true
4137 if (auto *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4138 CXXDestructorDecl *Destructor = Self.LookupDestructor(RD);
4139 if (!Destructor)
4140 return false;
4141 // C++14 [dcl.fct.def.delete]p2:
4142 // A program that refers to a deleted function implicitly or
4143 // explicitly, other than to declare it, is ill-formed.
4144 if (Destructor->isDeleted())
4145 return false;
4146 if (C.getLangOpts().AccessControl && Destructor->getAccess() != AS_public)
4147 return false;
4148 if (UTT == UTT_IsNothrowDestructible) {
4149 const FunctionProtoType *CPT =
4150 Destructor->getType()->getAs<FunctionProtoType>();
4151 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4152 if (!CPT || !CPT->isNothrow(C))
4153 return false;
4154 }
4155 }
4156 return true;
4157
4158 case UTT_HasTrivialDestructor:
4159 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4160 // If __is_pod (type) is true or type is a reference type
4161 // then the trait is true, else if type is a cv class or union
4162 // type (or array thereof) with a trivial destructor
4163 // ([class.dtor]) then the trait is true, else it is
4164 // false.
4165 if (T.isPODType(C) || T->isReferenceType())
4166 return true;
4167
4168 // Objective-C++ ARC: autorelease types don't require destruction.
4169 if (T->isObjCLifetimeType() &&
4170 T.getObjCLifetime() == Qualifiers::OCL_Autoreleasing)
4171 return true;
4172
4173 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl())
4174 return RD->hasTrivialDestructor();
4175 return false;
4176 // TODO: Propagate nothrowness for implicitly declared special members.
4177 case UTT_HasNothrowAssign:
4178 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4179 // If type is const qualified or is a reference type then the
4180 // trait is false. Otherwise if __has_trivial_assign (type)
4181 // is true then the trait is true, else if type is a cv class
4182 // or union type with copy assignment operators that are known
4183 // not to throw an exception then the trait is true, else it is
4184 // false.
4185 if (C.getBaseElementType(T).isConstQualified())
4186 return false;
4187 if (T->isReferenceType())
4188 return false;
4189 if (T.isPODType(C) || T->isObjCLifetimeType())
4190 return true;
4191
4192 if (const RecordType *RT = T->getAs<RecordType>())
4193 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4194 &CXXRecordDecl::hasTrivialCopyAssignment,
4195 &CXXRecordDecl::hasNonTrivialCopyAssignment,
4196 &CXXMethodDecl::isCopyAssignmentOperator);
4197 return false;
4198 case UTT_HasNothrowMoveAssign:
4199 // This trait is implemented by MSVC 2012 and needed to parse the
4200 // standard library headers. Specifically this is used as the logic
4201 // behind std::is_nothrow_move_assignable (20.9.4.3).
4202 if (T.isPODType(C))
4203 return true;
4204
4205 if (const RecordType *RT = C.getBaseElementType(T)->getAs<RecordType>())
4206 return HasNoThrowOperator(RT, OO_Equal, Self, KeyLoc, C,
4207 &CXXRecordDecl::hasTrivialMoveAssignment,
4208 &CXXRecordDecl::hasNonTrivialMoveAssignment,
4209 &CXXMethodDecl::isMoveAssignmentOperator);
4210 return false;
4211 case UTT_HasNothrowCopy:
4212 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4213 // If __has_trivial_copy (type) is true then the trait is true, else
4214 // if type is a cv class or union type with copy constructors that are
4215 // known not to throw an exception then the trait is true, else it is
4216 // false.
4217 if (T.isPODType(C) || T->isReferenceType() || T->isObjCLifetimeType())
4218 return true;
4219 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
4220 if (RD->hasTrivialCopyConstructor() &&
4221 !RD->hasNonTrivialCopyConstructor())
4222 return true;
4223
4224 bool FoundConstructor = false;
4225 unsigned FoundTQs;
4226 for (const auto *ND : Self.LookupConstructors(RD)) {
4227 // A template constructor is never a copy constructor.
4228 // FIXME: However, it may actually be selected at the actual overload
4229 // resolution point.
4230 if (isa<FunctionTemplateDecl>(ND))
4231 continue;
4232 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
4233 if (Constructor->isCopyConstructor(FoundTQs)) {
4234 FoundConstructor = true;
4235 const FunctionProtoType *CPT
4236 = Constructor->getType()->getAs<FunctionProtoType>();
4237 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4238 if (!CPT)
4239 return false;
4240 // TODO: check whether evaluating default arguments can throw.
4241 // For now, we'll be conservative and assume that they can throw.
4242 if (!CPT->isNothrow(C) || CPT->getNumParams() > 1)
4243 return false;
4244 }
4245 }
4246
4247 return FoundConstructor;
4248 }
4249 return false;
4250 case UTT_HasNothrowConstructor:
4251 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html
4252 // If __has_trivial_constructor (type) is true then the trait is
4253 // true, else if type is a cv class or union type (or array
4254 // thereof) with a default constructor that is known not to
4255 // throw an exception then the trait is true, else it is false.
4256 if (T.isPODType(C) || T->isObjCLifetimeType())
4257 return true;
4258 if (CXXRecordDecl *RD = C.getBaseElementType(T)->getAsCXXRecordDecl()) {
4259 if (RD->hasTrivialDefaultConstructor() &&
4260 !RD->hasNonTrivialDefaultConstructor())
4261 return true;
4262
4263 bool FoundConstructor = false;
4264 for (const auto *ND : Self.LookupConstructors(RD)) {
4265 // FIXME: In C++0x, a constructor template can be a default constructor.
4266 if (isa<FunctionTemplateDecl>(ND))
4267 continue;
4268 const CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(ND);
4269 if (Constructor->isDefaultConstructor()) {
4270 FoundConstructor = true;
4271 const FunctionProtoType *CPT
4272 = Constructor->getType()->getAs<FunctionProtoType>();
4273 CPT = Self.ResolveExceptionSpec(KeyLoc, CPT);
4274 if (!CPT)
4275 return false;
4276 // FIXME: check whether evaluating default arguments can throw.
4277 // For now, we'll be conservative and assume that they can throw.
4278 if (!CPT->isNothrow(C) || CPT->getNumParams() > 0)
4279 return false;
4280 }
4281 }
4282 return FoundConstructor;
4283 }
4284 return false;
4285 case UTT_HasVirtualDestructor:
4286 // http://gcc.gnu.org/onlinedocs/gcc/Type-Traits.html:
4287 // If type is a class type with a virtual destructor ([class.dtor])
4288 // then the trait is true, else it is false.
4289 if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
4290 if (CXXDestructorDecl *Destructor = Self.LookupDestructor(RD))
4291 return Destructor->isVirtual();
4292 return false;
4293
4294 // These type trait expressions are modeled on the specifications for the
4295 // Embarcadero C++0x type trait functions:
4296 // http://docwiki.embarcadero.com/RADStudio/XE/en/Type_Trait_Functions_(C%2B%2B0x)_Index
4297 case UTT_IsCompleteType:
4298 // http://docwiki.embarcadero.com/RADStudio/XE/en/Is_complete_type_(typename_T_):
4299 // Returns True if and only if T is a complete type at the point of the
4300 // function call.
4301 return !T->isIncompleteType();
4302 }
4303 }
4304
4305 /// \brief Determine whether T has a non-trivial Objective-C lifetime in
4306 /// ARC mode.
hasNontrivialObjCLifetime(QualType T)4307 static bool hasNontrivialObjCLifetime(QualType T) {
4308 switch (T.getObjCLifetime()) {
4309 case Qualifiers::OCL_ExplicitNone:
4310 return false;
4311
4312 case Qualifiers::OCL_Strong:
4313 case Qualifiers::OCL_Weak:
4314 case Qualifiers::OCL_Autoreleasing:
4315 return true;
4316
4317 case Qualifiers::OCL_None:
4318 return T->isObjCLifetimeType();
4319 }
4320
4321 llvm_unreachable("Unknown ObjC lifetime qualifier");
4322 }
4323
4324 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4325 QualType RhsT, SourceLocation KeyLoc);
4326
evaluateTypeTrait(Sema & S,TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)4327 static bool evaluateTypeTrait(Sema &S, TypeTrait Kind, SourceLocation KWLoc,
4328 ArrayRef<TypeSourceInfo *> Args,
4329 SourceLocation RParenLoc) {
4330 if (Kind <= UTT_Last)
4331 return EvaluateUnaryTypeTrait(S, Kind, KWLoc, Args[0]->getType());
4332
4333 if (Kind <= BTT_Last)
4334 return EvaluateBinaryTypeTrait(S, Kind, Args[0]->getType(),
4335 Args[1]->getType(), RParenLoc);
4336
4337 switch (Kind) {
4338 case clang::TT_IsConstructible:
4339 case clang::TT_IsNothrowConstructible:
4340 case clang::TT_IsTriviallyConstructible: {
4341 // C++11 [meta.unary.prop]:
4342 // is_trivially_constructible is defined as:
4343 //
4344 // is_constructible<T, Args...>::value is true and the variable
4345 // definition for is_constructible, as defined below, is known to call
4346 // no operation that is not trivial.
4347 //
4348 // The predicate condition for a template specialization
4349 // is_constructible<T, Args...> shall be satisfied if and only if the
4350 // following variable definition would be well-formed for some invented
4351 // variable t:
4352 //
4353 // T t(create<Args>()...);
4354 assert(!Args.empty());
4355
4356 // Precondition: T and all types in the parameter pack Args shall be
4357 // complete types, (possibly cv-qualified) void, or arrays of
4358 // unknown bound.
4359 for (const auto *TSI : Args) {
4360 QualType ArgTy = TSI->getType();
4361 if (ArgTy->isVoidType() || ArgTy->isIncompleteArrayType())
4362 continue;
4363
4364 if (S.RequireCompleteType(KWLoc, ArgTy,
4365 diag::err_incomplete_type_used_in_type_trait_expr))
4366 return false;
4367 }
4368
4369 // Make sure the first argument is not incomplete nor a function type.
4370 QualType T = Args[0]->getType();
4371 if (T->isIncompleteType() || T->isFunctionType())
4372 return false;
4373
4374 // Make sure the first argument is not an abstract type.
4375 CXXRecordDecl *RD = T->getAsCXXRecordDecl();
4376 if (RD && RD->isAbstract())
4377 return false;
4378
4379 SmallVector<OpaqueValueExpr, 2> OpaqueArgExprs;
4380 SmallVector<Expr *, 2> ArgExprs;
4381 ArgExprs.reserve(Args.size() - 1);
4382 for (unsigned I = 1, N = Args.size(); I != N; ++I) {
4383 QualType ArgTy = Args[I]->getType();
4384 if (ArgTy->isObjectType() || ArgTy->isFunctionType())
4385 ArgTy = S.Context.getRValueReferenceType(ArgTy);
4386 OpaqueArgExprs.push_back(
4387 OpaqueValueExpr(Args[I]->getTypeLoc().getLocStart(),
4388 ArgTy.getNonLValueExprType(S.Context),
4389 Expr::getValueKindForType(ArgTy)));
4390 }
4391 for (Expr &E : OpaqueArgExprs)
4392 ArgExprs.push_back(&E);
4393
4394 // Perform the initialization in an unevaluated context within a SFINAE
4395 // trap at translation unit scope.
4396 EnterExpressionEvaluationContext Unevaluated(S, Sema::Unevaluated);
4397 Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
4398 Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
4399 InitializedEntity To(InitializedEntity::InitializeTemporary(Args[0]));
4400 InitializationKind InitKind(InitializationKind::CreateDirect(KWLoc, KWLoc,
4401 RParenLoc));
4402 InitializationSequence Init(S, To, InitKind, ArgExprs);
4403 if (Init.Failed())
4404 return false;
4405
4406 ExprResult Result = Init.Perform(S, To, InitKind, ArgExprs);
4407 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4408 return false;
4409
4410 if (Kind == clang::TT_IsConstructible)
4411 return true;
4412
4413 if (Kind == clang::TT_IsNothrowConstructible)
4414 return S.canThrow(Result.get()) == CT_Cannot;
4415
4416 if (Kind == clang::TT_IsTriviallyConstructible) {
4417 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4418 // lifetime, this is a non-trivial construction.
4419 if (S.getLangOpts().ObjCAutoRefCount &&
4420 hasNontrivialObjCLifetime(T.getNonReferenceType()))
4421 return false;
4422
4423 // The initialization succeeded; now make sure there are no non-trivial
4424 // calls.
4425 return !Result.get()->hasNonTrivialCall(S.Context);
4426 }
4427
4428 llvm_unreachable("unhandled type trait");
4429 return false;
4430 }
4431 default: llvm_unreachable("not a TT");
4432 }
4433
4434 return false;
4435 }
4436
BuildTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<TypeSourceInfo * > Args,SourceLocation RParenLoc)4437 ExprResult Sema::BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4438 ArrayRef<TypeSourceInfo *> Args,
4439 SourceLocation RParenLoc) {
4440 QualType ResultType = Context.getLogicalOperationType();
4441
4442 if (Kind <= UTT_Last && !CheckUnaryTypeTraitTypeCompleteness(
4443 *this, Kind, KWLoc, Args[0]->getType()))
4444 return ExprError();
4445
4446 bool Dependent = false;
4447 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4448 if (Args[I]->getType()->isDependentType()) {
4449 Dependent = true;
4450 break;
4451 }
4452 }
4453
4454 bool Result = false;
4455 if (!Dependent)
4456 Result = evaluateTypeTrait(*this, Kind, KWLoc, Args, RParenLoc);
4457
4458 return TypeTraitExpr::Create(Context, ResultType, KWLoc, Kind, Args,
4459 RParenLoc, Result);
4460 }
4461
ActOnTypeTrait(TypeTrait Kind,SourceLocation KWLoc,ArrayRef<ParsedType> Args,SourceLocation RParenLoc)4462 ExprResult Sema::ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc,
4463 ArrayRef<ParsedType> Args,
4464 SourceLocation RParenLoc) {
4465 SmallVector<TypeSourceInfo *, 4> ConvertedArgs;
4466 ConvertedArgs.reserve(Args.size());
4467
4468 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
4469 TypeSourceInfo *TInfo;
4470 QualType T = GetTypeFromParser(Args[I], &TInfo);
4471 if (!TInfo)
4472 TInfo = Context.getTrivialTypeSourceInfo(T, KWLoc);
4473
4474 ConvertedArgs.push_back(TInfo);
4475 }
4476
4477 return BuildTypeTrait(Kind, KWLoc, ConvertedArgs, RParenLoc);
4478 }
4479
EvaluateBinaryTypeTrait(Sema & Self,TypeTrait BTT,QualType LhsT,QualType RhsT,SourceLocation KeyLoc)4480 static bool EvaluateBinaryTypeTrait(Sema &Self, TypeTrait BTT, QualType LhsT,
4481 QualType RhsT, SourceLocation KeyLoc) {
4482 assert(!LhsT->isDependentType() && !RhsT->isDependentType() &&
4483 "Cannot evaluate traits of dependent types");
4484
4485 switch(BTT) {
4486 case BTT_IsBaseOf: {
4487 // C++0x [meta.rel]p2
4488 // Base is a base class of Derived without regard to cv-qualifiers or
4489 // Base and Derived are not unions and name the same class type without
4490 // regard to cv-qualifiers.
4491
4492 const RecordType *lhsRecord = LhsT->getAs<RecordType>();
4493 if (!lhsRecord) return false;
4494
4495 const RecordType *rhsRecord = RhsT->getAs<RecordType>();
4496 if (!rhsRecord) return false;
4497
4498 assert(Self.Context.hasSameUnqualifiedType(LhsT, RhsT)
4499 == (lhsRecord == rhsRecord));
4500
4501 if (lhsRecord == rhsRecord)
4502 return !lhsRecord->getDecl()->isUnion();
4503
4504 // C++0x [meta.rel]p2:
4505 // If Base and Derived are class types and are different types
4506 // (ignoring possible cv-qualifiers) then Derived shall be a
4507 // complete type.
4508 if (Self.RequireCompleteType(KeyLoc, RhsT,
4509 diag::err_incomplete_type_used_in_type_trait_expr))
4510 return false;
4511
4512 return cast<CXXRecordDecl>(rhsRecord->getDecl())
4513 ->isDerivedFrom(cast<CXXRecordDecl>(lhsRecord->getDecl()));
4514 }
4515 case BTT_IsSame:
4516 return Self.Context.hasSameType(LhsT, RhsT);
4517 case BTT_TypeCompatible:
4518 return Self.Context.typesAreCompatible(LhsT.getUnqualifiedType(),
4519 RhsT.getUnqualifiedType());
4520 case BTT_IsConvertible:
4521 case BTT_IsConvertibleTo: {
4522 // C++0x [meta.rel]p4:
4523 // Given the following function prototype:
4524 //
4525 // template <class T>
4526 // typename add_rvalue_reference<T>::type create();
4527 //
4528 // the predicate condition for a template specialization
4529 // is_convertible<From, To> shall be satisfied if and only if
4530 // the return expression in the following code would be
4531 // well-formed, including any implicit conversions to the return
4532 // type of the function:
4533 //
4534 // To test() {
4535 // return create<From>();
4536 // }
4537 //
4538 // Access checking is performed as if in a context unrelated to To and
4539 // From. Only the validity of the immediate context of the expression
4540 // of the return-statement (including conversions to the return type)
4541 // is considered.
4542 //
4543 // We model the initialization as a copy-initialization of a temporary
4544 // of the appropriate type, which for this expression is identical to the
4545 // return statement (since NRVO doesn't apply).
4546
4547 // Functions aren't allowed to return function or array types.
4548 if (RhsT->isFunctionType() || RhsT->isArrayType())
4549 return false;
4550
4551 // A return statement in a void function must have void type.
4552 if (RhsT->isVoidType())
4553 return LhsT->isVoidType();
4554
4555 // A function definition requires a complete, non-abstract return type.
4556 if (!Self.isCompleteType(KeyLoc, RhsT) || Self.isAbstractType(KeyLoc, RhsT))
4557 return false;
4558
4559 // Compute the result of add_rvalue_reference.
4560 if (LhsT->isObjectType() || LhsT->isFunctionType())
4561 LhsT = Self.Context.getRValueReferenceType(LhsT);
4562
4563 // Build a fake source and destination for initialization.
4564 InitializedEntity To(InitializedEntity::InitializeTemporary(RhsT));
4565 OpaqueValueExpr From(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4566 Expr::getValueKindForType(LhsT));
4567 Expr *FromPtr = &From;
4568 InitializationKind Kind(InitializationKind::CreateCopy(KeyLoc,
4569 SourceLocation()));
4570
4571 // Perform the initialization in an unevaluated context within a SFINAE
4572 // trap at translation unit scope.
4573 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4574 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4575 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4576 InitializationSequence Init(Self, To, Kind, FromPtr);
4577 if (Init.Failed())
4578 return false;
4579
4580 ExprResult Result = Init.Perform(Self, To, Kind, FromPtr);
4581 return !Result.isInvalid() && !SFINAE.hasErrorOccurred();
4582 }
4583
4584 case BTT_IsAssignable:
4585 case BTT_IsNothrowAssignable:
4586 case BTT_IsTriviallyAssignable: {
4587 // C++11 [meta.unary.prop]p3:
4588 // is_trivially_assignable is defined as:
4589 // is_assignable<T, U>::value is true and the assignment, as defined by
4590 // is_assignable, is known to call no operation that is not trivial
4591 //
4592 // is_assignable is defined as:
4593 // The expression declval<T>() = declval<U>() is well-formed when
4594 // treated as an unevaluated operand (Clause 5).
4595 //
4596 // For both, T and U shall be complete types, (possibly cv-qualified)
4597 // void, or arrays of unknown bound.
4598 if (!LhsT->isVoidType() && !LhsT->isIncompleteArrayType() &&
4599 Self.RequireCompleteType(KeyLoc, LhsT,
4600 diag::err_incomplete_type_used_in_type_trait_expr))
4601 return false;
4602 if (!RhsT->isVoidType() && !RhsT->isIncompleteArrayType() &&
4603 Self.RequireCompleteType(KeyLoc, RhsT,
4604 diag::err_incomplete_type_used_in_type_trait_expr))
4605 return false;
4606
4607 // cv void is never assignable.
4608 if (LhsT->isVoidType() || RhsT->isVoidType())
4609 return false;
4610
4611 // Build expressions that emulate the effect of declval<T>() and
4612 // declval<U>().
4613 if (LhsT->isObjectType() || LhsT->isFunctionType())
4614 LhsT = Self.Context.getRValueReferenceType(LhsT);
4615 if (RhsT->isObjectType() || RhsT->isFunctionType())
4616 RhsT = Self.Context.getRValueReferenceType(RhsT);
4617 OpaqueValueExpr Lhs(KeyLoc, LhsT.getNonLValueExprType(Self.Context),
4618 Expr::getValueKindForType(LhsT));
4619 OpaqueValueExpr Rhs(KeyLoc, RhsT.getNonLValueExprType(Self.Context),
4620 Expr::getValueKindForType(RhsT));
4621
4622 // Attempt the assignment in an unevaluated context within a SFINAE
4623 // trap at translation unit scope.
4624 EnterExpressionEvaluationContext Unevaluated(Self, Sema::Unevaluated);
4625 Sema::SFINAETrap SFINAE(Self, /*AccessCheckingSFINAE=*/true);
4626 Sema::ContextRAII TUContext(Self, Self.Context.getTranslationUnitDecl());
4627 ExprResult Result = Self.BuildBinOp(/*S=*/nullptr, KeyLoc, BO_Assign, &Lhs,
4628 &Rhs);
4629 if (Result.isInvalid() || SFINAE.hasErrorOccurred())
4630 return false;
4631
4632 if (BTT == BTT_IsAssignable)
4633 return true;
4634
4635 if (BTT == BTT_IsNothrowAssignable)
4636 return Self.canThrow(Result.get()) == CT_Cannot;
4637
4638 if (BTT == BTT_IsTriviallyAssignable) {
4639 // Under Objective-C ARC, if the destination has non-trivial Objective-C
4640 // lifetime, this is a non-trivial assignment.
4641 if (Self.getLangOpts().ObjCAutoRefCount &&
4642 hasNontrivialObjCLifetime(LhsT.getNonReferenceType()))
4643 return false;
4644
4645 return !Result.get()->hasNonTrivialCall(Self.Context);
4646 }
4647
4648 llvm_unreachable("unhandled type trait");
4649 return false;
4650 }
4651 default: llvm_unreachable("not a BTT");
4652 }
4653 llvm_unreachable("Unknown type trait or not implemented");
4654 }
4655
ActOnArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,ParsedType Ty,Expr * DimExpr,SourceLocation RParen)4656 ExprResult Sema::ActOnArrayTypeTrait(ArrayTypeTrait ATT,
4657 SourceLocation KWLoc,
4658 ParsedType Ty,
4659 Expr* DimExpr,
4660 SourceLocation RParen) {
4661 TypeSourceInfo *TSInfo;
4662 QualType T = GetTypeFromParser(Ty, &TSInfo);
4663 if (!TSInfo)
4664 TSInfo = Context.getTrivialTypeSourceInfo(T);
4665
4666 return BuildArrayTypeTrait(ATT, KWLoc, TSInfo, DimExpr, RParen);
4667 }
4668
EvaluateArrayTypeTrait(Sema & Self,ArrayTypeTrait ATT,QualType T,Expr * DimExpr,SourceLocation KeyLoc)4669 static uint64_t EvaluateArrayTypeTrait(Sema &Self, ArrayTypeTrait ATT,
4670 QualType T, Expr *DimExpr,
4671 SourceLocation KeyLoc) {
4672 assert(!T->isDependentType() && "Cannot evaluate traits of dependent type");
4673
4674 switch(ATT) {
4675 case ATT_ArrayRank:
4676 if (T->isArrayType()) {
4677 unsigned Dim = 0;
4678 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4679 ++Dim;
4680 T = AT->getElementType();
4681 }
4682 return Dim;
4683 }
4684 return 0;
4685
4686 case ATT_ArrayExtent: {
4687 llvm::APSInt Value;
4688 uint64_t Dim;
4689 if (Self.VerifyIntegerConstantExpression(DimExpr, &Value,
4690 diag::err_dimension_expr_not_constant_integer,
4691 false).isInvalid())
4692 return 0;
4693 if (Value.isSigned() && Value.isNegative()) {
4694 Self.Diag(KeyLoc, diag::err_dimension_expr_not_constant_integer)
4695 << DimExpr->getSourceRange();
4696 return 0;
4697 }
4698 Dim = Value.getLimitedValue();
4699
4700 if (T->isArrayType()) {
4701 unsigned D = 0;
4702 bool Matched = false;
4703 while (const ArrayType *AT = Self.Context.getAsArrayType(T)) {
4704 if (Dim == D) {
4705 Matched = true;
4706 break;
4707 }
4708 ++D;
4709 T = AT->getElementType();
4710 }
4711
4712 if (Matched && T->isArrayType()) {
4713 if (const ConstantArrayType *CAT = Self.Context.getAsConstantArrayType(T))
4714 return CAT->getSize().getLimitedValue();
4715 }
4716 }
4717 return 0;
4718 }
4719 }
4720 llvm_unreachable("Unknown type trait or not implemented");
4721 }
4722
BuildArrayTypeTrait(ArrayTypeTrait ATT,SourceLocation KWLoc,TypeSourceInfo * TSInfo,Expr * DimExpr,SourceLocation RParen)4723 ExprResult Sema::BuildArrayTypeTrait(ArrayTypeTrait ATT,
4724 SourceLocation KWLoc,
4725 TypeSourceInfo *TSInfo,
4726 Expr* DimExpr,
4727 SourceLocation RParen) {
4728 QualType T = TSInfo->getType();
4729
4730 // FIXME: This should likely be tracked as an APInt to remove any host
4731 // assumptions about the width of size_t on the target.
4732 uint64_t Value = 0;
4733 if (!T->isDependentType())
4734 Value = EvaluateArrayTypeTrait(*this, ATT, T, DimExpr, KWLoc);
4735
4736 // While the specification for these traits from the Embarcadero C++
4737 // compiler's documentation says the return type is 'unsigned int', Clang
4738 // returns 'size_t'. On Windows, the primary platform for the Embarcadero
4739 // compiler, there is no difference. On several other platforms this is an
4740 // important distinction.
4741 return new (Context) ArrayTypeTraitExpr(KWLoc, ATT, TSInfo, Value, DimExpr,
4742 RParen, Context.getSizeType());
4743 }
4744
ActOnExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)4745 ExprResult Sema::ActOnExpressionTrait(ExpressionTrait ET,
4746 SourceLocation KWLoc,
4747 Expr *Queried,
4748 SourceLocation RParen) {
4749 // If error parsing the expression, ignore.
4750 if (!Queried)
4751 return ExprError();
4752
4753 ExprResult Result = BuildExpressionTrait(ET, KWLoc, Queried, RParen);
4754
4755 return Result;
4756 }
4757
EvaluateExpressionTrait(ExpressionTrait ET,Expr * E)4758 static bool EvaluateExpressionTrait(ExpressionTrait ET, Expr *E) {
4759 switch (ET) {
4760 case ET_IsLValueExpr: return E->isLValue();
4761 case ET_IsRValueExpr: return E->isRValue();
4762 }
4763 llvm_unreachable("Expression trait not covered by switch");
4764 }
4765
BuildExpressionTrait(ExpressionTrait ET,SourceLocation KWLoc,Expr * Queried,SourceLocation RParen)4766 ExprResult Sema::BuildExpressionTrait(ExpressionTrait ET,
4767 SourceLocation KWLoc,
4768 Expr *Queried,
4769 SourceLocation RParen) {
4770 if (Queried->isTypeDependent()) {
4771 // Delay type-checking for type-dependent expressions.
4772 } else if (Queried->getType()->isPlaceholderType()) {
4773 ExprResult PE = CheckPlaceholderExpr(Queried);
4774 if (PE.isInvalid()) return ExprError();
4775 return BuildExpressionTrait(ET, KWLoc, PE.get(), RParen);
4776 }
4777
4778 bool Value = EvaluateExpressionTrait(ET, Queried);
4779
4780 return new (Context)
4781 ExpressionTraitExpr(KWLoc, ET, Queried, Value, RParen, Context.BoolTy);
4782 }
4783
CheckPointerToMemberOperands(ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,SourceLocation Loc,bool isIndirect)4784 QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS,
4785 ExprValueKind &VK,
4786 SourceLocation Loc,
4787 bool isIndirect) {
4788 assert(!LHS.get()->getType()->isPlaceholderType() &&
4789 !RHS.get()->getType()->isPlaceholderType() &&
4790 "placeholders should have been weeded out by now");
4791
4792 // The LHS undergoes lvalue conversions if this is ->*.
4793 if (isIndirect) {
4794 LHS = DefaultLvalueConversion(LHS.get());
4795 if (LHS.isInvalid()) return QualType();
4796 }
4797
4798 // The RHS always undergoes lvalue conversions.
4799 RHS = DefaultLvalueConversion(RHS.get());
4800 if (RHS.isInvalid()) return QualType();
4801
4802 const char *OpSpelling = isIndirect ? "->*" : ".*";
4803 // C++ 5.5p2
4804 // The binary operator .* [p3: ->*] binds its second operand, which shall
4805 // be of type "pointer to member of T" (where T is a completely-defined
4806 // class type) [...]
4807 QualType RHSType = RHS.get()->getType();
4808 const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>();
4809 if (!MemPtr) {
4810 Diag(Loc, diag::err_bad_memptr_rhs)
4811 << OpSpelling << RHSType << RHS.get()->getSourceRange();
4812 return QualType();
4813 }
4814
4815 QualType Class(MemPtr->getClass(), 0);
4816
4817 // Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the
4818 // member pointer points must be completely-defined. However, there is no
4819 // reason for this semantic distinction, and the rule is not enforced by
4820 // other compilers. Therefore, we do not check this property, as it is
4821 // likely to be considered a defect.
4822
4823 // C++ 5.5p2
4824 // [...] to its first operand, which shall be of class T or of a class of
4825 // which T is an unambiguous and accessible base class. [p3: a pointer to
4826 // such a class]
4827 QualType LHSType = LHS.get()->getType();
4828 if (isIndirect) {
4829 if (const PointerType *Ptr = LHSType->getAs<PointerType>())
4830 LHSType = Ptr->getPointeeType();
4831 else {
4832 Diag(Loc, diag::err_bad_memptr_lhs)
4833 << OpSpelling << 1 << LHSType
4834 << FixItHint::CreateReplacement(SourceRange(Loc), ".*");
4835 return QualType();
4836 }
4837 }
4838
4839 if (!Context.hasSameUnqualifiedType(Class, LHSType)) {
4840 // If we want to check the hierarchy, we need a complete type.
4841 if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs,
4842 OpSpelling, (int)isIndirect)) {
4843 return QualType();
4844 }
4845
4846 if (!IsDerivedFrom(Loc, LHSType, Class)) {
4847 Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling
4848 << (int)isIndirect << LHS.get()->getType();
4849 return QualType();
4850 }
4851
4852 CXXCastPath BasePath;
4853 if (CheckDerivedToBaseConversion(LHSType, Class, Loc,
4854 SourceRange(LHS.get()->getLocStart(),
4855 RHS.get()->getLocEnd()),
4856 &BasePath))
4857 return QualType();
4858
4859 // Cast LHS to type of use.
4860 QualType UseType = isIndirect ? Context.getPointerType(Class) : Class;
4861 ExprValueKind VK = isIndirect ? VK_RValue : LHS.get()->getValueKind();
4862 LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK,
4863 &BasePath);
4864 }
4865
4866 if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) {
4867 // Diagnose use of pointer-to-member type which when used as
4868 // the functional cast in a pointer-to-member expression.
4869 Diag(Loc, diag::err_pointer_to_member_type) << isIndirect;
4870 return QualType();
4871 }
4872
4873 // C++ 5.5p2
4874 // The result is an object or a function of the type specified by the
4875 // second operand.
4876 // The cv qualifiers are the union of those in the pointer and the left side,
4877 // in accordance with 5.5p5 and 5.2.5.
4878 QualType Result = MemPtr->getPointeeType();
4879 Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers());
4880
4881 // C++0x [expr.mptr.oper]p6:
4882 // In a .* expression whose object expression is an rvalue, the program is
4883 // ill-formed if the second operand is a pointer to member function with
4884 // ref-qualifier &. In a ->* expression or in a .* expression whose object
4885 // expression is an lvalue, the program is ill-formed if the second operand
4886 // is a pointer to member function with ref-qualifier &&.
4887 if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) {
4888 switch (Proto->getRefQualifier()) {
4889 case RQ_None:
4890 // Do nothing
4891 break;
4892
4893 case RQ_LValue:
4894 if (!isIndirect && !LHS.get()->Classify(Context).isLValue())
4895 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4896 << RHSType << 1 << LHS.get()->getSourceRange();
4897 break;
4898
4899 case RQ_RValue:
4900 if (isIndirect || !LHS.get()->Classify(Context).isRValue())
4901 Diag(Loc, diag::err_pointer_to_member_oper_value_classify)
4902 << RHSType << 0 << LHS.get()->getSourceRange();
4903 break;
4904 }
4905 }
4906
4907 // C++ [expr.mptr.oper]p6:
4908 // The result of a .* expression whose second operand is a pointer
4909 // to a data member is of the same value category as its
4910 // first operand. The result of a .* expression whose second
4911 // operand is a pointer to a member function is a prvalue. The
4912 // result of an ->* expression is an lvalue if its second operand
4913 // is a pointer to data member and a prvalue otherwise.
4914 if (Result->isFunctionType()) {
4915 VK = VK_RValue;
4916 return Context.BoundMemberTy;
4917 } else if (isIndirect) {
4918 VK = VK_LValue;
4919 } else {
4920 VK = LHS.get()->getValueKind();
4921 }
4922
4923 return Result;
4924 }
4925
4926 /// \brief Try to convert a type to another according to C++11 5.16p3.
4927 ///
4928 /// This is part of the parameter validation for the ? operator. If either
4929 /// value operand is a class type, the two operands are attempted to be
4930 /// converted to each other. This function does the conversion in one direction.
4931 /// It returns true if the program is ill-formed and has already been diagnosed
4932 /// as such.
TryClassUnification(Sema & Self,Expr * From,Expr * To,SourceLocation QuestionLoc,bool & HaveConversion,QualType & ToType)4933 static bool TryClassUnification(Sema &Self, Expr *From, Expr *To,
4934 SourceLocation QuestionLoc,
4935 bool &HaveConversion,
4936 QualType &ToType) {
4937 HaveConversion = false;
4938 ToType = To->getType();
4939
4940 InitializationKind Kind = InitializationKind::CreateCopy(To->getLocStart(),
4941 SourceLocation());
4942 // C++11 5.16p3
4943 // The process for determining whether an operand expression E1 of type T1
4944 // can be converted to match an operand expression E2 of type T2 is defined
4945 // as follows:
4946 // -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be
4947 // implicitly converted to type "lvalue reference to T2", subject to the
4948 // constraint that in the conversion the reference must bind directly to
4949 // an lvalue.
4950 // -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be
4951 // implicitly conveted to the type "rvalue reference to R2", subject to
4952 // the constraint that the reference must bind directly.
4953 if (To->isLValue() || To->isXValue()) {
4954 QualType T = To->isLValue() ? Self.Context.getLValueReferenceType(ToType)
4955 : Self.Context.getRValueReferenceType(ToType);
4956
4957 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
4958
4959 InitializationSequence InitSeq(Self, Entity, Kind, From);
4960 if (InitSeq.isDirectReferenceBinding()) {
4961 ToType = T;
4962 HaveConversion = true;
4963 return false;
4964 }
4965
4966 if (InitSeq.isAmbiguous())
4967 return InitSeq.Diagnose(Self, Entity, Kind, From);
4968 }
4969
4970 // -- If E2 is an rvalue, or if the conversion above cannot be done:
4971 // -- if E1 and E2 have class type, and the underlying class types are
4972 // the same or one is a base class of the other:
4973 QualType FTy = From->getType();
4974 QualType TTy = To->getType();
4975 const RecordType *FRec = FTy->getAs<RecordType>();
4976 const RecordType *TRec = TTy->getAs<RecordType>();
4977 bool FDerivedFromT = FRec && TRec && FRec != TRec &&
4978 Self.IsDerivedFrom(QuestionLoc, FTy, TTy);
4979 if (FRec && TRec && (FRec == TRec || FDerivedFromT ||
4980 Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) {
4981 // E1 can be converted to match E2 if the class of T2 is the
4982 // same type as, or a base class of, the class of T1, and
4983 // [cv2 > cv1].
4984 if (FRec == TRec || FDerivedFromT) {
4985 if (TTy.isAtLeastAsQualifiedAs(FTy)) {
4986 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
4987 InitializationSequence InitSeq(Self, Entity, Kind, From);
4988 if (InitSeq) {
4989 HaveConversion = true;
4990 return false;
4991 }
4992
4993 if (InitSeq.isAmbiguous())
4994 return InitSeq.Diagnose(Self, Entity, Kind, From);
4995 }
4996 }
4997
4998 return false;
4999 }
5000
5001 // -- Otherwise: E1 can be converted to match E2 if E1 can be
5002 // implicitly converted to the type that expression E2 would have
5003 // if E2 were converted to an rvalue (or the type it has, if E2 is
5004 // an rvalue).
5005 //
5006 // This actually refers very narrowly to the lvalue-to-rvalue conversion, not
5007 // to the array-to-pointer or function-to-pointer conversions.
5008 if (!TTy->getAs<TagType>())
5009 TTy = TTy.getUnqualifiedType();
5010
5011 InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy);
5012 InitializationSequence InitSeq(Self, Entity, Kind, From);
5013 HaveConversion = !InitSeq.Failed();
5014 ToType = TTy;
5015 if (InitSeq.isAmbiguous())
5016 return InitSeq.Diagnose(Self, Entity, Kind, From);
5017
5018 return false;
5019 }
5020
5021 /// \brief Try to find a common type for two according to C++0x 5.16p5.
5022 ///
5023 /// This is part of the parameter validation for the ? operator. If either
5024 /// value operand is a class type, overload resolution is used to find a
5025 /// conversion to a common type.
FindConditionalOverload(Sema & Self,ExprResult & LHS,ExprResult & RHS,SourceLocation QuestionLoc)5026 static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS,
5027 SourceLocation QuestionLoc) {
5028 Expr *Args[2] = { LHS.get(), RHS.get() };
5029 OverloadCandidateSet CandidateSet(QuestionLoc,
5030 OverloadCandidateSet::CSK_Operator);
5031 Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args,
5032 CandidateSet);
5033
5034 OverloadCandidateSet::iterator Best;
5035 switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) {
5036 case OR_Success: {
5037 // We found a match. Perform the conversions on the arguments and move on.
5038 ExprResult LHSRes =
5039 Self.PerformImplicitConversion(LHS.get(), Best->BuiltinTypes.ParamTypes[0],
5040 Best->Conversions[0], Sema::AA_Converting);
5041 if (LHSRes.isInvalid())
5042 break;
5043 LHS = LHSRes;
5044
5045 ExprResult RHSRes =
5046 Self.PerformImplicitConversion(RHS.get(), Best->BuiltinTypes.ParamTypes[1],
5047 Best->Conversions[1], Sema::AA_Converting);
5048 if (RHSRes.isInvalid())
5049 break;
5050 RHS = RHSRes;
5051 if (Best->Function)
5052 Self.MarkFunctionReferenced(QuestionLoc, Best->Function);
5053 return false;
5054 }
5055
5056 case OR_No_Viable_Function:
5057
5058 // Emit a better diagnostic if one of the expressions is a null pointer
5059 // constant and the other is a pointer type. In this case, the user most
5060 // likely forgot to take the address of the other expression.
5061 if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5062 return true;
5063
5064 Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5065 << LHS.get()->getType() << RHS.get()->getType()
5066 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5067 return true;
5068
5069 case OR_Ambiguous:
5070 Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl)
5071 << LHS.get()->getType() << RHS.get()->getType()
5072 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5073 // FIXME: Print the possible common types by printing the return types of
5074 // the viable candidates.
5075 break;
5076
5077 case OR_Deleted:
5078 llvm_unreachable("Conditional operator has only built-in overloads");
5079 }
5080 return true;
5081 }
5082
5083 /// \brief Perform an "extended" implicit conversion as returned by
5084 /// TryClassUnification.
ConvertForConditional(Sema & Self,ExprResult & E,QualType T)5085 static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) {
5086 InitializedEntity Entity = InitializedEntity::InitializeTemporary(T);
5087 InitializationKind Kind = InitializationKind::CreateCopy(E.get()->getLocStart(),
5088 SourceLocation());
5089 Expr *Arg = E.get();
5090 InitializationSequence InitSeq(Self, Entity, Kind, Arg);
5091 ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg);
5092 if (Result.isInvalid())
5093 return true;
5094
5095 E = Result;
5096 return false;
5097 }
5098
5099 /// \brief Check the operands of ?: under C++ semantics.
5100 ///
5101 /// See C++ [expr.cond]. Note that LHS is never null, even for the GNU x ?: y
5102 /// extension. In this case, LHS == Cond. (But they're not aliases.)
CXXCheckConditionalOperands(ExprResult & Cond,ExprResult & LHS,ExprResult & RHS,ExprValueKind & VK,ExprObjectKind & OK,SourceLocation QuestionLoc)5103 QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS,
5104 ExprResult &RHS, ExprValueKind &VK,
5105 ExprObjectKind &OK,
5106 SourceLocation QuestionLoc) {
5107 // FIXME: Handle C99's complex types, vector types, block pointers and Obj-C++
5108 // interface pointers.
5109
5110 // C++11 [expr.cond]p1
5111 // The first expression is contextually converted to bool.
5112 if (!Cond.get()->isTypeDependent()) {
5113 ExprResult CondRes = CheckCXXBooleanCondition(Cond.get());
5114 if (CondRes.isInvalid())
5115 return QualType();
5116 Cond = CondRes;
5117 }
5118
5119 // Assume r-value.
5120 VK = VK_RValue;
5121 OK = OK_Ordinary;
5122
5123 // Either of the arguments dependent?
5124 if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent())
5125 return Context.DependentTy;
5126
5127 // C++11 [expr.cond]p2
5128 // If either the second or the third operand has type (cv) void, ...
5129 QualType LTy = LHS.get()->getType();
5130 QualType RTy = RHS.get()->getType();
5131 bool LVoid = LTy->isVoidType();
5132 bool RVoid = RTy->isVoidType();
5133 if (LVoid || RVoid) {
5134 // ... one of the following shall hold:
5135 // -- The second or the third operand (but not both) is a (possibly
5136 // parenthesized) throw-expression; the result is of the type
5137 // and value category of the other.
5138 bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts());
5139 bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts());
5140 if (LThrow != RThrow) {
5141 Expr *NonThrow = LThrow ? RHS.get() : LHS.get();
5142 VK = NonThrow->getValueKind();
5143 // DR (no number yet): the result is a bit-field if the
5144 // non-throw-expression operand is a bit-field.
5145 OK = NonThrow->getObjectKind();
5146 return NonThrow->getType();
5147 }
5148
5149 // -- Both the second and third operands have type void; the result is of
5150 // type void and is a prvalue.
5151 if (LVoid && RVoid)
5152 return Context.VoidTy;
5153
5154 // Neither holds, error.
5155 Diag(QuestionLoc, diag::err_conditional_void_nonvoid)
5156 << (LVoid ? RTy : LTy) << (LVoid ? 0 : 1)
5157 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5158 return QualType();
5159 }
5160
5161 // Neither is void.
5162
5163 // C++11 [expr.cond]p3
5164 // Otherwise, if the second and third operand have different types, and
5165 // either has (cv) class type [...] an attempt is made to convert each of
5166 // those operands to the type of the other.
5167 if (!Context.hasSameType(LTy, RTy) &&
5168 (LTy->isRecordType() || RTy->isRecordType())) {
5169 // These return true if a single direction is already ambiguous.
5170 QualType L2RType, R2LType;
5171 bool HaveL2R, HaveR2L;
5172 if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType))
5173 return QualType();
5174 if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType))
5175 return QualType();
5176
5177 // If both can be converted, [...] the program is ill-formed.
5178 if (HaveL2R && HaveR2L) {
5179 Diag(QuestionLoc, diag::err_conditional_ambiguous)
5180 << LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5181 return QualType();
5182 }
5183
5184 // If exactly one conversion is possible, that conversion is applied to
5185 // the chosen operand and the converted operands are used in place of the
5186 // original operands for the remainder of this section.
5187 if (HaveL2R) {
5188 if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid())
5189 return QualType();
5190 LTy = LHS.get()->getType();
5191 } else if (HaveR2L) {
5192 if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid())
5193 return QualType();
5194 RTy = RHS.get()->getType();
5195 }
5196 }
5197
5198 // C++11 [expr.cond]p3
5199 // if both are glvalues of the same value category and the same type except
5200 // for cv-qualification, an attempt is made to convert each of those
5201 // operands to the type of the other.
5202 ExprValueKind LVK = LHS.get()->getValueKind();
5203 ExprValueKind RVK = RHS.get()->getValueKind();
5204 if (!Context.hasSameType(LTy, RTy) &&
5205 Context.hasSameUnqualifiedType(LTy, RTy) &&
5206 LVK == RVK && LVK != VK_RValue) {
5207 // Since the unqualified types are reference-related and we require the
5208 // result to be as if a reference bound directly, the only conversion
5209 // we can perform is to add cv-qualifiers.
5210 Qualifiers LCVR = Qualifiers::fromCVRMask(LTy.getCVRQualifiers());
5211 Qualifiers RCVR = Qualifiers::fromCVRMask(RTy.getCVRQualifiers());
5212 if (RCVR.isStrictSupersetOf(LCVR)) {
5213 LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK);
5214 LTy = LHS.get()->getType();
5215 }
5216 else if (LCVR.isStrictSupersetOf(RCVR)) {
5217 RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK);
5218 RTy = RHS.get()->getType();
5219 }
5220 }
5221
5222 // C++11 [expr.cond]p4
5223 // If the second and third operands are glvalues of the same value
5224 // category and have the same type, the result is of that type and
5225 // value category and it is a bit-field if the second or the third
5226 // operand is a bit-field, or if both are bit-fields.
5227 // We only extend this to bitfields, not to the crazy other kinds of
5228 // l-values.
5229 bool Same = Context.hasSameType(LTy, RTy);
5230 if (Same && LVK == RVK && LVK != VK_RValue &&
5231 LHS.get()->isOrdinaryOrBitFieldObject() &&
5232 RHS.get()->isOrdinaryOrBitFieldObject()) {
5233 VK = LHS.get()->getValueKind();
5234 if (LHS.get()->getObjectKind() == OK_BitField ||
5235 RHS.get()->getObjectKind() == OK_BitField)
5236 OK = OK_BitField;
5237 return LTy;
5238 }
5239
5240 // C++11 [expr.cond]p5
5241 // Otherwise, the result is a prvalue. If the second and third operands
5242 // do not have the same type, and either has (cv) class type, ...
5243 if (!Same && (LTy->isRecordType() || RTy->isRecordType())) {
5244 // ... overload resolution is used to determine the conversions (if any)
5245 // to be applied to the operands. If the overload resolution fails, the
5246 // program is ill-formed.
5247 if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc))
5248 return QualType();
5249 }
5250
5251 // C++11 [expr.cond]p6
5252 // Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard
5253 // conversions are performed on the second and third operands.
5254 LHS = DefaultFunctionArrayLvalueConversion(LHS.get());
5255 RHS = DefaultFunctionArrayLvalueConversion(RHS.get());
5256 if (LHS.isInvalid() || RHS.isInvalid())
5257 return QualType();
5258 LTy = LHS.get()->getType();
5259 RTy = RHS.get()->getType();
5260
5261 // After those conversions, one of the following shall hold:
5262 // -- The second and third operands have the same type; the result
5263 // is of that type. If the operands have class type, the result
5264 // is a prvalue temporary of the result type, which is
5265 // copy-initialized from either the second operand or the third
5266 // operand depending on the value of the first operand.
5267 if (Context.getCanonicalType(LTy) == Context.getCanonicalType(RTy)) {
5268 if (LTy->isRecordType()) {
5269 // The operands have class type. Make a temporary copy.
5270 if (RequireNonAbstractType(QuestionLoc, LTy,
5271 diag::err_allocation_of_abstract_type))
5272 return QualType();
5273 InitializedEntity Entity = InitializedEntity::InitializeTemporary(LTy);
5274
5275 ExprResult LHSCopy = PerformCopyInitialization(Entity,
5276 SourceLocation(),
5277 LHS);
5278 if (LHSCopy.isInvalid())
5279 return QualType();
5280
5281 ExprResult RHSCopy = PerformCopyInitialization(Entity,
5282 SourceLocation(),
5283 RHS);
5284 if (RHSCopy.isInvalid())
5285 return QualType();
5286
5287 LHS = LHSCopy;
5288 RHS = RHSCopy;
5289 }
5290
5291 return LTy;
5292 }
5293
5294 // Extension: conditional operator involving vector types.
5295 if (LTy->isVectorType() || RTy->isVectorType())
5296 return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/false,
5297 /*AllowBothBool*/true,
5298 /*AllowBoolConversions*/false);
5299
5300 // -- The second and third operands have arithmetic or enumeration type;
5301 // the usual arithmetic conversions are performed to bring them to a
5302 // common type, and the result is of that type.
5303 if (LTy->isArithmeticType() && RTy->isArithmeticType()) {
5304 QualType ResTy = UsualArithmeticConversions(LHS, RHS);
5305 if (LHS.isInvalid() || RHS.isInvalid())
5306 return QualType();
5307 if (ResTy.isNull()) {
5308 Diag(QuestionLoc,
5309 diag::err_typecheck_cond_incompatible_operands) << LTy << RTy
5310 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5311 return QualType();
5312 }
5313
5314 LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy));
5315 RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy));
5316
5317 return ResTy;
5318 }
5319
5320 // -- The second and third operands have pointer type, or one has pointer
5321 // type and the other is a null pointer constant, or both are null
5322 // pointer constants, at least one of which is non-integral; pointer
5323 // conversions and qualification conversions are performed to bring them
5324 // to their composite pointer type. The result is of the composite
5325 // pointer type.
5326 // -- The second and third operands have pointer to member type, or one has
5327 // pointer to member type and the other is a null pointer constant;
5328 // pointer to member conversions and qualification conversions are
5329 // performed to bring them to a common type, whose cv-qualification
5330 // shall match the cv-qualification of either the second or the third
5331 // operand. The result is of the common type.
5332 bool NonStandardCompositeType = false;
5333 QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS,
5334 isSFINAEContext() ? nullptr
5335 : &NonStandardCompositeType);
5336 if (!Composite.isNull()) {
5337 if (NonStandardCompositeType)
5338 Diag(QuestionLoc,
5339 diag::ext_typecheck_cond_incompatible_operands_nonstandard)
5340 << LTy << RTy << Composite
5341 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5342
5343 return Composite;
5344 }
5345
5346 // Similarly, attempt to find composite type of two objective-c pointers.
5347 Composite = FindCompositeObjCPointerType(LHS, RHS, QuestionLoc);
5348 if (!Composite.isNull())
5349 return Composite;
5350
5351 // Check if we are using a null with a non-pointer type.
5352 if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc))
5353 return QualType();
5354
5355 Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands)
5356 << LHS.get()->getType() << RHS.get()->getType()
5357 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();
5358 return QualType();
5359 }
5360
5361 /// \brief Find a merged pointer type and convert the two expressions to it.
5362 ///
5363 /// This finds the composite pointer type (or member pointer type) for @p E1
5364 /// and @p E2 according to C++11 5.9p2. It converts both expressions to this
5365 /// type and returns it.
5366 /// It does not emit diagnostics.
5367 ///
5368 /// \param Loc The location of the operator requiring these two expressions to
5369 /// be converted to the composite pointer type.
5370 ///
5371 /// If \p NonStandardCompositeType is non-NULL, then we are permitted to find
5372 /// a non-standard (but still sane) composite type to which both expressions
5373 /// can be converted. When such a type is chosen, \c *NonStandardCompositeType
5374 /// will be set true.
FindCompositePointerType(SourceLocation Loc,Expr * & E1,Expr * & E2,bool * NonStandardCompositeType)5375 QualType Sema::FindCompositePointerType(SourceLocation Loc,
5376 Expr *&E1, Expr *&E2,
5377 bool *NonStandardCompositeType) {
5378 if (NonStandardCompositeType)
5379 *NonStandardCompositeType = false;
5380
5381 assert(getLangOpts().CPlusPlus && "This function assumes C++");
5382 QualType T1 = E1->getType(), T2 = E2->getType();
5383
5384 // C++11 5.9p2
5385 // Pointer conversions and qualification conversions are performed on
5386 // pointer operands to bring them to their composite pointer type. If
5387 // one operand is a null pointer constant, the composite pointer type is
5388 // std::nullptr_t if the other operand is also a null pointer constant or,
5389 // if the other operand is a pointer, the type of the other operand.
5390 if (!T1->isAnyPointerType() && !T1->isMemberPointerType() &&
5391 !T2->isAnyPointerType() && !T2->isMemberPointerType()) {
5392 if (T1->isNullPtrType() &&
5393 E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5394 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
5395 return T1;
5396 }
5397 if (T2->isNullPtrType() &&
5398 E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5399 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
5400 return T2;
5401 }
5402 return QualType();
5403 }
5404
5405 if (E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5406 if (T2->isMemberPointerType())
5407 E1 = ImpCastExprToType(E1, T2, CK_NullToMemberPointer).get();
5408 else
5409 E1 = ImpCastExprToType(E1, T2, CK_NullToPointer).get();
5410 return T2;
5411 }
5412 if (E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) {
5413 if (T1->isMemberPointerType())
5414 E2 = ImpCastExprToType(E2, T1, CK_NullToMemberPointer).get();
5415 else
5416 E2 = ImpCastExprToType(E2, T1, CK_NullToPointer).get();
5417 return T1;
5418 }
5419
5420 // Now both have to be pointers or member pointers.
5421 if ((!T1->isPointerType() && !T1->isMemberPointerType()) ||
5422 (!T2->isPointerType() && !T2->isMemberPointerType()))
5423 return QualType();
5424
5425 // Otherwise, of one of the operands has type "pointer to cv1 void," then
5426 // the other has type "pointer to cv2 T" and the composite pointer type is
5427 // "pointer to cv12 void," where cv12 is the union of cv1 and cv2.
5428 // Otherwise, the composite pointer type is a pointer type similar to the
5429 // type of one of the operands, with a cv-qualification signature that is
5430 // the union of the cv-qualification signatures of the operand types.
5431 // In practice, the first part here is redundant; it's subsumed by the second.
5432 // What we do here is, we build the two possible composite types, and try the
5433 // conversions in both directions. If only one works, or if the two composite
5434 // types are the same, we have succeeded.
5435 // FIXME: extended qualifiers?
5436 typedef SmallVector<unsigned, 4> QualifierVector;
5437 QualifierVector QualifierUnion;
5438 typedef SmallVector<std::pair<const Type *, const Type *>, 4>
5439 ContainingClassVector;
5440 ContainingClassVector MemberOfClass;
5441 QualType Composite1 = Context.getCanonicalType(T1),
5442 Composite2 = Context.getCanonicalType(T2);
5443 unsigned NeedConstBefore = 0;
5444 do {
5445 const PointerType *Ptr1, *Ptr2;
5446 if ((Ptr1 = Composite1->getAs<PointerType>()) &&
5447 (Ptr2 = Composite2->getAs<PointerType>())) {
5448 Composite1 = Ptr1->getPointeeType();
5449 Composite2 = Ptr2->getPointeeType();
5450
5451 // If we're allowed to create a non-standard composite type, keep track
5452 // of where we need to fill in additional 'const' qualifiers.
5453 if (NonStandardCompositeType &&
5454 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5455 NeedConstBefore = QualifierUnion.size();
5456
5457 QualifierUnion.push_back(
5458 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5459 MemberOfClass.push_back(std::make_pair(nullptr, nullptr));
5460 continue;
5461 }
5462
5463 const MemberPointerType *MemPtr1, *MemPtr2;
5464 if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) &&
5465 (MemPtr2 = Composite2->getAs<MemberPointerType>())) {
5466 Composite1 = MemPtr1->getPointeeType();
5467 Composite2 = MemPtr2->getPointeeType();
5468
5469 // If we're allowed to create a non-standard composite type, keep track
5470 // of where we need to fill in additional 'const' qualifiers.
5471 if (NonStandardCompositeType &&
5472 Composite1.getCVRQualifiers() != Composite2.getCVRQualifiers())
5473 NeedConstBefore = QualifierUnion.size();
5474
5475 QualifierUnion.push_back(
5476 Composite1.getCVRQualifiers() | Composite2.getCVRQualifiers());
5477 MemberOfClass.push_back(std::make_pair(MemPtr1->getClass(),
5478 MemPtr2->getClass()));
5479 continue;
5480 }
5481
5482 // FIXME: block pointer types?
5483
5484 // Cannot unwrap any more types.
5485 break;
5486 } while (true);
5487
5488 if (NeedConstBefore && NonStandardCompositeType) {
5489 // Extension: Add 'const' to qualifiers that come before the first qualifier
5490 // mismatch, so that our (non-standard!) composite type meets the
5491 // requirements of C++ [conv.qual]p4 bullet 3.
5492 for (unsigned I = 0; I != NeedConstBefore; ++I) {
5493 if ((QualifierUnion[I] & Qualifiers::Const) == 0) {
5494 QualifierUnion[I] = QualifierUnion[I] | Qualifiers::Const;
5495 *NonStandardCompositeType = true;
5496 }
5497 }
5498 }
5499
5500 // Rewrap the composites as pointers or member pointers with the union CVRs.
5501 ContainingClassVector::reverse_iterator MOC
5502 = MemberOfClass.rbegin();
5503 for (QualifierVector::reverse_iterator
5504 I = QualifierUnion.rbegin(),
5505 E = QualifierUnion.rend();
5506 I != E; (void)++I, ++MOC) {
5507 Qualifiers Quals = Qualifiers::fromCVRMask(*I);
5508 if (MOC->first && MOC->second) {
5509 // Rebuild member pointer type
5510 Composite1 = Context.getMemberPointerType(
5511 Context.getQualifiedType(Composite1, Quals),
5512 MOC->first);
5513 Composite2 = Context.getMemberPointerType(
5514 Context.getQualifiedType(Composite2, Quals),
5515 MOC->second);
5516 } else {
5517 // Rebuild pointer type
5518 Composite1
5519 = Context.getPointerType(Context.getQualifiedType(Composite1, Quals));
5520 Composite2
5521 = Context.getPointerType(Context.getQualifiedType(Composite2, Quals));
5522 }
5523 }
5524
5525 // Try to convert to the first composite pointer type.
5526 InitializedEntity Entity1
5527 = InitializedEntity::InitializeTemporary(Composite1);
5528 InitializationKind Kind
5529 = InitializationKind::CreateCopy(Loc, SourceLocation());
5530 InitializationSequence E1ToC1(*this, Entity1, Kind, E1);
5531 InitializationSequence E2ToC1(*this, Entity1, Kind, E2);
5532
5533 if (E1ToC1 && E2ToC1) {
5534 // Conversion to Composite1 is viable.
5535 if (!Context.hasSameType(Composite1, Composite2)) {
5536 // Composite2 is a different type from Composite1. Check whether
5537 // Composite2 is also viable.
5538 InitializedEntity Entity2
5539 = InitializedEntity::InitializeTemporary(Composite2);
5540 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5541 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
5542 if (E1ToC2 && E2ToC2) {
5543 // Both Composite1 and Composite2 are viable and are different;
5544 // this is an ambiguity.
5545 return QualType();
5546 }
5547 }
5548
5549 // Convert E1 to Composite1
5550 ExprResult E1Result
5551 = E1ToC1.Perform(*this, Entity1, Kind, E1);
5552 if (E1Result.isInvalid())
5553 return QualType();
5554 E1 = E1Result.getAs<Expr>();
5555
5556 // Convert E2 to Composite1
5557 ExprResult E2Result
5558 = E2ToC1.Perform(*this, Entity1, Kind, E2);
5559 if (E2Result.isInvalid())
5560 return QualType();
5561 E2 = E2Result.getAs<Expr>();
5562
5563 return Composite1;
5564 }
5565
5566 // Check whether Composite2 is viable.
5567 InitializedEntity Entity2
5568 = InitializedEntity::InitializeTemporary(Composite2);
5569 InitializationSequence E1ToC2(*this, Entity2, Kind, E1);
5570 InitializationSequence E2ToC2(*this, Entity2, Kind, E2);
5571 if (!E1ToC2 || !E2ToC2)
5572 return QualType();
5573
5574 // Convert E1 to Composite2
5575 ExprResult E1Result
5576 = E1ToC2.Perform(*this, Entity2, Kind, E1);
5577 if (E1Result.isInvalid())
5578 return QualType();
5579 E1 = E1Result.getAs<Expr>();
5580
5581 // Convert E2 to Composite2
5582 ExprResult E2Result
5583 = E2ToC2.Perform(*this, Entity2, Kind, E2);
5584 if (E2Result.isInvalid())
5585 return QualType();
5586 E2 = E2Result.getAs<Expr>();
5587
5588 return Composite2;
5589 }
5590
MaybeBindToTemporary(Expr * E)5591 ExprResult Sema::MaybeBindToTemporary(Expr *E) {
5592 if (!E)
5593 return ExprError();
5594
5595 assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?");
5596
5597 // If the result is a glvalue, we shouldn't bind it.
5598 if (!E->isRValue())
5599 return E;
5600
5601 // In ARC, calls that return a retainable type can return retained,
5602 // in which case we have to insert a consuming cast.
5603 if (getLangOpts().ObjCAutoRefCount &&
5604 E->getType()->isObjCRetainableType()) {
5605
5606 bool ReturnsRetained;
5607
5608 // For actual calls, we compute this by examining the type of the
5609 // called value.
5610 if (CallExpr *Call = dyn_cast<CallExpr>(E)) {
5611 Expr *Callee = Call->getCallee()->IgnoreParens();
5612 QualType T = Callee->getType();
5613
5614 if (T == Context.BoundMemberTy) {
5615 // Handle pointer-to-members.
5616 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee))
5617 T = BinOp->getRHS()->getType();
5618 else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee))
5619 T = Mem->getMemberDecl()->getType();
5620 }
5621
5622 if (const PointerType *Ptr = T->getAs<PointerType>())
5623 T = Ptr->getPointeeType();
5624 else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>())
5625 T = Ptr->getPointeeType();
5626 else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>())
5627 T = MemPtr->getPointeeType();
5628
5629 const FunctionType *FTy = T->getAs<FunctionType>();
5630 assert(FTy && "call to value not of function type?");
5631 ReturnsRetained = FTy->getExtInfo().getProducesResult();
5632
5633 // ActOnStmtExpr arranges things so that StmtExprs of retainable
5634 // type always produce a +1 object.
5635 } else if (isa<StmtExpr>(E)) {
5636 ReturnsRetained = true;
5637
5638 // We hit this case with the lambda conversion-to-block optimization;
5639 // we don't want any extra casts here.
5640 } else if (isa<CastExpr>(E) &&
5641 isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) {
5642 return E;
5643
5644 // For message sends and property references, we try to find an
5645 // actual method. FIXME: we should infer retention by selector in
5646 // cases where we don't have an actual method.
5647 } else {
5648 ObjCMethodDecl *D = nullptr;
5649 if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) {
5650 D = Send->getMethodDecl();
5651 } else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
5652 D = BoxedExpr->getBoxingMethod();
5653 } else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) {
5654 D = ArrayLit->getArrayWithObjectsMethod();
5655 } else if (ObjCDictionaryLiteral *DictLit
5656 = dyn_cast<ObjCDictionaryLiteral>(E)) {
5657 D = DictLit->getDictWithObjectsMethod();
5658 }
5659
5660 ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>());
5661
5662 // Don't do reclaims on performSelector calls; despite their
5663 // return type, the invoked method doesn't necessarily actually
5664 // return an object.
5665 if (!ReturnsRetained &&
5666 D && D->getMethodFamily() == OMF_performSelector)
5667 return E;
5668 }
5669
5670 // Don't reclaim an object of Class type.
5671 if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType())
5672 return E;
5673
5674 Cleanup.setExprNeedsCleanups(true);
5675
5676 CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject
5677 : CK_ARCReclaimReturnedObject);
5678 return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr,
5679 VK_RValue);
5680 }
5681
5682 if (!getLangOpts().CPlusPlus)
5683 return E;
5684
5685 // Search for the base element type (cf. ASTContext::getBaseElementType) with
5686 // a fast path for the common case that the type is directly a RecordType.
5687 const Type *T = Context.getCanonicalType(E->getType().getTypePtr());
5688 const RecordType *RT = nullptr;
5689 while (!RT) {
5690 switch (T->getTypeClass()) {
5691 case Type::Record:
5692 RT = cast<RecordType>(T);
5693 break;
5694 case Type::ConstantArray:
5695 case Type::IncompleteArray:
5696 case Type::VariableArray:
5697 case Type::DependentSizedArray:
5698 T = cast<ArrayType>(T)->getElementType().getTypePtr();
5699 break;
5700 default:
5701 return E;
5702 }
5703 }
5704
5705 // That should be enough to guarantee that this type is complete, if we're
5706 // not processing a decltype expression.
5707 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5708 if (RD->isInvalidDecl() || RD->isDependentContext())
5709 return E;
5710
5711 bool IsDecltype = ExprEvalContexts.back().IsDecltype;
5712 CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD);
5713
5714 if (Destructor) {
5715 MarkFunctionReferenced(E->getExprLoc(), Destructor);
5716 CheckDestructorAccess(E->getExprLoc(), Destructor,
5717 PDiag(diag::err_access_dtor_temp)
5718 << E->getType());
5719 if (DiagnoseUseOfDecl(Destructor, E->getExprLoc()))
5720 return ExprError();
5721
5722 // If destructor is trivial, we can avoid the extra copy.
5723 if (Destructor->isTrivial())
5724 return E;
5725
5726 // We need a cleanup, but we don't need to remember the temporary.
5727 Cleanup.setExprNeedsCleanups(true);
5728 }
5729
5730 CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor);
5731 CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E);
5732
5733 if (IsDecltype)
5734 ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind);
5735
5736 return Bind;
5737 }
5738
5739 ExprResult
MaybeCreateExprWithCleanups(ExprResult SubExpr)5740 Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) {
5741 if (SubExpr.isInvalid())
5742 return ExprError();
5743
5744 return MaybeCreateExprWithCleanups(SubExpr.get());
5745 }
5746
MaybeCreateExprWithCleanups(Expr * SubExpr)5747 Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) {
5748 assert(SubExpr && "subexpression can't be null!");
5749
5750 CleanupVarDeclMarking();
5751
5752 unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects;
5753 assert(ExprCleanupObjects.size() >= FirstCleanup);
5754 assert(Cleanup.exprNeedsCleanups() ||
5755 ExprCleanupObjects.size() == FirstCleanup);
5756 if (!Cleanup.exprNeedsCleanups())
5757 return SubExpr;
5758
5759 auto Cleanups = llvm::makeArrayRef(ExprCleanupObjects.begin() + FirstCleanup,
5760 ExprCleanupObjects.size() - FirstCleanup);
5761
5762 auto *E = ExprWithCleanups::Create(
5763 Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups);
5764 DiscardCleanupsInEvaluationContext();
5765
5766 return E;
5767 }
5768
MaybeCreateStmtWithCleanups(Stmt * SubStmt)5769 Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) {
5770 assert(SubStmt && "sub-statement can't be null!");
5771
5772 CleanupVarDeclMarking();
5773
5774 if (!Cleanup.exprNeedsCleanups())
5775 return SubStmt;
5776
5777 // FIXME: In order to attach the temporaries, wrap the statement into
5778 // a StmtExpr; currently this is only used for asm statements.
5779 // This is hacky, either create a new CXXStmtWithTemporaries statement or
5780 // a new AsmStmtWithTemporaries.
5781 CompoundStmt *CompStmt = new (Context) CompoundStmt(Context, SubStmt,
5782 SourceLocation(),
5783 SourceLocation());
5784 Expr *E = new (Context) StmtExpr(CompStmt, Context.VoidTy, SourceLocation(),
5785 SourceLocation());
5786 return MaybeCreateExprWithCleanups(E);
5787 }
5788
5789 /// Process the expression contained within a decltype. For such expressions,
5790 /// certain semantic checks on temporaries are delayed until this point, and
5791 /// are omitted for the 'topmost' call in the decltype expression. If the
5792 /// topmost call bound a temporary, strip that temporary off the expression.
ActOnDecltypeExpression(Expr * E)5793 ExprResult Sema::ActOnDecltypeExpression(Expr *E) {
5794 assert(ExprEvalContexts.back().IsDecltype && "not in a decltype expression");
5795
5796 // C++11 [expr.call]p11:
5797 // If a function call is a prvalue of object type,
5798 // -- if the function call is either
5799 // -- the operand of a decltype-specifier, or
5800 // -- the right operand of a comma operator that is the operand of a
5801 // decltype-specifier,
5802 // a temporary object is not introduced for the prvalue.
5803
5804 // Recursively rebuild ParenExprs and comma expressions to strip out the
5805 // outermost CXXBindTemporaryExpr, if any.
5806 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5807 ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr());
5808 if (SubExpr.isInvalid())
5809 return ExprError();
5810 if (SubExpr.get() == PE->getSubExpr())
5811 return E;
5812 return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
5813 }
5814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
5815 if (BO->getOpcode() == BO_Comma) {
5816 ExprResult RHS = ActOnDecltypeExpression(BO->getRHS());
5817 if (RHS.isInvalid())
5818 return ExprError();
5819 if (RHS.get() == BO->getRHS())
5820 return E;
5821 return new (Context) BinaryOperator(
5822 BO->getLHS(), RHS.get(), BO_Comma, BO->getType(), BO->getValueKind(),
5823 BO->getObjectKind(), BO->getOperatorLoc(), BO->isFPContractable());
5824 }
5825 }
5826
5827 CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E);
5828 CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr())
5829 : nullptr;
5830 if (TopCall)
5831 E = TopCall;
5832 else
5833 TopBind = nullptr;
5834
5835 // Disable the special decltype handling now.
5836 ExprEvalContexts.back().IsDecltype = false;
5837
5838 // In MS mode, don't perform any extra checking of call return types within a
5839 // decltype expression.
5840 if (getLangOpts().MSVCCompat)
5841 return E;
5842
5843 // Perform the semantic checks we delayed until this point.
5844 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size();
5845 I != N; ++I) {
5846 CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I];
5847 if (Call == TopCall)
5848 continue;
5849
5850 if (CheckCallReturnType(Call->getCallReturnType(Context),
5851 Call->getLocStart(),
5852 Call, Call->getDirectCallee()))
5853 return ExprError();
5854 }
5855
5856 // Now all relevant types are complete, check the destructors are accessible
5857 // and non-deleted, and annotate them on the temporaries.
5858 for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size();
5859 I != N; ++I) {
5860 CXXBindTemporaryExpr *Bind =
5861 ExprEvalContexts.back().DelayedDecltypeBinds[I];
5862 if (Bind == TopBind)
5863 continue;
5864
5865 CXXTemporary *Temp = Bind->getTemporary();
5866
5867 CXXRecordDecl *RD =
5868 Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5869 CXXDestructorDecl *Destructor = LookupDestructor(RD);
5870 Temp->setDestructor(Destructor);
5871
5872 MarkFunctionReferenced(Bind->getExprLoc(), Destructor);
5873 CheckDestructorAccess(Bind->getExprLoc(), Destructor,
5874 PDiag(diag::err_access_dtor_temp)
5875 << Bind->getType());
5876 if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc()))
5877 return ExprError();
5878
5879 // We need a cleanup, but we don't need to remember the temporary.
5880 Cleanup.setExprNeedsCleanups(true);
5881 }
5882
5883 // Possibly strip off the top CXXBindTemporaryExpr.
5884 return E;
5885 }
5886
5887 /// Note a set of 'operator->' functions that were used for a member access.
noteOperatorArrows(Sema & S,ArrayRef<FunctionDecl * > OperatorArrows)5888 static void noteOperatorArrows(Sema &S,
5889 ArrayRef<FunctionDecl *> OperatorArrows) {
5890 unsigned SkipStart = OperatorArrows.size(), SkipCount = 0;
5891 // FIXME: Make this configurable?
5892 unsigned Limit = 9;
5893 if (OperatorArrows.size() > Limit) {
5894 // Produce Limit-1 normal notes and one 'skipping' note.
5895 SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2;
5896 SkipCount = OperatorArrows.size() - (Limit - 1);
5897 }
5898
5899 for (unsigned I = 0; I < OperatorArrows.size(); /**/) {
5900 if (I == SkipStart) {
5901 S.Diag(OperatorArrows[I]->getLocation(),
5902 diag::note_operator_arrows_suppressed)
5903 << SkipCount;
5904 I += SkipCount;
5905 } else {
5906 S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here)
5907 << OperatorArrows[I]->getCallResultType();
5908 ++I;
5909 }
5910 }
5911 }
5912
ActOnStartCXXMemberReference(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,ParsedType & ObjectType,bool & MayBePseudoDestructor)5913 ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base,
5914 SourceLocation OpLoc,
5915 tok::TokenKind OpKind,
5916 ParsedType &ObjectType,
5917 bool &MayBePseudoDestructor) {
5918 // Since this might be a postfix expression, get rid of ParenListExprs.
5919 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
5920 if (Result.isInvalid()) return ExprError();
5921 Base = Result.get();
5922
5923 Result = CheckPlaceholderExpr(Base);
5924 if (Result.isInvalid()) return ExprError();
5925 Base = Result.get();
5926
5927 QualType BaseType = Base->getType();
5928 MayBePseudoDestructor = false;
5929 if (BaseType->isDependentType()) {
5930 // If we have a pointer to a dependent type and are using the -> operator,
5931 // the object type is the type that the pointer points to. We might still
5932 // have enough information about that type to do something useful.
5933 if (OpKind == tok::arrow)
5934 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
5935 BaseType = Ptr->getPointeeType();
5936
5937 ObjectType = ParsedType::make(BaseType);
5938 MayBePseudoDestructor = true;
5939 return Base;
5940 }
5941
5942 // C++ [over.match.oper]p8:
5943 // [...] When operator->returns, the operator-> is applied to the value
5944 // returned, with the original second operand.
5945 if (OpKind == tok::arrow) {
5946 QualType StartingType = BaseType;
5947 bool NoArrowOperatorFound = false;
5948 bool FirstIteration = true;
5949 FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext);
5950 // The set of types we've considered so far.
5951 llvm::SmallPtrSet<CanQualType,8> CTypes;
5952 SmallVector<FunctionDecl*, 8> OperatorArrows;
5953 CTypes.insert(Context.getCanonicalType(BaseType));
5954
5955 while (BaseType->isRecordType()) {
5956 if (OperatorArrows.size() >= getLangOpts().ArrowDepth) {
5957 Diag(OpLoc, diag::err_operator_arrow_depth_exceeded)
5958 << StartingType << getLangOpts().ArrowDepth << Base->getSourceRange();
5959 noteOperatorArrows(*this, OperatorArrows);
5960 Diag(OpLoc, diag::note_operator_arrow_depth)
5961 << getLangOpts().ArrowDepth;
5962 return ExprError();
5963 }
5964
5965 Result = BuildOverloadedArrowExpr(
5966 S, Base, OpLoc,
5967 // When in a template specialization and on the first loop iteration,
5968 // potentially give the default diagnostic (with the fixit in a
5969 // separate note) instead of having the error reported back to here
5970 // and giving a diagnostic with a fixit attached to the error itself.
5971 (FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization())
5972 ? nullptr
5973 : &NoArrowOperatorFound);
5974 if (Result.isInvalid()) {
5975 if (NoArrowOperatorFound) {
5976 if (FirstIteration) {
5977 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
5978 << BaseType << 1 << Base->getSourceRange()
5979 << FixItHint::CreateReplacement(OpLoc, ".");
5980 OpKind = tok::period;
5981 break;
5982 }
5983 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
5984 << BaseType << Base->getSourceRange();
5985 CallExpr *CE = dyn_cast<CallExpr>(Base);
5986 if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) {
5987 Diag(CD->getLocStart(),
5988 diag::note_member_reference_arrow_from_operator_arrow);
5989 }
5990 }
5991 return ExprError();
5992 }
5993 Base = Result.get();
5994 if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base))
5995 OperatorArrows.push_back(OpCall->getDirectCallee());
5996 BaseType = Base->getType();
5997 CanQualType CBaseType = Context.getCanonicalType(BaseType);
5998 if (!CTypes.insert(CBaseType).second) {
5999 Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType;
6000 noteOperatorArrows(*this, OperatorArrows);
6001 return ExprError();
6002 }
6003 FirstIteration = false;
6004 }
6005
6006 if (OpKind == tok::arrow &&
6007 (BaseType->isPointerType() || BaseType->isObjCObjectPointerType()))
6008 BaseType = BaseType->getPointeeType();
6009 }
6010
6011 // Objective-C properties allow "." access on Objective-C pointer types,
6012 // so adjust the base type to the object type itself.
6013 if (BaseType->isObjCObjectPointerType())
6014 BaseType = BaseType->getPointeeType();
6015
6016 // C++ [basic.lookup.classref]p2:
6017 // [...] If the type of the object expression is of pointer to scalar
6018 // type, the unqualified-id is looked up in the context of the complete
6019 // postfix-expression.
6020 //
6021 // This also indicates that we could be parsing a pseudo-destructor-name.
6022 // Note that Objective-C class and object types can be pseudo-destructor
6023 // expressions or normal member (ivar or property) access expressions, and
6024 // it's legal for the type to be incomplete if this is a pseudo-destructor
6025 // call. We'll do more incomplete-type checks later in the lookup process,
6026 // so just skip this check for ObjC types.
6027 if (BaseType->isObjCObjectOrInterfaceType()) {
6028 ObjectType = ParsedType::make(BaseType);
6029 MayBePseudoDestructor = true;
6030 return Base;
6031 } else if (!BaseType->isRecordType()) {
6032 ObjectType = nullptr;
6033 MayBePseudoDestructor = true;
6034 return Base;
6035 }
6036
6037 // The object type must be complete (or dependent), or
6038 // C++11 [expr.prim.general]p3:
6039 // Unlike the object expression in other contexts, *this is not required to
6040 // be of complete type for purposes of class member access (5.2.5) outside
6041 // the member function body.
6042 if (!BaseType->isDependentType() &&
6043 !isThisOutsideMemberFunctionBody(BaseType) &&
6044 RequireCompleteType(OpLoc, BaseType, diag::err_incomplete_member_access))
6045 return ExprError();
6046
6047 // C++ [basic.lookup.classref]p2:
6048 // If the id-expression in a class member access (5.2.5) is an
6049 // unqualified-id, and the type of the object expression is of a class
6050 // type C (or of pointer to a class type C), the unqualified-id is looked
6051 // up in the scope of class C. [...]
6052 ObjectType = ParsedType::make(BaseType);
6053 return Base;
6054 }
6055
CheckArrow(Sema & S,QualType & ObjectType,Expr * & Base,tok::TokenKind & OpKind,SourceLocation OpLoc)6056 static bool CheckArrow(Sema& S, QualType& ObjectType, Expr *&Base,
6057 tok::TokenKind& OpKind, SourceLocation OpLoc) {
6058 if (Base->hasPlaceholderType()) {
6059 ExprResult result = S.CheckPlaceholderExpr(Base);
6060 if (result.isInvalid()) return true;
6061 Base = result.get();
6062 }
6063 ObjectType = Base->getType();
6064
6065 // C++ [expr.pseudo]p2:
6066 // The left-hand side of the dot operator shall be of scalar type. The
6067 // left-hand side of the arrow operator shall be of pointer to scalar type.
6068 // This scalar type is the object type.
6069 // Note that this is rather different from the normal handling for the
6070 // arrow operator.
6071 if (OpKind == tok::arrow) {
6072 if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) {
6073 ObjectType = Ptr->getPointeeType();
6074 } else if (!Base->isTypeDependent()) {
6075 // The user wrote "p->" when they probably meant "p."; fix it.
6076 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
6077 << ObjectType << true
6078 << FixItHint::CreateReplacement(OpLoc, ".");
6079 if (S.isSFINAEContext())
6080 return true;
6081
6082 OpKind = tok::period;
6083 }
6084 }
6085
6086 return false;
6087 }
6088
BuildPseudoDestructorExpr(Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,const CXXScopeSpec & SS,TypeSourceInfo * ScopeTypeInfo,SourceLocation CCLoc,SourceLocation TildeLoc,PseudoDestructorTypeStorage Destructed)6089 ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base,
6090 SourceLocation OpLoc,
6091 tok::TokenKind OpKind,
6092 const CXXScopeSpec &SS,
6093 TypeSourceInfo *ScopeTypeInfo,
6094 SourceLocation CCLoc,
6095 SourceLocation TildeLoc,
6096 PseudoDestructorTypeStorage Destructed) {
6097 TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo();
6098
6099 QualType ObjectType;
6100 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6101 return ExprError();
6102
6103 if (!ObjectType->isDependentType() && !ObjectType->isScalarType() &&
6104 !ObjectType->isVectorType()) {
6105 if (getLangOpts().MSVCCompat && ObjectType->isVoidType())
6106 Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange();
6107 else {
6108 Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar)
6109 << ObjectType << Base->getSourceRange();
6110 return ExprError();
6111 }
6112 }
6113
6114 // C++ [expr.pseudo]p2:
6115 // [...] The cv-unqualified versions of the object type and of the type
6116 // designated by the pseudo-destructor-name shall be the same type.
6117 if (DestructedTypeInfo) {
6118 QualType DestructedType = DestructedTypeInfo->getType();
6119 SourceLocation DestructedTypeStart
6120 = DestructedTypeInfo->getTypeLoc().getLocalSourceRange().getBegin();
6121 if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) {
6122 if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) {
6123 Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch)
6124 << ObjectType << DestructedType << Base->getSourceRange()
6125 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6126
6127 // Recover by setting the destructed type to the object type.
6128 DestructedType = ObjectType;
6129 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6130 DestructedTypeStart);
6131 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6132 } else if (DestructedType.getObjCLifetime() !=
6133 ObjectType.getObjCLifetime()) {
6134
6135 if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) {
6136 // Okay: just pretend that the user provided the correctly-qualified
6137 // type.
6138 } else {
6139 Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals)
6140 << ObjectType << DestructedType << Base->getSourceRange()
6141 << DestructedTypeInfo->getTypeLoc().getLocalSourceRange();
6142 }
6143
6144 // Recover by setting the destructed type to the object type.
6145 DestructedType = ObjectType;
6146 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType,
6147 DestructedTypeStart);
6148 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6149 }
6150 }
6151 }
6152
6153 // C++ [expr.pseudo]p2:
6154 // [...] Furthermore, the two type-names in a pseudo-destructor-name of the
6155 // form
6156 //
6157 // ::[opt] nested-name-specifier[opt] type-name :: ~ type-name
6158 //
6159 // shall designate the same scalar type.
6160 if (ScopeTypeInfo) {
6161 QualType ScopeType = ScopeTypeInfo->getType();
6162 if (!ScopeType->isDependentType() && !ObjectType->isDependentType() &&
6163 !Context.hasSameUnqualifiedType(ScopeType, ObjectType)) {
6164
6165 Diag(ScopeTypeInfo->getTypeLoc().getLocalSourceRange().getBegin(),
6166 diag::err_pseudo_dtor_type_mismatch)
6167 << ObjectType << ScopeType << Base->getSourceRange()
6168 << ScopeTypeInfo->getTypeLoc().getLocalSourceRange();
6169
6170 ScopeType = QualType();
6171 ScopeTypeInfo = nullptr;
6172 }
6173 }
6174
6175 Expr *Result
6176 = new (Context) CXXPseudoDestructorExpr(Context, Base,
6177 OpKind == tok::arrow, OpLoc,
6178 SS.getWithLocInContext(Context),
6179 ScopeTypeInfo,
6180 CCLoc,
6181 TildeLoc,
6182 Destructed);
6183
6184 return Result;
6185 }
6186
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,UnqualifiedId & FirstTypeName,SourceLocation CCLoc,SourceLocation TildeLoc,UnqualifiedId & SecondTypeName)6187 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6188 SourceLocation OpLoc,
6189 tok::TokenKind OpKind,
6190 CXXScopeSpec &SS,
6191 UnqualifiedId &FirstTypeName,
6192 SourceLocation CCLoc,
6193 SourceLocation TildeLoc,
6194 UnqualifiedId &SecondTypeName) {
6195 assert((FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6196 FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6197 "Invalid first type name in pseudo-destructor");
6198 assert((SecondTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6199 SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) &&
6200 "Invalid second type name in pseudo-destructor");
6201
6202 QualType ObjectType;
6203 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6204 return ExprError();
6205
6206 // Compute the object type that we should use for name lookup purposes. Only
6207 // record types and dependent types matter.
6208 ParsedType ObjectTypePtrForLookup;
6209 if (!SS.isSet()) {
6210 if (ObjectType->isRecordType())
6211 ObjectTypePtrForLookup = ParsedType::make(ObjectType);
6212 else if (ObjectType->isDependentType())
6213 ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy);
6214 }
6215
6216 // Convert the name of the type being destructed (following the ~) into a
6217 // type (with source-location information).
6218 QualType DestructedType;
6219 TypeSourceInfo *DestructedTypeInfo = nullptr;
6220 PseudoDestructorTypeStorage Destructed;
6221 if (SecondTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6222 ParsedType T = getTypeName(*SecondTypeName.Identifier,
6223 SecondTypeName.StartLocation,
6224 S, &SS, true, false, ObjectTypePtrForLookup);
6225 if (!T &&
6226 ((SS.isSet() && !computeDeclContext(SS, false)) ||
6227 (!SS.isSet() && ObjectType->isDependentType()))) {
6228 // The name of the type being destroyed is a dependent name, and we
6229 // couldn't find anything useful in scope. Just store the identifier and
6230 // it's location, and we'll perform (qualified) name lookup again at
6231 // template instantiation time.
6232 Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier,
6233 SecondTypeName.StartLocation);
6234 } else if (!T) {
6235 Diag(SecondTypeName.StartLocation,
6236 diag::err_pseudo_dtor_destructor_non_type)
6237 << SecondTypeName.Identifier << ObjectType;
6238 if (isSFINAEContext())
6239 return ExprError();
6240
6241 // Recover by assuming we had the right type all along.
6242 DestructedType = ObjectType;
6243 } else
6244 DestructedType = GetTypeFromParser(T, &DestructedTypeInfo);
6245 } else {
6246 // Resolve the template-id to a type.
6247 TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId;
6248 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6249 TemplateId->NumArgs);
6250 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6251 TemplateId->TemplateKWLoc,
6252 TemplateId->Template,
6253 TemplateId->TemplateNameLoc,
6254 TemplateId->LAngleLoc,
6255 TemplateArgsPtr,
6256 TemplateId->RAngleLoc);
6257 if (T.isInvalid() || !T.get()) {
6258 // Recover by assuming we had the right type all along.
6259 DestructedType = ObjectType;
6260 } else
6261 DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo);
6262 }
6263
6264 // If we've performed some kind of recovery, (re-)build the type source
6265 // information.
6266 if (!DestructedType.isNull()) {
6267 if (!DestructedTypeInfo)
6268 DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType,
6269 SecondTypeName.StartLocation);
6270 Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo);
6271 }
6272
6273 // Convert the name of the scope type (the type prior to '::') into a type.
6274 TypeSourceInfo *ScopeTypeInfo = nullptr;
6275 QualType ScopeType;
6276 if (FirstTypeName.getKind() == UnqualifiedId::IK_TemplateId ||
6277 FirstTypeName.Identifier) {
6278 if (FirstTypeName.getKind() == UnqualifiedId::IK_Identifier) {
6279 ParsedType T = getTypeName(*FirstTypeName.Identifier,
6280 FirstTypeName.StartLocation,
6281 S, &SS, true, false, ObjectTypePtrForLookup);
6282 if (!T) {
6283 Diag(FirstTypeName.StartLocation,
6284 diag::err_pseudo_dtor_destructor_non_type)
6285 << FirstTypeName.Identifier << ObjectType;
6286
6287 if (isSFINAEContext())
6288 return ExprError();
6289
6290 // Just drop this type. It's unnecessary anyway.
6291 ScopeType = QualType();
6292 } else
6293 ScopeType = GetTypeFromParser(T, &ScopeTypeInfo);
6294 } else {
6295 // Resolve the template-id to a type.
6296 TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId;
6297 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6298 TemplateId->NumArgs);
6299 TypeResult T = ActOnTemplateIdType(TemplateId->SS,
6300 TemplateId->TemplateKWLoc,
6301 TemplateId->Template,
6302 TemplateId->TemplateNameLoc,
6303 TemplateId->LAngleLoc,
6304 TemplateArgsPtr,
6305 TemplateId->RAngleLoc);
6306 if (T.isInvalid() || !T.get()) {
6307 // Recover by dropping this type.
6308 ScopeType = QualType();
6309 } else
6310 ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo);
6311 }
6312 }
6313
6314 if (!ScopeType.isNull() && !ScopeTypeInfo)
6315 ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType,
6316 FirstTypeName.StartLocation);
6317
6318
6319 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS,
6320 ScopeTypeInfo, CCLoc, TildeLoc,
6321 Destructed);
6322 }
6323
ActOnPseudoDestructorExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,SourceLocation TildeLoc,const DeclSpec & DS)6324 ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base,
6325 SourceLocation OpLoc,
6326 tok::TokenKind OpKind,
6327 SourceLocation TildeLoc,
6328 const DeclSpec& DS) {
6329 QualType ObjectType;
6330 if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc))
6331 return ExprError();
6332
6333 QualType T = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc(),
6334 false);
6335
6336 TypeLocBuilder TLB;
6337 DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T);
6338 DecltypeTL.setNameLoc(DS.getTypeSpecTypeLoc());
6339 TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T);
6340 PseudoDestructorTypeStorage Destructed(DestructedTypeInfo);
6341
6342 return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(),
6343 nullptr, SourceLocation(), TildeLoc,
6344 Destructed);
6345 }
6346
BuildCXXMemberCallExpr(Expr * E,NamedDecl * FoundDecl,CXXConversionDecl * Method,bool HadMultipleCandidates)6347 ExprResult Sema::BuildCXXMemberCallExpr(Expr *E, NamedDecl *FoundDecl,
6348 CXXConversionDecl *Method,
6349 bool HadMultipleCandidates) {
6350 if (Method->getParent()->isLambda() &&
6351 Method->getConversionType()->isBlockPointerType()) {
6352 // This is a lambda coversion to block pointer; check if the argument
6353 // is a LambdaExpr.
6354 Expr *SubE = E;
6355 CastExpr *CE = dyn_cast<CastExpr>(SubE);
6356 if (CE && CE->getCastKind() == CK_NoOp)
6357 SubE = CE->getSubExpr();
6358 SubE = SubE->IgnoreParens();
6359 if (CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
6360 SubE = BE->getSubExpr();
6361 if (isa<LambdaExpr>(SubE)) {
6362 // For the conversion to block pointer on a lambda expression, we
6363 // construct a special BlockLiteral instead; this doesn't really make
6364 // a difference in ARC, but outside of ARC the resulting block literal
6365 // follows the normal lifetime rules for block literals instead of being
6366 // autoreleased.
6367 DiagnosticErrorTrap Trap(Diags);
6368 PushExpressionEvaluationContext(PotentiallyEvaluated);
6369 ExprResult Exp = BuildBlockForLambdaConversion(E->getExprLoc(),
6370 E->getExprLoc(),
6371 Method, E);
6372 PopExpressionEvaluationContext();
6373
6374 if (Exp.isInvalid())
6375 Diag(E->getExprLoc(), diag::note_lambda_to_block_conv);
6376 return Exp;
6377 }
6378 }
6379
6380 ExprResult Exp = PerformObjectArgumentInitialization(E, /*Qualifier=*/nullptr,
6381 FoundDecl, Method);
6382 if (Exp.isInvalid())
6383 return true;
6384
6385 MemberExpr *ME = new (Context) MemberExpr(
6386 Exp.get(), /*IsArrow=*/false, SourceLocation(), Method, SourceLocation(),
6387 Context.BoundMemberTy, VK_RValue, OK_Ordinary);
6388 if (HadMultipleCandidates)
6389 ME->setHadMultipleCandidates(true);
6390 MarkMemberReferenced(ME);
6391
6392 QualType ResultType = Method->getReturnType();
6393 ExprValueKind VK = Expr::getValueKindForType(ResultType);
6394 ResultType = ResultType.getNonLValueExprType(Context);
6395
6396 CXXMemberCallExpr *CE =
6397 new (Context) CXXMemberCallExpr(Context, ME, None, ResultType, VK,
6398 Exp.get()->getLocEnd());
6399 return CE;
6400 }
6401
BuildCXXNoexceptExpr(SourceLocation KeyLoc,Expr * Operand,SourceLocation RParen)6402 ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand,
6403 SourceLocation RParen) {
6404 // If the operand is an unresolved lookup expression, the expression is ill-
6405 // formed per [over.over]p1, because overloaded function names cannot be used
6406 // without arguments except in explicit contexts.
6407 ExprResult R = CheckPlaceholderExpr(Operand);
6408 if (R.isInvalid())
6409 return R;
6410
6411 // The operand may have been modified when checking the placeholder type.
6412 Operand = R.get();
6413
6414 if (ActiveTemplateInstantiations.empty() &&
6415 Operand->HasSideEffects(Context, false)) {
6416 // The expression operand for noexcept is in an unevaluated expression
6417 // context, so side effects could result in unintended consequences.
6418 Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6419 }
6420
6421 CanThrowResult CanThrow = canThrow(Operand);
6422 return new (Context)
6423 CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen);
6424 }
6425
ActOnNoexceptExpr(SourceLocation KeyLoc,SourceLocation,Expr * Operand,SourceLocation RParen)6426 ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation,
6427 Expr *Operand, SourceLocation RParen) {
6428 return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen);
6429 }
6430
IsSpecialDiscardedValue(Expr * E)6431 static bool IsSpecialDiscardedValue(Expr *E) {
6432 // In C++11, discarded-value expressions of a certain form are special,
6433 // according to [expr]p10:
6434 // The lvalue-to-rvalue conversion (4.1) is applied only if the
6435 // expression is an lvalue of volatile-qualified type and it has
6436 // one of the following forms:
6437 E = E->IgnoreParens();
6438
6439 // - id-expression (5.1.1),
6440 if (isa<DeclRefExpr>(E))
6441 return true;
6442
6443 // - subscripting (5.2.1),
6444 if (isa<ArraySubscriptExpr>(E))
6445 return true;
6446
6447 // - class member access (5.2.5),
6448 if (isa<MemberExpr>(E))
6449 return true;
6450
6451 // - indirection (5.3.1),
6452 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E))
6453 if (UO->getOpcode() == UO_Deref)
6454 return true;
6455
6456 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
6457 // - pointer-to-member operation (5.5),
6458 if (BO->isPtrMemOp())
6459 return true;
6460
6461 // - comma expression (5.18) where the right operand is one of the above.
6462 if (BO->getOpcode() == BO_Comma)
6463 return IsSpecialDiscardedValue(BO->getRHS());
6464 }
6465
6466 // - conditional expression (5.16) where both the second and the third
6467 // operands are one of the above, or
6468 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
6469 return IsSpecialDiscardedValue(CO->getTrueExpr()) &&
6470 IsSpecialDiscardedValue(CO->getFalseExpr());
6471 // The related edge case of "*x ?: *x".
6472 if (BinaryConditionalOperator *BCO =
6473 dyn_cast<BinaryConditionalOperator>(E)) {
6474 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
6475 return IsSpecialDiscardedValue(OVE->getSourceExpr()) &&
6476 IsSpecialDiscardedValue(BCO->getFalseExpr());
6477 }
6478
6479 // Objective-C++ extensions to the rule.
6480 if (isa<PseudoObjectExpr>(E) || isa<ObjCIvarRefExpr>(E))
6481 return true;
6482
6483 return false;
6484 }
6485
6486 /// Perform the conversions required for an expression used in a
6487 /// context that ignores the result.
IgnoredValueConversions(Expr * E)6488 ExprResult Sema::IgnoredValueConversions(Expr *E) {
6489 if (E->hasPlaceholderType()) {
6490 ExprResult result = CheckPlaceholderExpr(E);
6491 if (result.isInvalid()) return E;
6492 E = result.get();
6493 }
6494
6495 // C99 6.3.2.1:
6496 // [Except in specific positions,] an lvalue that does not have
6497 // array type is converted to the value stored in the
6498 // designated object (and is no longer an lvalue).
6499 if (E->isRValue()) {
6500 // In C, function designators (i.e. expressions of function type)
6501 // are r-values, but we still want to do function-to-pointer decay
6502 // on them. This is both technically correct and convenient for
6503 // some clients.
6504 if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType())
6505 return DefaultFunctionArrayConversion(E);
6506
6507 return E;
6508 }
6509
6510 if (getLangOpts().CPlusPlus) {
6511 // The C++11 standard defines the notion of a discarded-value expression;
6512 // normally, we don't need to do anything to handle it, but if it is a
6513 // volatile lvalue with a special form, we perform an lvalue-to-rvalue
6514 // conversion.
6515 if (getLangOpts().CPlusPlus11 && E->isGLValue() &&
6516 E->getType().isVolatileQualified() &&
6517 IsSpecialDiscardedValue(E)) {
6518 ExprResult Res = DefaultLvalueConversion(E);
6519 if (Res.isInvalid())
6520 return E;
6521 E = Res.get();
6522 }
6523 return E;
6524 }
6525
6526 // GCC seems to also exclude expressions of incomplete enum type.
6527 if (const EnumType *T = E->getType()->getAs<EnumType>()) {
6528 if (!T->getDecl()->isComplete()) {
6529 // FIXME: stupid workaround for a codegen bug!
6530 E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get();
6531 return E;
6532 }
6533 }
6534
6535 ExprResult Res = DefaultFunctionArrayLvalueConversion(E);
6536 if (Res.isInvalid())
6537 return E;
6538 E = Res.get();
6539
6540 if (!E->getType()->isVoidType())
6541 RequireCompleteType(E->getExprLoc(), E->getType(),
6542 diag::err_incomplete_type);
6543 return E;
6544 }
6545
6546 // If we can unambiguously determine whether Var can never be used
6547 // in a constant expression, return true.
6548 // - if the variable and its initializer are non-dependent, then
6549 // we can unambiguously check if the variable is a constant expression.
6550 // - if the initializer is not value dependent - we can determine whether
6551 // it can be used to initialize a constant expression. If Init can not
6552 // be used to initialize a constant expression we conclude that Var can
6553 // never be a constant expression.
6554 // - FXIME: if the initializer is dependent, we can still do some analysis and
6555 // identify certain cases unambiguously as non-const by using a Visitor:
6556 // - such as those that involve odr-use of a ParmVarDecl, involve a new
6557 // delete, lambda-expr, dynamic-cast, reinterpret-cast etc...
VariableCanNeverBeAConstantExpression(VarDecl * Var,ASTContext & Context)6558 static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var,
6559 ASTContext &Context) {
6560 if (isa<ParmVarDecl>(Var)) return true;
6561 const VarDecl *DefVD = nullptr;
6562
6563 // If there is no initializer - this can not be a constant expression.
6564 if (!Var->getAnyInitializer(DefVD)) return true;
6565 assert(DefVD);
6566 if (DefVD->isWeak()) return false;
6567 EvaluatedStmt *Eval = DefVD->ensureEvaluatedStmt();
6568
6569 Expr *Init = cast<Expr>(Eval->Value);
6570
6571 if (Var->getType()->isDependentType() || Init->isValueDependent()) {
6572 // FIXME: Teach the constant evaluator to deal with the non-dependent parts
6573 // of value-dependent expressions, and use it here to determine whether the
6574 // initializer is a potential constant expression.
6575 return false;
6576 }
6577
6578 return !IsVariableAConstantExpression(Var, Context);
6579 }
6580
6581 /// \brief Check if the current lambda has any potential captures
6582 /// that must be captured by any of its enclosing lambdas that are ready to
6583 /// capture. If there is a lambda that can capture a nested
6584 /// potential-capture, go ahead and do so. Also, check to see if any
6585 /// variables are uncaptureable or do not involve an odr-use so do not
6586 /// need to be captured.
6587
CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(Expr * const FE,LambdaScopeInfo * const CurrentLSI,Sema & S)6588 static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(
6589 Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) {
6590
6591 assert(!S.isUnevaluatedContext());
6592 assert(S.CurContext->isDependentContext());
6593 assert(CurrentLSI->CallOperator == S.CurContext &&
6594 "The current call operator must be synchronized with Sema's CurContext");
6595
6596 const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent();
6597
6598 ArrayRef<const FunctionScopeInfo *> FunctionScopesArrayRef(
6599 S.FunctionScopes.data(), S.FunctionScopes.size());
6600
6601 // All the potentially captureable variables in the current nested
6602 // lambda (within a generic outer lambda), must be captured by an
6603 // outer lambda that is enclosed within a non-dependent context.
6604 const unsigned NumPotentialCaptures =
6605 CurrentLSI->getNumPotentialVariableCaptures();
6606 for (unsigned I = 0; I != NumPotentialCaptures; ++I) {
6607 Expr *VarExpr = nullptr;
6608 VarDecl *Var = nullptr;
6609 CurrentLSI->getPotentialVariableCapture(I, Var, VarExpr);
6610 // If the variable is clearly identified as non-odr-used and the full
6611 // expression is not instantiation dependent, only then do we not
6612 // need to check enclosing lambda's for speculative captures.
6613 // For e.g.:
6614 // Even though 'x' is not odr-used, it should be captured.
6615 // int test() {
6616 // const int x = 10;
6617 // auto L = [=](auto a) {
6618 // (void) +x + a;
6619 // };
6620 // }
6621 if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) &&
6622 !IsFullExprInstantiationDependent)
6623 continue;
6624
6625 // If we have a capture-capable lambda for the variable, go ahead and
6626 // capture the variable in that lambda (and all its enclosing lambdas).
6627 if (const Optional<unsigned> Index =
6628 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6629 FunctionScopesArrayRef, Var, S)) {
6630 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6631 MarkVarDeclODRUsed(Var, VarExpr->getExprLoc(), S,
6632 &FunctionScopeIndexOfCapturableLambda);
6633 }
6634 const bool IsVarNeverAConstantExpression =
6635 VariableCanNeverBeAConstantExpression(Var, S.Context);
6636 if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) {
6637 // This full expression is not instantiation dependent or the variable
6638 // can not be used in a constant expression - which means
6639 // this variable must be odr-used here, so diagnose a
6640 // capture violation early, if the variable is un-captureable.
6641 // This is purely for diagnosing errors early. Otherwise, this
6642 // error would get diagnosed when the lambda becomes capture ready.
6643 QualType CaptureType, DeclRefType;
6644 SourceLocation ExprLoc = VarExpr->getExprLoc();
6645 if (S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6646 /*EllipsisLoc*/ SourceLocation(),
6647 /*BuildAndDiagnose*/false, CaptureType,
6648 DeclRefType, nullptr)) {
6649 // We will never be able to capture this variable, and we need
6650 // to be able to in any and all instantiations, so diagnose it.
6651 S.tryCaptureVariable(Var, ExprLoc, S.TryCapture_Implicit,
6652 /*EllipsisLoc*/ SourceLocation(),
6653 /*BuildAndDiagnose*/true, CaptureType,
6654 DeclRefType, nullptr);
6655 }
6656 }
6657 }
6658
6659 // Check if 'this' needs to be captured.
6660 if (CurrentLSI->hasPotentialThisCapture()) {
6661 // If we have a capture-capable lambda for 'this', go ahead and capture
6662 // 'this' in that lambda (and all its enclosing lambdas).
6663 if (const Optional<unsigned> Index =
6664 getStackIndexOfNearestEnclosingCaptureCapableLambda(
6665 FunctionScopesArrayRef, /*0 is 'this'*/ nullptr, S)) {
6666 const unsigned FunctionScopeIndexOfCapturableLambda = Index.getValue();
6667 S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation,
6668 /*Explicit*/ false, /*BuildAndDiagnose*/ true,
6669 &FunctionScopeIndexOfCapturableLambda);
6670 }
6671 }
6672
6673 // Reset all the potential captures at the end of each full-expression.
6674 CurrentLSI->clearPotentialCaptures();
6675 }
6676
attemptRecovery(Sema & SemaRef,const TypoCorrectionConsumer & Consumer,const TypoCorrection & TC)6677 static ExprResult attemptRecovery(Sema &SemaRef,
6678 const TypoCorrectionConsumer &Consumer,
6679 const TypoCorrection &TC) {
6680 LookupResult R(SemaRef, Consumer.getLookupResult().getLookupNameInfo(),
6681 Consumer.getLookupResult().getLookupKind());
6682 const CXXScopeSpec *SS = Consumer.getSS();
6683 CXXScopeSpec NewSS;
6684
6685 // Use an approprate CXXScopeSpec for building the expr.
6686 if (auto *NNS = TC.getCorrectionSpecifier())
6687 NewSS.MakeTrivial(SemaRef.Context, NNS, TC.getCorrectionRange());
6688 else if (SS && !TC.WillReplaceSpecifier())
6689 NewSS = *SS;
6690
6691 if (auto *ND = TC.getFoundDecl()) {
6692 R.setLookupName(ND->getDeclName());
6693 R.addDecl(ND);
6694 if (ND->isCXXClassMember()) {
6695 // Figure out the correct naming class to add to the LookupResult.
6696 CXXRecordDecl *Record = nullptr;
6697 if (auto *NNS = TC.getCorrectionSpecifier())
6698 Record = NNS->getAsType()->getAsCXXRecordDecl();
6699 if (!Record)
6700 Record =
6701 dyn_cast<CXXRecordDecl>(ND->getDeclContext()->getRedeclContext());
6702 if (Record)
6703 R.setNamingClass(Record);
6704
6705 // Detect and handle the case where the decl might be an implicit
6706 // member.
6707 bool MightBeImplicitMember;
6708 if (!Consumer.isAddressOfOperand())
6709 MightBeImplicitMember = true;
6710 else if (!NewSS.isEmpty())
6711 MightBeImplicitMember = false;
6712 else if (R.isOverloadedResult())
6713 MightBeImplicitMember = false;
6714 else if (R.isUnresolvableResult())
6715 MightBeImplicitMember = true;
6716 else
6717 MightBeImplicitMember = isa<FieldDecl>(ND) ||
6718 isa<IndirectFieldDecl>(ND) ||
6719 isa<MSPropertyDecl>(ND);
6720
6721 if (MightBeImplicitMember)
6722 return SemaRef.BuildPossibleImplicitMemberExpr(
6723 NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
6724 /*TemplateArgs*/ nullptr, /*S*/ nullptr);
6725 } else if (auto *Ivar = dyn_cast<ObjCIvarDecl>(ND)) {
6726 return SemaRef.LookupInObjCMethod(R, Consumer.getScope(),
6727 Ivar->getIdentifier());
6728 }
6729 }
6730
6731 return SemaRef.BuildDeclarationNameExpr(NewSS, R, /*NeedsADL*/ false,
6732 /*AcceptInvalidDecl*/ true);
6733 }
6734
6735 namespace {
6736 class FindTypoExprs : public RecursiveASTVisitor<FindTypoExprs> {
6737 llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs;
6738
6739 public:
FindTypoExprs(llvm::SmallSetVector<TypoExpr *,2> & TypoExprs)6740 explicit FindTypoExprs(llvm::SmallSetVector<TypoExpr *, 2> &TypoExprs)
6741 : TypoExprs(TypoExprs) {}
VisitTypoExpr(TypoExpr * TE)6742 bool VisitTypoExpr(TypoExpr *TE) {
6743 TypoExprs.insert(TE);
6744 return true;
6745 }
6746 };
6747
6748 class TransformTypos : public TreeTransform<TransformTypos> {
6749 typedef TreeTransform<TransformTypos> BaseTransform;
6750
6751 VarDecl *InitDecl; // A decl to avoid as a correction because it is in the
6752 // process of being initialized.
6753 llvm::function_ref<ExprResult(Expr *)> ExprFilter;
6754 llvm::SmallSetVector<TypoExpr *, 2> TypoExprs, AmbiguousTypoExprs;
6755 llvm::SmallDenseMap<TypoExpr *, ExprResult, 2> TransformCache;
6756 llvm::SmallDenseMap<OverloadExpr *, Expr *, 4> OverloadResolution;
6757
6758 /// \brief Emit diagnostics for all of the TypoExprs encountered.
6759 /// If the TypoExprs were successfully corrected, then the diagnostics should
6760 /// suggest the corrections. Otherwise the diagnostics will not suggest
6761 /// anything (having been passed an empty TypoCorrection).
EmitAllDiagnostics()6762 void EmitAllDiagnostics() {
6763 for (auto E : TypoExprs) {
6764 TypoExpr *TE = cast<TypoExpr>(E);
6765 auto &State = SemaRef.getTypoExprState(TE);
6766 if (State.DiagHandler) {
6767 TypoCorrection TC = State.Consumer->getCurrentCorrection();
6768 ExprResult Replacement = TransformCache[TE];
6769
6770 // Extract the NamedDecl from the transformed TypoExpr and add it to the
6771 // TypoCorrection, replacing the existing decls. This ensures the right
6772 // NamedDecl is used in diagnostics e.g. in the case where overload
6773 // resolution was used to select one from several possible decls that
6774 // had been stored in the TypoCorrection.
6775 if (auto *ND = getDeclFromExpr(
6776 Replacement.isInvalid() ? nullptr : Replacement.get()))
6777 TC.setCorrectionDecl(ND);
6778
6779 State.DiagHandler(TC);
6780 }
6781 SemaRef.clearDelayedTypo(TE);
6782 }
6783 }
6784
6785 /// \brief If corrections for the first TypoExpr have been exhausted for a
6786 /// given combination of the other TypoExprs, retry those corrections against
6787 /// the next combination of substitutions for the other TypoExprs by advancing
6788 /// to the next potential correction of the second TypoExpr. For the second
6789 /// and subsequent TypoExprs, if its stream of corrections has been exhausted,
6790 /// the stream is reset and the next TypoExpr's stream is advanced by one (a
6791 /// TypoExpr's correction stream is advanced by removing the TypoExpr from the
6792 /// TransformCache). Returns true if there is still any untried combinations
6793 /// of corrections.
CheckAndAdvanceTypoExprCorrectionStreams()6794 bool CheckAndAdvanceTypoExprCorrectionStreams() {
6795 for (auto TE : TypoExprs) {
6796 auto &State = SemaRef.getTypoExprState(TE);
6797 TransformCache.erase(TE);
6798 if (!State.Consumer->finished())
6799 return true;
6800 State.Consumer->resetCorrectionStream();
6801 }
6802 return false;
6803 }
6804
getDeclFromExpr(Expr * E)6805 NamedDecl *getDeclFromExpr(Expr *E) {
6806 if (auto *OE = dyn_cast_or_null<OverloadExpr>(E))
6807 E = OverloadResolution[OE];
6808
6809 if (!E)
6810 return nullptr;
6811 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
6812 return DRE->getFoundDecl();
6813 if (auto *ME = dyn_cast<MemberExpr>(E))
6814 return ME->getFoundDecl();
6815 // FIXME: Add any other expr types that could be be seen by the delayed typo
6816 // correction TreeTransform for which the corresponding TypoCorrection could
6817 // contain multiple decls.
6818 return nullptr;
6819 }
6820
TryTransform(Expr * E)6821 ExprResult TryTransform(Expr *E) {
6822 Sema::SFINAETrap Trap(SemaRef);
6823 ExprResult Res = TransformExpr(E);
6824 if (Trap.hasErrorOccurred() || Res.isInvalid())
6825 return ExprError();
6826
6827 return ExprFilter(Res.get());
6828 }
6829
6830 public:
TransformTypos(Sema & SemaRef,VarDecl * InitDecl,llvm::function_ref<ExprResult (Expr *)> Filter)6831 TransformTypos(Sema &SemaRef, VarDecl *InitDecl, llvm::function_ref<ExprResult(Expr *)> Filter)
6832 : BaseTransform(SemaRef), InitDecl(InitDecl), ExprFilter(Filter) {}
6833
RebuildCallExpr(Expr * Callee,SourceLocation LParenLoc,MultiExprArg Args,SourceLocation RParenLoc,Expr * ExecConfig=nullptr)6834 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
6835 MultiExprArg Args,
6836 SourceLocation RParenLoc,
6837 Expr *ExecConfig = nullptr) {
6838 auto Result = BaseTransform::RebuildCallExpr(Callee, LParenLoc, Args,
6839 RParenLoc, ExecConfig);
6840 if (auto *OE = dyn_cast<OverloadExpr>(Callee)) {
6841 if (Result.isUsable()) {
6842 Expr *ResultCall = Result.get();
6843 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(ResultCall))
6844 ResultCall = BE->getSubExpr();
6845 if (auto *CE = dyn_cast<CallExpr>(ResultCall))
6846 OverloadResolution[OE] = CE->getCallee();
6847 }
6848 }
6849 return Result;
6850 }
6851
TransformLambdaExpr(LambdaExpr * E)6852 ExprResult TransformLambdaExpr(LambdaExpr *E) { return Owned(E); }
6853
TransformBlockExpr(BlockExpr * E)6854 ExprResult TransformBlockExpr(BlockExpr *E) { return Owned(E); }
6855
TransformObjCPropertyRefExpr(ObjCPropertyRefExpr * E)6856 ExprResult TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
6857 return Owned(E);
6858 }
6859
TransformObjCIvarRefExpr(ObjCIvarRefExpr * E)6860 ExprResult TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
6861 return Owned(E);
6862 }
6863
Transform(Expr * E)6864 ExprResult Transform(Expr *E) {
6865 ExprResult Res;
6866 while (true) {
6867 Res = TryTransform(E);
6868
6869 // Exit if either the transform was valid or if there were no TypoExprs
6870 // to transform that still have any untried correction candidates..
6871 if (!Res.isInvalid() ||
6872 !CheckAndAdvanceTypoExprCorrectionStreams())
6873 break;
6874 }
6875
6876 // Ensure none of the TypoExprs have multiple typo correction candidates
6877 // with the same edit length that pass all the checks and filters.
6878 // TODO: Properly handle various permutations of possible corrections when
6879 // there is more than one potentially ambiguous typo correction.
6880 // Also, disable typo correction while attempting the transform when
6881 // handling potentially ambiguous typo corrections as any new TypoExprs will
6882 // have been introduced by the application of one of the correction
6883 // candidates and add little to no value if corrected.
6884 SemaRef.DisableTypoCorrection = true;
6885 while (!AmbiguousTypoExprs.empty()) {
6886 auto TE = AmbiguousTypoExprs.back();
6887 auto Cached = TransformCache[TE];
6888 auto &State = SemaRef.getTypoExprState(TE);
6889 State.Consumer->saveCurrentPosition();
6890 TransformCache.erase(TE);
6891 if (!TryTransform(E).isInvalid()) {
6892 State.Consumer->resetCorrectionStream();
6893 TransformCache.erase(TE);
6894 Res = ExprError();
6895 break;
6896 }
6897 AmbiguousTypoExprs.remove(TE);
6898 State.Consumer->restoreSavedPosition();
6899 TransformCache[TE] = Cached;
6900 }
6901 SemaRef.DisableTypoCorrection = false;
6902
6903 // Ensure that all of the TypoExprs within the current Expr have been found.
6904 if (!Res.isUsable())
6905 FindTypoExprs(TypoExprs).TraverseStmt(E);
6906
6907 EmitAllDiagnostics();
6908
6909 return Res;
6910 }
6911
TransformTypoExpr(TypoExpr * E)6912 ExprResult TransformTypoExpr(TypoExpr *E) {
6913 // If the TypoExpr hasn't been seen before, record it. Otherwise, return the
6914 // cached transformation result if there is one and the TypoExpr isn't the
6915 // first one that was encountered.
6916 auto &CacheEntry = TransformCache[E];
6917 if (!TypoExprs.insert(E) && !CacheEntry.isUnset()) {
6918 return CacheEntry;
6919 }
6920
6921 auto &State = SemaRef.getTypoExprState(E);
6922 assert(State.Consumer && "Cannot transform a cleared TypoExpr");
6923
6924 // For the first TypoExpr and an uncached TypoExpr, find the next likely
6925 // typo correction and return it.
6926 while (TypoCorrection TC = State.Consumer->getNextCorrection()) {
6927 if (InitDecl && TC.getFoundDecl() == InitDecl)
6928 continue;
6929 ExprResult NE = State.RecoveryHandler ?
6930 State.RecoveryHandler(SemaRef, E, TC) :
6931 attemptRecovery(SemaRef, *State.Consumer, TC);
6932 if (!NE.isInvalid()) {
6933 // Check whether there may be a second viable correction with the same
6934 // edit distance; if so, remember this TypoExpr may have an ambiguous
6935 // correction so it can be more thoroughly vetted later.
6936 TypoCorrection Next;
6937 if ((Next = State.Consumer->peekNextCorrection()) &&
6938 Next.getEditDistance(false) == TC.getEditDistance(false)) {
6939 AmbiguousTypoExprs.insert(E);
6940 } else {
6941 AmbiguousTypoExprs.remove(E);
6942 }
6943 assert(!NE.isUnset() &&
6944 "Typo was transformed into a valid-but-null ExprResult");
6945 return CacheEntry = NE;
6946 }
6947 }
6948 return CacheEntry = ExprError();
6949 }
6950 };
6951 }
6952
6953 ExprResult
CorrectDelayedTyposInExpr(Expr * E,VarDecl * InitDecl,llvm::function_ref<ExprResult (Expr *)> Filter)6954 Sema::CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl,
6955 llvm::function_ref<ExprResult(Expr *)> Filter) {
6956 // If the current evaluation context indicates there are uncorrected typos
6957 // and the current expression isn't guaranteed to not have typos, try to
6958 // resolve any TypoExpr nodes that might be in the expression.
6959 if (E && !ExprEvalContexts.empty() && ExprEvalContexts.back().NumTypos &&
6960 (E->isTypeDependent() || E->isValueDependent() ||
6961 E->isInstantiationDependent())) {
6962 auto TyposInContext = ExprEvalContexts.back().NumTypos;
6963 assert(TyposInContext < ~0U && "Recursive call of CorrectDelayedTyposInExpr");
6964 ExprEvalContexts.back().NumTypos = ~0U;
6965 auto TyposResolved = DelayedTypos.size();
6966 auto Result = TransformTypos(*this, InitDecl, Filter).Transform(E);
6967 ExprEvalContexts.back().NumTypos = TyposInContext;
6968 TyposResolved -= DelayedTypos.size();
6969 if (Result.isInvalid() || Result.get() != E) {
6970 ExprEvalContexts.back().NumTypos -= TyposResolved;
6971 return Result;
6972 }
6973 assert(TyposResolved == 0 && "Corrected typo but got same Expr back?");
6974 }
6975 return E;
6976 }
6977
ActOnFinishFullExpr(Expr * FE,SourceLocation CC,bool DiscardedValue,bool IsConstexpr,bool IsLambdaInitCaptureInitializer)6978 ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC,
6979 bool DiscardedValue,
6980 bool IsConstexpr,
6981 bool IsLambdaInitCaptureInitializer) {
6982 ExprResult FullExpr = FE;
6983
6984 if (!FullExpr.get())
6985 return ExprError();
6986
6987 // If we are an init-expression in a lambdas init-capture, we should not
6988 // diagnose an unexpanded pack now (will be diagnosed once lambda-expr
6989 // containing full-expression is done).
6990 // template<class ... Ts> void test(Ts ... t) {
6991 // test([&a(t)]() { <-- (t) is an init-expr that shouldn't be diagnosed now.
6992 // return a;
6993 // }() ...);
6994 // }
6995 // FIXME: This is a hack. It would be better if we pushed the lambda scope
6996 // when we parse the lambda introducer, and teach capturing (but not
6997 // unexpanded pack detection) to walk over LambdaScopeInfos which don't have a
6998 // corresponding class yet (that is, have LambdaScopeInfo either represent a
6999 // lambda where we've entered the introducer but not the body, or represent a
7000 // lambda where we've entered the body, depending on where the
7001 // parser/instantiation has got to).
7002 if (!IsLambdaInitCaptureInitializer &&
7003 DiagnoseUnexpandedParameterPack(FullExpr.get()))
7004 return ExprError();
7005
7006 // Top-level expressions default to 'id' when we're in a debugger.
7007 if (DiscardedValue && getLangOpts().DebuggerCastResultToId &&
7008 FullExpr.get()->getType() == Context.UnknownAnyTy) {
7009 FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType());
7010 if (FullExpr.isInvalid())
7011 return ExprError();
7012 }
7013
7014 if (DiscardedValue) {
7015 FullExpr = CheckPlaceholderExpr(FullExpr.get());
7016 if (FullExpr.isInvalid())
7017 return ExprError();
7018
7019 FullExpr = IgnoredValueConversions(FullExpr.get());
7020 if (FullExpr.isInvalid())
7021 return ExprError();
7022 }
7023
7024 FullExpr = CorrectDelayedTyposInExpr(FullExpr.get());
7025 if (FullExpr.isInvalid())
7026 return ExprError();
7027
7028 CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr);
7029
7030 // At the end of this full expression (which could be a deeply nested
7031 // lambda), if there is a potential capture within the nested lambda,
7032 // have the outer capture-able lambda try and capture it.
7033 // Consider the following code:
7034 // void f(int, int);
7035 // void f(const int&, double);
7036 // void foo() {
7037 // const int x = 10, y = 20;
7038 // auto L = [=](auto a) {
7039 // auto M = [=](auto b) {
7040 // f(x, b); <-- requires x to be captured by L and M
7041 // f(y, a); <-- requires y to be captured by L, but not all Ms
7042 // };
7043 // };
7044 // }
7045
7046 // FIXME: Also consider what happens for something like this that involves
7047 // the gnu-extension statement-expressions or even lambda-init-captures:
7048 // void f() {
7049 // const int n = 0;
7050 // auto L = [&](auto a) {
7051 // +n + ({ 0; a; });
7052 // };
7053 // }
7054 //
7055 // Here, we see +n, and then the full-expression 0; ends, so we don't
7056 // capture n (and instead remove it from our list of potential captures),
7057 // and then the full-expression +n + ({ 0; }); ends, but it's too late
7058 // for us to see that we need to capture n after all.
7059
7060 LambdaScopeInfo *const CurrentLSI = getCurLambda();
7061 // FIXME: PR 17877 showed that getCurLambda() can return a valid pointer
7062 // even if CurContext is not a lambda call operator. Refer to that Bug Report
7063 // for an example of the code that might cause this asynchrony.
7064 // By ensuring we are in the context of a lambda's call operator
7065 // we can fix the bug (we only need to check whether we need to capture
7066 // if we are within a lambda's body); but per the comments in that
7067 // PR, a proper fix would entail :
7068 // "Alternative suggestion:
7069 // - Add to Sema an integer holding the smallest (outermost) scope
7070 // index that we are *lexically* within, and save/restore/set to
7071 // FunctionScopes.size() in InstantiatingTemplate's
7072 // constructor/destructor.
7073 // - Teach the handful of places that iterate over FunctionScopes to
7074 // stop at the outermost enclosing lexical scope."
7075 const bool IsInLambdaDeclContext = isLambdaCallOperator(CurContext);
7076 if (IsInLambdaDeclContext && CurrentLSI &&
7077 CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid())
7078 CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI,
7079 *this);
7080 return MaybeCreateExprWithCleanups(FullExpr);
7081 }
7082
ActOnFinishFullStmt(Stmt * FullStmt)7083 StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) {
7084 if (!FullStmt) return StmtError();
7085
7086 return MaybeCreateStmtWithCleanups(FullStmt);
7087 }
7088
7089 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,CXXScopeSpec & SS,const DeclarationNameInfo & TargetNameInfo)7090 Sema::CheckMicrosoftIfExistsSymbol(Scope *S,
7091 CXXScopeSpec &SS,
7092 const DeclarationNameInfo &TargetNameInfo) {
7093 DeclarationName TargetName = TargetNameInfo.getName();
7094 if (!TargetName)
7095 return IER_DoesNotExist;
7096
7097 // If the name itself is dependent, then the result is dependent.
7098 if (TargetName.isDependentName())
7099 return IER_Dependent;
7100
7101 // Do the redeclaration lookup in the current scope.
7102 LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName,
7103 Sema::NotForRedeclaration);
7104 LookupParsedName(R, S, &SS);
7105 R.suppressDiagnostics();
7106
7107 switch (R.getResultKind()) {
7108 case LookupResult::Found:
7109 case LookupResult::FoundOverloaded:
7110 case LookupResult::FoundUnresolvedValue:
7111 case LookupResult::Ambiguous:
7112 return IER_Exists;
7113
7114 case LookupResult::NotFound:
7115 return IER_DoesNotExist;
7116
7117 case LookupResult::NotFoundInCurrentInstantiation:
7118 return IER_Dependent;
7119 }
7120
7121 llvm_unreachable("Invalid LookupResult Kind!");
7122 }
7123
7124 Sema::IfExistsResult
CheckMicrosoftIfExistsSymbol(Scope * S,SourceLocation KeywordLoc,bool IsIfExists,CXXScopeSpec & SS,UnqualifiedId & Name)7125 Sema::CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc,
7126 bool IsIfExists, CXXScopeSpec &SS,
7127 UnqualifiedId &Name) {
7128 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
7129
7130 // Check for unexpanded parameter packs.
7131 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
7132 collectUnexpandedParameterPacks(SS, Unexpanded);
7133 collectUnexpandedParameterPacks(TargetNameInfo, Unexpanded);
7134 if (!Unexpanded.empty()) {
7135 DiagnoseUnexpandedParameterPacks(KeywordLoc,
7136 IsIfExists? UPPC_IfExists
7137 : UPPC_IfNotExists,
7138 Unexpanded);
7139 return IER_Error;
7140 }
7141
7142 return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo);
7143 }
7144