| 1 |
//===--- SemaExprCXX.cpp - Semantic Analysis for Expressions --------------===// |
| 2 |
// |
| 3 |
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 |
// See https://llvm.org/LICENSE.txt for license information. |
| 5 |
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
| 6 |
// |
| 7 |
//===----------------------------------------------------------------------===// |
| 8 |
/// |
| 9 |
/// \file |
| 10 |
/// Implements semantic analysis for C++ expressions. |
| 11 |
/// |
| 12 |
//===----------------------------------------------------------------------===// |
| 13 |
|
| 14 |
#include "TreeTransform.h" |
| 15 |
#include "TypeLocBuilder.h" |
| 16 |
#include "clang/AST/ASTContext.h" |
| 17 |
#include "clang/AST/ASTLambda.h" |
| 18 |
#include "clang/AST/CXXInheritance.h" |
| 19 |
#include "clang/AST/CharUnits.h" |
| 20 |
#include "clang/AST/DeclCXX.h" |
| 21 |
#include "clang/AST/DeclObjC.h" |
| 22 |
#include "clang/AST/DynamicRecursiveASTVisitor.h" |
| 23 |
#include "clang/AST/ExprCXX.h" |
| 24 |
#include "clang/AST/ExprConcepts.h" |
| 25 |
#include "clang/AST/ExprObjC.h" |
| 26 |
#include "clang/AST/Type.h" |
| 27 |
#include "clang/AST/TypeLoc.h" |
| 28 |
#include "clang/Basic/AlignedAllocation.h" |
| 29 |
#include "clang/Basic/DiagnosticSema.h" |
| 30 |
#include "clang/Basic/PartialDiagnostic.h" |
| 31 |
#include "clang/Basic/TargetInfo.h" |
| 32 |
#include "clang/Basic/TokenKinds.h" |
| 33 |
#include "clang/Lex/Preprocessor.h" |
| 34 |
#include "clang/Sema/DeclSpec.h" |
| 35 |
#include "clang/Sema/EnterExpressionEvaluationContext.h" |
| 36 |
#include "clang/Sema/Initialization.h" |
| 37 |
#include "clang/Sema/Lookup.h" |
| 38 |
#include "clang/Sema/ParsedTemplate.h" |
| 39 |
#include "clang/Sema/Scope.h" |
| 40 |
#include "clang/Sema/ScopeInfo.h" |
| 41 |
#include "clang/Sema/SemaCUDA.h" |
| 42 |
#include "clang/Sema/SemaHLSL.h" |
| 43 |
#include "clang/Sema/SemaLambda.h" |
| 44 |
#include "clang/Sema/SemaObjC.h" |
| 45 |
#include "clang/Sema/SemaPPC.h" |
| 46 |
#include "clang/Sema/Template.h" |
| 47 |
#include "clang/Sema/TemplateDeduction.h" |
| 48 |
#include "llvm/ADT/APInt.h" |
| 49 |
#include "llvm/ADT/STLExtras.h" |
| 50 |
#include "llvm/ADT/StringExtras.h" |
| 51 |
#include "llvm/Support/ErrorHandling.h" |
| 52 |
#include "llvm/Support/TypeSize.h" |
| 53 |
#include <optional> |
| 54 |
using namespace clang; |
| 55 |
using namespace sema; |
| 56 |
|
| 57 |
ParsedType Sema::getInheritingConstructorName(CXXScopeSpec &SS, |
| 58 |
SourceLocation NameLoc, |
| 59 |
const IdentifierInfo &Name) { |
| 60 |
NestedNameSpecifier NNS = SS.getScopeRep(); |
| 61 |
QualType Type(NNS.getAsType(), 0); |
| 62 |
if ([[maybe_unused]] const auto *DNT = dyn_cast<DependentNameType>(Type)) |
| 63 |
assert(DNT->getIdentifier() == &Name && "not a constructor name"); |
| 64 |
|
| 65 |
// This reference to the type is located entirely at the location of the |
| 66 |
// final identifier in the qualified-id. |
| 67 |
return CreateParsedType(Type, |
| 68 |
Context.getTrivialTypeSourceInfo(Type, NameLoc)); |
| 69 |
} |
| 70 |
|
| 71 |
ParsedType Sema::getConstructorName(const IdentifierInfo &II, |
| 72 |
SourceLocation NameLoc, Scope *S, |
| 73 |
CXXScopeSpec &SS, bool EnteringContext) { |
| 74 |
CXXRecordDecl *CurClass = getCurrentClass(S, &SS); |
| 75 |
assert(CurClass && &II == CurClass->getIdentifier() && |
| 76 |
"not a constructor name"); |
| 77 |
|
| 78 |
// When naming a constructor as a member of a dependent context (eg, in a |
| 79 |
// friend declaration or an inherited constructor declaration), form an |
| 80 |
// unresolved "typename" type. |
| 81 |
if (CurClass->isDependentContext() && !EnteringContext && SS.getScopeRep()) { |
| 82 |
QualType T = Context.getDependentNameType(ElaboratedTypeKeyword::None, |
| 83 |
SS.getScopeRep(), &II); |
| 84 |
return ParsedType::make(T); |
| 85 |
} |
| 86 |
|
| 87 |
if (SS.isNotEmpty() && RequireCompleteDeclContext(SS, CurClass)) |
| 88 |
return ParsedType(); |
| 89 |
|
| 90 |
// Find the injected-class-name declaration. Note that we make no attempt to |
| 91 |
// diagnose cases where the injected-class-name is shadowed: the only |
| 92 |
// declaration that can validly shadow the injected-class-name is a |
| 93 |
// non-static data member, and if the class contains both a non-static data |
| 94 |
// member and a constructor then it is ill-formed (we check that in |
| 95 |
// CheckCompletedCXXClass). |
| 96 |
CXXRecordDecl *InjectedClassName = nullptr; |
| 97 |
for (NamedDecl *ND : CurClass->lookup(&II)) { |
| 98 |
auto *RD = dyn_cast<CXXRecordDecl>(ND); |
| 99 |
if (RD && RD->isInjectedClassName()) { |
| 100 |
InjectedClassName = RD; |
| 101 |
break; |
| 102 |
} |
| 103 |
} |
| 104 |
if (!InjectedClassName) { |
| 105 |
if (!CurClass->isInvalidDecl()) { |
| 106 |
// FIXME: RequireCompleteDeclContext doesn't check dependent contexts |
| 107 |
// properly. Work around it here for now. |
| 108 |
Diag(SS.getLastQualifierNameLoc(), |
| 109 |
diag::err_incomplete_nested_name_spec) << CurClass << SS.getRange(); |
| 110 |
} |
| 111 |
return ParsedType(); |
| 112 |
} |
| 113 |
|
| 114 |
QualType T = Context.getTagType(ElaboratedTypeKeyword::None, SS.getScopeRep(), |
| 115 |
InjectedClassName, /*OwnsTag=*/false); |
| 116 |
return ParsedType::make(T); |
| 117 |
} |
| 118 |
|
| 119 |
ParsedType Sema::getDestructorName(const IdentifierInfo &II, |
| 120 |
SourceLocation NameLoc, Scope *S, |
| 121 |
CXXScopeSpec &SS, ParsedType ObjectTypePtr, |
| 122 |
bool EnteringContext) { |
| 123 |
// Determine where to perform name lookup. |
| 124 |
|
| 125 |
// FIXME: This area of the standard is very messy, and the current |
| 126 |
// wording is rather unclear about which scopes we search for the |
| 127 |
// destructor name; see core issues 399 and 555. Issue 399 in |
| 128 |
// particular shows where the current description of destructor name |
| 129 |
// lookup is completely out of line with existing practice, e.g., |
| 130 |
// this appears to be ill-formed: |
| 131 |
// |
| 132 |
// namespace N { |
| 133 |
// template <typename T> struct S { |
| 134 |
// ~S(); |
| 135 |
// }; |
| 136 |
// } |
| 137 |
// |
| 138 |
// void f(N::S<int>* s) { |
| 139 |
// s->N::S<int>::~S(); |
| 140 |
// } |
| 141 |
// |
| 142 |
// See also PR6358 and PR6359. |
| 143 |
// |
| 144 |
// For now, we accept all the cases in which the name given could plausibly |
| 145 |
// be interpreted as a correct destructor name, issuing off-by-default |
| 146 |
// extension diagnostics on the cases that don't strictly conform to the |
| 147 |
// C++20 rules. This basically means we always consider looking in the |
| 148 |
// nested-name-specifier prefix, the complete nested-name-specifier, and |
| 149 |
// the scope, and accept if we find the expected type in any of the three |
| 150 |
// places. |
| 151 |
|
| 152 |
if (SS.isInvalid()) |
| 153 |
return nullptr; |
| 154 |
|
| 155 |
// Whether we've failed with a diagnostic already. |
| 156 |
bool Failed = false; |
| 157 |
|
| 158 |
llvm::SmallVector<NamedDecl*, 8> FoundDecls; |
| 159 |
llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 8> FoundDeclSet; |
| 160 |
|
| 161 |
// If we have an object type, it's because we are in a |
| 162 |
// pseudo-destructor-expression or a member access expression, and |
| 163 |
// we know what type we're looking for. |
| 164 |
QualType SearchType = |
| 165 |
ObjectTypePtr ? GetTypeFromParser(ObjectTypePtr) : QualType(); |
| 166 |
|
| 167 |
auto CheckLookupResult = [&](LookupResult &Found) -> ParsedType { |
| 168 |
auto IsAcceptableResult = [&](NamedDecl *D) -> bool { |
| 169 |
auto *Type = dyn_cast<TypeDecl>(D->getUnderlyingDecl()); |
| 170 |
if (!Type) |
| 171 |
return false; |
| 172 |
|
| 173 |
if (SearchType.isNull() || SearchType->isDependentType()) |
| 174 |
return true; |
| 175 |
|
| 176 |
CanQualType T = Context.getCanonicalTypeDeclType(Type); |
| 177 |
return Context.hasSameUnqualifiedType(T, SearchType); |
| 178 |
}; |
| 179 |
|
| 180 |
unsigned NumAcceptableResults = 0; |
| 181 |
for (NamedDecl *D : Found) { |
| 182 |
if (IsAcceptableResult(D)) |
| 183 |
++NumAcceptableResults; |
| 184 |
|
| 185 |
// Don't list a class twice in the lookup failure diagnostic if it's |
| 186 |
// found by both its injected-class-name and by the name in the enclosing |
| 187 |
// scope. |
| 188 |
if (auto *RD = dyn_cast<CXXRecordDecl>(D)) |
| 189 |
if (RD->isInjectedClassName()) |
| 190 |
D = cast<NamedDecl>(RD->getParent()); |
| 191 |
|
| 192 |
if (FoundDeclSet.insert(D).second) |
| 193 |
FoundDecls.push_back(D); |
| 194 |
} |
| 195 |
|
| 196 |
// As an extension, attempt to "fix" an ambiguity by erasing all non-type |
| 197 |
// results, and all non-matching results if we have a search type. It's not |
| 198 |
// clear what the right behavior is if destructor lookup hits an ambiguity, |
| 199 |
// but other compilers do generally accept at least some kinds of |
| 200 |
// ambiguity. |
| 201 |
if (Found.isAmbiguous() && NumAcceptableResults == 1) { |
| 202 |
Diag(NameLoc, diag::ext_dtor_name_ambiguous); |
| 203 |
LookupResult::Filter F = Found.makeFilter(); |
| 204 |
while (F.hasNext()) { |
| 205 |
NamedDecl *D = F.next(); |
| 206 |
if (auto *TD = dyn_cast<TypeDecl>(D->getUnderlyingDecl())) |
| 207 |
Diag(D->getLocation(), diag::note_destructor_type_here) |
| 208 |
<< Context.getTypeDeclType(ElaboratedTypeKeyword::None, |
| 209 |
/*Qualifier=*/std::nullopt, TD); |
| 210 |
else |
| 211 |
Diag(D->getLocation(), diag::note_destructor_nontype_here); |
| 212 |
|
| 213 |
if (!IsAcceptableResult(D)) |
| 214 |
F.erase(); |
| 215 |
} |
| 216 |
F.done(); |
| 217 |
} |
| 218 |
|
| 219 |
if (Found.isAmbiguous()) |
| 220 |
Failed = true; |
| 221 |
|
| 222 |
if (TypeDecl *Type = Found.getAsSingle<TypeDecl>()) { |
| 223 |
if (IsAcceptableResult(Type)) { |
| 224 |
QualType T = Context.getTypeDeclType(ElaboratedTypeKeyword::None, |
| 225 |
/*Qualifier=*/std::nullopt, Type); |
| 226 |
MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false); |
| 227 |
return CreateParsedType(T, |
| 228 |
Context.getTrivialTypeSourceInfo(T, NameLoc)); |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
return nullptr; |
| 233 |
}; |
| 234 |
|
| 235 |
bool IsDependent = false; |
| 236 |
|
| 237 |
auto LookupInObjectType = [&]() -> ParsedType { |
| 238 |
if (Failed || SearchType.isNull()) |
| 239 |
return nullptr; |
| 240 |
|
| 241 |
IsDependent |= SearchType->isDependentType(); |
| 242 |
|
| 243 |
LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
| 244 |
DeclContext *LookupCtx = computeDeclContext(SearchType); |
| 245 |
if (!LookupCtx) |
| 246 |
return nullptr; |
| 247 |
LookupQualifiedName(Found, LookupCtx); |
| 248 |
return CheckLookupResult(Found); |
| 249 |
}; |
| 250 |
|
| 251 |
auto LookupInNestedNameSpec = [&](CXXScopeSpec &LookupSS) -> ParsedType { |
| 252 |
if (Failed) |
| 253 |
return nullptr; |
| 254 |
|
| 255 |
IsDependent |= isDependentScopeSpecifier(LookupSS); |
| 256 |
DeclContext *LookupCtx = computeDeclContext(LookupSS, EnteringContext); |
| 257 |
if (!LookupCtx) |
| 258 |
return nullptr; |
| 259 |
|
| 260 |
LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
| 261 |
if (RequireCompleteDeclContext(LookupSS, LookupCtx)) { |
| 262 |
Failed = true; |
| 263 |
return nullptr; |
| 264 |
} |
| 265 |
LookupQualifiedName(Found, LookupCtx); |
| 266 |
return CheckLookupResult(Found); |
| 267 |
}; |
| 268 |
|
| 269 |
auto LookupInScope = [&]() -> ParsedType { |
| 270 |
if (Failed || !S) |
| 271 |
return nullptr; |
| 272 |
|
| 273 |
LookupResult Found(*this, &II, NameLoc, LookupDestructorName); |
| 274 |
LookupName(Found, S); |
| 275 |
return CheckLookupResult(Found); |
| 276 |
}; |
| 277 |
|
| 278 |
// C++2a [basic.lookup.qual]p6: |
| 279 |
// In a qualified-id of the form |
| 280 |
// |
| 281 |
// nested-name-specifier[opt] type-name :: ~ type-name |
| 282 |
// |
| 283 |
// the second type-name is looked up in the same scope as the first. |
| 284 |
// |
| 285 |
// We interpret this as meaning that if you do a dual-scope lookup for the |
| 286 |
// first name, you also do a dual-scope lookup for the second name, per |
| 287 |
// C++ [basic.lookup.classref]p4: |
| 288 |
// |
| 289 |
// If the id-expression in a class member access is a qualified-id of the |
| 290 |
// form |
| 291 |
// |
| 292 |
// class-name-or-namespace-name :: ... |
| 293 |
// |
| 294 |
// the class-name-or-namespace-name following the . or -> is first looked |
| 295 |
// up in the class of the object expression and the name, if found, is used. |
| 296 |
// Otherwise, it is looked up in the context of the entire |
| 297 |
// postfix-expression. |
| 298 |
// |
| 299 |
// This looks in the same scopes as for an unqualified destructor name: |
| 300 |
// |
| 301 |
// C++ [basic.lookup.classref]p3: |
| 302 |
// If the unqualified-id is ~ type-name, the type-name is looked up |
| 303 |
// in the context of the entire postfix-expression. If the type T |
| 304 |
// of the object expression is of a class type C, the type-name is |
| 305 |
// also looked up in the scope of class C. At least one of the |
| 306 |
// lookups shall find a name that refers to cv T. |
| 307 |
// |
| 308 |
// FIXME: The intent is unclear here. Should type-name::~type-name look in |
| 309 |
// the scope anyway if it finds a non-matching name declared in the class? |
| 310 |
// If both lookups succeed and find a dependent result, which result should |
| 311 |
// we retain? (Same question for p->~type-name().) |
| 312 |
|
| 313 |
auto Prefix = [&]() -> NestedNameSpecifierLoc { |
| 314 |
NestedNameSpecifierLoc NNS = SS.getWithLocInContext(Context); |
| 315 |
if (!NNS) |
| 316 |
return NestedNameSpecifierLoc(); |
| 317 |
if (auto TL = NNS.getAsTypeLoc()) |
| 318 |
return TL.getPrefix(); |
| 319 |
return NNS.getAsNamespaceAndPrefix().Prefix; |
| 320 |
}(); |
| 321 |
|
| 322 |
if (Prefix) { |
| 323 |
// This is |
| 324 |
// |
| 325 |
// nested-name-specifier type-name :: ~ type-name |
| 326 |
// |
| 327 |
// Look for the second type-name in the nested-name-specifier. |
| 328 |
CXXScopeSpec PrefixSS; |
| 329 |
PrefixSS.Adopt(Prefix); |
| 330 |
if (ParsedType T = LookupInNestedNameSpec(PrefixSS)) |
| 331 |
return T; |
| 332 |
} else { |
| 333 |
// This is one of |
| 334 |
// |
| 335 |
// type-name :: ~ type-name |
| 336 |
// ~ type-name |
| 337 |
// |
| 338 |
// Look in the scope and (if any) the object type. |
| 339 |
if (ParsedType T = LookupInScope()) |
| 340 |
return T; |
| 341 |
if (ParsedType T = LookupInObjectType()) |
| 342 |
return T; |
| 343 |
} |
| 344 |
|
| 345 |
if (Failed) |
| 346 |
return nullptr; |
| 347 |
|
| 348 |
if (IsDependent) { |
| 349 |
// We didn't find our type, but that's OK: it's dependent anyway. |
| 350 |
|
| 351 |
// FIXME: What if we have no nested-name-specifier? |
| 352 |
TypeSourceInfo *TSI = nullptr; |
| 353 |
QualType T = |
| 354 |
CheckTypenameType(ElaboratedTypeKeyword::None, SourceLocation(), |
| 355 |
SS.getWithLocInContext(Context), II, NameLoc, &TSI, |
| 356 |
/*DeducedTSTContext=*/true); |
| 357 |
if (T.isNull()) |
| 358 |
return ParsedType(); |
| 359 |
return CreateParsedType(T, TSI); |
| 360 |
} |
| 361 |
|
| 362 |
// The remaining cases are all non-standard extensions imitating the behavior |
| 363 |
// of various other compilers. |
| 364 |
unsigned NumNonExtensionDecls = FoundDecls.size(); |
| 365 |
|
| 366 |
if (SS.isSet()) { |
| 367 |
// For compatibility with older broken C++ rules and existing code, |
| 368 |
// |
| 369 |
// nested-name-specifier :: ~ type-name |
| 370 |
// |
| 371 |
// also looks for type-name within the nested-name-specifier. |
| 372 |
if (ParsedType T = LookupInNestedNameSpec(SS)) { |
| 373 |
Diag(SS.getEndLoc(), diag::ext_dtor_named_in_wrong_scope) |
| 374 |
<< SS.getRange() |
| 375 |
<< FixItHint::CreateInsertion(SS.getEndLoc(), |
| 376 |
("::" + II.getName()).str()); |
| 377 |
return T; |
| 378 |
} |
| 379 |
|
| 380 |
// For compatibility with other compilers and older versions of Clang, |
| 381 |
// |
| 382 |
// nested-name-specifier type-name :: ~ type-name |
| 383 |
// |
| 384 |
// also looks for type-name in the scope. Unfortunately, we can't |
| 385 |
// reasonably apply this fallback for dependent nested-name-specifiers. |
| 386 |
if (Prefix) { |
| 387 |
if (ParsedType T = LookupInScope()) { |
| 388 |
Diag(SS.getEndLoc(), diag::ext_qualified_dtor_named_in_lexical_scope) |
| 389 |
<< FixItHint::CreateRemoval(SS.getRange()); |
| 390 |
Diag(FoundDecls.back()->getLocation(), diag::note_destructor_type_here) |
| 391 |
<< GetTypeFromParser(T); |
| 392 |
return T; |
| 393 |
} |
| 394 |
} |
| 395 |
} |
| 396 |
|
| 397 |
// We didn't find anything matching; tell the user what we did find (if |
| 398 |
// anything). |
| 399 |
|
| 400 |
// Don't tell the user about declarations we shouldn't have found. |
| 401 |
FoundDecls.resize(NumNonExtensionDecls); |
| 402 |
|
| 403 |
// List types before non-types. |
| 404 |
llvm::stable_sort(FoundDecls, [](NamedDecl *A, NamedDecl *B) { |
| 405 |
return isa<TypeDecl>(A->getUnderlyingDecl()) > |
| 406 |
isa<TypeDecl>(B->getUnderlyingDecl()); |
| 407 |
}); |
| 408 |
|
| 409 |
// Suggest a fixit to properly name the destroyed type. |
| 410 |
auto MakeFixItHint = [&]{ |
| 411 |
const CXXRecordDecl *Destroyed = nullptr; |
| 412 |
// FIXME: If we have a scope specifier, suggest its last component? |
| 413 |
if (!SearchType.isNull()) |
| 414 |
Destroyed = SearchType->getAsCXXRecordDecl(); |
| 415 |
else if (S) |
| 416 |
Destroyed = dyn_cast_or_null<CXXRecordDecl>(S->getEntity()); |
| 417 |
if (Destroyed) |
| 418 |
return FixItHint::CreateReplacement(SourceRange(NameLoc), |
| 419 |
Destroyed->getNameAsString()); |
| 420 |
return FixItHint(); |
| 421 |
}; |
| 422 |
|
| 423 |
if (FoundDecls.empty()) { |
| 424 |
// FIXME: Attempt typo-correction? |
| 425 |
Diag(NameLoc, diag::err_undeclared_destructor_name) |
| 426 |
<< &II << MakeFixItHint(); |
| 427 |
} else if (!SearchType.isNull() && FoundDecls.size() == 1) { |
| 428 |
if (auto *TD = dyn_cast<TypeDecl>(FoundDecls[0]->getUnderlyingDecl())) { |
| 429 |
assert(!SearchType.isNull() && |
| 430 |
"should only reject a type result if we have a search type"); |
| 431 |
Diag(NameLoc, diag::err_destructor_expr_type_mismatch) |
| 432 |
<< Context.getTypeDeclType(ElaboratedTypeKeyword::None, |
| 433 |
/*Qualifier=*/std::nullopt, TD) |
| 434 |
<< SearchType << MakeFixItHint(); |
| 435 |
} else { |
| 436 |
Diag(NameLoc, diag::err_destructor_expr_nontype) |
| 437 |
<< &II << MakeFixItHint(); |
| 438 |
} |
| 439 |
} else { |
| 440 |
Diag(NameLoc, SearchType.isNull() ? diag::err_destructor_name_nontype |
| 441 |
: diag::err_destructor_expr_mismatch) |
| 442 |
<< &II << SearchType << MakeFixItHint(); |
| 443 |
} |
| 444 |
|
| 445 |
for (NamedDecl *FoundD : FoundDecls) { |
| 446 |
if (auto *TD = dyn_cast<TypeDecl>(FoundD->getUnderlyingDecl())) |
| 447 |
Diag(FoundD->getLocation(), diag::note_destructor_type_here) |
| 448 |
<< Context.getTypeDeclType(ElaboratedTypeKeyword::None, |
| 449 |
/*Qualifier=*/std::nullopt, TD); |
| 450 |
else |
| 451 |
Diag(FoundD->getLocation(), diag::note_destructor_nontype_here) |
| 452 |
<< FoundD; |
| 453 |
} |
| 454 |
|
| 455 |
return nullptr; |
| 456 |
} |
| 457 |
|
| 458 |
ParsedType Sema::getDestructorTypeForDecltype(const DeclSpec &DS, |
| 459 |
ParsedType ObjectType) { |
| 460 |
if (DS.getTypeSpecType() == DeclSpec::TST_error) |
| 461 |
return nullptr; |
| 462 |
|
| 463 |
if (DS.getTypeSpecType() == DeclSpec::TST_decltype_auto) { |
| 464 |
Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
| 465 |
return nullptr; |
| 466 |
} |
| 467 |
|
| 468 |
assert(DS.getTypeSpecType() == DeclSpec::TST_decltype && |
| 469 |
"unexpected type in getDestructorType"); |
| 470 |
QualType T = BuildDecltypeType(DS.getRepAsExpr()); |
| 471 |
|
| 472 |
// If we know the type of the object, check that the correct destructor |
| 473 |
// type was named now; we can give better diagnostics this way. |
| 474 |
QualType SearchType = GetTypeFromParser(ObjectType); |
| 475 |
if (!SearchType.isNull() && !SearchType->isDependentType() && |
| 476 |
!Context.hasSameUnqualifiedType(T, SearchType)) { |
| 477 |
Diag(DS.getTypeSpecTypeLoc(), diag::err_destructor_expr_type_mismatch) |
| 478 |
<< T << SearchType; |
| 479 |
return nullptr; |
| 480 |
} |
| 481 |
|
| 482 |
return ParsedType::make(T); |
| 483 |
} |
| 484 |
|
| 485 |
bool Sema::checkLiteralOperatorId(const CXXScopeSpec &SS, |
| 486 |
const UnqualifiedId &Name, bool IsUDSuffix) { |
| 487 |
assert(Name.getKind() == UnqualifiedIdKind::IK_LiteralOperatorId); |
| 488 |
if (!IsUDSuffix) { |
| 489 |
// [over.literal] p8 |
| 490 |
// |
| 491 |
// double operator""_Bq(long double); // OK: not a reserved identifier |
| 492 |
// double operator"" _Bq(long double); // ill-formed, no diagnostic required |
| 493 |
const IdentifierInfo *II = Name.Identifier; |
| 494 |
ReservedIdentifierStatus Status = II->isReserved(PP.getLangOpts()); |
| 495 |
SourceLocation Loc = Name.getEndLoc(); |
| 496 |
|
| 497 |
auto Hint = FixItHint::CreateReplacement( |
| 498 |
Name.getSourceRange(), |
| 499 |
(StringRef("operator\"\"") + II->getName()).str()); |
| 500 |
|
| 501 |
// Only emit this diagnostic if we start with an underscore, else the |
| 502 |
// diagnostic for C++11 requiring a space between the quotes and the |
| 503 |
// identifier conflicts with this and gets confusing. The diagnostic stating |
| 504 |
// this is a reserved name should force the underscore, which gets this |
| 505 |
// back. |
| 506 |
if (II->isReservedLiteralSuffixId() != |
| 507 |
ReservedLiteralSuffixIdStatus::NotStartsWithUnderscore) |
| 508 |
Diag(Loc, diag::warn_deprecated_literal_operator_id) << II << Hint; |
| 509 |
|
| 510 |
if (isReservedInAllContexts(Status)) |
| 511 |
Diag(Loc, diag::warn_reserved_extern_symbol) |
| 512 |
<< II << static_cast<int>(Status) << Hint; |
| 513 |
} |
| 514 |
|
| 515 |
switch (SS.getScopeRep().getKind()) { |
| 516 |
case NestedNameSpecifier::Kind::Type: |
| 517 |
// Per C++11 [over.literal]p2, literal operators can only be declared at |
| 518 |
// namespace scope. Therefore, this unqualified-id cannot name anything. |
| 519 |
// Reject it early, because we have no AST representation for this in the |
| 520 |
// case where the scope is dependent. |
| 521 |
Diag(Name.getBeginLoc(), diag::err_literal_operator_id_outside_namespace) |
| 522 |
<< SS.getScopeRep(); |
| 523 |
return true; |
| 524 |
|
| 525 |
case NestedNameSpecifier::Kind::Null: |
| 526 |
case NestedNameSpecifier::Kind::Global: |
| 527 |
case NestedNameSpecifier::Kind::MicrosoftSuper: |
| 528 |
case NestedNameSpecifier::Kind::Namespace: |
| 529 |
return false; |
| 530 |
} |
| 531 |
|
| 532 |
llvm_unreachable("unknown nested name specifier kind"); |
| 533 |
} |
| 534 |
|
| 535 |
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
| 536 |
SourceLocation TypeidLoc, |
| 537 |
TypeSourceInfo *Operand, |
| 538 |
SourceLocation RParenLoc) { |
| 539 |
// C++ [expr.typeid]p4: |
| 540 |
// The top-level cv-qualifiers of the lvalue expression or the type-id |
| 541 |
// that is the operand of typeid are always ignored. |
| 542 |
// If the type of the type-id is a class type or a reference to a class |
| 543 |
// type, the class shall be completely-defined. |
| 544 |
Qualifiers Quals; |
| 545 |
QualType T |
| 546 |
= Context.getUnqualifiedArrayType(Operand->getType().getNonReferenceType(), |
| 547 |
Quals); |
| 548 |
if (T->isRecordType() && |
| 549 |
RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) |
| 550 |
return ExprError(); |
| 551 |
|
| 552 |
if (T->isVariablyModifiedType()) |
| 553 |
return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) << T); |
| 554 |
|
| 555 |
if (CheckQualifiedFunctionForTypeId(T, TypeidLoc)) |
| 556 |
return ExprError(); |
| 557 |
|
| 558 |
return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), Operand, |
| 559 |
SourceRange(TypeidLoc, RParenLoc)); |
| 560 |
} |
| 561 |
|
| 562 |
ExprResult Sema::BuildCXXTypeId(QualType TypeInfoType, |
| 563 |
SourceLocation TypeidLoc, |
| 564 |
Expr *E, |
| 565 |
SourceLocation RParenLoc) { |
| 566 |
bool WasEvaluated = false; |
| 567 |
if (E && !E->isTypeDependent()) { |
| 568 |
if (E->hasPlaceholderType()) { |
| 569 |
ExprResult result = CheckPlaceholderExpr(E); |
| 570 |
if (result.isInvalid()) return ExprError(); |
| 571 |
E = result.get(); |
| 572 |
} |
| 573 |
|
| 574 |
QualType T = E->getType(); |
| 575 |
if (auto *RecordD = T->getAsCXXRecordDecl()) { |
| 576 |
// C++ [expr.typeid]p3: |
| 577 |
// [...] If the type of the expression is a class type, the class |
| 578 |
// shall be completely-defined. |
| 579 |
if (RequireCompleteType(TypeidLoc, T, diag::err_incomplete_typeid)) |
| 580 |
return ExprError(); |
| 581 |
|
| 582 |
// C++ [expr.typeid]p3: |
| 583 |
// When typeid is applied to an expression other than an glvalue of a |
| 584 |
// polymorphic class type [...] [the] expression is an unevaluated |
| 585 |
// operand. [...] |
| 586 |
if (RecordD->isPolymorphic() && E->isGLValue()) { |
| 587 |
if (isUnevaluatedContext()) { |
| 588 |
// The operand was processed in unevaluated context, switch the |
| 589 |
// context and recheck the subexpression. |
| 590 |
ExprResult Result = TransformToPotentiallyEvaluated(E); |
| 591 |
if (Result.isInvalid()) |
| 592 |
return ExprError(); |
| 593 |
E = Result.get(); |
| 594 |
} |
| 595 |
|
| 596 |
// We require a vtable to query the type at run time. |
| 597 |
MarkVTableUsed(TypeidLoc, RecordD); |
| 598 |
WasEvaluated = true; |
| 599 |
} |
| 600 |
} |
| 601 |
|
| 602 |
ExprResult Result = CheckUnevaluatedOperand(E); |
| 603 |
if (Result.isInvalid()) |
| 604 |
return ExprError(); |
| 605 |
E = Result.get(); |
| 606 |
|
| 607 |
// C++ [expr.typeid]p4: |
| 608 |
// [...] If the type of the type-id is a reference to a possibly |
| 609 |
// cv-qualified type, the result of the typeid expression refers to a |
| 610 |
// std::type_info object representing the cv-unqualified referenced |
| 611 |
// type. |
| 612 |
Qualifiers Quals; |
| 613 |
QualType UnqualT = Context.getUnqualifiedArrayType(T, Quals); |
| 614 |
if (!Context.hasSameType(T, UnqualT)) { |
| 615 |
T = UnqualT; |
| 616 |
E = ImpCastExprToType(E, UnqualT, CK_NoOp, E->getValueKind()).get(); |
| 617 |
} |
| 618 |
} |
| 619 |
|
| 620 |
if (E->getType()->isVariablyModifiedType()) |
| 621 |
return ExprError(Diag(TypeidLoc, diag::err_variably_modified_typeid) |
| 622 |
<< E->getType()); |
| 623 |
else if (!inTemplateInstantiation() && |
| 624 |
E->HasSideEffects(Context, WasEvaluated)) { |
| 625 |
// The expression operand for typeid is in an unevaluated expression |
| 626 |
// context, so side effects could result in unintended consequences. |
| 627 |
Diag(E->getExprLoc(), WasEvaluated |
| 628 |
? diag::warn_side_effects_typeid |
| 629 |
: diag::warn_side_effects_unevaluated_context); |
| 630 |
} |
| 631 |
|
| 632 |
return new (Context) CXXTypeidExpr(TypeInfoType.withConst(), E, |
| 633 |
SourceRange(TypeidLoc, RParenLoc)); |
| 634 |
} |
| 635 |
|
| 636 |
/// ActOnCXXTypeidOfType - Parse typeid( type-id ) or typeid (expression); |
| 637 |
ExprResult |
| 638 |
Sema::ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, |
| 639 |
bool isType, void *TyOrExpr, SourceLocation RParenLoc) { |
| 640 |
// typeid is not supported in OpenCL. |
| 641 |
if (getLangOpts().OpenCLCPlusPlus) { |
| 642 |
return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported) |
| 643 |
<< "typeid"); |
| 644 |
} |
| 645 |
|
| 646 |
// Find the std::type_info type. |
| 647 |
if (!getStdNamespace()) { |
| 648 |
return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid) |
| 649 |
<< (getLangOpts().CPlusPlus20 ? 1 : 0)); |
| 650 |
} |
| 651 |
|
| 652 |
if (!CXXTypeInfoDecl) { |
| 653 |
IdentifierInfo *TypeInfoII = &PP.getIdentifierTable().get("type_info"); |
| 654 |
LookupResult R(*this, TypeInfoII, SourceLocation(), LookupTagName); |
| 655 |
LookupQualifiedName(R, getStdNamespace()); |
| 656 |
CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); |
| 657 |
// Microsoft's typeinfo doesn't have type_info in std but in the global |
| 658 |
// namespace if _HAS_EXCEPTIONS is defined to 0. See PR13153. |
| 659 |
if (!CXXTypeInfoDecl && LangOpts.MSVCCompat) { |
| 660 |
LookupQualifiedName(R, Context.getTranslationUnitDecl()); |
| 661 |
CXXTypeInfoDecl = R.getAsSingle<RecordDecl>(); |
| 662 |
} |
| 663 |
if (!CXXTypeInfoDecl) |
| 664 |
return ExprError(Diag(OpLoc, diag::err_need_header_before_typeid) |
| 665 |
<< (getLangOpts().CPlusPlus20 ? 1 : 0)); |
| 666 |
} |
| 667 |
|
| 668 |
if (!getLangOpts().RTTI) { |
| 669 |
return ExprError(Diag(OpLoc, diag::err_no_typeid_with_fno_rtti)); |
| 670 |
} |
| 671 |
|
| 672 |
CanQualType TypeInfoType = Context.getCanonicalTagType(CXXTypeInfoDecl); |
| 673 |
|
| 674 |
if (isType) { |
| 675 |
// The operand is a type; handle it as such. |
| 676 |
TypeSourceInfo *TInfo = nullptr; |
| 677 |
QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), |
| 678 |
&TInfo); |
| 679 |
if (T.isNull()) |
| 680 |
return ExprError(); |
| 681 |
|
| 682 |
if (!TInfo) |
| 683 |
TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); |
| 684 |
|
| 685 |
return BuildCXXTypeId(TypeInfoType, OpLoc, TInfo, RParenLoc); |
| 686 |
} |
| 687 |
|
| 688 |
// The operand is an expression. |
| 689 |
ExprResult Result = |
| 690 |
BuildCXXTypeId(TypeInfoType, OpLoc, (Expr *)TyOrExpr, RParenLoc); |
| 691 |
|
| 692 |
if (!getLangOpts().RTTIData && !Result.isInvalid()) |
| 693 |
if (auto *CTE = dyn_cast<CXXTypeidExpr>(Result.get())) |
| 694 |
if (CTE->isPotentiallyEvaluated() && !CTE->isMostDerived(Context)) |
| 695 |
Diag(OpLoc, diag::warn_no_typeid_with_rtti_disabled) |
| 696 |
<< (getDiagnostics().getDiagnosticOptions().getFormat() == |
| 697 |
DiagnosticOptions::MSVC); |
| 698 |
return Result; |
| 699 |
} |
| 700 |
|
| 701 |
/// Grabs __declspec(uuid()) off a type, or returns 0 if we cannot resolve to |
| 702 |
/// a single GUID. |
| 703 |
static void |
| 704 |
getUuidAttrOfType(Sema &SemaRef, QualType QT, |
| 705 |
llvm::SmallSetVector<const UuidAttr *, 1> &UuidAttrs) { |
| 706 |
// Optionally remove one level of pointer, reference or array indirection. |
| 707 |
const Type *Ty = QT.getTypePtr(); |
| 708 |
if (QT->isPointerOrReferenceType()) |
| 709 |
Ty = QT->getPointeeType().getTypePtr(); |
| 710 |
else if (QT->isArrayType()) |
| 711 |
Ty = Ty->getBaseElementTypeUnsafe(); |
| 712 |
|
| 713 |
const auto *TD = Ty->getAsTagDecl(); |
| 714 |
if (!TD) |
| 715 |
return; |
| 716 |
|
| 717 |
if (const auto *Uuid = TD->getMostRecentDecl()->getAttr<UuidAttr>()) { |
| 718 |
UuidAttrs.insert(Uuid); |
| 719 |
return; |
| 720 |
} |
| 721 |
|
| 722 |
// __uuidof can grab UUIDs from template arguments. |
| 723 |
if (const auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(TD)) { |
| 724 |
const TemplateArgumentList &TAL = CTSD->getTemplateArgs(); |
| 725 |
for (const TemplateArgument &TA : TAL.asArray()) { |
| 726 |
const UuidAttr *UuidForTA = nullptr; |
| 727 |
if (TA.getKind() == TemplateArgument::Type) |
| 728 |
getUuidAttrOfType(SemaRef, TA.getAsType(), UuidAttrs); |
| 729 |
else if (TA.getKind() == TemplateArgument::Declaration) |
| 730 |
getUuidAttrOfType(SemaRef, TA.getAsDecl()->getType(), UuidAttrs); |
| 731 |
|
| 732 |
if (UuidForTA) |
| 733 |
UuidAttrs.insert(UuidForTA); |
| 734 |
} |
| 735 |
} |
| 736 |
} |
| 737 |
|
| 738 |
ExprResult Sema::BuildCXXUuidof(QualType Type, |
| 739 |
SourceLocation TypeidLoc, |
| 740 |
TypeSourceInfo *Operand, |
| 741 |
SourceLocation RParenLoc) { |
| 742 |
MSGuidDecl *Guid = nullptr; |
| 743 |
if (!Operand->getType()->isDependentType()) { |
| 744 |
llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; |
| 745 |
getUuidAttrOfType(*this, Operand->getType(), UuidAttrs); |
| 746 |
if (UuidAttrs.empty()) |
| 747 |
return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); |
| 748 |
if (UuidAttrs.size() > 1) |
| 749 |
return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); |
| 750 |
Guid = UuidAttrs.back()->getGuidDecl(); |
| 751 |
} |
| 752 |
|
| 753 |
return new (Context) |
| 754 |
CXXUuidofExpr(Type, Operand, Guid, SourceRange(TypeidLoc, RParenLoc)); |
| 755 |
} |
| 756 |
|
| 757 |
ExprResult Sema::BuildCXXUuidof(QualType Type, SourceLocation TypeidLoc, |
| 758 |
Expr *E, SourceLocation RParenLoc) { |
| 759 |
MSGuidDecl *Guid = nullptr; |
| 760 |
if (!E->getType()->isDependentType()) { |
| 761 |
if (E->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { |
| 762 |
// A null pointer results in {00000000-0000-0000-0000-000000000000}. |
| 763 |
Guid = Context.getMSGuidDecl(MSGuidDecl::Parts{}); |
| 764 |
} else { |
| 765 |
llvm::SmallSetVector<const UuidAttr *, 1> UuidAttrs; |
| 766 |
getUuidAttrOfType(*this, E->getType(), UuidAttrs); |
| 767 |
if (UuidAttrs.empty()) |
| 768 |
return ExprError(Diag(TypeidLoc, diag::err_uuidof_without_guid)); |
| 769 |
if (UuidAttrs.size() > 1) |
| 770 |
return ExprError(Diag(TypeidLoc, diag::err_uuidof_with_multiple_guids)); |
| 771 |
Guid = UuidAttrs.back()->getGuidDecl(); |
| 772 |
} |
| 773 |
} |
| 774 |
|
| 775 |
return new (Context) |
| 776 |
CXXUuidofExpr(Type, E, Guid, SourceRange(TypeidLoc, RParenLoc)); |
| 777 |
} |
| 778 |
|
| 779 |
/// ActOnCXXUuidof - Parse __uuidof( type-id ) or __uuidof (expression); |
| 780 |
ExprResult |
| 781 |
Sema::ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, |
| 782 |
bool isType, void *TyOrExpr, SourceLocation RParenLoc) { |
| 783 |
QualType GuidType = Context.getMSGuidType(); |
| 784 |
GuidType.addConst(); |
| 785 |
|
| 786 |
if (isType) { |
| 787 |
// The operand is a type; handle it as such. |
| 788 |
TypeSourceInfo *TInfo = nullptr; |
| 789 |
QualType T = GetTypeFromParser(ParsedType::getFromOpaquePtr(TyOrExpr), |
| 790 |
&TInfo); |
| 791 |
if (T.isNull()) |
| 792 |
return ExprError(); |
| 793 |
|
| 794 |
if (!TInfo) |
| 795 |
TInfo = Context.getTrivialTypeSourceInfo(T, OpLoc); |
| 796 |
|
| 797 |
return BuildCXXUuidof(GuidType, OpLoc, TInfo, RParenLoc); |
| 798 |
} |
| 799 |
|
| 800 |
// The operand is an expression. |
| 801 |
return BuildCXXUuidof(GuidType, OpLoc, (Expr*)TyOrExpr, RParenLoc); |
| 802 |
} |
| 803 |
|
| 804 |
ExprResult |
| 805 |
Sema::ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind) { |
| 806 |
assert((Kind == tok::kw_true || Kind == tok::kw_false) && |
| 807 |
"Unknown C++ Boolean value!"); |
| 808 |
return new (Context) |
| 809 |
CXXBoolLiteralExpr(Kind == tok::kw_true, Context.BoolTy, OpLoc); |
| 810 |
} |
| 811 |
|
| 812 |
ExprResult |
| 813 |
Sema::ActOnCXXNullPtrLiteral(SourceLocation Loc) { |
| 814 |
return new (Context) CXXNullPtrLiteralExpr(Context.NullPtrTy, Loc); |
| 815 |
} |
| 816 |
|
| 817 |
ExprResult |
| 818 |
Sema::ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *Ex) { |
| 819 |
bool IsThrownVarInScope = false; |
| 820 |
if (Ex) { |
| 821 |
// C++0x [class.copymove]p31: |
| 822 |
// When certain criteria are met, an implementation is allowed to omit the |
| 823 |
// copy/move construction of a class object [...] |
| 824 |
// |
| 825 |
// - in a throw-expression, when the operand is the name of a |
| 826 |
// non-volatile automatic object (other than a function or catch- |
| 827 |
// clause parameter) whose scope does not extend beyond the end of the |
| 828 |
// innermost enclosing try-block (if there is one), the copy/move |
| 829 |
// operation from the operand to the exception object (15.1) can be |
| 830 |
// omitted by constructing the automatic object directly into the |
| 831 |
// exception object |
| 832 |
if (const auto *DRE = dyn_cast<DeclRefExpr>(Ex->IgnoreParens())) |
| 833 |
if (const auto *Var = dyn_cast<VarDecl>(DRE->getDecl()); |
| 834 |
Var && Var->hasLocalStorage() && |
| 835 |
!Var->getType().isVolatileQualified()) { |
| 836 |
for (; S; S = S->getParent()) { |
| 837 |
if (S->isDeclScope(Var)) { |
| 838 |
IsThrownVarInScope = true; |
| 839 |
break; |
| 840 |
} |
| 841 |
|
| 842 |
// FIXME: Many of the scope checks here seem incorrect. |
| 843 |
if (S->getFlags() & |
| 844 |
(Scope::FnScope | Scope::ClassScope | Scope::BlockScope | |
| 845 |
Scope::ObjCMethodScope | Scope::TryScope)) |
| 846 |
break; |
| 847 |
} |
| 848 |
} |
| 849 |
} |
| 850 |
|
| 851 |
return BuildCXXThrow(OpLoc, Ex, IsThrownVarInScope); |
| 852 |
} |
| 853 |
|
| 854 |
ExprResult Sema::BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, |
| 855 |
bool IsThrownVarInScope) { |
| 856 |
const llvm::Triple &T = Context.getTargetInfo().getTriple(); |
| 857 |
const bool IsOpenMPGPUTarget = |
| 858 |
getLangOpts().OpenMPIsTargetDevice && T.isGPU(); |
| 859 |
|
| 860 |
DiagnoseExceptionUse(OpLoc, /* IsTry= */ false); |
| 861 |
|
| 862 |
// In OpenMP target regions, we replace 'throw' with a trap on GPU targets. |
| 863 |
if (IsOpenMPGPUTarget) |
| 864 |
targetDiag(OpLoc, diag::warn_throw_not_valid_on_target) << T.str(); |
| 865 |
|
| 866 |
// Exceptions aren't allowed in CUDA device code. |
| 867 |
if (getLangOpts().CUDA) |
| 868 |
CUDA().DiagIfDeviceCode(OpLoc, diag::err_cuda_device_exceptions) |
| 869 |
<< "throw" << CUDA().CurrentTarget(); |
| 870 |
|
| 871 |
if (getCurScope() && getCurScope()->isOpenMPSimdDirectiveScope()) |
| 872 |
Diag(OpLoc, diag::err_omp_simd_region_cannot_use_stmt) << "throw"; |
| 873 |
|
| 874 |
// Exceptions that escape a compute construct are ill-formed. |
| 875 |
if (getLangOpts().OpenACC && getCurScope() && |
| 876 |
getCurScope()->isInOpenACCComputeConstructScope(Scope::TryScope)) |
| 877 |
Diag(OpLoc, diag::err_acc_branch_in_out_compute_construct) |
| 878 |
<< /*throw*/ 2 << /*out of*/ 0; |
| 879 |
|
| 880 |
if (Ex && !Ex->isTypeDependent()) { |
| 881 |
// Initialize the exception result. This implicitly weeds out |
| 882 |
// abstract types or types with inaccessible copy constructors. |
| 883 |
|
| 884 |
// C++0x [class.copymove]p31: |
| 885 |
// When certain criteria are met, an implementation is allowed to omit the |
| 886 |
// copy/move construction of a class object [...] |
| 887 |
// |
| 888 |
// - in a throw-expression, when the operand is the name of a |
| 889 |
// non-volatile automatic object (other than a function or |
| 890 |
// catch-clause |
| 891 |
// parameter) whose scope does not extend beyond the end of the |
| 892 |
// innermost enclosing try-block (if there is one), the copy/move |
| 893 |
// operation from the operand to the exception object (15.1) can be |
| 894 |
// omitted by constructing the automatic object directly into the |
| 895 |
// exception object |
| 896 |
NamedReturnInfo NRInfo = |
| 897 |
IsThrownVarInScope ? getNamedReturnInfo(Ex) : NamedReturnInfo(); |
| 898 |
|
| 899 |
QualType ExceptionObjectTy = Context.getExceptionObjectType(Ex->getType()); |
| 900 |
if (CheckCXXThrowOperand(OpLoc, ExceptionObjectTy, Ex)) |
| 901 |
return ExprError(); |
| 902 |
|
| 903 |
InitializedEntity Entity = |
| 904 |
InitializedEntity::InitializeException(OpLoc, ExceptionObjectTy); |
| 905 |
ExprResult Res = PerformMoveOrCopyInitialization(Entity, NRInfo, Ex); |
| 906 |
if (Res.isInvalid()) |
| 907 |
return ExprError(); |
| 908 |
Ex = Res.get(); |
| 909 |
} |
| 910 |
|
| 911 |
// PPC MMA non-pointer types are not allowed as throw expr types. |
| 912 |
if (Ex && Context.getTargetInfo().getTriple().isPPC64()) |
| 913 |
PPC().CheckPPCMMAType(Ex->getType(), Ex->getBeginLoc()); |
| 914 |
|
| 915 |
return new (Context) |
| 916 |
CXXThrowExpr(Ex, Context.VoidTy, OpLoc, IsThrownVarInScope); |
| 917 |
} |
| 918 |
|
| 919 |
static void |
| 920 |
collectPublicBases(CXXRecordDecl *RD, |
| 921 |
llvm::DenseMap<CXXRecordDecl *, unsigned> &SubobjectsSeen, |
| 922 |
llvm::SmallPtrSetImpl<CXXRecordDecl *> &VBases, |
| 923 |
llvm::SetVector<CXXRecordDecl *> &PublicSubobjectsSeen, |
| 924 |
bool ParentIsPublic) { |
| 925 |
for (const CXXBaseSpecifier &BS : RD->bases()) { |
| 926 |
CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl(); |
| 927 |
bool NewSubobject; |
| 928 |
// Virtual bases constitute the same subobject. Non-virtual bases are |
| 929 |
// always distinct subobjects. |
| 930 |
if (BS.isVirtual()) |
| 931 |
NewSubobject = VBases.insert(BaseDecl).second; |
| 932 |
else |
| 933 |
NewSubobject = true; |
| 934 |
|
| 935 |
if (NewSubobject) |
| 936 |
++SubobjectsSeen[BaseDecl]; |
| 937 |
|
| 938 |
// Only add subobjects which have public access throughout the entire chain. |
| 939 |
bool PublicPath = ParentIsPublic && BS.getAccessSpecifier() == AS_public; |
| 940 |
if (PublicPath) |
| 941 |
PublicSubobjectsSeen.insert(BaseDecl); |
| 942 |
|
| 943 |
// Recurse on to each base subobject. |
| 944 |
collectPublicBases(BaseDecl, SubobjectsSeen, VBases, PublicSubobjectsSeen, |
| 945 |
PublicPath); |
| 946 |
} |
| 947 |
} |
| 948 |
|
| 949 |
static void getUnambiguousPublicSubobjects( |
| 950 |
CXXRecordDecl *RD, llvm::SmallVectorImpl<CXXRecordDecl *> &Objects) { |
| 951 |
llvm::DenseMap<CXXRecordDecl *, unsigned> SubobjectsSeen; |
| 952 |
llvm::SmallPtrSet<CXXRecordDecl *, 2> VBases; |
| 953 |
llvm::SetVector<CXXRecordDecl *> PublicSubobjectsSeen; |
| 954 |
SubobjectsSeen[RD] = 1; |
| 955 |
PublicSubobjectsSeen.insert(RD); |
| 956 |
collectPublicBases(RD, SubobjectsSeen, VBases, PublicSubobjectsSeen, |
| 957 |
/*ParentIsPublic=*/true); |
| 958 |
|
| 959 |
for (CXXRecordDecl *PublicSubobject : PublicSubobjectsSeen) { |
| 960 |
// Skip ambiguous objects. |
| 961 |
if (SubobjectsSeen[PublicSubobject] > 1) |
| 962 |
continue; |
| 963 |
|
| 964 |
Objects.push_back(PublicSubobject); |
| 965 |
} |
| 966 |
} |
| 967 |
|
| 968 |
bool Sema::CheckCXXThrowOperand(SourceLocation ThrowLoc, |
| 969 |
QualType ExceptionObjectTy, Expr *E) { |
| 970 |
// If the type of the exception would be an incomplete type or a pointer |
| 971 |
// to an incomplete type other than (cv) void the program is ill-formed. |
| 972 |
QualType Ty = ExceptionObjectTy; |
| 973 |
bool isPointer = false; |
| 974 |
if (const PointerType* Ptr = Ty->getAs<PointerType>()) { |
| 975 |
Ty = Ptr->getPointeeType(); |
| 976 |
isPointer = true; |
| 977 |
} |
| 978 |
|
| 979 |
// Cannot throw WebAssembly reference type. |
| 980 |
if (Ty.isWebAssemblyReferenceType()) { |
| 981 |
Diag(ThrowLoc, diag::err_wasm_reftype_tc) << 0 << E->getSourceRange(); |
| 982 |
return true; |
| 983 |
} |
| 984 |
|
| 985 |
// Cannot throw WebAssembly table. |
| 986 |
if (isPointer && Ty.isWebAssemblyReferenceType()) { |
| 987 |
Diag(ThrowLoc, diag::err_wasm_table_art) << 2 << E->getSourceRange(); |
| 988 |
return true; |
| 989 |
} |
| 990 |
|
| 991 |
if (!isPointer || !Ty->isVoidType()) { |
| 992 |
if (RequireCompleteType(ThrowLoc, Ty, |
| 993 |
isPointer ? diag::err_throw_incomplete_ptr |
| 994 |
: diag::err_throw_incomplete, |
| 995 |
E->getSourceRange())) |
| 996 |
return true; |
| 997 |
|
| 998 |
if (!isPointer && Ty->isSizelessType()) { |
| 999 |
Diag(ThrowLoc, diag::err_throw_sizeless) << Ty << E->getSourceRange(); |
| 1000 |
return true; |
| 1001 |
} |
| 1002 |
|
| 1003 |
if (RequireNonAbstractType(ThrowLoc, ExceptionObjectTy, |
| 1004 |
diag::err_throw_abstract_type, E)) |
| 1005 |
return true; |
| 1006 |
} |
| 1007 |
|
| 1008 |
// If the exception has class type, we need additional handling. |
| 1009 |
CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); |
| 1010 |
if (!RD) |
| 1011 |
return false; |
| 1012 |
|
| 1013 |
// If we are throwing a polymorphic class type or pointer thereof, |
| 1014 |
// exception handling will make use of the vtable. |
| 1015 |
MarkVTableUsed(ThrowLoc, RD); |
| 1016 |
|
| 1017 |
// If a pointer is thrown, the referenced object will not be destroyed. |
| 1018 |
if (isPointer) |
| 1019 |
return false; |
| 1020 |
|
| 1021 |
// If the class has a destructor, we must be able to call it. |
| 1022 |
if (!RD->hasIrrelevantDestructor()) { |
| 1023 |
if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) { |
| 1024 |
MarkFunctionReferenced(E->getExprLoc(), Destructor); |
| 1025 |
CheckDestructorAccess(E->getExprLoc(), Destructor, |
| 1026 |
PDiag(diag::err_access_dtor_exception) << Ty); |
| 1027 |
if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) |
| 1028 |
return true; |
| 1029 |
} |
| 1030 |
} |
| 1031 |
|
| 1032 |
// The MSVC ABI creates a list of all types which can catch the exception |
| 1033 |
// object. This list also references the appropriate copy constructor to call |
| 1034 |
// if the object is caught by value and has a non-trivial copy constructor. |
| 1035 |
if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { |
| 1036 |
// We are only interested in the public, unambiguous bases contained within |
| 1037 |
// the exception object. Bases which are ambiguous or otherwise |
| 1038 |
// inaccessible are not catchable types. |
| 1039 |
llvm::SmallVector<CXXRecordDecl *, 2> UnambiguousPublicSubobjects; |
| 1040 |
getUnambiguousPublicSubobjects(RD, UnambiguousPublicSubobjects); |
| 1041 |
|
| 1042 |
for (CXXRecordDecl *Subobject : UnambiguousPublicSubobjects) { |
| 1043 |
// Attempt to lookup the copy constructor. Various pieces of machinery |
| 1044 |
// will spring into action, like template instantiation, which means this |
| 1045 |
// cannot be a simple walk of the class's decls. Instead, we must perform |
| 1046 |
// lookup and overload resolution. |
| 1047 |
CXXConstructorDecl *CD = LookupCopyingConstructor(Subobject, 0); |
| 1048 |
if (!CD || CD->isDeleted()) |
| 1049 |
continue; |
| 1050 |
|
| 1051 |
// Mark the constructor referenced as it is used by this throw expression. |
| 1052 |
MarkFunctionReferenced(E->getExprLoc(), CD); |
| 1053 |
|
| 1054 |
// Skip this copy constructor if it is trivial, we don't need to record it |
| 1055 |
// in the catchable type data. |
| 1056 |
if (CD->isTrivial()) |
| 1057 |
continue; |
| 1058 |
|
| 1059 |
// The copy constructor is non-trivial, create a mapping from this class |
| 1060 |
// type to this constructor. |
| 1061 |
// N.B. The selection of copy constructor is not sensitive to this |
| 1062 |
// particular throw-site. Lookup will be performed at the catch-site to |
| 1063 |
// ensure that the copy constructor is, in fact, accessible (via |
| 1064 |
// friendship or any other means). |
| 1065 |
Context.addCopyConstructorForExceptionObject(Subobject, CD); |
| 1066 |
|
| 1067 |
// We don't keep the instantiated default argument expressions around so |
| 1068 |
// we must rebuild them here. |
| 1069 |
for (unsigned I = 1, E = CD->getNumParams(); I != E; ++I) { |
| 1070 |
if (CheckCXXDefaultArgExpr(ThrowLoc, CD, CD->getParamDecl(I))) |
| 1071 |
return true; |
| 1072 |
} |
| 1073 |
} |
| 1074 |
} |
| 1075 |
|
| 1076 |
// Under the Itanium C++ ABI, memory for the exception object is allocated by |
| 1077 |
// the runtime with no ability for the compiler to request additional |
| 1078 |
// alignment. Warn if the exception type requires alignment beyond the minimum |
| 1079 |
// guaranteed by the target C++ runtime. |
| 1080 |
if (Context.getTargetInfo().getCXXABI().isItaniumFamily()) { |
| 1081 |
CharUnits TypeAlign = Context.getTypeAlignInChars(Ty); |
| 1082 |
CharUnits ExnObjAlign = Context.getExnObjectAlignment(); |
| 1083 |
if (ExnObjAlign < TypeAlign) { |
| 1084 |
Diag(ThrowLoc, diag::warn_throw_underaligned_obj); |
| 1085 |
Diag(ThrowLoc, diag::note_throw_underaligned_obj) |
| 1086 |
<< Ty << (unsigned)TypeAlign.getQuantity() |
| 1087 |
<< (unsigned)ExnObjAlign.getQuantity(); |
| 1088 |
} |
| 1089 |
} |
| 1090 |
if (!isPointer && getLangOpts().AssumeNothrowExceptionDtor) { |
| 1091 |
if (CXXDestructorDecl *Dtor = RD->getDestructor()) { |
| 1092 |
auto Ty = Dtor->getType(); |
| 1093 |
if (auto *FT = Ty.getTypePtr()->getAs<FunctionProtoType>()) { |
| 1094 |
if (!isUnresolvedExceptionSpec(FT->getExceptionSpecType()) && |
| 1095 |
!FT->isNothrow()) |
| 1096 |
Diag(ThrowLoc, diag::err_throw_object_throwing_dtor) << RD; |
| 1097 |
} |
| 1098 |
} |
| 1099 |
} |
| 1100 |
|
| 1101 |
return false; |
| 1102 |
} |
| 1103 |
|
| 1104 |
static QualType adjustCVQualifiersForCXXThisWithinLambda( |
| 1105 |
ArrayRef<FunctionScopeInfo *> FunctionScopes, QualType ThisTy, |
| 1106 |
DeclContext *CurSemaContext, ASTContext &ASTCtx) { |
| 1107 |
|
| 1108 |
QualType ClassType = ThisTy->getPointeeType(); |
| 1109 |
LambdaScopeInfo *CurLSI = nullptr; |
| 1110 |
DeclContext *CurDC = CurSemaContext; |
| 1111 |
|
| 1112 |
// Iterate through the stack of lambdas starting from the innermost lambda to |
| 1113 |
// the outermost lambda, checking if '*this' is ever captured by copy - since |
| 1114 |
// that could change the cv-qualifiers of the '*this' object. |
| 1115 |
// The object referred to by '*this' starts out with the cv-qualifiers of its |
| 1116 |
// member function. We then start with the innermost lambda and iterate |
| 1117 |
// outward checking to see if any lambda performs a by-copy capture of '*this' |
| 1118 |
// - and if so, any nested lambda must respect the 'constness' of that |
| 1119 |
// capturing lamdbda's call operator. |
| 1120 |
// |
| 1121 |
|
| 1122 |
// Since the FunctionScopeInfo stack is representative of the lexical |
| 1123 |
// nesting of the lambda expressions during initial parsing (and is the best |
| 1124 |
// place for querying information about captures about lambdas that are |
| 1125 |
// partially processed) and perhaps during instantiation of function templates |
| 1126 |
// that contain lambda expressions that need to be transformed BUT not |
| 1127 |
// necessarily during instantiation of a nested generic lambda's function call |
| 1128 |
// operator (which might even be instantiated at the end of the TU) - at which |
| 1129 |
// time the DeclContext tree is mature enough to query capture information |
| 1130 |
// reliably - we use a two pronged approach to walk through all the lexically |
| 1131 |
// enclosing lambda expressions: |
| 1132 |
// |
| 1133 |
// 1) Climb down the FunctionScopeInfo stack as long as each item represents |
| 1134 |
// a Lambda (i.e. LambdaScopeInfo) AND each LSI's 'closure-type' is lexically |
| 1135 |
// enclosed by the call-operator of the LSI below it on the stack (while |
| 1136 |
// tracking the enclosing DC for step 2 if needed). Note the topmost LSI on |
| 1137 |
// the stack represents the innermost lambda. |
| 1138 |
// |
| 1139 |
// 2) If we run out of enclosing LSI's, check if the enclosing DeclContext |
| 1140 |
// represents a lambda's call operator. If it does, we must be instantiating |
| 1141 |
// a generic lambda's call operator (represented by the Current LSI, and |
| 1142 |
// should be the only scenario where an inconsistency between the LSI and the |
| 1143 |
// DeclContext should occur), so climb out the DeclContexts if they |
| 1144 |
// represent lambdas, while querying the corresponding closure types |
| 1145 |
// regarding capture information. |
| 1146 |
|
| 1147 |
// 1) Climb down the function scope info stack. |
| 1148 |
for (int I = FunctionScopes.size(); |
| 1149 |
I-- && isa<LambdaScopeInfo>(FunctionScopes[I]) && |
| 1150 |
(!CurLSI || !CurLSI->Lambda || CurLSI->Lambda->getDeclContext() == |
| 1151 |
cast<LambdaScopeInfo>(FunctionScopes[I])->CallOperator); |
| 1152 |
CurDC = getLambdaAwareParentOfDeclContext(CurDC)) { |
| 1153 |
CurLSI = cast<LambdaScopeInfo>(FunctionScopes[I]); |
| 1154 |
|
| 1155 |
if (!CurLSI->isCXXThisCaptured()) |
| 1156 |
continue; |
| 1157 |
|
| 1158 |
auto C = CurLSI->getCXXThisCapture(); |
| 1159 |
|
| 1160 |
if (C.isCopyCapture()) { |
| 1161 |
if (CurLSI->lambdaCaptureShouldBeConst()) |
| 1162 |
ClassType.addConst(); |
| 1163 |
return ASTCtx.getPointerType(ClassType); |
| 1164 |
} |
| 1165 |
} |
| 1166 |
|
| 1167 |
// 2) We've run out of ScopeInfos but check 1. if CurDC is a lambda (which |
| 1168 |
// can happen during instantiation of its nested generic lambda call |
| 1169 |
// operator); 2. if we're in a lambda scope (lambda body). |
| 1170 |
if (CurLSI && isLambdaCallOperator(CurDC)) { |
| 1171 |
assert(isGenericLambdaCallOperatorSpecialization(CurLSI->CallOperator) && |
| 1172 |
"While computing 'this' capture-type for a generic lambda, when we " |
| 1173 |
"run out of enclosing LSI's, yet the enclosing DC is a " |
| 1174 |
"lambda-call-operator we must be (i.e. Current LSI) in a generic " |
| 1175 |
"lambda call oeprator"); |
| 1176 |
assert(CurDC == getLambdaAwareParentOfDeclContext(CurLSI->CallOperator)); |
| 1177 |
|
| 1178 |
auto IsThisCaptured = |
| 1179 |
[](CXXRecordDecl *Closure, bool &IsByCopy, bool &IsConst) { |
| 1180 |
IsConst = false; |
| 1181 |
IsByCopy = false; |
| 1182 |
for (auto &&C : Closure->captures()) { |
| 1183 |
if (C.capturesThis()) { |
| 1184 |
if (C.getCaptureKind() == LCK_StarThis) |
| 1185 |
IsByCopy = true; |
| 1186 |
if (Closure->getLambdaCallOperator()->isConst()) |
| 1187 |
IsConst = true; |
| 1188 |
return true; |
| 1189 |
} |
| 1190 |
} |
| 1191 |
return false; |
| 1192 |
}; |
| 1193 |
|
| 1194 |
bool IsByCopyCapture = false; |
| 1195 |
bool IsConstCapture = false; |
| 1196 |
CXXRecordDecl *Closure = cast<CXXRecordDecl>(CurDC->getParent()); |
| 1197 |
while (Closure && |
| 1198 |
IsThisCaptured(Closure, IsByCopyCapture, IsConstCapture)) { |
| 1199 |
if (IsByCopyCapture) { |
| 1200 |
if (IsConstCapture) |
| 1201 |
ClassType.addConst(); |
| 1202 |
return ASTCtx.getPointerType(ClassType); |
| 1203 |
} |
| 1204 |
Closure = isLambdaCallOperator(Closure->getParent()) |
| 1205 |
? cast<CXXRecordDecl>(Closure->getParent()->getParent()) |
| 1206 |
: nullptr; |
| 1207 |
} |
| 1208 |
} |
| 1209 |
return ThisTy; |
| 1210 |
} |
| 1211 |
|
| 1212 |
QualType Sema::getCurrentThisType() { |
| 1213 |
DeclContext *DC = getFunctionLevelDeclContext(); |
| 1214 |
QualType ThisTy = CXXThisTypeOverride; |
| 1215 |
|
| 1216 |
if (CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(DC)) { |
| 1217 |
if (method && method->isImplicitObjectMemberFunction()) |
| 1218 |
ThisTy = method->getThisType().getNonReferenceType(); |
| 1219 |
} |
| 1220 |
|
| 1221 |
if (ThisTy.isNull() && isLambdaCallWithImplicitObjectParameter(CurContext) && |
| 1222 |
inTemplateInstantiation() && isa<CXXRecordDecl>(DC)) { |
| 1223 |
|
| 1224 |
// This is a lambda call operator that is being instantiated as a default |
| 1225 |
// initializer. DC must point to the enclosing class type, so we can recover |
| 1226 |
// the 'this' type from it. |
| 1227 |
CanQualType ClassTy = Context.getCanonicalTagType(cast<CXXRecordDecl>(DC)); |
| 1228 |
// There are no cv-qualifiers for 'this' within default initializers, |
| 1229 |
// per [expr.prim.general]p4. |
| 1230 |
ThisTy = Context.getPointerType(ClassTy); |
| 1231 |
} |
| 1232 |
|
| 1233 |
// If we are within a lambda's call operator, the cv-qualifiers of 'this' |
| 1234 |
// might need to be adjusted if the lambda or any of its enclosing lambda's |
| 1235 |
// captures '*this' by copy. |
| 1236 |
if (!ThisTy.isNull() && isLambdaCallOperator(CurContext)) |
| 1237 |
return adjustCVQualifiersForCXXThisWithinLambda(FunctionScopes, ThisTy, |
| 1238 |
CurContext, Context); |
| 1239 |
return ThisTy; |
| 1240 |
} |
| 1241 |
|
| 1242 |
Sema::CXXThisScopeRAII::CXXThisScopeRAII(Sema &S, |
| 1243 |
Decl *ContextDecl, |
| 1244 |
Qualifiers CXXThisTypeQuals, |
| 1245 |
bool Enabled) |
| 1246 |
: S(S), OldCXXThisTypeOverride(S.CXXThisTypeOverride), Enabled(false) |
| 1247 |
{ |
| 1248 |
if (!Enabled || !ContextDecl) |
| 1249 |
return; |
| 1250 |
|
| 1251 |
CXXRecordDecl *Record = nullptr; |
| 1252 |
if (ClassTemplateDecl *Template = dyn_cast<ClassTemplateDecl>(ContextDecl)) |
| 1253 |
Record = Template->getTemplatedDecl(); |
| 1254 |
else |
| 1255 |
Record = cast<CXXRecordDecl>(ContextDecl); |
| 1256 |
|
| 1257 |
// 'this' never refers to the lambda class itself. |
| 1258 |
if (Record->isLambda()) |
| 1259 |
return; |
| 1260 |
|
| 1261 |
QualType T = S.Context.getCanonicalTagType(Record); |
| 1262 |
T = S.getASTContext().getQualifiedType(T, CXXThisTypeQuals); |
| 1263 |
|
| 1264 |
S.CXXThisTypeOverride = |
| 1265 |
S.Context.getLangOpts().HLSL ? T : S.Context.getPointerType(T); |
| 1266 |
|
| 1267 |
this->Enabled = true; |
| 1268 |
} |
| 1269 |
|
| 1270 |
|
| 1271 |
Sema::CXXThisScopeRAII::~CXXThisScopeRAII() { |
| 1272 |
if (Enabled) { |
| 1273 |
S.CXXThisTypeOverride = OldCXXThisTypeOverride; |
| 1274 |
} |
| 1275 |
} |
| 1276 |
|
| 1277 |
static void buildLambdaThisCaptureFixit(Sema &Sema, LambdaScopeInfo *LSI) { |
| 1278 |
SourceLocation DiagLoc = LSI->IntroducerRange.getEnd(); |
| 1279 |
assert(!LSI->isCXXThisCaptured()); |
| 1280 |
// [=, this] {}; // until C++20: Error: this when = is the default |
| 1281 |
if (LSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval && |
| 1282 |
!Sema.getLangOpts().CPlusPlus20) |
| 1283 |
return; |
| 1284 |
Sema.Diag(DiagLoc, diag::note_lambda_this_capture_fixit) |
| 1285 |
<< FixItHint::CreateInsertion( |
| 1286 |
DiagLoc, LSI->NumExplicitCaptures > 0 ? ", this" : "this"); |
| 1287 |
} |
| 1288 |
|
| 1289 |
bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit, |
| 1290 |
bool BuildAndDiagnose, const unsigned *const FunctionScopeIndexToStopAt, |
| 1291 |
const bool ByCopy) { |
| 1292 |
// We don't need to capture this in an unevaluated context. |
| 1293 |
if (isUnevaluatedContext() && !Explicit) |
| 1294 |
return true; |
| 1295 |
|
| 1296 |
assert((!ByCopy || Explicit) && "cannot implicitly capture *this by value"); |
| 1297 |
|
| 1298 |
const int MaxFunctionScopesIndex = FunctionScopeIndexToStopAt |
| 1299 |
? *FunctionScopeIndexToStopAt |
| 1300 |
: FunctionScopes.size() - 1; |
| 1301 |
|
| 1302 |
// Check that we can capture the *enclosing object* (referred to by '*this') |
| 1303 |
// by the capturing-entity/closure (lambda/block/etc) at |
| 1304 |
// MaxFunctionScopesIndex-deep on the FunctionScopes stack. |
| 1305 |
|
| 1306 |
// Note: The *enclosing object* can only be captured by-value by a |
| 1307 |
// closure that is a lambda, using the explicit notation: |
| 1308 |
// [*this] { ... }. |
| 1309 |
// Every other capture of the *enclosing object* results in its by-reference |
| 1310 |
// capture. |
| 1311 |
|
| 1312 |
// For a closure 'L' (at MaxFunctionScopesIndex in the FunctionScopes |
| 1313 |
// stack), we can capture the *enclosing object* only if: |
| 1314 |
// - 'L' has an explicit byref or byval capture of the *enclosing object* |
| 1315 |
// - or, 'L' has an implicit capture. |
| 1316 |
// AND |
| 1317 |
// -- there is no enclosing closure |
| 1318 |
// -- or, there is some enclosing closure 'E' that has already captured the |
| 1319 |
// *enclosing object*, and every intervening closure (if any) between 'E' |
| 1320 |
// and 'L' can implicitly capture the *enclosing object*. |
| 1321 |
// -- or, every enclosing closure can implicitly capture the |
| 1322 |
// *enclosing object* |
| 1323 |
|
| 1324 |
|
| 1325 |
unsigned NumCapturingClosures = 0; |
| 1326 |
for (int idx = MaxFunctionScopesIndex; idx >= 0; idx--) { |
| 1327 |
if (CapturingScopeInfo *CSI = |
| 1328 |
dyn_cast<CapturingScopeInfo>(FunctionScopes[idx])) { |
| 1329 |
if (CSI->CXXThisCaptureIndex != 0) { |
| 1330 |
// 'this' is already being captured; there isn't anything more to do. |
| 1331 |
CSI->Captures[CSI->CXXThisCaptureIndex - 1].markUsed(BuildAndDiagnose); |
| 1332 |
break; |
| 1333 |
} |
| 1334 |
LambdaScopeInfo *LSI = dyn_cast<LambdaScopeInfo>(CSI); |
| 1335 |
if (LSI && isGenericLambdaCallOperatorSpecialization(LSI->CallOperator)) { |
| 1336 |
// This context can't implicitly capture 'this'; fail out. |
| 1337 |
if (BuildAndDiagnose) { |
| 1338 |
LSI->CallOperator->setInvalidDecl(); |
| 1339 |
Diag(Loc, diag::err_this_capture) |
| 1340 |
<< (Explicit && idx == MaxFunctionScopesIndex); |
| 1341 |
if (!Explicit) |
| 1342 |
buildLambdaThisCaptureFixit(*this, LSI); |
| 1343 |
} |
| 1344 |
return true; |
| 1345 |
} |
| 1346 |
if (CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByref || |
| 1347 |
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_LambdaByval || |
| 1348 |
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_Block || |
| 1349 |
CSI->ImpCaptureStyle == CapturingScopeInfo::ImpCap_CapturedRegion || |
| 1350 |
(Explicit && idx == MaxFunctionScopesIndex)) { |
| 1351 |
// Regarding (Explicit && idx == MaxFunctionScopesIndex): only the first |
| 1352 |
// iteration through can be an explicit capture, all enclosing closures, |
| 1353 |
// if any, must perform implicit captures. |
| 1354 |
|
| 1355 |
// This closure can capture 'this'; continue looking upwards. |
| 1356 |
NumCapturingClosures++; |
| 1357 |
continue; |
| 1358 |
} |
| 1359 |
// This context can't implicitly capture 'this'; fail out. |
| 1360 |
if (BuildAndDiagnose) { |
| 1361 |
LSI->CallOperator->setInvalidDecl(); |
| 1362 |
Diag(Loc, diag::err_this_capture) |
| 1363 |
<< (Explicit && idx == MaxFunctionScopesIndex); |
| 1364 |
} |
| 1365 |
if (!Explicit) |
| 1366 |
buildLambdaThisCaptureFixit(*this, LSI); |
| 1367 |
return true; |
| 1368 |
} |
| 1369 |
break; |
| 1370 |
} |
| 1371 |
if (!BuildAndDiagnose) return false; |
| 1372 |
|
| 1373 |
// If we got here, then the closure at MaxFunctionScopesIndex on the |
| 1374 |
// FunctionScopes stack, can capture the *enclosing object*, so capture it |
| 1375 |
// (including implicit by-reference captures in any enclosing closures). |
| 1376 |
|
| 1377 |
// In the loop below, respect the ByCopy flag only for the closure requesting |
| 1378 |
// the capture (i.e. first iteration through the loop below). Ignore it for |
| 1379 |
// all enclosing closure's up to NumCapturingClosures (since they must be |
| 1380 |
// implicitly capturing the *enclosing object* by reference (see loop |
| 1381 |
// above)). |
| 1382 |
assert((!ByCopy || |
| 1383 |
isa<LambdaScopeInfo>(FunctionScopes[MaxFunctionScopesIndex])) && |
| 1384 |
"Only a lambda can capture the enclosing object (referred to by " |
| 1385 |
"*this) by copy"); |
| 1386 |
QualType ThisTy = getCurrentThisType(); |
| 1387 |
for (int idx = MaxFunctionScopesIndex; NumCapturingClosures; |
| 1388 |
--idx, --NumCapturingClosures) { |
| 1389 |
CapturingScopeInfo *CSI = cast<CapturingScopeInfo>(FunctionScopes[idx]); |
| 1390 |
|
| 1391 |
// The type of the corresponding data member (not a 'this' pointer if 'by |
| 1392 |
// copy'). |
| 1393 |
QualType CaptureType = ByCopy ? ThisTy->getPointeeType() : ThisTy; |
| 1394 |
|
| 1395 |
bool isNested = NumCapturingClosures > 1; |
| 1396 |
CSI->addThisCapture(isNested, Loc, CaptureType, ByCopy); |
| 1397 |
} |
| 1398 |
return false; |
| 1399 |
} |
| 1400 |
|
| 1401 |
ExprResult Sema::ActOnCXXThis(SourceLocation Loc) { |
| 1402 |
// C++20 [expr.prim.this]p1: |
| 1403 |
// The keyword this names a pointer to the object for which an |
| 1404 |
// implicit object member function is invoked or a non-static |
| 1405 |
// data member's initializer is evaluated. |
| 1406 |
QualType ThisTy = getCurrentThisType(); |
| 1407 |
|
| 1408 |
if (CheckCXXThisType(Loc, ThisTy)) |
| 1409 |
return ExprError(); |
| 1410 |
|
| 1411 |
return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false); |
| 1412 |
} |
| 1413 |
|
| 1414 |
bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) { |
| 1415 |
if (!Type.isNull()) |
| 1416 |
return false; |
| 1417 |
|
| 1418 |
// C++20 [expr.prim.this]p3: |
| 1419 |
// If a declaration declares a member function or member function template |
| 1420 |
// of a class X, the expression this is a prvalue of type |
| 1421 |
// "pointer to cv-qualifier-seq X" wherever X is the current class between |
| 1422 |
// the optional cv-qualifier-seq and the end of the function-definition, |
| 1423 |
// member-declarator, or declarator. It shall not appear within the |
| 1424 |
// declaration of either a static member function or an explicit object |
| 1425 |
// member function of the current class (although its type and value |
| 1426 |
// category are defined within such member functions as they are within |
| 1427 |
// an implicit object member function). |
| 1428 |
DeclContext *DC = getFunctionLevelDeclContext(); |
| 1429 |
const auto *Method = dyn_cast<CXXMethodDecl>(DC); |
| 1430 |
if (Method && Method->isExplicitObjectMemberFunction()) { |
| 1431 |
Diag(Loc, diag::err_invalid_this_use) << 1; |
| 1432 |
} else if (Method && isLambdaCallWithExplicitObjectParameter(CurContext)) { |
| 1433 |
Diag(Loc, diag::err_invalid_this_use) << 1; |
| 1434 |
} else { |
| 1435 |
Diag(Loc, diag::err_invalid_this_use) << 0; |
| 1436 |
} |
| 1437 |
return true; |
| 1438 |
} |
| 1439 |
|
| 1440 |
Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type, |
| 1441 |
bool IsImplicit) { |
| 1442 |
auto *This = CXXThisExpr::Create(Context, Loc, Type, IsImplicit); |
| 1443 |
MarkThisReferenced(This); |
| 1444 |
return This; |
| 1445 |
} |
| 1446 |
|
| 1447 |
void Sema::MarkThisReferenced(CXXThisExpr *This) { |
| 1448 |
CheckCXXThisCapture(This->getExprLoc()); |
| 1449 |
if (This->isTypeDependent()) |
| 1450 |
return; |
| 1451 |
|
| 1452 |
// Check if 'this' is captured by value in a lambda with a dependent explicit |
| 1453 |
// object parameter, and mark it as type-dependent as well if so. |
| 1454 |
auto IsDependent = [&]() { |
| 1455 |
for (auto *Scope : llvm::reverse(FunctionScopes)) { |
| 1456 |
auto *LSI = dyn_cast<sema::LambdaScopeInfo>(Scope); |
| 1457 |
if (!LSI) |
| 1458 |
continue; |
| 1459 |
|
| 1460 |
if (LSI->Lambda && !LSI->Lambda->Encloses(CurContext) && |
| 1461 |
LSI->AfterParameterList) |
| 1462 |
return false; |
| 1463 |
|
| 1464 |
// If this lambda captures 'this' by value, then 'this' is dependent iff |
| 1465 |
// this lambda has a dependent explicit object parameter. If we can't |
| 1466 |
// determine whether it does (e.g. because the CXXMethodDecl's type is |
| 1467 |
// null), assume it doesn't. |
| 1468 |
if (LSI->isCXXThisCaptured()) { |
| 1469 |
if (!LSI->getCXXThisCapture().isCopyCapture()) |
| 1470 |
continue; |
| 1471 |
|
| 1472 |
const auto *MD = LSI->CallOperator; |
| 1473 |
if (MD->getType().isNull()) |
| 1474 |
return false; |
| 1475 |
|
| 1476 |
const auto *Ty = MD->getType()->getAs<FunctionProtoType>(); |
| 1477 |
return Ty && MD->isExplicitObjectMemberFunction() && |
| 1478 |
Ty->getParamType(0)->isDependentType(); |
| 1479 |
} |
| 1480 |
} |
| 1481 |
return false; |
| 1482 |
}(); |
| 1483 |
|
| 1484 |
This->setCapturedByCopyInLambdaWithExplicitObjectParameter(IsDependent); |
| 1485 |
} |
| 1486 |
|
| 1487 |
bool Sema::isThisOutsideMemberFunctionBody(QualType BaseType) { |
| 1488 |
// If we're outside the body of a member function, then we'll have a specified |
| 1489 |
// type for 'this'. |
| 1490 |
if (CXXThisTypeOverride.isNull()) |
| 1491 |
return false; |
| 1492 |
|
| 1493 |
// Determine whether we're looking into a class that's currently being |
| 1494 |
// defined. |
| 1495 |
CXXRecordDecl *Class = BaseType->getAsCXXRecordDecl(); |
| 1496 |
return Class && Class->isBeingDefined(); |
| 1497 |
} |
| 1498 |
|
| 1499 |
ExprResult |
| 1500 |
Sema::ActOnCXXTypeConstructExpr(ParsedType TypeRep, |
| 1501 |
SourceLocation LParenOrBraceLoc, |
| 1502 |
MultiExprArg exprs, |
| 1503 |
SourceLocation RParenOrBraceLoc, |
| 1504 |
bool ListInitialization) { |
| 1505 |
if (!TypeRep) |
| 1506 |
return ExprError(); |
| 1507 |
|
| 1508 |
TypeSourceInfo *TInfo; |
| 1509 |
QualType Ty = GetTypeFromParser(TypeRep, &TInfo); |
| 1510 |
if (!TInfo) |
| 1511 |
TInfo = Context.getTrivialTypeSourceInfo(Ty, SourceLocation()); |
| 1512 |
|
| 1513 |
auto Result = BuildCXXTypeConstructExpr(TInfo, LParenOrBraceLoc, exprs, |
| 1514 |
RParenOrBraceLoc, ListInitialization); |
| 1515 |
if (Result.isInvalid()) |
| 1516 |
Result = CreateRecoveryExpr(TInfo->getTypeLoc().getBeginLoc(), |
| 1517 |
RParenOrBraceLoc, exprs, Ty); |
| 1518 |
return Result; |
| 1519 |
} |
| 1520 |
|
| 1521 |
ExprResult |
| 1522 |
Sema::BuildCXXTypeConstructExpr(TypeSourceInfo *TInfo, |
| 1523 |
SourceLocation LParenOrBraceLoc, |
| 1524 |
MultiExprArg Exprs, |
| 1525 |
SourceLocation RParenOrBraceLoc, |
| 1526 |
bool ListInitialization) { |
| 1527 |
QualType Ty = TInfo->getType(); |
| 1528 |
SourceLocation TyBeginLoc = TInfo->getTypeLoc().getBeginLoc(); |
| 1529 |
SourceRange FullRange = SourceRange(TyBeginLoc, RParenOrBraceLoc); |
| 1530 |
|
| 1531 |
InitializedEntity Entity = |
| 1532 |
InitializedEntity::InitializeTemporary(Context, TInfo); |
| 1533 |
InitializationKind Kind = |
| 1534 |
Exprs.size() |
| 1535 |
? ListInitialization |
| 1536 |
? InitializationKind::CreateDirectList( |
| 1537 |
TyBeginLoc, LParenOrBraceLoc, RParenOrBraceLoc) |
| 1538 |
: InitializationKind::CreateDirect(TyBeginLoc, LParenOrBraceLoc, |
| 1539 |
RParenOrBraceLoc) |
| 1540 |
: InitializationKind::CreateValue(TyBeginLoc, LParenOrBraceLoc, |
| 1541 |
RParenOrBraceLoc); |
| 1542 |
|
| 1543 |
// C++17 [expr.type.conv]p1: |
| 1544 |
// If the type is a placeholder for a deduced class type, [...perform class |
| 1545 |
// template argument deduction...] |
| 1546 |
// C++23: |
| 1547 |
// Otherwise, if the type contains a placeholder type, it is replaced by the |
| 1548 |
// type determined by placeholder type deduction. |
| 1549 |
DeducedType *Deduced = Ty->getContainedDeducedType(); |
| 1550 |
if (Deduced && !Deduced->isDeduced() && |
| 1551 |
isa<DeducedTemplateSpecializationType>(Deduced)) { |
| 1552 |
Ty = DeduceTemplateSpecializationFromInitializer(TInfo, Entity, |
| 1553 |
Kind, Exprs); |
| 1554 |
if (Ty.isNull()) |
| 1555 |
return ExprError(); |
| 1556 |
Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); |
| 1557 |
} else if (Deduced && !Deduced->isDeduced()) { |
| 1558 |
MultiExprArg Inits = Exprs; |
| 1559 |
if (ListInitialization) { |
| 1560 |
auto *ILE = cast<InitListExpr>(Exprs[0]); |
| 1561 |
Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); |
| 1562 |
} |
| 1563 |
|
| 1564 |
if (Inits.empty()) |
| 1565 |
return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_init_no_expression) |
| 1566 |
<< Ty << FullRange); |
| 1567 |
if (Inits.size() > 1) { |
| 1568 |
Expr *FirstBad = Inits[1]; |
| 1569 |
return ExprError(Diag(FirstBad->getBeginLoc(), |
| 1570 |
diag::err_auto_expr_init_multiple_expressions) |
| 1571 |
<< Ty << FullRange); |
| 1572 |
} |
| 1573 |
if (getLangOpts().CPlusPlus23) { |
| 1574 |
if (Ty->getAs<AutoType>()) |
| 1575 |
Diag(TyBeginLoc, diag::warn_cxx20_compat_auto_expr) << FullRange; |
| 1576 |
} |
| 1577 |
Expr *Deduce = Inits[0]; |
| 1578 |
if (isa<InitListExpr>(Deduce)) |
| 1579 |
return ExprError( |
| 1580 |
Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) |
| 1581 |
<< ListInitialization << Ty << FullRange); |
| 1582 |
QualType DeducedType; |
| 1583 |
TemplateDeductionInfo Info(Deduce->getExprLoc()); |
| 1584 |
TemplateDeductionResult Result = |
| 1585 |
DeduceAutoType(TInfo->getTypeLoc(), Deduce, DeducedType, Info); |
| 1586 |
if (Result != TemplateDeductionResult::Success && |
| 1587 |
Result != TemplateDeductionResult::AlreadyDiagnosed) |
| 1588 |
return ExprError(Diag(TyBeginLoc, diag::err_auto_expr_deduction_failure) |
| 1589 |
<< Ty << Deduce->getType() << FullRange |
| 1590 |
<< Deduce->getSourceRange()); |
| 1591 |
if (DeducedType.isNull()) { |
| 1592 |
assert(Result == TemplateDeductionResult::AlreadyDiagnosed); |
| 1593 |
return ExprError(); |
| 1594 |
} |
| 1595 |
|
| 1596 |
Ty = DeducedType; |
| 1597 |
Entity = InitializedEntity::InitializeTemporary(TInfo, Ty); |
| 1598 |
} |
| 1599 |
|
| 1600 |
if (Ty->isDependentType() || CallExpr::hasAnyTypeDependentArguments(Exprs)) |
| 1601 |
return CXXUnresolvedConstructExpr::Create( |
| 1602 |
Context, Ty.getNonReferenceType(), TInfo, LParenOrBraceLoc, Exprs, |
| 1603 |
RParenOrBraceLoc, ListInitialization); |
| 1604 |
|
| 1605 |
// C++ [expr.type.conv]p1: |
| 1606 |
// If the expression list is a parenthesized single expression, the type |
| 1607 |
// conversion expression is equivalent (in definedness, and if defined in |
| 1608 |
// meaning) to the corresponding cast expression. |
| 1609 |
if (Exprs.size() == 1 && !ListInitialization && |
| 1610 |
!isa<InitListExpr>(Exprs[0])) { |
| 1611 |
Expr *Arg = Exprs[0]; |
| 1612 |
return BuildCXXFunctionalCastExpr(TInfo, Ty, LParenOrBraceLoc, Arg, |
| 1613 |
RParenOrBraceLoc); |
| 1614 |
} |
| 1615 |
|
| 1616 |
// For an expression of the form T(), T shall not be an array type. |
| 1617 |
QualType ElemTy = Ty; |
| 1618 |
if (Ty->isArrayType()) { |
| 1619 |
if (!ListInitialization) |
| 1620 |
return ExprError(Diag(TyBeginLoc, diag::err_value_init_for_array_type) |
| 1621 |
<< FullRange); |
| 1622 |
ElemTy = Context.getBaseElementType(Ty); |
| 1623 |
} |
| 1624 |
|
| 1625 |
// Only construct objects with object types. |
| 1626 |
// The standard doesn't explicitly forbid function types here, but that's an |
| 1627 |
// obvious oversight, as there's no way to dynamically construct a function |
| 1628 |
// in general. |
| 1629 |
if (Ty->isFunctionType()) |
| 1630 |
return ExprError(Diag(TyBeginLoc, diag::err_init_for_function_type) |
| 1631 |
<< Ty << FullRange); |
| 1632 |
|
| 1633 |
// C++17 [expr.type.conv]p2, per DR2351: |
| 1634 |
// If the type is cv void and the initializer is () or {}, the expression is |
| 1635 |
// a prvalue of the specified type that performs no initialization. |
| 1636 |
if (Ty->isVoidType()) { |
| 1637 |
if (Exprs.empty()) |
| 1638 |
return new (Context) CXXScalarValueInitExpr( |
| 1639 |
Ty.getUnqualifiedType(), TInfo, Kind.getRange().getEnd()); |
| 1640 |
if (ListInitialization && |
| 1641 |
cast<InitListExpr>(Exprs[0])->getNumInits() == 0) { |
| 1642 |
return CXXFunctionalCastExpr::Create( |
| 1643 |
Context, Ty.getUnqualifiedType(), VK_PRValue, TInfo, CK_ToVoid, |
| 1644 |
Exprs[0], /*Path=*/nullptr, CurFPFeatureOverrides(), |
| 1645 |
Exprs[0]->getBeginLoc(), Exprs[0]->getEndLoc()); |
| 1646 |
} |
| 1647 |
} else if (RequireCompleteType(TyBeginLoc, ElemTy, |
| 1648 |
diag::err_invalid_incomplete_type_use, |
| 1649 |
FullRange)) |
| 1650 |
return ExprError(); |
| 1651 |
|
| 1652 |
// Otherwise, the expression is a prvalue of the specified type whose |
| 1653 |
// result object is direct-initialized (11.6) with the initializer. |
| 1654 |
InitializationSequence InitSeq(*this, Entity, Kind, Exprs); |
| 1655 |
ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Exprs); |
| 1656 |
|
| 1657 |
if (Result.isInvalid()) |
| 1658 |
return Result; |
| 1659 |
|
| 1660 |
Expr *Inner = Result.get(); |
| 1661 |
if (CXXBindTemporaryExpr *BTE = dyn_cast_or_null<CXXBindTemporaryExpr>(Inner)) |
| 1662 |
Inner = BTE->getSubExpr(); |
| 1663 |
if (auto *CE = dyn_cast<ConstantExpr>(Inner); |
| 1664 |
CE && CE->isImmediateInvocation()) |
| 1665 |
Inner = CE->getSubExpr(); |
| 1666 |
if (!isa<CXXTemporaryObjectExpr>(Inner) && |
| 1667 |
!isa<CXXScalarValueInitExpr>(Inner)) { |
| 1668 |
// If we created a CXXTemporaryObjectExpr, that node also represents the |
| 1669 |
// functional cast. Otherwise, create an explicit cast to represent |
| 1670 |
// the syntactic form of a functional-style cast that was used here. |
| 1671 |
// |
| 1672 |
// FIXME: Creating a CXXFunctionalCastExpr around a CXXConstructExpr |
| 1673 |
// would give a more consistent AST representation than using a |
| 1674 |
// CXXTemporaryObjectExpr. It's also weird that the functional cast |
| 1675 |
// is sometimes handled by initialization and sometimes not. |
| 1676 |
QualType ResultType = Result.get()->getType(); |
| 1677 |
SourceRange Locs = ListInitialization |
| 1678 |
? SourceRange() |
| 1679 |
: SourceRange(LParenOrBraceLoc, RParenOrBraceLoc); |
| 1680 |
Result = CXXFunctionalCastExpr::Create( |
| 1681 |
Context, ResultType, Expr::getValueKindForType(Ty), TInfo, CK_NoOp, |
| 1682 |
Result.get(), /*Path=*/nullptr, CurFPFeatureOverrides(), |
| 1683 |
Locs.getBegin(), Locs.getEnd()); |
| 1684 |
} |
| 1685 |
|
| 1686 |
return Result; |
| 1687 |
} |
| 1688 |
|
| 1689 |
bool Sema::isUsualDeallocationFunction(const CXXMethodDecl *Method) { |
| 1690 |
// [CUDA] Ignore this function, if we can't call it. |
| 1691 |
const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true); |
| 1692 |
if (getLangOpts().CUDA) { |
| 1693 |
auto CallPreference = CUDA().IdentifyPreference(Caller, Method); |
| 1694 |
// If it's not callable at all, it's not the right function. |
| 1695 |
if (CallPreference < SemaCUDA::CFP_WrongSide) |
| 1696 |
return false; |
| 1697 |
if (CallPreference == SemaCUDA::CFP_WrongSide) { |
| 1698 |
// Maybe. We have to check if there are better alternatives. |
| 1699 |
DeclContext::lookup_result R = |
| 1700 |
Method->getDeclContext()->lookup(Method->getDeclName()); |
| 1701 |
for (const auto *D : R) { |
| 1702 |
if (const auto *FD = dyn_cast<FunctionDecl>(D)) { |
| 1703 |
if (CUDA().IdentifyPreference(Caller, FD) > SemaCUDA::CFP_WrongSide) |
| 1704 |
return false; |
| 1705 |
} |
| 1706 |
} |
| 1707 |
// We've found no better variants. |
| 1708 |
} |
| 1709 |
} |
| 1710 |
|
| 1711 |
SmallVector<const FunctionDecl*, 4> PreventedBy; |
| 1712 |
bool Result = Method->isUsualDeallocationFunction(PreventedBy); |
| 1713 |
|
| 1714 |
if (Result || !getLangOpts().CUDA || PreventedBy.empty()) |
| 1715 |
return Result; |
| 1716 |
|
| 1717 |
// In case of CUDA, return true if none of the 1-argument deallocator |
| 1718 |
// functions are actually callable. |
| 1719 |
return llvm::none_of(PreventedBy, [&](const FunctionDecl *FD) { |
| 1720 |
assert(FD->getNumParams() == 1 && |
| 1721 |
"Only single-operand functions should be in PreventedBy"); |
| 1722 |
return CUDA().IdentifyPreference(Caller, FD) >= SemaCUDA::CFP_HostDevice; |
| 1723 |
}); |
| 1724 |
} |
| 1725 |
|
| 1726 |
/// Determine whether the given function is a non-placement |
| 1727 |
/// deallocation function. |
| 1728 |
static bool isNonPlacementDeallocationFunction(Sema &S, FunctionDecl *FD) { |
| 1729 |
if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FD)) |
| 1730 |
return S.isUsualDeallocationFunction(Method); |
| 1731 |
|
| 1732 |
if (!FD->getDeclName().isAnyOperatorDelete()) |
| 1733 |
return false; |
| 1734 |
|
| 1735 |
if (FD->isTypeAwareOperatorNewOrDelete()) |
| 1736 |
return FunctionDecl::RequiredTypeAwareDeleteParameterCount == |
| 1737 |
FD->getNumParams(); |
| 1738 |
|
| 1739 |
unsigned UsualParams = 1; |
| 1740 |
if (S.getLangOpts().SizedDeallocation && UsualParams < FD->getNumParams() && |
| 1741 |
S.Context.hasSameUnqualifiedType( |
| 1742 |
FD->getParamDecl(UsualParams)->getType(), |
| 1743 |
S.Context.getSizeType())) |
| 1744 |
++UsualParams; |
| 1745 |
|
| 1746 |
if (S.getLangOpts().AlignedAllocation && UsualParams < FD->getNumParams() && |
| 1747 |
S.Context.hasSameUnqualifiedType( |
| 1748 |
FD->getParamDecl(UsualParams)->getType(), |
| 1749 |
S.Context.getCanonicalTagType(S.getStdAlignValT()))) |
| 1750 |
++UsualParams; |
| 1751 |
|
| 1752 |
return UsualParams == FD->getNumParams(); |
| 1753 |
} |
| 1754 |
|
| 1755 |
namespace { |
| 1756 |
struct UsualDeallocFnInfo { |
| 1757 |
UsualDeallocFnInfo() |
| 1758 |
: Found(), FD(nullptr), |
| 1759 |
IDP(AlignedAllocationMode::No, SizedDeallocationMode::No) {} |
| 1760 |
UsualDeallocFnInfo(Sema &S, DeclAccessPair Found, QualType AllocType, |
| 1761 |
SourceLocation Loc) |
| 1762 |
: Found(Found), FD(dyn_cast<FunctionDecl>(Found->getUnderlyingDecl())), |
| 1763 |
Destroying(false), |
| 1764 |
IDP({AllocType, TypeAwareAllocationMode::No, |
| 1765 |
AlignedAllocationMode::No, SizedDeallocationMode::No}), |
| 1766 |
CUDAPref(SemaCUDA::CFP_Native) { |
| 1767 |
// A function template declaration is only a usual deallocation function |
| 1768 |
// if it is a typed delete. |
| 1769 |
if (!FD) { |
| 1770 |
if (AllocType.isNull()) |
| 1771 |
return; |
| 1772 |
auto *FTD = dyn_cast<FunctionTemplateDecl>(Found->getUnderlyingDecl()); |
| 1773 |
if (!FTD) |
| 1774 |
return; |
| 1775 |
FunctionDecl *InstantiatedDecl = |
| 1776 |
S.BuildTypeAwareUsualDelete(FTD, AllocType, Loc); |
| 1777 |
if (!InstantiatedDecl) |
| 1778 |
return; |
| 1779 |
FD = InstantiatedDecl; |
| 1780 |
} |
| 1781 |
unsigned NumBaseParams = 1; |
| 1782 |
if (FD->isTypeAwareOperatorNewOrDelete()) { |
| 1783 |
// If this is a type aware operator delete we instantiate an appropriate |
| 1784 |
// specialization of std::type_identity<>. If we do not know the |
| 1785 |
// type being deallocated, or if the type-identity parameter of the |
| 1786 |
// deallocation function does not match the constructed type_identity |
| 1787 |
// specialization we reject the declaration. |
| 1788 |
if (AllocType.isNull()) { |
| 1789 |
FD = nullptr; |
| 1790 |
return; |
| 1791 |
} |
| 1792 |
QualType TypeIdentityTag = FD->getParamDecl(0)->getType(); |
| 1793 |
QualType ExpectedTypeIdentityTag = |
| 1794 |
S.tryBuildStdTypeIdentity(AllocType, Loc); |
| 1795 |
if (ExpectedTypeIdentityTag.isNull()) { |
| 1796 |
FD = nullptr; |
| 1797 |
return; |
| 1798 |
} |
| 1799 |
if (!S.Context.hasSameType(TypeIdentityTag, ExpectedTypeIdentityTag)) { |
| 1800 |
FD = nullptr; |
| 1801 |
return; |
| 1802 |
} |
| 1803 |
IDP.PassTypeIdentity = TypeAwareAllocationMode::Yes; |
| 1804 |
++NumBaseParams; |
| 1805 |
} |
| 1806 |
|
| 1807 |
if (FD->isDestroyingOperatorDelete()) { |
| 1808 |
Destroying = true; |
| 1809 |
++NumBaseParams; |
| 1810 |
} |
| 1811 |
|
| 1812 |
if (NumBaseParams < FD->getNumParams() && |
| 1813 |
S.Context.hasSameUnqualifiedType( |
| 1814 |
FD->getParamDecl(NumBaseParams)->getType(), |
| 1815 |
S.Context.getSizeType())) { |
| 1816 |
++NumBaseParams; |
| 1817 |
IDP.PassSize = SizedDeallocationMode::Yes; |
| 1818 |
} |
| 1819 |
|
| 1820 |
if (NumBaseParams < FD->getNumParams() && |
| 1821 |
FD->getParamDecl(NumBaseParams)->getType()->isAlignValT()) { |
| 1822 |
++NumBaseParams; |
| 1823 |
IDP.PassAlignment = AlignedAllocationMode::Yes; |
| 1824 |
} |
| 1825 |
|
| 1826 |
// In CUDA, determine how much we'd like / dislike to call this. |
| 1827 |
if (S.getLangOpts().CUDA) |
| 1828 |
CUDAPref = S.CUDA().IdentifyPreference( |
| 1829 |
S.getCurFunctionDecl(/*AllowLambda=*/true), FD); |
| 1830 |
} |
| 1831 |
|
| 1832 |
explicit operator bool() const { return FD; } |
| 1833 |
|
| 1834 |
int Compare(Sema &S, const UsualDeallocFnInfo &Other, |
| 1835 |
ImplicitDeallocationParameters TargetIDP) const { |
| 1836 |
assert(!TargetIDP.Type.isNull() || |
| 1837 |
!isTypeAwareAllocation(Other.IDP.PassTypeIdentity)); |
| 1838 |
|
| 1839 |
// C++ P0722: |
| 1840 |
// A destroying operator delete is preferred over a non-destroying |
| 1841 |
// operator delete. |
| 1842 |
if (Destroying != Other.Destroying) |
| 1843 |
return Destroying ? 1 : -1; |
| 1844 |
|
| 1845 |
const ImplicitDeallocationParameters &OtherIDP = Other.IDP; |
| 1846 |
// Selection for type awareness has priority over alignment and size |
| 1847 |
if (IDP.PassTypeIdentity != OtherIDP.PassTypeIdentity) |
| 1848 |
return IDP.PassTypeIdentity == TargetIDP.PassTypeIdentity ? 1 : -1; |
| 1849 |
|
| 1850 |
// C++17 [expr.delete]p10: |
| 1851 |
// If the type has new-extended alignment, a function with a parameter |
| 1852 |
// of type std::align_val_t is preferred; otherwise a function without |
| 1853 |
// such a parameter is preferred |
| 1854 |
if (IDP.PassAlignment != OtherIDP.PassAlignment) |
| 1855 |
return IDP.PassAlignment == TargetIDP.PassAlignment ? 1 : -1; |
| 1856 |
|
| 1857 |
if (IDP.PassSize != OtherIDP.PassSize) |
| 1858 |
return IDP.PassSize == TargetIDP.PassSize ? 1 : -1; |
| 1859 |
|
| 1860 |
if (isTypeAwareAllocation(IDP.PassTypeIdentity)) { |
| 1861 |
// Type aware allocation involves templates so we need to choose |
| 1862 |
// the best type |
| 1863 |
FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate(); |
| 1864 |
FunctionTemplateDecl *OtherPrimaryTemplate = |
| 1865 |
Other.FD->getPrimaryTemplate(); |
| 1866 |
if ((!PrimaryTemplate) != (!OtherPrimaryTemplate)) |
| 1867 |
return OtherPrimaryTemplate ? 1 : -1; |
| 1868 |
|
| 1869 |
if (PrimaryTemplate && OtherPrimaryTemplate) { |
| 1870 |
const auto *DC = dyn_cast<CXXRecordDecl>(Found->getDeclContext()); |
| 1871 |
const auto *OtherDC = |
| 1872 |
dyn_cast<CXXRecordDecl>(Other.Found->getDeclContext()); |
| 1873 |
unsigned ImplicitArgCount = Destroying + IDP.getNumImplicitArgs(); |
| 1874 |
if (FunctionTemplateDecl *Best = S.getMoreSpecializedTemplate( |
| 1875 |
PrimaryTemplate, OtherPrimaryTemplate, SourceLocation(), |
| 1876 |
TPOC_Call, ImplicitArgCount, |
| 1877 |
DC ? S.Context.getCanonicalTagType(DC) : QualType{}, |
| 1878 |
OtherDC ? S.Context.getCanonicalTagType(OtherDC) : QualType{}, |
| 1879 |
false)) { |
| 1880 |
return Best == PrimaryTemplate ? 1 : -1; |
| 1881 |
} |
| 1882 |
} |
| 1883 |
} |
| 1884 |
|
| 1885 |
// Use CUDA call preference as a tiebreaker. |
| 1886 |
if (CUDAPref > Other.CUDAPref) |
| 1887 |
return 1; |
| 1888 |
if (CUDAPref == Other.CUDAPref) |
| 1889 |
return 0; |
| 1890 |
return -1; |
| 1891 |
} |
| 1892 |
|
| 1893 |
DeclAccessPair Found; |
| 1894 |
FunctionDecl *FD; |
| 1895 |
bool Destroying; |
| 1896 |
ImplicitDeallocationParameters IDP; |
| 1897 |
SemaCUDA::CUDAFunctionPreference CUDAPref; |
| 1898 |
}; |
| 1899 |
} |
| 1900 |
|
| 1901 |
/// Determine whether a type has new-extended alignment. This may be called when |
| 1902 |
/// the type is incomplete (for a delete-expression with an incomplete pointee |
| 1903 |
/// type), in which case it will conservatively return false if the alignment is |
| 1904 |
/// not known. |
| 1905 |
static bool hasNewExtendedAlignment(Sema &S, QualType AllocType) { |
| 1906 |
return S.getLangOpts().AlignedAllocation && |
| 1907 |
S.getASTContext().getTypeAlignIfKnown(AllocType) > |
| 1908 |
S.getASTContext().getTargetInfo().getNewAlign(); |
| 1909 |
} |
| 1910 |
|
| 1911 |
static bool CheckDeleteOperator(Sema &S, SourceLocation StartLoc, |
| 1912 |
SourceRange Range, bool Diagnose, |
| 1913 |
CXXRecordDecl *NamingClass, DeclAccessPair Decl, |
| 1914 |
FunctionDecl *Operator) { |
| 1915 |
if (Operator->isTypeAwareOperatorNewOrDelete()) { |
| 1916 |
QualType SelectedTypeIdentityParameter = |
| 1917 |
Operator->getParamDecl(0)->getType(); |
| 1918 |
if (S.RequireCompleteType(StartLoc, SelectedTypeIdentityParameter, |
| 1919 |
diag::err_incomplete_type)) |
| 1920 |
return true; |
| 1921 |
} |
| 1922 |
|
| 1923 |
// FIXME: DiagnoseUseOfDecl? |
| 1924 |
if (Operator->isDeleted()) { |
| 1925 |
if (Diagnose) { |
| 1926 |
StringLiteral *Msg = Operator->getDeletedMessage(); |
| 1927 |
S.Diag(StartLoc, diag::err_deleted_function_use) |
| 1928 |
<< (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()); |
| 1929 |
S.NoteDeletedFunction(Operator); |
| 1930 |
} |
| 1931 |
return true; |
| 1932 |
} |
| 1933 |
Sema::AccessResult Accessible = |
| 1934 |
S.CheckAllocationAccess(StartLoc, Range, NamingClass, Decl, Diagnose); |
| 1935 |
return Accessible == Sema::AR_inaccessible; |
| 1936 |
} |
| 1937 |
|
| 1938 |
/// Select the correct "usual" deallocation function to use from a selection of |
| 1939 |
/// deallocation functions (either global or class-scope). |
| 1940 |
static UsualDeallocFnInfo resolveDeallocationOverload( |
| 1941 |
Sema &S, LookupResult &R, const ImplicitDeallocationParameters &IDP, |
| 1942 |
SourceLocation Loc, |
| 1943 |
llvm::SmallVectorImpl<UsualDeallocFnInfo> *BestFns = nullptr) { |
| 1944 |
|
| 1945 |
UsualDeallocFnInfo Best; |
| 1946 |
for (auto I = R.begin(), E = R.end(); I != E; ++I) { |
| 1947 |
UsualDeallocFnInfo Info(S, I.getPair(), IDP.Type, Loc); |
| 1948 |
if (!Info || !isNonPlacementDeallocationFunction(S, Info.FD) || |
| 1949 |
Info.CUDAPref == SemaCUDA::CFP_Never) |
| 1950 |
continue; |
| 1951 |
|
| 1952 |
if (!isTypeAwareAllocation(IDP.PassTypeIdentity) && |
| 1953 |
isTypeAwareAllocation(Info.IDP.PassTypeIdentity)) |
| 1954 |
continue; |
| 1955 |
if (!Best) { |
| 1956 |
Best = Info; |
| 1957 |
if (BestFns) |
| 1958 |
BestFns->push_back(Info); |
| 1959 |
continue; |
| 1960 |
} |
| 1961 |
int ComparisonResult = Best.Compare(S, Info, IDP); |
| 1962 |
if (ComparisonResult > 0) |
| 1963 |
continue; |
| 1964 |
|
| 1965 |
// If more than one preferred function is found, all non-preferred |
| 1966 |
// functions are eliminated from further consideration. |
| 1967 |
if (BestFns && ComparisonResult < 0) |
| 1968 |
BestFns->clear(); |
| 1969 |
|
| 1970 |
Best = Info; |
| 1971 |
if (BestFns) |
| 1972 |
BestFns->push_back(Info); |
| 1973 |
} |
| 1974 |
|
| 1975 |
return Best; |
| 1976 |
} |
| 1977 |
|
| 1978 |
/// Determine whether a given type is a class for which 'delete[]' would call |
| 1979 |
/// a member 'operator delete[]' with a 'size_t' parameter. This implies that |
| 1980 |
/// we need to store the array size (even if the type is |
| 1981 |
/// trivially-destructible). |
| 1982 |
static bool doesUsualArrayDeleteWantSize(Sema &S, SourceLocation loc, |
| 1983 |
TypeAwareAllocationMode PassType, |
| 1984 |
QualType allocType) { |
| 1985 |
const auto *record = |
| 1986 |
allocType->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>(); |
| 1987 |
if (!record) return false; |
| 1988 |
|
| 1989 |
// Try to find an operator delete[] in class scope. |
| 1990 |
|
| 1991 |
DeclarationName deleteName = |
| 1992 |
S.Context.DeclarationNames.getCXXOperatorName(OO_Array_Delete); |
| 1993 |
LookupResult ops(S, deleteName, loc, Sema::LookupOrdinaryName); |
| 1994 |
S.LookupQualifiedName(ops, record->getDecl()->getDefinitionOrSelf()); |
| 1995 |
|
| 1996 |
// We're just doing this for information. |
| 1997 |
ops.suppressDiagnostics(); |
| 1998 |
|
| 1999 |
// Very likely: there's no operator delete[]. |
| 2000 |
if (ops.empty()) return false; |
| 2001 |
|
| 2002 |
// If it's ambiguous, it should be illegal to call operator delete[] |
| 2003 |
// on this thing, so it doesn't matter if we allocate extra space or not. |
| 2004 |
if (ops.isAmbiguous()) return false; |
| 2005 |
|
| 2006 |
// C++17 [expr.delete]p10: |
| 2007 |
// If the deallocation functions have class scope, the one without a |
| 2008 |
// parameter of type std::size_t is selected. |
| 2009 |
ImplicitDeallocationParameters IDP = { |
| 2010 |
allocType, PassType, |
| 2011 |
alignedAllocationModeFromBool(hasNewExtendedAlignment(S, allocType)), |
| 2012 |
SizedDeallocationMode::No}; |
| 2013 |
auto Best = resolveDeallocationOverload(S, ops, IDP, loc); |
| 2014 |
return Best && isSizedDeallocation(Best.IDP.PassSize); |
| 2015 |
} |
| 2016 |
|
| 2017 |
ExprResult |
| 2018 |
Sema::ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, |
| 2019 |
SourceLocation PlacementLParen, MultiExprArg PlacementArgs, |
| 2020 |
SourceLocation PlacementRParen, SourceRange TypeIdParens, |
| 2021 |
Declarator &D, Expr *Initializer) { |
| 2022 |
std::optional<Expr *> ArraySize; |
| 2023 |
// If the specified type is an array, unwrap it and save the expression. |
| 2024 |
if (D.getNumTypeObjects() > 0 && |
| 2025 |
D.getTypeObject(0).Kind == DeclaratorChunk::Array) { |
| 2026 |
DeclaratorChunk &Chunk = D.getTypeObject(0); |
| 2027 |
if (D.getDeclSpec().hasAutoTypeSpec()) |
| 2028 |
return ExprError(Diag(Chunk.Loc, diag::err_new_array_of_auto) |
| 2029 |
<< D.getSourceRange()); |
| 2030 |
if (Chunk.Arr.hasStatic) |
| 2031 |
return ExprError(Diag(Chunk.Loc, diag::err_static_illegal_in_new) |
| 2032 |
<< D.getSourceRange()); |
| 2033 |
if (!Chunk.Arr.NumElts && !Initializer) |
| 2034 |
return ExprError(Diag(Chunk.Loc, diag::err_array_new_needs_size) |
| 2035 |
<< D.getSourceRange()); |
| 2036 |
|
| 2037 |
ArraySize = Chunk.Arr.NumElts; |
| 2038 |
D.DropFirstTypeObject(); |
| 2039 |
} |
| 2040 |
|
| 2041 |
// Every dimension shall be of constant size. |
| 2042 |
if (ArraySize) { |
| 2043 |
for (unsigned I = 0, N = D.getNumTypeObjects(); I < N; ++I) { |
| 2044 |
if (D.getTypeObject(I).Kind != DeclaratorChunk::Array) |
| 2045 |
break; |
| 2046 |
|
| 2047 |
DeclaratorChunk::ArrayTypeInfo &Array = D.getTypeObject(I).Arr; |
| 2048 |
if (Expr *NumElts = Array.NumElts) { |
| 2049 |
if (!NumElts->isTypeDependent() && !NumElts->isValueDependent()) { |
| 2050 |
// FIXME: GCC permits constant folding here. We should either do so consistently |
| 2051 |
// or not do so at all, rather than changing behavior in C++14 onwards. |
| 2052 |
if (getLangOpts().CPlusPlus14) { |
| 2053 |
// C++1y [expr.new]p6: Every constant-expression in a noptr-new-declarator |
| 2054 |
// shall be a converted constant expression (5.19) of type std::size_t |
| 2055 |
// and shall evaluate to a strictly positive value. |
| 2056 |
llvm::APSInt Value(Context.getIntWidth(Context.getSizeType())); |
| 2057 |
Array.NumElts = |
| 2058 |
CheckConvertedConstantExpression(NumElts, Context.getSizeType(), |
| 2059 |
Value, CCEKind::ArrayBound) |
| 2060 |
.get(); |
| 2061 |
} else { |
| 2062 |
Array.NumElts = VerifyIntegerConstantExpression( |
| 2063 |
NumElts, nullptr, diag::err_new_array_nonconst, |
| 2064 |
AllowFoldKind::Allow) |
| 2065 |
.get(); |
| 2066 |
} |
| 2067 |
if (!Array.NumElts) |
| 2068 |
return ExprError(); |
| 2069 |
} |
| 2070 |
} |
| 2071 |
} |
| 2072 |
} |
| 2073 |
|
| 2074 |
TypeSourceInfo *TInfo = GetTypeForDeclarator(D); |
| 2075 |
QualType AllocType = TInfo->getType(); |
| 2076 |
if (D.isInvalidType()) |
| 2077 |
return ExprError(); |
| 2078 |
|
| 2079 |
SourceRange DirectInitRange; |
| 2080 |
if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) |
| 2081 |
DirectInitRange = List->getSourceRange(); |
| 2082 |
|
| 2083 |
return BuildCXXNew(SourceRange(StartLoc, D.getEndLoc()), UseGlobal, |
| 2084 |
PlacementLParen, PlacementArgs, PlacementRParen, |
| 2085 |
TypeIdParens, AllocType, TInfo, ArraySize, DirectInitRange, |
| 2086 |
Initializer); |
| 2087 |
} |
| 2088 |
|
| 2089 |
static bool isLegalArrayNewInitializer(CXXNewInitializationStyle Style, |
| 2090 |
Expr *Init, bool IsCPlusPlus20) { |
| 2091 |
if (!Init) |
| 2092 |
return true; |
| 2093 |
if (ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) |
| 2094 |
return IsCPlusPlus20 || PLE->getNumExprs() == 0; |
| 2095 |
if (isa<ImplicitValueInitExpr>(Init)) |
| 2096 |
return true; |
| 2097 |
else if (CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) |
| 2098 |
return !CCE->isListInitialization() && |
| 2099 |
CCE->getConstructor()->isDefaultConstructor(); |
| 2100 |
else if (Style == CXXNewInitializationStyle::Braces) { |
| 2101 |
assert(isa<InitListExpr>(Init) && |
| 2102 |
"Shouldn't create list CXXConstructExprs for arrays."); |
| 2103 |
return true; |
| 2104 |
} |
| 2105 |
return false; |
| 2106 |
} |
| 2107 |
|
| 2108 |
bool |
| 2109 |
Sema::isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const { |
| 2110 |
if (!getLangOpts().AlignedAllocationUnavailable) |
| 2111 |
return false; |
| 2112 |
if (FD.isDefined()) |
| 2113 |
return false; |
| 2114 |
UnsignedOrNone AlignmentParam = std::nullopt; |
| 2115 |
if (FD.isReplaceableGlobalAllocationFunction(&AlignmentParam) && |
| 2116 |
AlignmentParam) |
| 2117 |
return true; |
| 2118 |
return false; |
| 2119 |
} |
| 2120 |
|
| 2121 |
// Emit a diagnostic if an aligned allocation/deallocation function that is not |
| 2122 |
// implemented in the standard library is selected. |
| 2123 |
void Sema::diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, |
| 2124 |
SourceLocation Loc) { |
| 2125 |
if (isUnavailableAlignedAllocationFunction(FD)) { |
| 2126 |
const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); |
| 2127 |
StringRef OSName = AvailabilityAttr::getPlatformNameSourceSpelling( |
| 2128 |
getASTContext().getTargetInfo().getPlatformName()); |
| 2129 |
VersionTuple OSVersion = alignedAllocMinVersion(T.getOS()); |
| 2130 |
|
| 2131 |
bool IsDelete = FD.getDeclName().isAnyOperatorDelete(); |
| 2132 |
Diag(Loc, diag::err_aligned_allocation_unavailable) |
| 2133 |
<< IsDelete << FD.getType().getAsString() << OSName |
| 2134 |
<< OSVersion.getAsString() << OSVersion.empty(); |
| 2135 |
Diag(Loc, diag::note_silence_aligned_allocation_unavailable); |
| 2136 |
} |
| 2137 |
} |
| 2138 |
|
| 2139 |
ExprResult Sema::BuildCXXNew(SourceRange Range, bool UseGlobal, |
| 2140 |
SourceLocation PlacementLParen, |
| 2141 |
MultiExprArg PlacementArgs, |
| 2142 |
SourceLocation PlacementRParen, |
| 2143 |
SourceRange TypeIdParens, QualType AllocType, |
| 2144 |
TypeSourceInfo *AllocTypeInfo, |
| 2145 |
std::optional<Expr *> ArraySize, |
| 2146 |
SourceRange DirectInitRange, Expr *Initializer) { |
| 2147 |
SourceRange TypeRange = AllocTypeInfo->getTypeLoc().getSourceRange(); |
| 2148 |
SourceLocation StartLoc = Range.getBegin(); |
| 2149 |
|
| 2150 |
CXXNewInitializationStyle InitStyle; |
| 2151 |
if (DirectInitRange.isValid()) { |
| 2152 |
assert(Initializer && "Have parens but no initializer."); |
| 2153 |
InitStyle = CXXNewInitializationStyle::Parens; |
| 2154 |
} else if (isa_and_nonnull<InitListExpr>(Initializer)) |
| 2155 |
InitStyle = CXXNewInitializationStyle::Braces; |
| 2156 |
else { |
| 2157 |
assert((!Initializer || isa<ImplicitValueInitExpr>(Initializer) || |
| 2158 |
isa<CXXConstructExpr>(Initializer)) && |
| 2159 |
"Initializer expression that cannot have been implicitly created."); |
| 2160 |
InitStyle = CXXNewInitializationStyle::None; |
| 2161 |
} |
| 2162 |
|
| 2163 |
MultiExprArg Exprs(&Initializer, Initializer ? 1 : 0); |
| 2164 |
if (ParenListExpr *List = dyn_cast_or_null<ParenListExpr>(Initializer)) { |
| 2165 |
assert(InitStyle == CXXNewInitializationStyle::Parens && |
| 2166 |
"paren init for non-call init"); |
| 2167 |
Exprs = MultiExprArg(List->getExprs(), List->getNumExprs()); |
| 2168 |
} else if (auto *List = dyn_cast_or_null<CXXParenListInitExpr>(Initializer)) { |
| 2169 |
assert(InitStyle == CXXNewInitializationStyle::Parens && |
| 2170 |
"paren init for non-call init"); |
| 2171 |
Exprs = List->getInitExprs(); |
| 2172 |
} |
| 2173 |
|
| 2174 |
// C++11 [expr.new]p15: |
| 2175 |
// A new-expression that creates an object of type T initializes that |
| 2176 |
// object as follows: |
| 2177 |
InitializationKind Kind = [&] { |
| 2178 |
switch (InitStyle) { |
| 2179 |
// - If the new-initializer is omitted, the object is default- |
| 2180 |
// initialized (8.5); if no initialization is performed, |
| 2181 |
// the object has indeterminate value |
| 2182 |
case CXXNewInitializationStyle::None: |
| 2183 |
return InitializationKind::CreateDefault(TypeRange.getBegin()); |
| 2184 |
// - Otherwise, the new-initializer is interpreted according to the |
| 2185 |
// initialization rules of 8.5 for direct-initialization. |
| 2186 |
case CXXNewInitializationStyle::Parens: |
| 2187 |
return InitializationKind::CreateDirect(TypeRange.getBegin(), |
| 2188 |
DirectInitRange.getBegin(), |
| 2189 |
DirectInitRange.getEnd()); |
| 2190 |
case CXXNewInitializationStyle::Braces: |
| 2191 |
return InitializationKind::CreateDirectList(TypeRange.getBegin(), |
| 2192 |
Initializer->getBeginLoc(), |
| 2193 |
Initializer->getEndLoc()); |
| 2194 |
} |
| 2195 |
llvm_unreachable("Unknown initialization kind"); |
| 2196 |
}(); |
| 2197 |
|
| 2198 |
// C++11 [dcl.spec.auto]p6. Deduce the type which 'auto' stands in for. |
| 2199 |
auto *Deduced = AllocType->getContainedDeducedType(); |
| 2200 |
if (Deduced && !Deduced->isDeduced() && |
| 2201 |
isa<DeducedTemplateSpecializationType>(Deduced)) { |
| 2202 |
if (ArraySize) |
| 2203 |
return ExprError( |
| 2204 |
Diag(*ArraySize ? (*ArraySize)->getExprLoc() : TypeRange.getBegin(), |
| 2205 |
diag::err_deduced_class_template_compound_type) |
| 2206 |
<< /*array*/ 2 |
| 2207 |
<< (*ArraySize ? (*ArraySize)->getSourceRange() : TypeRange)); |
| 2208 |
|
| 2209 |
InitializedEntity Entity |
| 2210 |
= InitializedEntity::InitializeNew(StartLoc, AllocType); |
| 2211 |
AllocType = DeduceTemplateSpecializationFromInitializer( |
| 2212 |
AllocTypeInfo, Entity, Kind, Exprs); |
| 2213 |
if (AllocType.isNull()) |
| 2214 |
return ExprError(); |
| 2215 |
} else if (Deduced && !Deduced->isDeduced()) { |
| 2216 |
MultiExprArg Inits = Exprs; |
| 2217 |
bool Braced = (InitStyle == CXXNewInitializationStyle::Braces); |
| 2218 |
if (Braced) { |
| 2219 |
auto *ILE = cast<InitListExpr>(Exprs[0]); |
| 2220 |
Inits = MultiExprArg(ILE->getInits(), ILE->getNumInits()); |
| 2221 |
} |
| 2222 |
|
| 2223 |
if (InitStyle == CXXNewInitializationStyle::None || Inits.empty()) |
| 2224 |
return ExprError(Diag(StartLoc, diag::err_auto_new_requires_ctor_arg) |
| 2225 |
<< AllocType << TypeRange); |
| 2226 |
if (Inits.size() > 1) { |
| 2227 |
Expr *FirstBad = Inits[1]; |
| 2228 |
return ExprError(Diag(FirstBad->getBeginLoc(), |
| 2229 |
diag::err_auto_new_ctor_multiple_expressions) |
| 2230 |
<< AllocType << TypeRange); |
| 2231 |
} |
| 2232 |
if (Braced && !getLangOpts().CPlusPlus17) |
| 2233 |
Diag(Initializer->getBeginLoc(), diag::ext_auto_new_list_init) |
| 2234 |
<< AllocType << TypeRange; |
| 2235 |
Expr *Deduce = Inits[0]; |
| 2236 |
if (isa<InitListExpr>(Deduce)) |
| 2237 |
return ExprError( |
| 2238 |
Diag(Deduce->getBeginLoc(), diag::err_auto_expr_init_paren_braces) |
| 2239 |
<< Braced << AllocType << TypeRange); |
| 2240 |
QualType DeducedType; |
| 2241 |
TemplateDeductionInfo Info(Deduce->getExprLoc()); |
| 2242 |
TemplateDeductionResult Result = |
| 2243 |
DeduceAutoType(AllocTypeInfo->getTypeLoc(), Deduce, DeducedType, Info); |
| 2244 |
if (Result != TemplateDeductionResult::Success && |
| 2245 |
Result != TemplateDeductionResult::AlreadyDiagnosed) |
| 2246 |
return ExprError(Diag(StartLoc, diag::err_auto_new_deduction_failure) |
| 2247 |
<< AllocType << Deduce->getType() << TypeRange |
| 2248 |
<< Deduce->getSourceRange()); |
| 2249 |
if (DeducedType.isNull()) { |
| 2250 |
assert(Result == TemplateDeductionResult::AlreadyDiagnosed); |
| 2251 |
return ExprError(); |
| 2252 |
} |
| 2253 |
AllocType = DeducedType; |
| 2254 |
} |
| 2255 |
|
| 2256 |
// Per C++0x [expr.new]p5, the type being constructed may be a |
| 2257 |
// typedef of an array type. |
| 2258 |
// Dependent case will be handled separately. |
| 2259 |
if (!ArraySize && !AllocType->isDependentType()) { |
| 2260 |
if (const ConstantArrayType *Array |
| 2261 |
= Context.getAsConstantArrayType(AllocType)) { |
| 2262 |
ArraySize = IntegerLiteral::Create(Context, Array->getSize(), |
| 2263 |
Context.getSizeType(), |
| 2264 |
TypeRange.getEnd()); |
| 2265 |
AllocType = Array->getElementType(); |
| 2266 |
} |
| 2267 |
} |
| 2268 |
|
| 2269 |
if (CheckAllocatedType(AllocType, TypeRange.getBegin(), TypeRange)) |
| 2270 |
return ExprError(); |
| 2271 |
|
| 2272 |
if (ArraySize && !checkArrayElementAlignment(AllocType, TypeRange.getBegin())) |
| 2273 |
return ExprError(); |
| 2274 |
|
| 2275 |
// In ARC, infer 'retaining' for the allocated |
| 2276 |
if (getLangOpts().ObjCAutoRefCount && |
| 2277 |
AllocType.getObjCLifetime() == Qualifiers::OCL_None && |
| 2278 |
AllocType->isObjCLifetimeType()) { |
| 2279 |
AllocType = Context.getLifetimeQualifiedType(AllocType, |
| 2280 |
AllocType->getObjCARCImplicitLifetime()); |
| 2281 |
} |
| 2282 |
|
| 2283 |
QualType ResultType = Context.getPointerType(AllocType); |
| 2284 |
|
| 2285 |
if (ArraySize && *ArraySize && |
| 2286 |
(*ArraySize)->getType()->isNonOverloadPlaceholderType()) { |
| 2287 |
ExprResult result = CheckPlaceholderExpr(*ArraySize); |
| 2288 |
if (result.isInvalid()) return ExprError(); |
| 2289 |
ArraySize = result.get(); |
| 2290 |
} |
| 2291 |
// C++98 5.3.4p6: "The expression in a direct-new-declarator shall have |
| 2292 |
// integral or enumeration type with a non-negative value." |
| 2293 |
// C++11 [expr.new]p6: The expression [...] shall be of integral or unscoped |
| 2294 |
// enumeration type, or a class type for which a single non-explicit |
| 2295 |
// conversion function to integral or unscoped enumeration type exists. |
| 2296 |
// C++1y [expr.new]p6: The expression [...] is implicitly converted to |
| 2297 |
// std::size_t. |
| 2298 |
std::optional<uint64_t> KnownArraySize; |
| 2299 |
if (ArraySize && *ArraySize && !(*ArraySize)->isTypeDependent()) { |
| 2300 |
ExprResult ConvertedSize; |
| 2301 |
if (getLangOpts().CPlusPlus14) { |
| 2302 |
assert(Context.getTargetInfo().getIntWidth() && "Builtin type of size 0?"); |
| 2303 |
|
| 2304 |
ConvertedSize = PerformImplicitConversion( |
| 2305 |
*ArraySize, Context.getSizeType(), AssignmentAction::Converting); |
| 2306 |
|
| 2307 |
if (!ConvertedSize.isInvalid() && (*ArraySize)->getType()->isRecordType()) |
| 2308 |
// Diagnose the compatibility of this conversion. |
| 2309 |
Diag(StartLoc, diag::warn_cxx98_compat_array_size_conversion) |
| 2310 |
<< (*ArraySize)->getType() << 0 << "'size_t'"; |
| 2311 |
} else { |
| 2312 |
class SizeConvertDiagnoser : public ICEConvertDiagnoser { |
| 2313 |
protected: |
| 2314 |
Expr *ArraySize; |
| 2315 |
|
| 2316 |
public: |
| 2317 |
SizeConvertDiagnoser(Expr *ArraySize) |
| 2318 |
: ICEConvertDiagnoser(/*AllowScopedEnumerations*/false, false, false), |
| 2319 |
ArraySize(ArraySize) {} |
| 2320 |
|
| 2321 |
SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, |
| 2322 |
QualType T) override { |
| 2323 |
return S.Diag(Loc, diag::err_array_size_not_integral) |
| 2324 |
<< S.getLangOpts().CPlusPlus11 << T; |
| 2325 |
} |
| 2326 |
|
| 2327 |
SemaDiagnosticBuilder diagnoseIncomplete( |
| 2328 |
Sema &S, SourceLocation Loc, QualType T) override { |
| 2329 |
return S.Diag(Loc, diag::err_array_size_incomplete_type) |
| 2330 |
<< T << ArraySize->getSourceRange(); |
| 2331 |
} |
| 2332 |
|
| 2333 |
SemaDiagnosticBuilder diagnoseExplicitConv( |
| 2334 |
Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override { |
| 2335 |
return S.Diag(Loc, diag::err_array_size_explicit_conversion) << T << ConvTy; |
| 2336 |
} |
| 2337 |
|
| 2338 |
SemaDiagnosticBuilder noteExplicitConv( |
| 2339 |
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
| 2340 |
return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) |
| 2341 |
<< ConvTy->isEnumeralType() << ConvTy; |
| 2342 |
} |
| 2343 |
|
| 2344 |
SemaDiagnosticBuilder diagnoseAmbiguous( |
| 2345 |
Sema &S, SourceLocation Loc, QualType T) override { |
| 2346 |
return S.Diag(Loc, diag::err_array_size_ambiguous_conversion) << T; |
| 2347 |
} |
| 2348 |
|
| 2349 |
SemaDiagnosticBuilder noteAmbiguous( |
| 2350 |
Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override { |
| 2351 |
return S.Diag(Conv->getLocation(), diag::note_array_size_conversion) |
| 2352 |
<< ConvTy->isEnumeralType() << ConvTy; |
| 2353 |
} |
| 2354 |
|
| 2355 |
SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, |
| 2356 |
QualType T, |
| 2357 |
QualType ConvTy) override { |
| 2358 |
return S.Diag(Loc, |
| 2359 |
S.getLangOpts().CPlusPlus11 |
| 2360 |
? diag::warn_cxx98_compat_array_size_conversion |
| 2361 |
: diag::ext_array_size_conversion) |
| 2362 |
<< T << ConvTy->isEnumeralType() << ConvTy; |
| 2363 |
} |
| 2364 |
} SizeDiagnoser(*ArraySize); |
| 2365 |
|
| 2366 |
ConvertedSize = PerformContextualImplicitConversion(StartLoc, *ArraySize, |
| 2367 |
SizeDiagnoser); |
| 2368 |
} |
| 2369 |
if (ConvertedSize.isInvalid()) |
| 2370 |
return ExprError(); |
| 2371 |
|
| 2372 |
ArraySize = ConvertedSize.get(); |
| 2373 |
QualType SizeType = (*ArraySize)->getType(); |
| 2374 |
|
| 2375 |
if (!SizeType->isIntegralOrUnscopedEnumerationType()) |
| 2376 |
return ExprError(); |
| 2377 |
|
| 2378 |
// C++98 [expr.new]p7: |
| 2379 |
// The expression in a direct-new-declarator shall have integral type |
| 2380 |
// with a non-negative value. |
| 2381 |
// |
| 2382 |
// Let's see if this is a constant < 0. If so, we reject it out of hand, |
| 2383 |
// per CWG1464. Otherwise, if it's not a constant, we must have an |
| 2384 |
// unparenthesized array type. |
| 2385 |
|
| 2386 |
// We've already performed any required implicit conversion to integer or |
| 2387 |
// unscoped enumeration type. |
| 2388 |
// FIXME: Per CWG1464, we are required to check the value prior to |
| 2389 |
// converting to size_t. This will never find a negative array size in |
| 2390 |
// C++14 onwards, because Value is always unsigned here! |
| 2391 |
if (std::optional<llvm::APSInt> Value = |
| 2392 |
(*ArraySize)->getIntegerConstantExpr(Context)) { |
| 2393 |
if (Value->isSigned() && Value->isNegative()) { |
| 2394 |
return ExprError(Diag((*ArraySize)->getBeginLoc(), |
| 2395 |
diag::err_typecheck_negative_array_size) |
| 2396 |
<< (*ArraySize)->getSourceRange()); |
| 2397 |
} |
| 2398 |
|
| 2399 |
if (!AllocType->isDependentType()) { |
| 2400 |
unsigned ActiveSizeBits = |
| 2401 |
ConstantArrayType::getNumAddressingBits(Context, AllocType, *Value); |
| 2402 |
if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) |
| 2403 |
return ExprError( |
| 2404 |
Diag((*ArraySize)->getBeginLoc(), diag::err_array_too_large) |
| 2405 |
<< toString(*Value, 10, Value->isSigned(), |
| 2406 |
/*formatAsCLiteral=*/false, /*UpperCase=*/false, |
| 2407 |
/*InsertSeparators=*/true) |
| 2408 |
<< (*ArraySize)->getSourceRange()); |
| 2409 |
} |
| 2410 |
|
| 2411 |
KnownArraySize = Value->getZExtValue(); |
| 2412 |
} else if (TypeIdParens.isValid()) { |
| 2413 |
// Can't have dynamic array size when the type-id is in parentheses. |
| 2414 |
Diag((*ArraySize)->getBeginLoc(), diag::ext_new_paren_array_nonconst) |
| 2415 |
<< (*ArraySize)->getSourceRange() |
| 2416 |
<< FixItHint::CreateRemoval(TypeIdParens.getBegin()) |
| 2417 |
<< FixItHint::CreateRemoval(TypeIdParens.getEnd()); |
| 2418 |
|
| 2419 |
TypeIdParens = SourceRange(); |
| 2420 |
} |
| 2421 |
|
| 2422 |
// Note that we do *not* convert the argument in any way. It can |
| 2423 |
// be signed, larger than size_t, whatever. |
| 2424 |
} |
| 2425 |
|
| 2426 |
FunctionDecl *OperatorNew = nullptr; |
| 2427 |
FunctionDecl *OperatorDelete = nullptr; |
| 2428 |
unsigned Alignment = |
| 2429 |
AllocType->isDependentType() ? 0 : Context.getTypeAlign(AllocType); |
| 2430 |
unsigned NewAlignment = Context.getTargetInfo().getNewAlign(); |
| 2431 |
ImplicitAllocationParameters IAP = { |
| 2432 |
AllocType, ShouldUseTypeAwareOperatorNewOrDelete(), |
| 2433 |
alignedAllocationModeFromBool(getLangOpts().AlignedAllocation && |
| 2434 |
Alignment > NewAlignment)}; |
| 2435 |
|
| 2436 |
if (CheckArgsForPlaceholders(PlacementArgs)) |
| 2437 |
return ExprError(); |
| 2438 |
|
| 2439 |
AllocationFunctionScope Scope = UseGlobal ? AllocationFunctionScope::Global |
| 2440 |
: AllocationFunctionScope::Both; |
| 2441 |
SourceRange AllocationParameterRange = Range; |
| 2442 |
if (PlacementLParen.isValid() && PlacementRParen.isValid()) |
| 2443 |
AllocationParameterRange = SourceRange(PlacementLParen, PlacementRParen); |
| 2444 |
if (!AllocType->isDependentType() && |
| 2445 |
!Expr::hasAnyTypeDependentArguments(PlacementArgs) && |
| 2446 |
FindAllocationFunctions(StartLoc, AllocationParameterRange, Scope, Scope, |
| 2447 |
AllocType, ArraySize.has_value(), IAP, |
| 2448 |
PlacementArgs, OperatorNew, OperatorDelete)) |
| 2449 |
return ExprError(); |
| 2450 |
|
| 2451 |
// If this is an array allocation, compute whether the usual array |
| 2452 |
// deallocation function for the type has a size_t parameter. |
| 2453 |
bool UsualArrayDeleteWantsSize = false; |
| 2454 |
if (ArraySize && !AllocType->isDependentType()) |
| 2455 |
UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize( |
| 2456 |
*this, StartLoc, IAP.PassTypeIdentity, AllocType); |
| 2457 |
|
| 2458 |
SmallVector<Expr *, 8> AllPlaceArgs; |
| 2459 |
if (OperatorNew) { |
| 2460 |
auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); |
| 2461 |
VariadicCallType CallType = Proto->isVariadic() |
| 2462 |
? VariadicCallType::Function |
| 2463 |
: VariadicCallType::DoesNotApply; |
| 2464 |
|
| 2465 |
// We've already converted the placement args, just fill in any default |
| 2466 |
// arguments. Skip the first parameter because we don't have a corresponding |
| 2467 |
// argument. Skip the second parameter too if we're passing in the |
| 2468 |
// alignment; we've already filled it in. |
| 2469 |
unsigned NumImplicitArgs = 1; |
| 2470 |
if (isTypeAwareAllocation(IAP.PassTypeIdentity)) { |
| 2471 |
assert(OperatorNew->isTypeAwareOperatorNewOrDelete()); |
| 2472 |
NumImplicitArgs++; |
| 2473 |
} |
| 2474 |
if (isAlignedAllocation(IAP.PassAlignment)) |
| 2475 |
NumImplicitArgs++; |
| 2476 |
if (GatherArgumentsForCall(AllocationParameterRange.getBegin(), OperatorNew, |
| 2477 |
Proto, NumImplicitArgs, PlacementArgs, |
| 2478 |
AllPlaceArgs, CallType)) |
| 2479 |
return ExprError(); |
| 2480 |
|
| 2481 |
if (!AllPlaceArgs.empty()) |
| 2482 |
PlacementArgs = AllPlaceArgs; |
| 2483 |
|
| 2484 |
// We would like to perform some checking on the given `operator new` call, |
| 2485 |
// but the PlacementArgs does not contain the implicit arguments, |
| 2486 |
// namely allocation size and maybe allocation alignment, |
| 2487 |
// so we need to conjure them. |
| 2488 |
|
| 2489 |
QualType SizeTy = Context.getSizeType(); |
| 2490 |
unsigned SizeTyWidth = Context.getTypeSize(SizeTy); |
| 2491 |
|
| 2492 |
llvm::APInt SingleEltSize( |
| 2493 |
SizeTyWidth, Context.getTypeSizeInChars(AllocType).getQuantity()); |
| 2494 |
|
| 2495 |
// How many bytes do we want to allocate here? |
| 2496 |
std::optional<llvm::APInt> AllocationSize; |
| 2497 |
if (!ArraySize && !AllocType->isDependentType()) { |
| 2498 |
// For non-array operator new, we only want to allocate one element. |
| 2499 |
AllocationSize = SingleEltSize; |
| 2500 |
} else if (KnownArraySize && !AllocType->isDependentType()) { |
| 2501 |
// For array operator new, only deal with static array size case. |
| 2502 |
bool Overflow; |
| 2503 |
AllocationSize = llvm::APInt(SizeTyWidth, *KnownArraySize) |
| 2504 |
.umul_ov(SingleEltSize, Overflow); |
| 2505 |
(void)Overflow; |
| 2506 |
assert( |
| 2507 |
!Overflow && |
| 2508 |
"Expected that all the overflows would have been handled already."); |
| 2509 |
} |
| 2510 |
|
| 2511 |
IntegerLiteral AllocationSizeLiteral( |
| 2512 |
Context, AllocationSize.value_or(llvm::APInt::getZero(SizeTyWidth)), |
| 2513 |
SizeTy, StartLoc); |
| 2514 |
// Otherwise, if we failed to constant-fold the allocation size, we'll |
| 2515 |
// just give up and pass-in something opaque, that isn't a null pointer. |
| 2516 |
OpaqueValueExpr OpaqueAllocationSize(StartLoc, SizeTy, VK_PRValue, |
| 2517 |
OK_Ordinary, /*SourceExpr=*/nullptr); |
| 2518 |
|
| 2519 |
// Let's synthesize the alignment argument in case we will need it. |
| 2520 |
// Since we *really* want to allocate these on stack, this is slightly ugly |
| 2521 |
// because there might not be a `std::align_val_t` type. |
| 2522 |
EnumDecl *StdAlignValT = getStdAlignValT(); |
| 2523 |
QualType AlignValT = |
| 2524 |
StdAlignValT ? Context.getCanonicalTagType(StdAlignValT) : SizeTy; |
| 2525 |
IntegerLiteral AlignmentLiteral( |
| 2526 |
Context, |
| 2527 |
llvm::APInt(Context.getTypeSize(SizeTy), |
| 2528 |
Alignment / Context.getCharWidth()), |
| 2529 |
SizeTy, StartLoc); |
| 2530 |
ImplicitCastExpr DesiredAlignment(ImplicitCastExpr::OnStack, AlignValT, |
| 2531 |
CK_IntegralCast, &AlignmentLiteral, |
| 2532 |
VK_PRValue, FPOptionsOverride()); |
| 2533 |
|
| 2534 |
// Adjust placement args by prepending conjured size and alignment exprs. |
| 2535 |
llvm::SmallVector<Expr *, 8> CallArgs; |
| 2536 |
CallArgs.reserve(NumImplicitArgs + PlacementArgs.size()); |
| 2537 |
CallArgs.emplace_back(AllocationSize |
| 2538 |
? static_cast<Expr *>(&AllocationSizeLiteral) |
| 2539 |
: &OpaqueAllocationSize); |
| 2540 |
if (isAlignedAllocation(IAP.PassAlignment)) |
| 2541 |
CallArgs.emplace_back(&DesiredAlignment); |
| 2542 |
llvm::append_range(CallArgs, PlacementArgs); |
| 2543 |
|
| 2544 |
DiagnoseSentinelCalls(OperatorNew, PlacementLParen, CallArgs); |
| 2545 |
|
| 2546 |
checkCall(OperatorNew, Proto, /*ThisArg=*/nullptr, CallArgs, |
| 2547 |
/*IsMemberFunction=*/false, StartLoc, Range, CallType); |
| 2548 |
|
| 2549 |
// Warn if the type is over-aligned and is being allocated by (unaligned) |
| 2550 |
// global operator new. |
| 2551 |
if (PlacementArgs.empty() && !isAlignedAllocation(IAP.PassAlignment) && |
| 2552 |
(OperatorNew->isImplicit() || |
| 2553 |
(OperatorNew->getBeginLoc().isValid() && |
| 2554 |
getSourceManager().isInSystemHeader(OperatorNew->getBeginLoc())))) { |
| 2555 |
if (Alignment > NewAlignment) |
| 2556 |
Diag(StartLoc, diag::warn_overaligned_type) |
| 2557 |
<< AllocType |
| 2558 |
<< unsigned(Alignment / Context.getCharWidth()) |
| 2559 |
<< unsigned(NewAlignment / Context.getCharWidth()); |
| 2560 |
} |
| 2561 |
} |
| 2562 |
|
| 2563 |
// Array 'new' can't have any initializers except empty parentheses. |
| 2564 |
// Initializer lists are also allowed, in C++11. Rely on the parser for the |
| 2565 |
// dialect distinction. |
| 2566 |
if (ArraySize && !isLegalArrayNewInitializer(InitStyle, Initializer, |
| 2567 |
getLangOpts().CPlusPlus20)) { |
| 2568 |
SourceRange InitRange(Exprs.front()->getBeginLoc(), |
| 2569 |
Exprs.back()->getEndLoc()); |
| 2570 |
Diag(StartLoc, diag::err_new_array_init_args) << InitRange; |
| 2571 |
return ExprError(); |
| 2572 |
} |
| 2573 |
|
| 2574 |
// If we can perform the initialization, and we've not already done so, |
| 2575 |
// do it now. |
| 2576 |
if (!AllocType->isDependentType() && |
| 2577 |
!Expr::hasAnyTypeDependentArguments(Exprs)) { |
| 2578 |
// The type we initialize is the complete type, including the array bound. |
| 2579 |
QualType InitType; |
| 2580 |
if (KnownArraySize) |
| 2581 |
InitType = Context.getConstantArrayType( |
| 2582 |
AllocType, |
| 2583 |
llvm::APInt(Context.getTypeSize(Context.getSizeType()), |
| 2584 |
*KnownArraySize), |
| 2585 |
*ArraySize, ArraySizeModifier::Normal, 0); |
| 2586 |
else if (ArraySize) |
| 2587 |
InitType = Context.getIncompleteArrayType(AllocType, |
| 2588 |
ArraySizeModifier::Normal, 0); |
| 2589 |
else |
| 2590 |
InitType = AllocType; |
| 2591 |
|
| 2592 |
InitializedEntity Entity |
| 2593 |
= InitializedEntity::InitializeNew(StartLoc, InitType); |
| 2594 |
InitializationSequence InitSeq(*this, Entity, Kind, Exprs); |
| 2595 |
ExprResult FullInit = InitSeq.Perform(*this, Entity, Kind, Exprs); |
| 2596 |
if (FullInit.isInvalid()) |
| 2597 |
return ExprError(); |
| 2598 |
|
| 2599 |
// FullInit is our initializer; strip off CXXBindTemporaryExprs, because |
| 2600 |
// we don't want the initialized object to be destructed. |
| 2601 |
// FIXME: We should not create these in the first place. |
| 2602 |
if (CXXBindTemporaryExpr *Binder = |
| 2603 |
dyn_cast_or_null<CXXBindTemporaryExpr>(FullInit.get())) |
| 2604 |
FullInit = Binder->getSubExpr(); |
| 2605 |
|
| 2606 |
Initializer = FullInit.get(); |
| 2607 |
|
| 2608 |
// FIXME: If we have a KnownArraySize, check that the array bound of the |
| 2609 |
// initializer is no greater than that constant value. |
| 2610 |
|
| 2611 |
if (ArraySize && !*ArraySize) { |
| 2612 |
auto *CAT = Context.getAsConstantArrayType(Initializer->getType()); |
| 2613 |
if (CAT) { |
| 2614 |
// FIXME: Track that the array size was inferred rather than explicitly |
| 2615 |
// specified. |
| 2616 |
ArraySize = IntegerLiteral::Create( |
| 2617 |
Context, CAT->getSize(), Context.getSizeType(), TypeRange.getEnd()); |
| 2618 |
} else { |
| 2619 |
Diag(TypeRange.getEnd(), diag::err_new_array_size_unknown_from_init) |
| 2620 |
<< Initializer->getSourceRange(); |
| 2621 |
} |
| 2622 |
} |
| 2623 |
} |
| 2624 |
|
| 2625 |
// Mark the new and delete operators as referenced. |
| 2626 |
if (OperatorNew) { |
| 2627 |
if (DiagnoseUseOfDecl(OperatorNew, StartLoc)) |
| 2628 |
return ExprError(); |
| 2629 |
MarkFunctionReferenced(StartLoc, OperatorNew); |
| 2630 |
} |
| 2631 |
if (OperatorDelete) { |
| 2632 |
if (DiagnoseUseOfDecl(OperatorDelete, StartLoc)) |
| 2633 |
return ExprError(); |
| 2634 |
MarkFunctionReferenced(StartLoc, OperatorDelete); |
| 2635 |
} |
| 2636 |
|
| 2637 |
// For MSVC vector deleting destructors support we record that for the class |
| 2638 |
// new[] was called. We try to optimize the code size and only emit vector |
| 2639 |
// deleting destructors when they are required. Vector deleting destructors |
| 2640 |
// are required for delete[] call but MSVC triggers emission of them |
| 2641 |
// whenever new[] is called for an object of the class and we do the same |
| 2642 |
// for compatibility. |
| 2643 |
if (const CXXConstructExpr *CCE = |
| 2644 |
dyn_cast_or_null<CXXConstructExpr>(Initializer); |
| 2645 |
CCE && ArraySize) { |
| 2646 |
Context.setClassNeedsVectorDeletingDestructor( |
| 2647 |
CCE->getConstructor()->getParent()); |
| 2648 |
} |
| 2649 |
|
| 2650 |
return CXXNewExpr::Create(Context, UseGlobal, OperatorNew, OperatorDelete, |
| 2651 |
IAP, UsualArrayDeleteWantsSize, PlacementArgs, |
| 2652 |
TypeIdParens, ArraySize, InitStyle, Initializer, |
| 2653 |
ResultType, AllocTypeInfo, Range, DirectInitRange); |
| 2654 |
} |
| 2655 |
|
| 2656 |
bool Sema::CheckAllocatedType(QualType AllocType, SourceLocation Loc, |
| 2657 |
SourceRange R) { |
| 2658 |
// C++ 5.3.4p1: "[The] type shall be a complete object type, but not an |
| 2659 |
// abstract class type or array thereof. |
| 2660 |
if (AllocType->isFunctionType()) |
| 2661 |
return Diag(Loc, diag::err_bad_new_type) |
| 2662 |
<< AllocType << 0 << R; |
| 2663 |
else if (AllocType->isReferenceType()) |
| 2664 |
return Diag(Loc, diag::err_bad_new_type) |
| 2665 |
<< AllocType << 1 << R; |
| 2666 |
else if (!AllocType->isDependentType() && |
| 2667 |
RequireCompleteSizedType( |
| 2668 |
Loc, AllocType, diag::err_new_incomplete_or_sizeless_type, R)) |
| 2669 |
return true; |
| 2670 |
else if (RequireNonAbstractType(Loc, AllocType, |
| 2671 |
diag::err_allocation_of_abstract_type)) |
| 2672 |
return true; |
| 2673 |
else if (AllocType->isVariablyModifiedType()) |
| 2674 |
return Diag(Loc, diag::err_variably_modified_new_type) |
| 2675 |
<< AllocType; |
| 2676 |
else if (AllocType.getAddressSpace() != LangAS::Default && |
| 2677 |
!getLangOpts().OpenCLCPlusPlus) |
| 2678 |
return Diag(Loc, diag::err_address_space_qualified_new) |
| 2679 |
<< AllocType.getUnqualifiedType() |
| 2680 |
<< AllocType.getQualifiers().getAddressSpaceAttributePrintValue(); |
| 2681 |
else if (getLangOpts().ObjCAutoRefCount) { |
| 2682 |
if (const ArrayType *AT = Context.getAsArrayType(AllocType)) { |
| 2683 |
QualType BaseAllocType = Context.getBaseElementType(AT); |
| 2684 |
if (BaseAllocType.getObjCLifetime() == Qualifiers::OCL_None && |
| 2685 |
BaseAllocType->isObjCLifetimeType()) |
| 2686 |
return Diag(Loc, diag::err_arc_new_array_without_ownership) |
| 2687 |
<< BaseAllocType; |
| 2688 |
} |
| 2689 |
} |
| 2690 |
|
| 2691 |
return false; |
| 2692 |
} |
| 2693 |
|
| 2694 |
enum class ResolveMode { Typed, Untyped }; |
| 2695 |
static bool resolveAllocationOverloadInterior( |
| 2696 |
Sema &S, LookupResult &R, SourceRange Range, ResolveMode Mode, |
| 2697 |
SmallVectorImpl<Expr *> &Args, AlignedAllocationMode &PassAlignment, |
| 2698 |
FunctionDecl *&Operator, OverloadCandidateSet *AlignedCandidates, |
| 2699 |
Expr *AlignArg, bool Diagnose) { |
| 2700 |
unsigned NonTypeArgumentOffset = 0; |
| 2701 |
if (Mode == ResolveMode::Typed) { |
| 2702 |
++NonTypeArgumentOffset; |
| 2703 |
} |
| 2704 |
|
| 2705 |
OverloadCandidateSet Candidates(R.getNameLoc(), |
| 2706 |
OverloadCandidateSet::CSK_Normal); |
| 2707 |
for (LookupResult::iterator Alloc = R.begin(), AllocEnd = R.end(); |
| 2708 |
Alloc != AllocEnd; ++Alloc) { |
| 2709 |
// Even member operator new/delete are implicitly treated as |
| 2710 |
// static, so don't use AddMemberCandidate. |
| 2711 |
NamedDecl *D = (*Alloc)->getUnderlyingDecl(); |
| 2712 |
bool IsTypeAware = D->getAsFunction()->isTypeAwareOperatorNewOrDelete(); |
| 2713 |
if (IsTypeAware == (Mode != ResolveMode::Typed)) |
| 2714 |
continue; |
| 2715 |
|
| 2716 |
if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { |
| 2717 |
S.AddTemplateOverloadCandidate(FnTemplate, Alloc.getPair(), |
| 2718 |
/*ExplicitTemplateArgs=*/nullptr, Args, |
| 2719 |
Candidates, |
| 2720 |
/*SuppressUserConversions=*/false); |
| 2721 |
continue; |
| 2722 |
} |
| 2723 |
|
| 2724 |
FunctionDecl *Fn = cast<FunctionDecl>(D); |
| 2725 |
S.AddOverloadCandidate(Fn, Alloc.getPair(), Args, Candidates, |
| 2726 |
/*SuppressUserConversions=*/false); |
| 2727 |
} |
| 2728 |
|
| 2729 |
// Do the resolution. |
| 2730 |
OverloadCandidateSet::iterator Best; |
| 2731 |
switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { |
| 2732 |
case OR_Success: { |
| 2733 |
// Got one! |
| 2734 |
FunctionDecl *FnDecl = Best->Function; |
| 2735 |
if (S.CheckAllocationAccess(R.getNameLoc(), Range, R.getNamingClass(), |
| 2736 |
Best->FoundDecl) == Sema::AR_inaccessible) |
| 2737 |
return true; |
| 2738 |
|
| 2739 |
Operator = FnDecl; |
| 2740 |
return false; |
| 2741 |
} |
| 2742 |
|
| 2743 |
case OR_No_Viable_Function: |
| 2744 |
// C++17 [expr.new]p13: |
| 2745 |
// If no matching function is found and the allocated object type has |
| 2746 |
// new-extended alignment, the alignment argument is removed from the |
| 2747 |
// argument list, and overload resolution is performed again. |
| 2748 |
if (isAlignedAllocation(PassAlignment)) { |
| 2749 |
PassAlignment = AlignedAllocationMode::No; |
| 2750 |
AlignArg = Args[NonTypeArgumentOffset + 1]; |
| 2751 |
Args.erase(Args.begin() + NonTypeArgumentOffset + 1); |
| 2752 |
return resolveAllocationOverloadInterior(S, R, Range, Mode, Args, |
| 2753 |
PassAlignment, Operator, |
| 2754 |
&Candidates, AlignArg, Diagnose); |
| 2755 |
} |
| 2756 |
|
| 2757 |
// MSVC will fall back on trying to find a matching global operator new |
| 2758 |
// if operator new[] cannot be found. Also, MSVC will leak by not |
| 2759 |
// generating a call to operator delete or operator delete[], but we |
| 2760 |
// will not replicate that bug. |
| 2761 |
// FIXME: Find out how this interacts with the std::align_val_t fallback |
| 2762 |
// once MSVC implements it. |
| 2763 |
if (R.getLookupName().getCXXOverloadedOperator() == OO_Array_New && |
| 2764 |
S.Context.getLangOpts().MSVCCompat && Mode != ResolveMode::Typed) { |
| 2765 |
R.clear(); |
| 2766 |
R.setLookupName(S.Context.DeclarationNames.getCXXOperatorName(OO_New)); |
| 2767 |
S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); |
| 2768 |
// FIXME: This will give bad diagnostics pointing at the wrong functions. |
| 2769 |
return resolveAllocationOverloadInterior(S, R, Range, Mode, Args, |
| 2770 |
PassAlignment, Operator, |
| 2771 |
/*Candidates=*/nullptr, |
| 2772 |
/*AlignArg=*/nullptr, Diagnose); |
| 2773 |
} |
| 2774 |
if (Mode == ResolveMode::Typed) { |
| 2775 |
// If we can't find a matching type aware operator we don't consider this |
| 2776 |
// a failure. |
| 2777 |
Operator = nullptr; |
| 2778 |
return false; |
| 2779 |
} |
| 2780 |
if (Diagnose) { |
| 2781 |
// If this is an allocation of the form 'new (p) X' for some object |
| 2782 |
// pointer p (or an expression that will decay to such a pointer), |
| 2783 |
// diagnose the reason for the error. |
| 2784 |
if (!R.isClassLookup() && Args.size() == 2 && |
| 2785 |
(Args[1]->getType()->isObjectPointerType() || |
| 2786 |
Args[1]->getType()->isArrayType())) { |
| 2787 |
const QualType Arg1Type = Args[1]->getType(); |
| 2788 |
QualType UnderlyingType = S.Context.getBaseElementType(Arg1Type); |
| 2789 |
if (UnderlyingType->isPointerType()) |
| 2790 |
UnderlyingType = UnderlyingType->getPointeeType(); |
| 2791 |
if (UnderlyingType.isConstQualified()) { |
| 2792 |
S.Diag(Args[1]->getExprLoc(), |
| 2793 |
diag::err_placement_new_into_const_qualified_storage) |
| 2794 |
<< Arg1Type << Args[1]->getSourceRange(); |
| 2795 |
return true; |
| 2796 |
} |
| 2797 |
S.Diag(R.getNameLoc(), diag::err_need_header_before_placement_new) |
| 2798 |
<< R.getLookupName() << Range; |
| 2799 |
// Listing the candidates is unlikely to be useful; skip it. |
| 2800 |
return true; |
| 2801 |
} |
| 2802 |
|
| 2803 |
// Finish checking all candidates before we note any. This checking can |
| 2804 |
// produce additional diagnostics so can't be interleaved with our |
| 2805 |
// emission of notes. |
| 2806 |
// |
| 2807 |
// For an aligned allocation, separately check the aligned and unaligned |
| 2808 |
// candidates with their respective argument lists. |
| 2809 |
SmallVector<OverloadCandidate*, 32> Cands; |
| 2810 |
SmallVector<OverloadCandidate*, 32> AlignedCands; |
| 2811 |
llvm::SmallVector<Expr*, 4> AlignedArgs; |
| 2812 |
if (AlignedCandidates) { |
| 2813 |
auto IsAligned = [NonTypeArgumentOffset](OverloadCandidate &C) { |
| 2814 |
auto AlignArgOffset = NonTypeArgumentOffset + 1; |
| 2815 |
return C.Function->getNumParams() > AlignArgOffset && |
| 2816 |
C.Function->getParamDecl(AlignArgOffset) |
| 2817 |
->getType() |
| 2818 |
->isAlignValT(); |
| 2819 |
}; |
| 2820 |
auto IsUnaligned = [&](OverloadCandidate &C) { return !IsAligned(C); }; |
| 2821 |
|
| 2822 |
AlignedArgs.reserve(Args.size() + NonTypeArgumentOffset + 1); |
| 2823 |
for (unsigned Idx = 0; Idx < NonTypeArgumentOffset + 1; ++Idx) |
| 2824 |
AlignedArgs.push_back(Args[Idx]); |
| 2825 |
AlignedArgs.push_back(AlignArg); |
| 2826 |
AlignedArgs.append(Args.begin() + NonTypeArgumentOffset + 1, |
| 2827 |
Args.end()); |
| 2828 |
AlignedCands = AlignedCandidates->CompleteCandidates( |
| 2829 |
S, OCD_AllCandidates, AlignedArgs, R.getNameLoc(), IsAligned); |
| 2830 |
|
| 2831 |
Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, |
| 2832 |
R.getNameLoc(), IsUnaligned); |
| 2833 |
} else { |
| 2834 |
Cands = Candidates.CompleteCandidates(S, OCD_AllCandidates, Args, |
| 2835 |
R.getNameLoc()); |
| 2836 |
} |
| 2837 |
|
| 2838 |
S.Diag(R.getNameLoc(), diag::err_ovl_no_viable_function_in_call) |
| 2839 |
<< R.getLookupName() << Range; |
| 2840 |
if (AlignedCandidates) |
| 2841 |
AlignedCandidates->NoteCandidates(S, AlignedArgs, AlignedCands, "", |
| 2842 |
R.getNameLoc()); |
| 2843 |
Candidates.NoteCandidates(S, Args, Cands, "", R.getNameLoc()); |
| 2844 |
} |
| 2845 |
return true; |
| 2846 |
|
| 2847 |
case OR_Ambiguous: |
| 2848 |
if (Diagnose) { |
| 2849 |
Candidates.NoteCandidates( |
| 2850 |
PartialDiagnosticAt(R.getNameLoc(), |
| 2851 |
S.PDiag(diag::err_ovl_ambiguous_call) |
| 2852 |
<< R.getLookupName() << Range), |
| 2853 |
S, OCD_AmbiguousCandidates, Args); |
| 2854 |
} |
| 2855 |
return true; |
| 2856 |
|
| 2857 |
case OR_Deleted: { |
| 2858 |
if (Diagnose) |
| 2859 |
S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(), |
| 2860 |
Candidates, Best->Function, Args); |
| 2861 |
return true; |
| 2862 |
} |
| 2863 |
} |
| 2864 |
llvm_unreachable("Unreachable, bad result from BestViableFunction"); |
| 2865 |
} |
| 2866 |
|
| 2867 |
enum class DeallocLookupMode { Untyped, OptionallyTyped }; |
| 2868 |
|
| 2869 |
static void LookupGlobalDeallocationFunctions(Sema &S, SourceLocation Loc, |
| 2870 |
LookupResult &FoundDelete, |
| 2871 |
DeallocLookupMode Mode, |
| 2872 |
DeclarationName Name) { |
| 2873 |
S.LookupQualifiedName(FoundDelete, S.Context.getTranslationUnitDecl()); |
| 2874 |
if (Mode != DeallocLookupMode::OptionallyTyped) { |
| 2875 |
// We're going to remove either the typed or the non-typed |
| 2876 |
bool RemoveTypedDecl = Mode == DeallocLookupMode::Untyped; |
| 2877 |
LookupResult::Filter Filter = FoundDelete.makeFilter(); |
| 2878 |
while (Filter.hasNext()) { |
| 2879 |
FunctionDecl *FD = Filter.next()->getUnderlyingDecl()->getAsFunction(); |
| 2880 |
if (FD->isTypeAwareOperatorNewOrDelete() == RemoveTypedDecl) |
| 2881 |
Filter.erase(); |
| 2882 |
} |
| 2883 |
Filter.done(); |
| 2884 |
} |
| 2885 |
} |
| 2886 |
|
| 2887 |
static bool resolveAllocationOverload( |
| 2888 |
Sema &S, LookupResult &R, SourceRange Range, SmallVectorImpl<Expr *> &Args, |
| 2889 |
ImplicitAllocationParameters &IAP, FunctionDecl *&Operator, |
| 2890 |
OverloadCandidateSet *AlignedCandidates, Expr *AlignArg, bool Diagnose) { |
| 2891 |
Operator = nullptr; |
| 2892 |
if (isTypeAwareAllocation(IAP.PassTypeIdentity)) { |
| 2893 |
assert(S.isStdTypeIdentity(Args[0]->getType(), nullptr)); |
| 2894 |
// The internal overload resolution work mutates the argument list |
| 2895 |
// in accordance with the spec. We may want to change that in future, |
| 2896 |
// but for now we deal with this by making a copy of the non-type-identity |
| 2897 |
// arguments. |
| 2898 |
SmallVector<Expr *> UntypedParameters; |
| 2899 |
UntypedParameters.reserve(Args.size() - 1); |
| 2900 |
UntypedParameters.push_back(Args[1]); |
| 2901 |
// Type aware allocation implicitly includes the alignment parameter so |
| 2902 |
// only include it in the untyped parameter list if alignment was explicitly |
| 2903 |
// requested |
| 2904 |
if (isAlignedAllocation(IAP.PassAlignment)) |
| 2905 |
UntypedParameters.push_back(Args[2]); |
| 2906 |
UntypedParameters.append(Args.begin() + 3, Args.end()); |
| 2907 |
|
| 2908 |
AlignedAllocationMode InitialAlignmentMode = IAP.PassAlignment; |
| 2909 |
IAP.PassAlignment = AlignedAllocationMode::Yes; |
| 2910 |
if (resolveAllocationOverloadInterior( |
| 2911 |
S, R, Range, ResolveMode::Typed, Args, IAP.PassAlignment, Operator, |
| 2912 |
AlignedCandidates, AlignArg, Diagnose)) |
| 2913 |
return true; |
| 2914 |
if (Operator) |
| 2915 |
return false; |
| 2916 |
|
| 2917 |
// If we got to this point we could not find a matching typed operator |
| 2918 |
// so we update the IAP flags, and revert to our stored copy of the |
| 2919 |
// type-identity-less argument list. |
| 2920 |
IAP.PassTypeIdentity = TypeAwareAllocationMode::No; |
| 2921 |
IAP.PassAlignment = InitialAlignmentMode; |
| 2922 |
Args = std::move(UntypedParameters); |
| 2923 |
} |
| 2924 |
assert(!S.isStdTypeIdentity(Args[0]->getType(), nullptr)); |
| 2925 |
return resolveAllocationOverloadInterior( |
| 2926 |
S, R, Range, ResolveMode::Untyped, Args, IAP.PassAlignment, Operator, |
| 2927 |
AlignedCandidates, AlignArg, Diagnose); |
| 2928 |
} |
| 2929 |
|
| 2930 |
bool Sema::FindAllocationFunctions( |
| 2931 |
SourceLocation StartLoc, SourceRange Range, |
| 2932 |
AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, |
| 2933 |
QualType AllocType, bool IsArray, ImplicitAllocationParameters &IAP, |
| 2934 |
MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, |
| 2935 |
FunctionDecl *&OperatorDelete, bool Diagnose) { |
| 2936 |
// --- Choosing an allocation function --- |
| 2937 |
// C++ 5.3.4p8 - 14 & 18 |
| 2938 |
// 1) If looking in AllocationFunctionScope::Global scope for allocation |
| 2939 |
// functions, only look in |
| 2940 |
// the global scope. Else, if AllocationFunctionScope::Class, only look in |
| 2941 |
// the scope of the allocated class. If AllocationFunctionScope::Both, look |
| 2942 |
// in both. |
| 2943 |
// 2) If an array size is given, look for operator new[], else look for |
| 2944 |
// operator new. |
| 2945 |
// 3) The first argument is always size_t. Append the arguments from the |
| 2946 |
// placement form. |
| 2947 |
|
| 2948 |
SmallVector<Expr*, 8> AllocArgs; |
| 2949 |
AllocArgs.reserve(IAP.getNumImplicitArgs() + PlaceArgs.size()); |
| 2950 |
|
| 2951 |
// C++ [expr.new]p8: |
| 2952 |
// If the allocated type is a non-array type, the allocation |
| 2953 |
// function's name is operator new and the deallocation function's |
| 2954 |
// name is operator delete. If the allocated type is an array |
| 2955 |
// type, the allocation function's name is operator new[] and the |
| 2956 |
// deallocation function's name is operator delete[]. |
| 2957 |
DeclarationName NewName = Context.DeclarationNames.getCXXOperatorName( |
| 2958 |
IsArray ? OO_Array_New : OO_New); |
| 2959 |
|
| 2960 |
QualType AllocElemType = Context.getBaseElementType(AllocType); |
| 2961 |
|
| 2962 |
// We don't care about the actual value of these arguments. |
| 2963 |
// FIXME: Should the Sema create the expression and embed it in the syntax |
| 2964 |
// tree? Or should the consumer just recalculate the value? |
| 2965 |
// FIXME: Using a dummy value will interact poorly with attribute enable_if. |
| 2966 |
|
| 2967 |
// We use size_t as a stand in so that we can construct the init |
| 2968 |
// expr on the stack |
| 2969 |
QualType TypeIdentity = Context.getSizeType(); |
| 2970 |
if (isTypeAwareAllocation(IAP.PassTypeIdentity)) { |
| 2971 |
QualType SpecializedTypeIdentity = |
| 2972 |
tryBuildStdTypeIdentity(IAP.Type, StartLoc); |
| 2973 |
if (!SpecializedTypeIdentity.isNull()) { |
| 2974 |
TypeIdentity = SpecializedTypeIdentity; |
| 2975 |
if (RequireCompleteType(StartLoc, TypeIdentity, |
| 2976 |
diag::err_incomplete_type)) |
| 2977 |
return true; |
| 2978 |
} else |
| 2979 |
IAP.PassTypeIdentity = TypeAwareAllocationMode::No; |
| 2980 |
} |
| 2981 |
TypeAwareAllocationMode OriginalTypeAwareState = IAP.PassTypeIdentity; |
| 2982 |
|
| 2983 |
CXXScalarValueInitExpr TypeIdentityParam(TypeIdentity, nullptr, StartLoc); |
| 2984 |
if (isTypeAwareAllocation(IAP.PassTypeIdentity)) |
| 2985 |
AllocArgs.push_back(&TypeIdentityParam); |
| 2986 |
|
| 2987 |
QualType SizeTy = Context.getSizeType(); |
| 2988 |
unsigned SizeTyWidth = Context.getTypeSize(SizeTy); |
| 2989 |
IntegerLiteral Size(Context, llvm::APInt::getZero(SizeTyWidth), SizeTy, |
| 2990 |
SourceLocation()); |
| 2991 |
AllocArgs.push_back(&Size); |
| 2992 |
|
| 2993 |
QualType AlignValT = Context.VoidTy; |
| 2994 |
bool IncludeAlignParam = isAlignedAllocation(IAP.PassAlignment) || |
| 2995 |
isTypeAwareAllocation(IAP.PassTypeIdentity); |
| 2996 |
if (IncludeAlignParam) { |
| 2997 |
DeclareGlobalNewDelete(); |
| 2998 |
AlignValT = Context.getCanonicalTagType(getStdAlignValT()); |
| 2999 |
} |
| 3000 |
CXXScalarValueInitExpr Align(AlignValT, nullptr, SourceLocation()); |
| 3001 |
if (IncludeAlignParam) |
| 3002 |
AllocArgs.push_back(&Align); |
| 3003 |
|
| 3004 |
llvm::append_range(AllocArgs, PlaceArgs); |
| 3005 |
|
| 3006 |
// Find the allocation function. |
| 3007 |
{ |
| 3008 |
LookupResult R(*this, NewName, StartLoc, LookupOrdinaryName); |
| 3009 |
|
| 3010 |
// C++1z [expr.new]p9: |
| 3011 |
// If the new-expression begins with a unary :: operator, the allocation |
| 3012 |
// function's name is looked up in the global scope. Otherwise, if the |
| 3013 |
// allocated type is a class type T or array thereof, the allocation |
| 3014 |
// function's name is looked up in the scope of T. |
| 3015 |
if (AllocElemType->isRecordType() && |
| 3016 |
NewScope != AllocationFunctionScope::Global) |
| 3017 |
LookupQualifiedName(R, AllocElemType->getAsCXXRecordDecl()); |
| 3018 |
|
| 3019 |
// We can see ambiguity here if the allocation function is found in |
| 3020 |
// multiple base classes. |
| 3021 |
if (R.isAmbiguous()) |
| 3022 |
return true; |
| 3023 |
|
| 3024 |
// If this lookup fails to find the name, or if the allocated type is not |
| 3025 |
// a class type, the allocation function's name is looked up in the |
| 3026 |
// global scope. |
| 3027 |
if (R.empty()) { |
| 3028 |
if (NewScope == AllocationFunctionScope::Class) |
| 3029 |
return true; |
| 3030 |
|
| 3031 |
LookupQualifiedName(R, Context.getTranslationUnitDecl()); |
| 3032 |
} |
| 3033 |
|
| 3034 |
if (getLangOpts().OpenCLCPlusPlus && R.empty()) { |
| 3035 |
if (PlaceArgs.empty()) { |
| 3036 |
Diag(StartLoc, diag::err_openclcxx_not_supported) << "default new"; |
| 3037 |
} else { |
| 3038 |
Diag(StartLoc, diag::err_openclcxx_placement_new); |
| 3039 |
} |
| 3040 |
return true; |
| 3041 |
} |
| 3042 |
|
| 3043 |
assert(!R.empty() && "implicitly declared allocation functions not found"); |
| 3044 |
assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); |
| 3045 |
|
| 3046 |
// We do our own custom access checks below. |
| 3047 |
R.suppressDiagnostics(); |
| 3048 |
|
| 3049 |
if (resolveAllocationOverload(*this, R, Range, AllocArgs, IAP, OperatorNew, |
| 3050 |
/*Candidates=*/nullptr, |
| 3051 |
/*AlignArg=*/nullptr, Diagnose)) |
| 3052 |
return true; |
| 3053 |
} |
| 3054 |
|
| 3055 |
// We don't need an operator delete if we're running under -fno-exceptions. |
| 3056 |
if (!getLangOpts().Exceptions) { |
| 3057 |
OperatorDelete = nullptr; |
| 3058 |
return false; |
| 3059 |
} |
| 3060 |
|
| 3061 |
// Note, the name of OperatorNew might have been changed from array to |
| 3062 |
// non-array by resolveAllocationOverload. |
| 3063 |
DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( |
| 3064 |
OperatorNew->getDeclName().getCXXOverloadedOperator() == OO_Array_New |
| 3065 |
? OO_Array_Delete |
| 3066 |
: OO_Delete); |
| 3067 |
|
| 3068 |
// C++ [expr.new]p19: |
| 3069 |
// |
| 3070 |
// If the new-expression begins with a unary :: operator, the |
| 3071 |
// deallocation function's name is looked up in the global |
| 3072 |
// scope. Otherwise, if the allocated type is a class type T or an |
| 3073 |
// array thereof, the deallocation function's name is looked up in |
| 3074 |
// the scope of T. If this lookup fails to find the name, or if |
| 3075 |
// the allocated type is not a class type or array thereof, the |
| 3076 |
// deallocation function's name is looked up in the global scope. |
| 3077 |
LookupResult FoundDelete(*this, DeleteName, StartLoc, LookupOrdinaryName); |
| 3078 |
if (AllocElemType->isRecordType() && |
| 3079 |
DeleteScope != AllocationFunctionScope::Global) { |
| 3080 |
auto *RD = AllocElemType->castAsCXXRecordDecl(); |
| 3081 |
LookupQualifiedName(FoundDelete, RD); |
| 3082 |
} |
| 3083 |
if (FoundDelete.isAmbiguous()) |
| 3084 |
return true; // FIXME: clean up expressions? |
| 3085 |
|
| 3086 |
// Filter out any destroying operator deletes. We can't possibly call such a |
| 3087 |
// function in this context, because we're handling the case where the object |
| 3088 |
// was not successfully constructed. |
| 3089 |
// FIXME: This is not covered by the language rules yet. |
| 3090 |
{ |
| 3091 |
LookupResult::Filter Filter = FoundDelete.makeFilter(); |
| 3092 |
while (Filter.hasNext()) { |
| 3093 |
auto *FD = dyn_cast<FunctionDecl>(Filter.next()->getUnderlyingDecl()); |
| 3094 |
if (FD && FD->isDestroyingOperatorDelete()) |
| 3095 |
Filter.erase(); |
| 3096 |
} |
| 3097 |
Filter.done(); |
| 3098 |
} |
| 3099 |
|
| 3100 |
auto GetRedeclContext = [](Decl *D) { |
| 3101 |
return D->getDeclContext()->getRedeclContext(); |
| 3102 |
}; |
| 3103 |
|
| 3104 |
DeclContext *OperatorNewContext = GetRedeclContext(OperatorNew); |
| 3105 |
|
| 3106 |
bool FoundGlobalDelete = FoundDelete.empty(); |
| 3107 |
bool IsClassScopedTypeAwareNew = |
| 3108 |
isTypeAwareAllocation(IAP.PassTypeIdentity) && |
| 3109 |
OperatorNewContext->isRecord(); |
| 3110 |
auto DiagnoseMissingTypeAwareCleanupOperator = [&](bool IsPlacementOperator) { |
| 3111 |
assert(isTypeAwareAllocation(IAP.PassTypeIdentity)); |
| 3112 |
if (Diagnose) { |
| 3113 |
Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator) |
| 3114 |
<< OperatorNew->getDeclName() << IsPlacementOperator << DeleteName; |
| 3115 |
Diag(OperatorNew->getLocation(), diag::note_type_aware_operator_declared) |
| 3116 |
<< OperatorNew->isTypeAwareOperatorNewOrDelete() |
| 3117 |
<< OperatorNew->getDeclName() << OperatorNewContext; |
| 3118 |
} |
| 3119 |
}; |
| 3120 |
if (IsClassScopedTypeAwareNew && FoundDelete.empty()) { |
| 3121 |
DiagnoseMissingTypeAwareCleanupOperator(/*isPlacementNew=*/false); |
| 3122 |
return true; |
| 3123 |
} |
| 3124 |
if (FoundDelete.empty()) { |
| 3125 |
FoundDelete.clear(LookupOrdinaryName); |
| 3126 |
|
| 3127 |
if (DeleteScope == AllocationFunctionScope::Class) |
| 3128 |
return true; |
| 3129 |
|
| 3130 |
DeclareGlobalNewDelete(); |
| 3131 |
DeallocLookupMode LookupMode = isTypeAwareAllocation(OriginalTypeAwareState) |
| 3132 |
? DeallocLookupMode::OptionallyTyped |
| 3133 |
: DeallocLookupMode::Untyped; |
| 3134 |
LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete, LookupMode, |
| 3135 |
DeleteName); |
| 3136 |
} |
| 3137 |
|
| 3138 |
FoundDelete.suppressDiagnostics(); |
| 3139 |
|
| 3140 |
SmallVector<std::pair<DeclAccessPair,FunctionDecl*>, 2> Matches; |
| 3141 |
|
| 3142 |
// Whether we're looking for a placement operator delete is dictated |
| 3143 |
// by whether we selected a placement operator new, not by whether |
| 3144 |
// we had explicit placement arguments. This matters for things like |
| 3145 |
// struct A { void *operator new(size_t, int = 0); ... }; |
| 3146 |
// A *a = new A() |
| 3147 |
// |
| 3148 |
// We don't have any definition for what a "placement allocation function" |
| 3149 |
// is, but we assume it's any allocation function whose |
| 3150 |
// parameter-declaration-clause is anything other than (size_t). |
| 3151 |
// |
| 3152 |
// FIXME: Should (size_t, std::align_val_t) also be considered non-placement? |
| 3153 |
// This affects whether an exception from the constructor of an overaligned |
| 3154 |
// type uses the sized or non-sized form of aligned operator delete. |
| 3155 |
|
| 3156 |
unsigned NonPlacementNewArgCount = 1; // size parameter |
| 3157 |
if (isTypeAwareAllocation(IAP.PassTypeIdentity)) |
| 3158 |
NonPlacementNewArgCount = |
| 3159 |
/* type-identity */ 1 + /* size */ 1 + /* alignment */ 1; |
| 3160 |
bool isPlacementNew = !PlaceArgs.empty() || |
| 3161 |
OperatorNew->param_size() != NonPlacementNewArgCount || |
| 3162 |
OperatorNew->isVariadic(); |
| 3163 |
|
| 3164 |
if (isPlacementNew) { |
| 3165 |
// C++ [expr.new]p20: |
| 3166 |
// A declaration of a placement deallocation function matches the |
| 3167 |
// declaration of a placement allocation function if it has the |
| 3168 |
// same number of parameters and, after parameter transformations |
| 3169 |
// (8.3.5), all parameter types except the first are |
| 3170 |
// identical. [...] |
| 3171 |
// |
| 3172 |
// To perform this comparison, we compute the function type that |
| 3173 |
// the deallocation function should have, and use that type both |
| 3174 |
// for template argument deduction and for comparison purposes. |
| 3175 |
QualType ExpectedFunctionType; |
| 3176 |
{ |
| 3177 |
auto *Proto = OperatorNew->getType()->castAs<FunctionProtoType>(); |
| 3178 |
|
| 3179 |
SmallVector<QualType, 6> ArgTypes; |
| 3180 |
int InitialParamOffset = 0; |
| 3181 |
if (isTypeAwareAllocation(IAP.PassTypeIdentity)) { |
| 3182 |
ArgTypes.push_back(TypeIdentity); |
| 3183 |
InitialParamOffset = 1; |
| 3184 |
} |
| 3185 |
ArgTypes.push_back(Context.VoidPtrTy); |
| 3186 |
for (unsigned I = ArgTypes.size() - InitialParamOffset, |
| 3187 |
N = Proto->getNumParams(); |
| 3188 |
I < N; ++I) |
| 3189 |
ArgTypes.push_back(Proto->getParamType(I)); |
| 3190 |
|
| 3191 |
FunctionProtoType::ExtProtoInfo EPI; |
| 3192 |
// FIXME: This is not part of the standard's rule. |
| 3193 |
EPI.Variadic = Proto->isVariadic(); |
| 3194 |
|
| 3195 |
ExpectedFunctionType |
| 3196 |
= Context.getFunctionType(Context.VoidTy, ArgTypes, EPI); |
| 3197 |
} |
| 3198 |
|
| 3199 |
for (LookupResult::iterator D = FoundDelete.begin(), |
| 3200 |
DEnd = FoundDelete.end(); |
| 3201 |
D != DEnd; ++D) { |
| 3202 |
FunctionDecl *Fn = nullptr; |
| 3203 |
if (FunctionTemplateDecl *FnTmpl = |
| 3204 |
dyn_cast<FunctionTemplateDecl>((*D)->getUnderlyingDecl())) { |
| 3205 |
// Perform template argument deduction to try to match the |
| 3206 |
// expected function type. |
| 3207 |
TemplateDeductionInfo Info(StartLoc); |
| 3208 |
if (DeduceTemplateArguments(FnTmpl, nullptr, ExpectedFunctionType, Fn, |
| 3209 |
Info) != TemplateDeductionResult::Success) |
| 3210 |
continue; |
| 3211 |
} else |
| 3212 |
Fn = cast<FunctionDecl>((*D)->getUnderlyingDecl()); |
| 3213 |
|
| 3214 |
if (Context.hasSameType(adjustCCAndNoReturn(Fn->getType(), |
| 3215 |
ExpectedFunctionType, |
| 3216 |
/*AdjustExcpetionSpec*/true), |
| 3217 |
ExpectedFunctionType)) |
| 3218 |
Matches.push_back(std::make_pair(D.getPair(), Fn)); |
| 3219 |
} |
| 3220 |
|
| 3221 |
if (getLangOpts().CUDA) |
| 3222 |
CUDA().EraseUnwantedMatches(getCurFunctionDecl(/*AllowLambda=*/true), |
| 3223 |
Matches); |
| 3224 |
if (Matches.empty() && isTypeAwareAllocation(IAP.PassTypeIdentity)) { |
| 3225 |
DiagnoseMissingTypeAwareCleanupOperator(isPlacementNew); |
| 3226 |
return true; |
| 3227 |
} |
| 3228 |
} else { |
| 3229 |
// C++1y [expr.new]p22: |
| 3230 |
// For a non-placement allocation function, the normal deallocation |
| 3231 |
// function lookup is used |
| 3232 |
// |
| 3233 |
// Per [expr.delete]p10, this lookup prefers a member operator delete |
| 3234 |
// without a size_t argument, but prefers a non-member operator delete |
| 3235 |
// with a size_t where possible (which it always is in this case). |
| 3236 |
llvm::SmallVector<UsualDeallocFnInfo, 4> BestDeallocFns; |
| 3237 |
ImplicitDeallocationParameters IDP = { |
| 3238 |
AllocElemType, OriginalTypeAwareState, |
| 3239 |
alignedAllocationModeFromBool( |
| 3240 |
hasNewExtendedAlignment(*this, AllocElemType)), |
| 3241 |
sizedDeallocationModeFromBool(FoundGlobalDelete)}; |
| 3242 |
UsualDeallocFnInfo Selected = resolveDeallocationOverload( |
| 3243 |
*this, FoundDelete, IDP, StartLoc, &BestDeallocFns); |
| 3244 |
if (Selected && BestDeallocFns.empty()) |
| 3245 |
Matches.push_back(std::make_pair(Selected.Found, Selected.FD)); |
| 3246 |
else { |
| 3247 |
// If we failed to select an operator, all remaining functions are viable |
| 3248 |
// but ambiguous. |
| 3249 |
for (auto Fn : BestDeallocFns) |
| 3250 |
Matches.push_back(std::make_pair(Fn.Found, Fn.FD)); |
| 3251 |
} |
| 3252 |
} |
| 3253 |
|
| 3254 |
// C++ [expr.new]p20: |
| 3255 |
// [...] If the lookup finds a single matching deallocation |
| 3256 |
// function, that function will be called; otherwise, no |
| 3257 |
// deallocation function will be called. |
| 3258 |
if (Matches.size() == 1) { |
| 3259 |
OperatorDelete = Matches[0].second; |
| 3260 |
DeclContext *OperatorDeleteContext = GetRedeclContext(OperatorDelete); |
| 3261 |
bool FoundTypeAwareOperator = |
| 3262 |
OperatorDelete->isTypeAwareOperatorNewOrDelete() || |
| 3263 |
OperatorNew->isTypeAwareOperatorNewOrDelete(); |
| 3264 |
if (Diagnose && FoundTypeAwareOperator) { |
| 3265 |
bool MismatchedTypeAwareness = |
| 3266 |
OperatorDelete->isTypeAwareOperatorNewOrDelete() != |
| 3267 |
OperatorNew->isTypeAwareOperatorNewOrDelete(); |
| 3268 |
bool MismatchedContext = OperatorDeleteContext != OperatorNewContext; |
| 3269 |
if (MismatchedTypeAwareness || MismatchedContext) { |
| 3270 |
FunctionDecl *Operators[] = {OperatorDelete, OperatorNew}; |
| 3271 |
bool TypeAwareOperatorIndex = |
| 3272 |
OperatorNew->isTypeAwareOperatorNewOrDelete(); |
| 3273 |
Diag(StartLoc, diag::err_mismatching_type_aware_cleanup_deallocator) |
| 3274 |
<< Operators[TypeAwareOperatorIndex]->getDeclName() |
| 3275 |
<< isPlacementNew |
| 3276 |
<< Operators[!TypeAwareOperatorIndex]->getDeclName() |
| 3277 |
<< GetRedeclContext(Operators[TypeAwareOperatorIndex]); |
| 3278 |
Diag(OperatorNew->getLocation(), |
| 3279 |
diag::note_type_aware_operator_declared) |
| 3280 |
<< OperatorNew->isTypeAwareOperatorNewOrDelete() |
| 3281 |
<< OperatorNew->getDeclName() << OperatorNewContext; |
| 3282 |
Diag(OperatorDelete->getLocation(), |
| 3283 |
diag::note_type_aware_operator_declared) |
| 3284 |
<< OperatorDelete->isTypeAwareOperatorNewOrDelete() |
| 3285 |
<< OperatorDelete->getDeclName() << OperatorDeleteContext; |
| 3286 |
} |
| 3287 |
} |
| 3288 |
|
| 3289 |
// C++1z [expr.new]p23: |
| 3290 |
// If the lookup finds a usual deallocation function (3.7.4.2) |
| 3291 |
// with a parameter of type std::size_t and that function, considered |
| 3292 |
// as a placement deallocation function, would have been |
| 3293 |
// selected as a match for the allocation function, the program |
| 3294 |
// is ill-formed. |
| 3295 |
if (getLangOpts().CPlusPlus11 && isPlacementNew && |
| 3296 |
isNonPlacementDeallocationFunction(*this, OperatorDelete)) { |
| 3297 |
UsualDeallocFnInfo Info(*this, |
| 3298 |
DeclAccessPair::make(OperatorDelete, AS_public), |
| 3299 |
AllocElemType, StartLoc); |
| 3300 |
// Core issue, per mail to core reflector, 2016-10-09: |
| 3301 |
// If this is a member operator delete, and there is a corresponding |
| 3302 |
// non-sized member operator delete, this isn't /really/ a sized |
| 3303 |
// deallocation function, it just happens to have a size_t parameter. |
| 3304 |
bool IsSizedDelete = isSizedDeallocation(Info.IDP.PassSize); |
| 3305 |
if (IsSizedDelete && !FoundGlobalDelete) { |
| 3306 |
ImplicitDeallocationParameters SizeTestingIDP = { |
| 3307 |
AllocElemType, Info.IDP.PassTypeIdentity, Info.IDP.PassAlignment, |
| 3308 |
SizedDeallocationMode::No}; |
| 3309 |
auto NonSizedDelete = resolveDeallocationOverload( |
| 3310 |
*this, FoundDelete, SizeTestingIDP, StartLoc); |
| 3311 |
if (NonSizedDelete && |
| 3312 |
!isSizedDeallocation(NonSizedDelete.IDP.PassSize) && |
| 3313 |
NonSizedDelete.IDP.PassAlignment == Info.IDP.PassAlignment) |
| 3314 |
IsSizedDelete = false; |
| 3315 |
} |
| 3316 |
|
| 3317 |
if (IsSizedDelete && !isTypeAwareAllocation(IAP.PassTypeIdentity)) { |
| 3318 |
SourceRange R = PlaceArgs.empty() |
| 3319 |
? SourceRange() |
| 3320 |
: SourceRange(PlaceArgs.front()->getBeginLoc(), |
| 3321 |
PlaceArgs.back()->getEndLoc()); |
| 3322 |
Diag(StartLoc, diag::err_placement_new_non_placement_delete) << R; |
| 3323 |
if (!OperatorDelete->isImplicit()) |
| 3324 |
Diag(OperatorDelete->getLocation(), diag::note_previous_decl) |
| 3325 |
<< DeleteName; |
| 3326 |
} |
| 3327 |
} |
| 3328 |
if (CheckDeleteOperator(*this, StartLoc, Range, Diagnose, |
| 3329 |
FoundDelete.getNamingClass(), Matches[0].first, |
| 3330 |
Matches[0].second)) |
| 3331 |
return true; |
| 3332 |
|
| 3333 |
} else if (!Matches.empty()) { |
| 3334 |
// We found multiple suitable operators. Per [expr.new]p20, that means we |
| 3335 |
// call no 'operator delete' function, but we should at least warn the user. |
| 3336 |
// FIXME: Suppress this warning if the construction cannot throw. |
| 3337 |
Diag(StartLoc, diag::warn_ambiguous_suitable_delete_function_found) |
| 3338 |
<< DeleteName << AllocElemType; |
| 3339 |
|
| 3340 |
for (auto &Match : Matches) |
| 3341 |
Diag(Match.second->getLocation(), |
| 3342 |
diag::note_member_declared_here) << DeleteName; |
| 3343 |
} |
| 3344 |
|
| 3345 |
return false; |
| 3346 |
} |
| 3347 |
|
| 3348 |
void Sema::DeclareGlobalNewDelete() { |
| 3349 |
if (GlobalNewDeleteDeclared) |
| 3350 |
return; |
| 3351 |
|
| 3352 |
// The implicitly declared new and delete operators |
| 3353 |
// are not supported in OpenCL. |
| 3354 |
if (getLangOpts().OpenCLCPlusPlus) |
| 3355 |
return; |
| 3356 |
|
| 3357 |
// C++ [basic.stc.dynamic.general]p2: |
| 3358 |
// The library provides default definitions for the global allocation |
| 3359 |
// and deallocation functions. Some global allocation and deallocation |
| 3360 |
// functions are replaceable ([new.delete]); these are attached to the |
| 3361 |
// global module ([module.unit]). |
| 3362 |
if (getLangOpts().CPlusPlusModules && getCurrentModule()) |
| 3363 |
PushGlobalModuleFragment(SourceLocation()); |
| 3364 |
|
| 3365 |
// C++ [basic.std.dynamic]p2: |
| 3366 |
// [...] The following allocation and deallocation functions (18.4) are |
| 3367 |
// implicitly declared in global scope in each translation unit of a |
| 3368 |
// program |
| 3369 |
// |
| 3370 |
// C++03: |
| 3371 |
// void* operator new(std::size_t) throw(std::bad_alloc); |
| 3372 |
// void* operator new[](std::size_t) throw(std::bad_alloc); |
| 3373 |
// void operator delete(void*) throw(); |
| 3374 |
// void operator delete[](void*) throw(); |
| 3375 |
// C++11: |
| 3376 |
// void* operator new(std::size_t); |
| 3377 |
// void* operator new[](std::size_t); |
| 3378 |
// void operator delete(void*) noexcept; |
| 3379 |
// void operator delete[](void*) noexcept; |
| 3380 |
// C++1y: |
| 3381 |
// void* operator new(std::size_t); |
| 3382 |
// void* operator new[](std::size_t); |
| 3383 |
// void operator delete(void*) noexcept; |
| 3384 |
// void operator delete[](void*) noexcept; |
| 3385 |
// void operator delete(void*, std::size_t) noexcept; |
| 3386 |
// void operator delete[](void*, std::size_t) noexcept; |
| 3387 |
// |
| 3388 |
// These implicit declarations introduce only the function names operator |
| 3389 |
// new, operator new[], operator delete, operator delete[]. |
| 3390 |
// |
| 3391 |
// Here, we need to refer to std::bad_alloc, so we will implicitly declare |
| 3392 |
// "std" or "bad_alloc" as necessary to form the exception specification. |
| 3393 |
// However, we do not make these implicit declarations visible to name |
| 3394 |
// lookup. |
| 3395 |
if (!StdBadAlloc && !getLangOpts().CPlusPlus11) { |
| 3396 |
// The "std::bad_alloc" class has not yet been declared, so build it |
| 3397 |
// implicitly. |
| 3398 |
StdBadAlloc = CXXRecordDecl::Create( |
| 3399 |
Context, TagTypeKind::Class, getOrCreateStdNamespace(), |
| 3400 |
SourceLocation(), SourceLocation(), |
| 3401 |
&PP.getIdentifierTable().get("bad_alloc"), nullptr); |
| 3402 |
getStdBadAlloc()->setImplicit(true); |
| 3403 |
|
| 3404 |
// The implicitly declared "std::bad_alloc" should live in global module |
| 3405 |
// fragment. |
| 3406 |
if (TheGlobalModuleFragment) { |
| 3407 |
getStdBadAlloc()->setModuleOwnershipKind( |
| 3408 |
Decl::ModuleOwnershipKind::ReachableWhenImported); |
| 3409 |
getStdBadAlloc()->setLocalOwningModule(TheGlobalModuleFragment); |
| 3410 |
} |
| 3411 |
} |
| 3412 |
if (!StdAlignValT && getLangOpts().AlignedAllocation) { |
| 3413 |
// The "std::align_val_t" enum class has not yet been declared, so build it |
| 3414 |
// implicitly. |
| 3415 |
auto *AlignValT = EnumDecl::Create( |
| 3416 |
Context, getOrCreateStdNamespace(), SourceLocation(), SourceLocation(), |
| 3417 |
&PP.getIdentifierTable().get("align_val_t"), nullptr, true, true, true); |
| 3418 |
|
| 3419 |
// The implicitly declared "std::align_val_t" should live in global module |
| 3420 |
// fragment. |
| 3421 |
if (TheGlobalModuleFragment) { |
| 3422 |
AlignValT->setModuleOwnershipKind( |
| 3423 |
Decl::ModuleOwnershipKind::ReachableWhenImported); |
| 3424 |
AlignValT->setLocalOwningModule(TheGlobalModuleFragment); |
| 3425 |
} |
| 3426 |
|
| 3427 |
AlignValT->setIntegerType(Context.getSizeType()); |
| 3428 |
AlignValT->setPromotionType(Context.getSizeType()); |
| 3429 |
AlignValT->setImplicit(true); |
| 3430 |
|
| 3431 |
StdAlignValT = AlignValT; |
| 3432 |
} |
| 3433 |
|
| 3434 |
GlobalNewDeleteDeclared = true; |
| 3435 |
|
| 3436 |
QualType VoidPtr = Context.getPointerType(Context.VoidTy); |
| 3437 |
QualType SizeT = Context.getSizeType(); |
| 3438 |
|
| 3439 |
auto DeclareGlobalAllocationFunctions = [&](OverloadedOperatorKind Kind, |
| 3440 |
QualType Return, QualType Param) { |
| 3441 |
llvm::SmallVector<QualType, 3> Params; |
| 3442 |
Params.push_back(Param); |
| 3443 |
|
| 3444 |
// Create up to four variants of the function (sized/aligned). |
| 3445 |
bool HasSizedVariant = getLangOpts().SizedDeallocation && |
| 3446 |
(Kind == OO_Delete || Kind == OO_Array_Delete); |
| 3447 |
bool HasAlignedVariant = getLangOpts().AlignedAllocation; |
| 3448 |
|
| 3449 |
int NumSizeVariants = (HasSizedVariant ? 2 : 1); |
| 3450 |
int NumAlignVariants = (HasAlignedVariant ? 2 : 1); |
| 3451 |
for (int Sized = 0; Sized < NumSizeVariants; ++Sized) { |
| 3452 |
if (Sized) |
| 3453 |
Params.push_back(SizeT); |
| 3454 |
|
| 3455 |
for (int Aligned = 0; Aligned < NumAlignVariants; ++Aligned) { |
| 3456 |
if (Aligned) |
| 3457 |
Params.push_back(Context.getCanonicalTagType(getStdAlignValT())); |
| 3458 |
|
| 3459 |
DeclareGlobalAllocationFunction( |
| 3460 |
Context.DeclarationNames.getCXXOperatorName(Kind), Return, Params); |
| 3461 |
|
| 3462 |
if (Aligned) |
| 3463 |
Params.pop_back(); |
| 3464 |
} |
| 3465 |
} |
| 3466 |
}; |
| 3467 |
|
| 3468 |
DeclareGlobalAllocationFunctions(OO_New, VoidPtr, SizeT); |
| 3469 |
DeclareGlobalAllocationFunctions(OO_Array_New, VoidPtr, SizeT); |
| 3470 |
DeclareGlobalAllocationFunctions(OO_Delete, Context.VoidTy, VoidPtr); |
| 3471 |
DeclareGlobalAllocationFunctions(OO_Array_Delete, Context.VoidTy, VoidPtr); |
| 3472 |
|
| 3473 |
if (getLangOpts().CPlusPlusModules && getCurrentModule()) |
| 3474 |
PopGlobalModuleFragment(); |
| 3475 |
} |
| 3476 |
|
| 3477 |
/// DeclareGlobalAllocationFunction - Declares a single implicit global |
| 3478 |
/// allocation function if it doesn't already exist. |
| 3479 |
void Sema::DeclareGlobalAllocationFunction(DeclarationName Name, |
| 3480 |
QualType Return, |
| 3481 |
ArrayRef<QualType> Params) { |
| 3482 |
DeclContext *GlobalCtx = Context.getTranslationUnitDecl(); |
| 3483 |
|
| 3484 |
// Check if this function is already declared. |
| 3485 |
DeclContext::lookup_result R = GlobalCtx->lookup(Name); |
| 3486 |
for (DeclContext::lookup_iterator Alloc = R.begin(), AllocEnd = R.end(); |
| 3487 |
Alloc != AllocEnd; ++Alloc) { |
| 3488 |
// Only look at non-template functions, as it is the predefined, |
| 3489 |
// non-templated allocation function we are trying to declare here. |
| 3490 |
if (FunctionDecl *Func = dyn_cast<FunctionDecl>(*Alloc)) { |
| 3491 |
if (Func->getNumParams() == Params.size()) { |
| 3492 |
if (std::equal(Func->param_begin(), Func->param_end(), Params.begin(), |
| 3493 |
Params.end(), [&](ParmVarDecl *D, QualType RT) { |
| 3494 |
return Context.hasSameUnqualifiedType(D->getType(), |
| 3495 |
RT); |
| 3496 |
})) { |
| 3497 |
// Make the function visible to name lookup, even if we found it in |
| 3498 |
// an unimported module. It either is an implicitly-declared global |
| 3499 |
// allocation function, or is suppressing that function. |
| 3500 |
Func->setVisibleDespiteOwningModule(); |
| 3501 |
return; |
| 3502 |
} |
| 3503 |
} |
| 3504 |
} |
| 3505 |
} |
| 3506 |
|
| 3507 |
FunctionProtoType::ExtProtoInfo EPI( |
| 3508 |
Context.getTargetInfo().getDefaultCallingConv()); |
| 3509 |
|
| 3510 |
QualType BadAllocType; |
| 3511 |
bool HasBadAllocExceptionSpec = Name.isAnyOperatorNew(); |
| 3512 |
if (HasBadAllocExceptionSpec) { |
| 3513 |
if (!getLangOpts().CPlusPlus11) { |
| 3514 |
BadAllocType = Context.getCanonicalTagType(getStdBadAlloc()); |
| 3515 |
assert(StdBadAlloc && "Must have std::bad_alloc declared"); |
| 3516 |
EPI.ExceptionSpec.Type = EST_Dynamic; |
| 3517 |
EPI.ExceptionSpec.Exceptions = llvm::ArrayRef(BadAllocType); |
| 3518 |
} |
| 3519 |
if (getLangOpts().NewInfallible) { |
| 3520 |
EPI.ExceptionSpec.Type = EST_DynamicNone; |
| 3521 |
} |
| 3522 |
} else { |
| 3523 |
EPI.ExceptionSpec = |
| 3524 |
getLangOpts().CPlusPlus11 ? EST_BasicNoexcept : EST_DynamicNone; |
| 3525 |
} |
| 3526 |
|
| 3527 |
auto CreateAllocationFunctionDecl = [&](Attr *ExtraAttr) { |
| 3528 |
// The MSVC STL has explicit cdecl on its (host-side) allocation function |
| 3529 |
// specializations for the allocation, so in order to prevent a CC clash |
| 3530 |
// we use the host's CC, if available, or CC_C as a fallback, for the |
| 3531 |
// host-side implicit decls, knowing these do not get emitted when compiling |
| 3532 |
// for device. |
| 3533 |
if (getLangOpts().CUDAIsDevice && ExtraAttr && |
| 3534 |
isa<CUDAHostAttr>(ExtraAttr) && |
| 3535 |
Context.getTargetInfo().getTriple().isSPIRV()) { |
| 3536 |
if (auto *ATI = Context.getAuxTargetInfo()) |
| 3537 |
EPI.ExtInfo = EPI.ExtInfo.withCallingConv(ATI->getDefaultCallingConv()); |
| 3538 |
else |
| 3539 |
EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallingConv::CC_C); |
| 3540 |
} |
| 3541 |
QualType FnType = Context.getFunctionType(Return, Params, EPI); |
| 3542 |
FunctionDecl *Alloc = FunctionDecl::Create( |
| 3543 |
Context, GlobalCtx, SourceLocation(), SourceLocation(), Name, FnType, |
| 3544 |
/*TInfo=*/nullptr, SC_None, getCurFPFeatures().isFPConstrained(), false, |
| 3545 |
true); |
| 3546 |
Alloc->setImplicit(); |
| 3547 |
// Global allocation functions should always be visible. |
| 3548 |
Alloc->setVisibleDespiteOwningModule(); |
| 3549 |
|
| 3550 |
if (HasBadAllocExceptionSpec && getLangOpts().NewInfallible && |
| 3551 |
!getLangOpts().CheckNew) |
| 3552 |
Alloc->addAttr( |
| 3553 |
ReturnsNonNullAttr::CreateImplicit(Context, Alloc->getLocation())); |
| 3554 |
|
| 3555 |
// C++ [basic.stc.dynamic.general]p2: |
| 3556 |
// The library provides default definitions for the global allocation |
| 3557 |
// and deallocation functions. Some global allocation and deallocation |
| 3558 |
// functions are replaceable ([new.delete]); these are attached to the |
| 3559 |
// global module ([module.unit]). |
| 3560 |
// |
| 3561 |
// In the language wording, these functions are attched to the global |
| 3562 |
// module all the time. But in the implementation, the global module |
| 3563 |
// is only meaningful when we're in a module unit. So here we attach |
| 3564 |
// these allocation functions to global module conditionally. |
| 3565 |
if (TheGlobalModuleFragment) { |
| 3566 |
Alloc->setModuleOwnershipKind( |
| 3567 |
Decl::ModuleOwnershipKind::ReachableWhenImported); |
| 3568 |
Alloc->setLocalOwningModule(TheGlobalModuleFragment); |
| 3569 |
} |
| 3570 |
|
| 3571 |
if (LangOpts.hasGlobalAllocationFunctionVisibility()) |
| 3572 |
Alloc->addAttr(VisibilityAttr::CreateImplicit( |
| 3573 |
Context, LangOpts.hasHiddenGlobalAllocationFunctionVisibility() |
| 3574 |
? VisibilityAttr::Hidden |
| 3575 |
: LangOpts.hasProtectedGlobalAllocationFunctionVisibility() |
| 3576 |
? VisibilityAttr::Protected |
| 3577 |
: VisibilityAttr::Default)); |
| 3578 |
|
| 3579 |
llvm::SmallVector<ParmVarDecl *, 3> ParamDecls; |
| 3580 |
for (QualType T : Params) { |
| 3581 |
ParamDecls.push_back(ParmVarDecl::Create( |
| 3582 |
Context, Alloc, SourceLocation(), SourceLocation(), nullptr, T, |
| 3583 |
/*TInfo=*/nullptr, SC_None, nullptr)); |
| 3584 |
ParamDecls.back()->setImplicit(); |
| 3585 |
} |
| 3586 |
Alloc->setParams(ParamDecls); |
| 3587 |
if (ExtraAttr) |
| 3588 |
Alloc->addAttr(ExtraAttr); |
| 3589 |
AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(Alloc); |
| 3590 |
Context.getTranslationUnitDecl()->addDecl(Alloc); |
| 3591 |
IdResolver.tryAddTopLevelDecl(Alloc, Name); |
| 3592 |
}; |
| 3593 |
|
| 3594 |
if (!LangOpts.CUDA) |
| 3595 |
CreateAllocationFunctionDecl(nullptr); |
| 3596 |
else { |
| 3597 |
// Host and device get their own declaration so each can be |
| 3598 |
// defined or re-declared independently. |
| 3599 |
CreateAllocationFunctionDecl(CUDAHostAttr::CreateImplicit(Context)); |
| 3600 |
CreateAllocationFunctionDecl(CUDADeviceAttr::CreateImplicit(Context)); |
| 3601 |
} |
| 3602 |
} |
| 3603 |
|
| 3604 |
FunctionDecl * |
| 3605 |
Sema::FindUsualDeallocationFunction(SourceLocation StartLoc, |
| 3606 |
ImplicitDeallocationParameters IDP, |
| 3607 |
DeclarationName Name, bool Diagnose) { |
| 3608 |
DeclareGlobalNewDelete(); |
| 3609 |
|
| 3610 |
LookupResult FoundDelete(*this, Name, StartLoc, LookupOrdinaryName); |
| 3611 |
LookupGlobalDeallocationFunctions(*this, StartLoc, FoundDelete, |
| 3612 |
DeallocLookupMode::OptionallyTyped, Name); |
| 3613 |
|
| 3614 |
// FIXME: It's possible for this to result in ambiguity, through a |
| 3615 |
// user-declared variadic operator delete or the enable_if attribute. We |
| 3616 |
// should probably not consider those cases to be usual deallocation |
| 3617 |
// functions. But for now we just make an arbitrary choice in that case. |
| 3618 |
auto Result = resolveDeallocationOverload(*this, FoundDelete, IDP, StartLoc); |
| 3619 |
if (!Result) |
| 3620 |
return nullptr; |
| 3621 |
|
| 3622 |
if (CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose, |
| 3623 |
FoundDelete.getNamingClass(), Result.Found, |
| 3624 |
Result.FD)) |
| 3625 |
return nullptr; |
| 3626 |
|
| 3627 |
assert(Result.FD && "operator delete missing from global scope?"); |
| 3628 |
return Result.FD; |
| 3629 |
} |
| 3630 |
|
| 3631 |
FunctionDecl *Sema::FindDeallocationFunctionForDestructor( |
| 3632 |
SourceLocation Loc, CXXRecordDecl *RD, bool Diagnose, bool LookForGlobal, |
| 3633 |
DeclarationName Name) { |
| 3634 |
|
| 3635 |
FunctionDecl *OperatorDelete = nullptr; |
| 3636 |
CanQualType DeallocType = Context.getCanonicalTagType(RD); |
| 3637 |
ImplicitDeallocationParameters IDP = { |
| 3638 |
DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(), |
| 3639 |
AlignedAllocationMode::No, SizedDeallocationMode::No}; |
| 3640 |
|
| 3641 |
if (!LookForGlobal) { |
| 3642 |
if (FindDeallocationFunction(Loc, RD, Name, OperatorDelete, IDP, Diagnose)) |
| 3643 |
return nullptr; |
| 3644 |
|
| 3645 |
if (OperatorDelete) |
| 3646 |
return OperatorDelete; |
| 3647 |
} |
| 3648 |
|
| 3649 |
// If there's no class-specific operator delete, look up the global |
| 3650 |
// non-array delete. |
| 3651 |
IDP.PassAlignment = alignedAllocationModeFromBool( |
| 3652 |
hasNewExtendedAlignment(*this, DeallocType)); |
| 3653 |
IDP.PassSize = SizedDeallocationMode::Yes; |
| 3654 |
return FindUsualDeallocationFunction(Loc, IDP, Name, Diagnose); |
| 3655 |
} |
| 3656 |
|
| 3657 |
bool Sema::FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, |
| 3658 |
DeclarationName Name, |
| 3659 |
FunctionDecl *&Operator, |
| 3660 |
ImplicitDeallocationParameters IDP, |
| 3661 |
bool Diagnose) { |
| 3662 |
LookupResult Found(*this, Name, StartLoc, LookupOrdinaryName); |
| 3663 |
// Try to find operator delete/operator delete[] in class scope. |
| 3664 |
LookupQualifiedName(Found, RD); |
| 3665 |
|
| 3666 |
if (Found.isAmbiguous()) { |
| 3667 |
if (!Diagnose) |
| 3668 |
Found.suppressDiagnostics(); |
| 3669 |
return true; |
| 3670 |
} |
| 3671 |
|
| 3672 |
Found.suppressDiagnostics(); |
| 3673 |
|
| 3674 |
if (!isAlignedAllocation(IDP.PassAlignment) && |
| 3675 |
hasNewExtendedAlignment(*this, Context.getCanonicalTagType(RD))) |
| 3676 |
IDP.PassAlignment = AlignedAllocationMode::Yes; |
| 3677 |
|
| 3678 |
// C++17 [expr.delete]p10: |
| 3679 |
// If the deallocation functions have class scope, the one without a |
| 3680 |
// parameter of type std::size_t is selected. |
| 3681 |
llvm::SmallVector<UsualDeallocFnInfo, 4> Matches; |
| 3682 |
resolveDeallocationOverload(*this, Found, IDP, StartLoc, &Matches); |
| 3683 |
|
| 3684 |
// If we could find an overload, use it. |
| 3685 |
if (Matches.size() == 1) { |
| 3686 |
Operator = cast<CXXMethodDecl>(Matches[0].FD); |
| 3687 |
return CheckDeleteOperator(*this, StartLoc, StartLoc, Diagnose, |
| 3688 |
Found.getNamingClass(), Matches[0].Found, |
| 3689 |
Operator); |
| 3690 |
} |
| 3691 |
|
| 3692 |
// We found multiple suitable operators; complain about the ambiguity. |
| 3693 |
// FIXME: The standard doesn't say to do this; it appears that the intent |
| 3694 |
// is that this should never happen. |
| 3695 |
if (!Matches.empty()) { |
| 3696 |
if (Diagnose) { |
| 3697 |
Diag(StartLoc, diag::err_ambiguous_suitable_delete_member_function_found) |
| 3698 |
<< Name << RD; |
| 3699 |
for (auto &Match : Matches) |
| 3700 |
Diag(Match.FD->getLocation(), diag::note_member_declared_here) << Name; |
| 3701 |
} |
| 3702 |
return true; |
| 3703 |
} |
| 3704 |
|
| 3705 |
// We did find operator delete/operator delete[] declarations, but |
| 3706 |
// none of them were suitable. |
| 3707 |
if (!Found.empty()) { |
| 3708 |
if (Diagnose) { |
| 3709 |
Diag(StartLoc, diag::err_no_suitable_delete_member_function_found) |
| 3710 |
<< Name << RD; |
| 3711 |
|
| 3712 |
for (NamedDecl *D : Found) |
| 3713 |
Diag(D->getUnderlyingDecl()->getLocation(), |
| 3714 |
diag::note_member_declared_here) << Name; |
| 3715 |
} |
| 3716 |
return true; |
| 3717 |
} |
| 3718 |
|
| 3719 |
Operator = nullptr; |
| 3720 |
return false; |
| 3721 |
} |
| 3722 |
|
| 3723 |
namespace { |
| 3724 |
/// Checks whether delete-expression, and new-expression used for |
| 3725 |
/// initializing deletee have the same array form. |
| 3726 |
class MismatchingNewDeleteDetector { |
| 3727 |
public: |
| 3728 |
enum MismatchResult { |
| 3729 |
/// Indicates that there is no mismatch or a mismatch cannot be proven. |
| 3730 |
NoMismatch, |
| 3731 |
/// Indicates that variable is initialized with mismatching form of \a new. |
| 3732 |
VarInitMismatches, |
| 3733 |
/// Indicates that member is initialized with mismatching form of \a new. |
| 3734 |
MemberInitMismatches, |
| 3735 |
/// Indicates that 1 or more constructors' definitions could not been |
| 3736 |
/// analyzed, and they will be checked again at the end of translation unit. |
| 3737 |
AnalyzeLater |
| 3738 |
}; |
| 3739 |
|
| 3740 |
/// \param EndOfTU True, if this is the final analysis at the end of |
| 3741 |
/// translation unit. False, if this is the initial analysis at the point |
| 3742 |
/// delete-expression was encountered. |
| 3743 |
explicit MismatchingNewDeleteDetector(bool EndOfTU) |
| 3744 |
: Field(nullptr), IsArrayForm(false), EndOfTU(EndOfTU), |
| 3745 |
HasUndefinedConstructors(false) {} |
| 3746 |
|
| 3747 |
/// Checks whether pointee of a delete-expression is initialized with |
| 3748 |
/// matching form of new-expression. |
| 3749 |
/// |
| 3750 |
/// If return value is \c VarInitMismatches or \c MemberInitMismatches at the |
| 3751 |
/// point where delete-expression is encountered, then a warning will be |
| 3752 |
/// issued immediately. If return value is \c AnalyzeLater at the point where |
| 3753 |
/// delete-expression is seen, then member will be analyzed at the end of |
| 3754 |
/// translation unit. \c AnalyzeLater is returned iff at least one constructor |
| 3755 |
/// couldn't be analyzed. If at least one constructor initializes the member |
| 3756 |
/// with matching type of new, the return value is \c NoMismatch. |
| 3757 |
MismatchResult analyzeDeleteExpr(const CXXDeleteExpr *DE); |
| 3758 |
/// Analyzes a class member. |
| 3759 |
/// \param Field Class member to analyze. |
| 3760 |
/// \param DeleteWasArrayForm Array form-ness of the delete-expression used |
| 3761 |
/// for deleting the \p Field. |
| 3762 |
MismatchResult analyzeField(FieldDecl *Field, bool DeleteWasArrayForm); |
| 3763 |
FieldDecl *Field; |
| 3764 |
/// List of mismatching new-expressions used for initialization of the pointee |
| 3765 |
llvm::SmallVector<const CXXNewExpr *, 4> NewExprs; |
| 3766 |
/// Indicates whether delete-expression was in array form. |
| 3767 |
bool IsArrayForm; |
| 3768 |
|
| 3769 |
private: |
| 3770 |
const bool EndOfTU; |
| 3771 |
/// Indicates that there is at least one constructor without body. |
| 3772 |
bool HasUndefinedConstructors; |
| 3773 |
/// Returns \c CXXNewExpr from given initialization expression. |
| 3774 |
/// \param E Expression used for initializing pointee in delete-expression. |
| 3775 |
/// E can be a single-element \c InitListExpr consisting of new-expression. |
| 3776 |
const CXXNewExpr *getNewExprFromInitListOrExpr(const Expr *E); |
| 3777 |
/// Returns whether member is initialized with mismatching form of |
| 3778 |
/// \c new either by the member initializer or in-class initialization. |
| 3779 |
/// |
| 3780 |
/// If bodies of all constructors are not visible at the end of translation |
| 3781 |
/// unit or at least one constructor initializes member with the matching |
| 3782 |
/// form of \c new, mismatch cannot be proven, and this function will return |
| 3783 |
/// \c NoMismatch. |
| 3784 |
MismatchResult analyzeMemberExpr(const MemberExpr *ME); |
| 3785 |
/// Returns whether variable is initialized with mismatching form of |
| 3786 |
/// \c new. |
| 3787 |
/// |
| 3788 |
/// If variable is initialized with matching form of \c new or variable is not |
| 3789 |
/// initialized with a \c new expression, this function will return true. |
| 3790 |
/// If variable is initialized with mismatching form of \c new, returns false. |
| 3791 |
/// \param D Variable to analyze. |
| 3792 |
bool hasMatchingVarInit(const DeclRefExpr *D); |
| 3793 |
/// Checks whether the constructor initializes pointee with mismatching |
| 3794 |
/// form of \c new. |
| 3795 |
/// |
| 3796 |
/// Returns true, if member is initialized with matching form of \c new in |
| 3797 |
/// member initializer list. Returns false, if member is initialized with the |
| 3798 |
/// matching form of \c new in this constructor's initializer or given |
| 3799 |
/// constructor isn't defined at the point where delete-expression is seen, or |
| 3800 |
/// member isn't initialized by the constructor. |
| 3801 |
bool hasMatchingNewInCtor(const CXXConstructorDecl *CD); |
| 3802 |
/// Checks whether member is initialized with matching form of |
| 3803 |
/// \c new in member initializer list. |
| 3804 |
bool hasMatchingNewInCtorInit(const CXXCtorInitializer *CI); |
| 3805 |
/// Checks whether member is initialized with mismatching form of \c new by |
| 3806 |
/// in-class initializer. |
| 3807 |
MismatchResult analyzeInClassInitializer(); |
| 3808 |
}; |
| 3809 |
} |
| 3810 |
|
| 3811 |
MismatchingNewDeleteDetector::MismatchResult |
| 3812 |
MismatchingNewDeleteDetector::analyzeDeleteExpr(const CXXDeleteExpr *DE) { |
| 3813 |
NewExprs.clear(); |
| 3814 |
assert(DE && "Expected delete-expression"); |
| 3815 |
IsArrayForm = DE->isArrayForm(); |
| 3816 |
const Expr *E = DE->getArgument()->IgnoreParenImpCasts(); |
| 3817 |
if (const MemberExpr *ME = dyn_cast<const MemberExpr>(E)) { |
| 3818 |
return analyzeMemberExpr(ME); |
| 3819 |
} else if (const DeclRefExpr *D = dyn_cast<const DeclRefExpr>(E)) { |
| 3820 |
if (!hasMatchingVarInit(D)) |
| 3821 |
return VarInitMismatches; |
| 3822 |
} |
| 3823 |
return NoMismatch; |
| 3824 |
} |
| 3825 |
|
| 3826 |
const CXXNewExpr * |
| 3827 |
MismatchingNewDeleteDetector::getNewExprFromInitListOrExpr(const Expr *E) { |
| 3828 |
assert(E != nullptr && "Expected a valid initializer expression"); |
| 3829 |
E = E->IgnoreParenImpCasts(); |
| 3830 |
if (const InitListExpr *ILE = dyn_cast<const InitListExpr>(E)) { |
| 3831 |
if (ILE->getNumInits() == 1) |
| 3832 |
E = dyn_cast<const CXXNewExpr>(ILE->getInit(0)->IgnoreParenImpCasts()); |
| 3833 |
} |
| 3834 |
|
| 3835 |
return dyn_cast_or_null<const CXXNewExpr>(E); |
| 3836 |
} |
| 3837 |
|
| 3838 |
bool MismatchingNewDeleteDetector::hasMatchingNewInCtorInit( |
| 3839 |
const CXXCtorInitializer *CI) { |
| 3840 |
const CXXNewExpr *NE = nullptr; |
| 3841 |
if (Field == CI->getMember() && |
| 3842 |
(NE = getNewExprFromInitListOrExpr(CI->getInit()))) { |
| 3843 |
if (NE->isArray() == IsArrayForm) |
| 3844 |
return true; |
| 3845 |
else |
| 3846 |
NewExprs.push_back(NE); |
| 3847 |
} |
| 3848 |
return false; |
| 3849 |
} |
| 3850 |
|
| 3851 |
bool MismatchingNewDeleteDetector::hasMatchingNewInCtor( |
| 3852 |
const CXXConstructorDecl *CD) { |
| 3853 |
if (CD->isImplicit()) |
| 3854 |
return false; |
| 3855 |
const FunctionDecl *Definition = CD; |
| 3856 |
if (!CD->isThisDeclarationADefinition() && !CD->isDefined(Definition)) { |
| 3857 |
HasUndefinedConstructors = true; |
| 3858 |
return EndOfTU; |
| 3859 |
} |
| 3860 |
for (const auto *CI : cast<const CXXConstructorDecl>(Definition)->inits()) { |
| 3861 |
if (hasMatchingNewInCtorInit(CI)) |
| 3862 |
return true; |
| 3863 |
} |
| 3864 |
return false; |
| 3865 |
} |
| 3866 |
|
| 3867 |
MismatchingNewDeleteDetector::MismatchResult |
| 3868 |
MismatchingNewDeleteDetector::analyzeInClassInitializer() { |
| 3869 |
assert(Field != nullptr && "This should be called only for members"); |
| 3870 |
const Expr *InitExpr = Field->getInClassInitializer(); |
| 3871 |
if (!InitExpr) |
| 3872 |
return EndOfTU ? NoMismatch : AnalyzeLater; |
| 3873 |
if (const CXXNewExpr *NE = getNewExprFromInitListOrExpr(InitExpr)) { |
| 3874 |
if (NE->isArray() != IsArrayForm) { |
| 3875 |
NewExprs.push_back(NE); |
| 3876 |
return MemberInitMismatches; |
| 3877 |
} |
| 3878 |
} |
| 3879 |
return NoMismatch; |
| 3880 |
} |
| 3881 |
|
| 3882 |
MismatchingNewDeleteDetector::MismatchResult |
| 3883 |
MismatchingNewDeleteDetector::analyzeField(FieldDecl *Field, |
| 3884 |
bool DeleteWasArrayForm) { |
| 3885 |
assert(Field != nullptr && "Analysis requires a valid class member."); |
| 3886 |
this->Field = Field; |
| 3887 |
IsArrayForm = DeleteWasArrayForm; |
| 3888 |
const CXXRecordDecl *RD = cast<const CXXRecordDecl>(Field->getParent()); |
| 3889 |
for (const auto *CD : RD->ctors()) { |
| 3890 |
if (hasMatchingNewInCtor(CD)) |
| 3891 |
return NoMismatch; |
| 3892 |
} |
| 3893 |
if (HasUndefinedConstructors) |
| 3894 |
return EndOfTU ? NoMismatch : AnalyzeLater; |
| 3895 |
if (!NewExprs.empty()) |
| 3896 |
return MemberInitMismatches; |
| 3897 |
return Field->hasInClassInitializer() ? analyzeInClassInitializer() |
| 3898 |
: NoMismatch; |
| 3899 |
} |
| 3900 |
|
| 3901 |
MismatchingNewDeleteDetector::MismatchResult |
| 3902 |
MismatchingNewDeleteDetector::analyzeMemberExpr(const MemberExpr *ME) { |
| 3903 |
assert(ME != nullptr && "Expected a member expression"); |
| 3904 |
if (FieldDecl *F = dyn_cast<FieldDecl>(ME->getMemberDecl())) |
| 3905 |
return analyzeField(F, IsArrayForm); |
| 3906 |
return NoMismatch; |
| 3907 |
} |
| 3908 |
|
| 3909 |
bool MismatchingNewDeleteDetector::hasMatchingVarInit(const DeclRefExpr *D) { |
| 3910 |
const CXXNewExpr *NE = nullptr; |
| 3911 |
if (const VarDecl *VD = dyn_cast<const VarDecl>(D->getDecl())) { |
| 3912 |
if (VD->hasInit() && (NE = getNewExprFromInitListOrExpr(VD->getInit())) && |
| 3913 |
NE->isArray() != IsArrayForm) { |
| 3914 |
NewExprs.push_back(NE); |
| 3915 |
} |
| 3916 |
} |
| 3917 |
return NewExprs.empty(); |
| 3918 |
} |
| 3919 |
|
| 3920 |
static void |
| 3921 |
DiagnoseMismatchedNewDelete(Sema &SemaRef, SourceLocation DeleteLoc, |
| 3922 |
const MismatchingNewDeleteDetector &Detector) { |
| 3923 |
SourceLocation EndOfDelete = SemaRef.getLocForEndOfToken(DeleteLoc); |
| 3924 |
FixItHint H; |
| 3925 |
if (!Detector.IsArrayForm) |
| 3926 |
H = FixItHint::CreateInsertion(EndOfDelete, "[]"); |
| 3927 |
else { |
| 3928 |
SourceLocation RSquare = Lexer::findLocationAfterToken( |
| 3929 |
DeleteLoc, tok::l_square, SemaRef.getSourceManager(), |
| 3930 |
SemaRef.getLangOpts(), true); |
| 3931 |
if (RSquare.isValid()) |
| 3932 |
H = FixItHint::CreateRemoval(SourceRange(EndOfDelete, RSquare)); |
| 3933 |
} |
| 3934 |
SemaRef.Diag(DeleteLoc, diag::warn_mismatched_delete_new) |
| 3935 |
<< Detector.IsArrayForm << H; |
| 3936 |
|
| 3937 |
for (const auto *NE : Detector.NewExprs) |
| 3938 |
SemaRef.Diag(NE->getExprLoc(), diag::note_allocated_here) |
| 3939 |
<< Detector.IsArrayForm; |
| 3940 |
} |
| 3941 |
|
| 3942 |
void Sema::AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE) { |
| 3943 |
if (Diags.isIgnored(diag::warn_mismatched_delete_new, SourceLocation())) |
| 3944 |
return; |
| 3945 |
MismatchingNewDeleteDetector Detector(/*EndOfTU=*/false); |
| 3946 |
switch (Detector.analyzeDeleteExpr(DE)) { |
| 3947 |
case MismatchingNewDeleteDetector::VarInitMismatches: |
| 3948 |
case MismatchingNewDeleteDetector::MemberInitMismatches: { |
| 3949 |
DiagnoseMismatchedNewDelete(*this, DE->getBeginLoc(), Detector); |
| 3950 |
break; |
| 3951 |
} |
| 3952 |
case MismatchingNewDeleteDetector::AnalyzeLater: { |
| 3953 |
DeleteExprs[Detector.Field].push_back( |
| 3954 |
std::make_pair(DE->getBeginLoc(), DE->isArrayForm())); |
| 3955 |
break; |
| 3956 |
} |
| 3957 |
case MismatchingNewDeleteDetector::NoMismatch: |
| 3958 |
break; |
| 3959 |
} |
| 3960 |
} |
| 3961 |
|
| 3962 |
void Sema::AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, |
| 3963 |
bool DeleteWasArrayForm) { |
| 3964 |
MismatchingNewDeleteDetector Detector(/*EndOfTU=*/true); |
| 3965 |
switch (Detector.analyzeField(Field, DeleteWasArrayForm)) { |
| 3966 |
case MismatchingNewDeleteDetector::VarInitMismatches: |
| 3967 |
llvm_unreachable("This analysis should have been done for class members."); |
| 3968 |
case MismatchingNewDeleteDetector::AnalyzeLater: |
| 3969 |
llvm_unreachable("Analysis cannot be postponed any point beyond end of " |
| 3970 |
"translation unit."); |
| 3971 |
case MismatchingNewDeleteDetector::MemberInitMismatches: |
| 3972 |
DiagnoseMismatchedNewDelete(*this, DeleteLoc, Detector); |
| 3973 |
break; |
| 3974 |
case MismatchingNewDeleteDetector::NoMismatch: |
| 3975 |
break; |
| 3976 |
} |
| 3977 |
} |
| 3978 |
|
| 3979 |
ExprResult |
| 3980 |
Sema::ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, |
| 3981 |
bool ArrayForm, Expr *ExE) { |
| 3982 |
// C++ [expr.delete]p1: |
| 3983 |
// The operand shall have a pointer type, or a class type having a single |
| 3984 |
// non-explicit conversion function to a pointer type. The result has type |
| 3985 |
// void. |
| 3986 |
// |
| 3987 |
// DR599 amends "pointer type" to "pointer to object type" in both cases. |
| 3988 |
|
| 3989 |
ExprResult Ex = ExE; |
| 3990 |
FunctionDecl *OperatorDelete = nullptr; |
| 3991 |
bool ArrayFormAsWritten = ArrayForm; |
| 3992 |
bool UsualArrayDeleteWantsSize = false; |
| 3993 |
|
| 3994 |
if (!Ex.get()->isTypeDependent()) { |
| 3995 |
// Perform lvalue-to-rvalue cast, if needed. |
| 3996 |
Ex = DefaultLvalueConversion(Ex.get()); |
| 3997 |
if (Ex.isInvalid()) |
| 3998 |
return ExprError(); |
| 3999 |
|
| 4000 |
QualType Type = Ex.get()->getType(); |
| 4001 |
|
| 4002 |
class DeleteConverter : public ContextualImplicitConverter { |
| 4003 |
public: |
| 4004 |
DeleteConverter() : ContextualImplicitConverter(false, true) {} |
| 4005 |
|
| 4006 |
bool match(QualType ConvType) override { |
| 4007 |
// FIXME: If we have an operator T* and an operator void*, we must pick |
| 4008 |
// the operator T*. |
| 4009 |
if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) |
| 4010 |
if (ConvPtrType->getPointeeType()->isIncompleteOrObjectType()) |
| 4011 |
return true; |
| 4012 |
return false; |
| 4013 |
} |
| 4014 |
|
| 4015 |
SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, |
| 4016 |
QualType T) override { |
| 4017 |
return S.Diag(Loc, diag::err_delete_operand) << T; |
| 4018 |
} |
| 4019 |
|
| 4020 |
SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, |
| 4021 |
QualType T) override { |
| 4022 |
return S.Diag(Loc, diag::err_delete_incomplete_class_type) << T; |
| 4023 |
} |
| 4024 |
|
| 4025 |
SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, |
| 4026 |
QualType T, |
| 4027 |
QualType ConvTy) override { |
| 4028 |
return S.Diag(Loc, diag::err_delete_explicit_conversion) << T << ConvTy; |
| 4029 |
} |
| 4030 |
|
| 4031 |
SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, |
| 4032 |
QualType ConvTy) override { |
| 4033 |
return S.Diag(Conv->getLocation(), diag::note_delete_conversion) |
| 4034 |
<< ConvTy; |
| 4035 |
} |
| 4036 |
|
| 4037 |
SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, |
| 4038 |
QualType T) override { |
| 4039 |
return S.Diag(Loc, diag::err_ambiguous_delete_operand) << T; |
| 4040 |
} |
| 4041 |
|
| 4042 |
SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, |
| 4043 |
QualType ConvTy) override { |
| 4044 |
return S.Diag(Conv->getLocation(), diag::note_delete_conversion) |
| 4045 |
<< ConvTy; |
| 4046 |
} |
| 4047 |
|
| 4048 |
SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, |
| 4049 |
QualType T, |
| 4050 |
QualType ConvTy) override { |
| 4051 |
llvm_unreachable("conversion functions are permitted"); |
| 4052 |
} |
| 4053 |
} Converter; |
| 4054 |
|
| 4055 |
Ex = PerformContextualImplicitConversion(StartLoc, Ex.get(), Converter); |
| 4056 |
if (Ex.isInvalid()) |
| 4057 |
return ExprError(); |
| 4058 |
Type = Ex.get()->getType(); |
| 4059 |
if (!Converter.match(Type)) |
| 4060 |
// FIXME: PerformContextualImplicitConversion should return ExprError |
| 4061 |
// itself in this case. |
| 4062 |
return ExprError(); |
| 4063 |
|
| 4064 |
QualType Pointee = Type->castAs<PointerType>()->getPointeeType(); |
| 4065 |
QualType PointeeElem = Context.getBaseElementType(Pointee); |
| 4066 |
|
| 4067 |
if (Pointee.getAddressSpace() != LangAS::Default && |
| 4068 |
!getLangOpts().OpenCLCPlusPlus) |
| 4069 |
return Diag(Ex.get()->getBeginLoc(), |
| 4070 |
diag::err_address_space_qualified_delete) |
| 4071 |
<< Pointee.getUnqualifiedType() |
| 4072 |
<< Pointee.getQualifiers().getAddressSpaceAttributePrintValue(); |
| 4073 |
|
| 4074 |
CXXRecordDecl *PointeeRD = nullptr; |
| 4075 |
if (Pointee->isVoidType() && !isSFINAEContext()) { |
| 4076 |
// The C++ standard bans deleting a pointer to a non-object type, which |
| 4077 |
// effectively bans deletion of "void*". However, most compilers support |
| 4078 |
// this, so we treat it as a warning unless we're in a SFINAE context. |
| 4079 |
// But we still prohibit this since C++26. |
| 4080 |
Diag(StartLoc, LangOpts.CPlusPlus26 ? diag::err_delete_incomplete |
| 4081 |
: diag::ext_delete_void_ptr_operand) |
| 4082 |
<< (LangOpts.CPlusPlus26 ? Pointee : Type) |
| 4083 |
<< Ex.get()->getSourceRange(); |
| 4084 |
} else if (Pointee->isFunctionType() || Pointee->isVoidType() || |
| 4085 |
Pointee->isSizelessType()) { |
| 4086 |
return ExprError(Diag(StartLoc, diag::err_delete_operand) |
| 4087 |
<< Type << Ex.get()->getSourceRange()); |
| 4088 |
} else if (!Pointee->isDependentType()) { |
| 4089 |
// FIXME: This can result in errors if the definition was imported from a |
| 4090 |
// module but is hidden. |
| 4091 |
if (Pointee->isEnumeralType() || |
| 4092 |
!RequireCompleteType(StartLoc, Pointee, |
| 4093 |
LangOpts.CPlusPlus26 |
| 4094 |
? diag::err_delete_incomplete |
| 4095 |
: diag::warn_delete_incomplete, |
| 4096 |
Ex.get())) { |
| 4097 |
PointeeRD = PointeeElem->getAsCXXRecordDecl(); |
| 4098 |
} |
| 4099 |
} |
| 4100 |
|
| 4101 |
if (Pointee->isArrayType() && !ArrayForm) { |
| 4102 |
Diag(StartLoc, diag::warn_delete_array_type) |
| 4103 |
<< Type << Ex.get()->getSourceRange() |
| 4104 |
<< FixItHint::CreateInsertion(getLocForEndOfToken(StartLoc), "[]"); |
| 4105 |
ArrayForm = true; |
| 4106 |
} |
| 4107 |
|
| 4108 |
DeclarationName DeleteName = Context.DeclarationNames.getCXXOperatorName( |
| 4109 |
ArrayForm ? OO_Array_Delete : OO_Delete); |
| 4110 |
|
| 4111 |
if (PointeeRD) { |
| 4112 |
ImplicitDeallocationParameters IDP = { |
| 4113 |
Pointee, ShouldUseTypeAwareOperatorNewOrDelete(), |
| 4114 |
AlignedAllocationMode::No, SizedDeallocationMode::No}; |
| 4115 |
if (!UseGlobal && |
| 4116 |
FindDeallocationFunction(StartLoc, PointeeRD, DeleteName, |
| 4117 |
OperatorDelete, IDP)) |
| 4118 |
return ExprError(); |
| 4119 |
|
| 4120 |
// If we're allocating an array of records, check whether the |
| 4121 |
// usual operator delete[] has a size_t parameter. |
| 4122 |
if (ArrayForm) { |
| 4123 |
// If the user specifically asked to use the global allocator, |
| 4124 |
// we'll need to do the lookup into the class. |
| 4125 |
if (UseGlobal) |
| 4126 |
UsualArrayDeleteWantsSize = doesUsualArrayDeleteWantSize( |
| 4127 |
*this, StartLoc, IDP.PassTypeIdentity, PointeeElem); |
| 4128 |
|
| 4129 |
// Otherwise, the usual operator delete[] should be the |
| 4130 |
// function we just found. |
| 4131 |
else if (isa_and_nonnull<CXXMethodDecl>(OperatorDelete)) { |
| 4132 |
UsualDeallocFnInfo UDFI( |
| 4133 |
*this, DeclAccessPair::make(OperatorDelete, AS_public), Pointee, |
| 4134 |
StartLoc); |
| 4135 |
UsualArrayDeleteWantsSize = isSizedDeallocation(UDFI.IDP.PassSize); |
| 4136 |
} |
| 4137 |
} |
| 4138 |
|
| 4139 |
if (!PointeeRD->hasIrrelevantDestructor()) { |
| 4140 |
if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { |
| 4141 |
if (Dtor->isCalledByDelete(OperatorDelete)) { |
| 4142 |
MarkFunctionReferenced(StartLoc, Dtor); |
| 4143 |
if (DiagnoseUseOfDecl(Dtor, StartLoc)) |
| 4144 |
return ExprError(); |
| 4145 |
} |
| 4146 |
} |
| 4147 |
} |
| 4148 |
|
| 4149 |
CheckVirtualDtorCall(PointeeRD->getDestructor(), StartLoc, |
| 4150 |
/*IsDelete=*/true, /*CallCanBeVirtual=*/true, |
| 4151 |
/*WarnOnNonAbstractTypes=*/!ArrayForm, |
| 4152 |
SourceLocation()); |
| 4153 |
} |
| 4154 |
|
| 4155 |
if (!OperatorDelete) { |
| 4156 |
if (getLangOpts().OpenCLCPlusPlus) { |
| 4157 |
Diag(StartLoc, diag::err_openclcxx_not_supported) << "default delete"; |
| 4158 |
return ExprError(); |
| 4159 |
} |
| 4160 |
|
| 4161 |
bool IsComplete = isCompleteType(StartLoc, Pointee); |
| 4162 |
bool CanProvideSize = |
| 4163 |
IsComplete && (!ArrayForm || UsualArrayDeleteWantsSize || |
| 4164 |
Pointee.isDestructedType()); |
| 4165 |
bool Overaligned = hasNewExtendedAlignment(*this, Pointee); |
| 4166 |
|
| 4167 |
// Look for a global declaration. |
| 4168 |
ImplicitDeallocationParameters IDP = { |
| 4169 |
Pointee, ShouldUseTypeAwareOperatorNewOrDelete(), |
| 4170 |
alignedAllocationModeFromBool(Overaligned), |
| 4171 |
sizedDeallocationModeFromBool(CanProvideSize)}; |
| 4172 |
OperatorDelete = FindUsualDeallocationFunction(StartLoc, IDP, DeleteName); |
| 4173 |
if (!OperatorDelete) |
| 4174 |
return ExprError(); |
| 4175 |
} |
| 4176 |
|
| 4177 |
if (OperatorDelete->isInvalidDecl()) |
| 4178 |
return ExprError(); |
| 4179 |
|
| 4180 |
MarkFunctionReferenced(StartLoc, OperatorDelete); |
| 4181 |
|
| 4182 |
// Check access and ambiguity of destructor if we're going to call it. |
| 4183 |
// Note that this is required even for a virtual delete. |
| 4184 |
bool IsVirtualDelete = false; |
| 4185 |
if (PointeeRD) { |
| 4186 |
if (CXXDestructorDecl *Dtor = LookupDestructor(PointeeRD)) { |
| 4187 |
if (Dtor->isCalledByDelete(OperatorDelete)) |
| 4188 |
CheckDestructorAccess(Ex.get()->getExprLoc(), Dtor, |
| 4189 |
PDiag(diag::err_access_dtor) << PointeeElem); |
| 4190 |
IsVirtualDelete = Dtor->isVirtual(); |
| 4191 |
} |
| 4192 |
} |
| 4193 |
|
| 4194 |
DiagnoseUseOfDecl(OperatorDelete, StartLoc); |
| 4195 |
|
| 4196 |
unsigned AddressParamIdx = 0; |
| 4197 |
if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) { |
| 4198 |
QualType TypeIdentity = OperatorDelete->getParamDecl(0)->getType(); |
| 4199 |
if (RequireCompleteType(StartLoc, TypeIdentity, |
| 4200 |
diag::err_incomplete_type)) |
| 4201 |
return ExprError(); |
| 4202 |
AddressParamIdx = 1; |
| 4203 |
} |
| 4204 |
|
| 4205 |
// Convert the operand to the type of the first parameter of operator |
| 4206 |
// delete. This is only necessary if we selected a destroying operator |
| 4207 |
// delete that we are going to call (non-virtually); converting to void* |
| 4208 |
// is trivial and left to AST consumers to handle. |
| 4209 |
QualType ParamType = |
| 4210 |
OperatorDelete->getParamDecl(AddressParamIdx)->getType(); |
| 4211 |
if (!IsVirtualDelete && !ParamType->getPointeeType()->isVoidType()) { |
| 4212 |
Qualifiers Qs = Pointee.getQualifiers(); |
| 4213 |
if (Qs.hasCVRQualifiers()) { |
| 4214 |
// Qualifiers are irrelevant to this conversion; we're only looking |
| 4215 |
// for access and ambiguity. |
| 4216 |
Qs.removeCVRQualifiers(); |
| 4217 |
QualType Unqual = Context.getPointerType( |
| 4218 |
Context.getQualifiedType(Pointee.getUnqualifiedType(), Qs)); |
| 4219 |
Ex = ImpCastExprToType(Ex.get(), Unqual, CK_NoOp); |
| 4220 |
} |
| 4221 |
Ex = PerformImplicitConversion(Ex.get(), ParamType, |
| 4222 |
AssignmentAction::Passing); |
| 4223 |
if (Ex.isInvalid()) |
| 4224 |
return ExprError(); |
| 4225 |
} |
| 4226 |
} |
| 4227 |
|
| 4228 |
CXXDeleteExpr *Result = new (Context) CXXDeleteExpr( |
| 4229 |
Context.VoidTy, UseGlobal, ArrayForm, ArrayFormAsWritten, |
| 4230 |
UsualArrayDeleteWantsSize, OperatorDelete, Ex.get(), StartLoc); |
| 4231 |
AnalyzeDeleteExprMismatch(Result); |
| 4232 |
return Result; |
| 4233 |
} |
| 4234 |
|
| 4235 |
static bool resolveBuiltinNewDeleteOverload(Sema &S, CallExpr *TheCall, |
| 4236 |
bool IsDelete, |
| 4237 |
FunctionDecl *&Operator) { |
| 4238 |
|
| 4239 |
DeclarationName NewName = S.Context.DeclarationNames.getCXXOperatorName( |
| 4240 |
IsDelete ? OO_Delete : OO_New); |
| 4241 |
|
| 4242 |
LookupResult R(S, NewName, TheCall->getBeginLoc(), Sema::LookupOrdinaryName); |
| 4243 |
S.LookupQualifiedName(R, S.Context.getTranslationUnitDecl()); |
| 4244 |
assert(!R.empty() && "implicitly declared allocation functions not found"); |
| 4245 |
assert(!R.isAmbiguous() && "global allocation functions are ambiguous"); |
| 4246 |
|
| 4247 |
// We do our own custom access checks below. |
| 4248 |
R.suppressDiagnostics(); |
| 4249 |
|
| 4250 |
SmallVector<Expr *, 8> Args(TheCall->arguments()); |
| 4251 |
OverloadCandidateSet Candidates(R.getNameLoc(), |
| 4252 |
OverloadCandidateSet::CSK_Normal); |
| 4253 |
for (LookupResult::iterator FnOvl = R.begin(), FnOvlEnd = R.end(); |
| 4254 |
FnOvl != FnOvlEnd; ++FnOvl) { |
| 4255 |
// Even member operator new/delete are implicitly treated as |
| 4256 |
// static, so don't use AddMemberCandidate. |
| 4257 |
NamedDecl *D = (*FnOvl)->getUnderlyingDecl(); |
| 4258 |
|
| 4259 |
if (FunctionTemplateDecl *FnTemplate = dyn_cast<FunctionTemplateDecl>(D)) { |
| 4260 |
S.AddTemplateOverloadCandidate(FnTemplate, FnOvl.getPair(), |
| 4261 |
/*ExplicitTemplateArgs=*/nullptr, Args, |
| 4262 |
Candidates, |
| 4263 |
/*SuppressUserConversions=*/false); |
| 4264 |
continue; |
| 4265 |
} |
| 4266 |
|
| 4267 |
FunctionDecl *Fn = cast<FunctionDecl>(D); |
| 4268 |
S.AddOverloadCandidate(Fn, FnOvl.getPair(), Args, Candidates, |
| 4269 |
/*SuppressUserConversions=*/false); |
| 4270 |
} |
| 4271 |
|
| 4272 |
SourceRange Range = TheCall->getSourceRange(); |
| 4273 |
|
| 4274 |
// Do the resolution. |
| 4275 |
OverloadCandidateSet::iterator Best; |
| 4276 |
switch (Candidates.BestViableFunction(S, R.getNameLoc(), Best)) { |
| 4277 |
case OR_Success: { |
| 4278 |
// Got one! |
| 4279 |
FunctionDecl *FnDecl = Best->Function; |
| 4280 |
assert(R.getNamingClass() == nullptr && |
| 4281 |
"class members should not be considered"); |
| 4282 |
|
| 4283 |
if (!FnDecl->isReplaceableGlobalAllocationFunction()) { |
| 4284 |
S.Diag(R.getNameLoc(), diag::err_builtin_operator_new_delete_not_usual) |
| 4285 |
<< (IsDelete ? 1 : 0) << Range; |
| 4286 |
S.Diag(FnDecl->getLocation(), diag::note_non_usual_function_declared_here) |
| 4287 |
<< R.getLookupName() << FnDecl->getSourceRange(); |
| 4288 |
return true; |
| 4289 |
} |
| 4290 |
|
| 4291 |
Operator = FnDecl; |
| 4292 |
return false; |
| 4293 |
} |
| 4294 |
|
| 4295 |
case OR_No_Viable_Function: |
| 4296 |
Candidates.NoteCandidates( |
| 4297 |
PartialDiagnosticAt(R.getNameLoc(), |
| 4298 |
S.PDiag(diag::err_ovl_no_viable_function_in_call) |
| 4299 |
<< R.getLookupName() << Range), |
| 4300 |
S, OCD_AllCandidates, Args); |
| 4301 |
return true; |
| 4302 |
|
| 4303 |
case OR_Ambiguous: |
| 4304 |
Candidates.NoteCandidates( |
| 4305 |
PartialDiagnosticAt(R.getNameLoc(), |
| 4306 |
S.PDiag(diag::err_ovl_ambiguous_call) |
| 4307 |
<< R.getLookupName() << Range), |
| 4308 |
S, OCD_AmbiguousCandidates, Args); |
| 4309 |
return true; |
| 4310 |
|
| 4311 |
case OR_Deleted: |
| 4312 |
S.DiagnoseUseOfDeletedFunction(R.getNameLoc(), Range, R.getLookupName(), |
| 4313 |
Candidates, Best->Function, Args); |
| 4314 |
return true; |
| 4315 |
} |
| 4316 |
llvm_unreachable("Unreachable, bad result from BestViableFunction"); |
| 4317 |
} |
| 4318 |
|
| 4319 |
ExprResult Sema::BuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, |
| 4320 |
bool IsDelete) { |
| 4321 |
CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); |
| 4322 |
if (!getLangOpts().CPlusPlus) { |
| 4323 |
Diag(TheCall->getExprLoc(), diag::err_builtin_requires_language) |
| 4324 |
<< (IsDelete ? "__builtin_operator_delete" : "__builtin_operator_new") |
| 4325 |
<< "C++"; |
| 4326 |
return ExprError(); |
| 4327 |
} |
| 4328 |
// CodeGen assumes it can find the global new and delete to call, |
| 4329 |
// so ensure that they are declared. |
| 4330 |
DeclareGlobalNewDelete(); |
| 4331 |
|
| 4332 |
FunctionDecl *OperatorNewOrDelete = nullptr; |
| 4333 |
if (resolveBuiltinNewDeleteOverload(*this, TheCall, IsDelete, |
| 4334 |
OperatorNewOrDelete)) |
| 4335 |
return ExprError(); |
| 4336 |
assert(OperatorNewOrDelete && "should be found"); |
| 4337 |
|
| 4338 |
DiagnoseUseOfDecl(OperatorNewOrDelete, TheCall->getExprLoc()); |
| 4339 |
MarkFunctionReferenced(TheCall->getExprLoc(), OperatorNewOrDelete); |
| 4340 |
|
| 4341 |
TheCall->setType(OperatorNewOrDelete->getReturnType()); |
| 4342 |
for (unsigned i = 0; i != TheCall->getNumArgs(); ++i) { |
| 4343 |
QualType ParamTy = OperatorNewOrDelete->getParamDecl(i)->getType(); |
| 4344 |
InitializedEntity Entity = |
| 4345 |
InitializedEntity::InitializeParameter(Context, ParamTy, false); |
| 4346 |
ExprResult Arg = PerformCopyInitialization( |
| 4347 |
Entity, TheCall->getArg(i)->getBeginLoc(), TheCall->getArg(i)); |
| 4348 |
if (Arg.isInvalid()) |
| 4349 |
return ExprError(); |
| 4350 |
TheCall->setArg(i, Arg.get()); |
| 4351 |
} |
| 4352 |
auto Callee = dyn_cast<ImplicitCastExpr>(TheCall->getCallee()); |
| 4353 |
assert(Callee && Callee->getCastKind() == CK_BuiltinFnToFnPtr && |
| 4354 |
"Callee expected to be implicit cast to a builtin function pointer"); |
| 4355 |
Callee->setType(OperatorNewOrDelete->getType()); |
| 4356 |
|
| 4357 |
return TheCallResult; |
| 4358 |
} |
| 4359 |
|
| 4360 |
void Sema::CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, |
| 4361 |
bool IsDelete, bool CallCanBeVirtual, |
| 4362 |
bool WarnOnNonAbstractTypes, |
| 4363 |
SourceLocation DtorLoc) { |
| 4364 |
if (!dtor || dtor->isVirtual() || !CallCanBeVirtual || isUnevaluatedContext()) |
| 4365 |
return; |
| 4366 |
|
| 4367 |
// C++ [expr.delete]p3: |
| 4368 |
// In the first alternative (delete object), if the static type of the |
| 4369 |
// object to be deleted is different from its dynamic type, the static |
| 4370 |
// type shall be a base class of the dynamic type of the object to be |
| 4371 |
// deleted and the static type shall have a virtual destructor or the |
| 4372 |
// behavior is undefined. |
| 4373 |
// |
| 4374 |
const CXXRecordDecl *PointeeRD = dtor->getParent(); |
| 4375 |
// Note: a final class cannot be derived from, no issue there |
| 4376 |
if (!PointeeRD->isPolymorphic() || PointeeRD->hasAttr<FinalAttr>()) |
| 4377 |
return; |
| 4378 |
|
| 4379 |
// If the superclass is in a system header, there's nothing that can be done. |
| 4380 |
// The `delete` (where we emit the warning) can be in a system header, |
| 4381 |
// what matters for this warning is where the deleted type is defined. |
| 4382 |
if (getSourceManager().isInSystemHeader(PointeeRD->getLocation())) |
| 4383 |
return; |
| 4384 |
|
| 4385 |
QualType ClassType = dtor->getFunctionObjectParameterType(); |
| 4386 |
if (PointeeRD->isAbstract()) { |
| 4387 |
// If the class is abstract, we warn by default, because we're |
| 4388 |
// sure the code has undefined behavior. |
| 4389 |
Diag(Loc, diag::warn_delete_abstract_non_virtual_dtor) << (IsDelete ? 0 : 1) |
| 4390 |
<< ClassType; |
| 4391 |
} else if (WarnOnNonAbstractTypes) { |
| 4392 |
// Otherwise, if this is not an array delete, it's a bit suspect, |
| 4393 |
// but not necessarily wrong. |
| 4394 |
Diag(Loc, diag::warn_delete_non_virtual_dtor) << (IsDelete ? 0 : 1) |
| 4395 |
<< ClassType; |
| 4396 |
} |
| 4397 |
if (!IsDelete) { |
| 4398 |
std::string TypeStr; |
| 4399 |
ClassType.getAsStringInternal(TypeStr, getPrintingPolicy()); |
| 4400 |
Diag(DtorLoc, diag::note_delete_non_virtual) |
| 4401 |
<< FixItHint::CreateInsertion(DtorLoc, TypeStr + "::"); |
| 4402 |
} |
| 4403 |
} |
| 4404 |
|
| 4405 |
Sema::ConditionResult Sema::ActOnConditionVariable(Decl *ConditionVar, |
| 4406 |
SourceLocation StmtLoc, |
| 4407 |
ConditionKind CK) { |
| 4408 |
ExprResult E = |
| 4409 |
CheckConditionVariable(cast<VarDecl>(ConditionVar), StmtLoc, CK); |
| 4410 |
if (E.isInvalid()) |
| 4411 |
return ConditionError(); |
| 4412 |
E = ActOnFinishFullExpr(E.get(), /*DiscardedValue*/ false); |
| 4413 |
return ConditionResult(*this, ConditionVar, E, |
| 4414 |
CK == ConditionKind::ConstexprIf); |
| 4415 |
} |
| 4416 |
|
| 4417 |
ExprResult Sema::CheckConditionVariable(VarDecl *ConditionVar, |
| 4418 |
SourceLocation StmtLoc, |
| 4419 |
ConditionKind CK) { |
| 4420 |
if (ConditionVar->isInvalidDecl()) |
| 4421 |
return ExprError(); |
| 4422 |
|
| 4423 |
QualType T = ConditionVar->getType(); |
| 4424 |
|
| 4425 |
// C++ [stmt.select]p2: |
| 4426 |
// The declarator shall not specify a function or an array. |
| 4427 |
if (T->isFunctionType()) |
| 4428 |
return ExprError(Diag(ConditionVar->getLocation(), |
| 4429 |
diag::err_invalid_use_of_function_type) |
| 4430 |
<< ConditionVar->getSourceRange()); |
| 4431 |
else if (T->isArrayType()) |
| 4432 |
return ExprError(Diag(ConditionVar->getLocation(), |
| 4433 |
diag::err_invalid_use_of_array_type) |
| 4434 |
<< ConditionVar->getSourceRange()); |
| 4435 |
|
| 4436 |
ExprResult Condition = BuildDeclRefExpr( |
| 4437 |
ConditionVar, ConditionVar->getType().getNonReferenceType(), VK_LValue, |
| 4438 |
ConditionVar->getLocation()); |
| 4439 |
|
| 4440 |
switch (CK) { |
| 4441 |
case ConditionKind::Boolean: |
| 4442 |
return CheckBooleanCondition(StmtLoc, Condition.get()); |
| 4443 |
|
| 4444 |
case ConditionKind::ConstexprIf: |
| 4445 |
return CheckBooleanCondition(StmtLoc, Condition.get(), true); |
| 4446 |
|
| 4447 |
case ConditionKind::Switch: |
| 4448 |
return CheckSwitchCondition(StmtLoc, Condition.get()); |
| 4449 |
} |
| 4450 |
|
| 4451 |
llvm_unreachable("unexpected condition kind"); |
| 4452 |
} |
| 4453 |
|
| 4454 |
ExprResult Sema::CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr) { |
| 4455 |
// C++11 6.4p4: |
| 4456 |
// The value of a condition that is an initialized declaration in a statement |
| 4457 |
// other than a switch statement is the value of the declared variable |
| 4458 |
// implicitly converted to type bool. If that conversion is ill-formed, the |
| 4459 |
// program is ill-formed. |
| 4460 |
// The value of a condition that is an expression is the value of the |
| 4461 |
// expression, implicitly converted to bool. |
| 4462 |
// |
| 4463 |
// C++23 8.5.2p2 |
| 4464 |
// If the if statement is of the form if constexpr, the value of the condition |
| 4465 |
// is contextually converted to bool and the converted expression shall be |
| 4466 |
// a constant expression. |
| 4467 |
// |
| 4468 |
|
| 4469 |
ExprResult E = PerformContextuallyConvertToBool(CondExpr); |
| 4470 |
if (!IsConstexpr || E.isInvalid() || E.get()->isValueDependent()) |
| 4471 |
return E; |
| 4472 |
|
| 4473 |
E = ActOnFinishFullExpr(E.get(), E.get()->getExprLoc(), |
| 4474 |
/*DiscardedValue*/ false, |
| 4475 |
/*IsConstexpr*/ true); |
| 4476 |
if (E.isInvalid()) |
| 4477 |
return E; |
| 4478 |
|
| 4479 |
// FIXME: Return this value to the caller so they don't need to recompute it. |
| 4480 |
llvm::APSInt Cond; |
| 4481 |
E = VerifyIntegerConstantExpression( |
| 4482 |
E.get(), &Cond, |
| 4483 |
diag::err_constexpr_if_condition_expression_is_not_constant); |
| 4484 |
return E; |
| 4485 |
} |
| 4486 |
|
| 4487 |
bool |
| 4488 |
Sema::IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType) { |
| 4489 |
// Look inside the implicit cast, if it exists. |
| 4490 |
if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(From)) |
| 4491 |
From = Cast->getSubExpr(); |
| 4492 |
|
| 4493 |
// A string literal (2.13.4) that is not a wide string literal can |
| 4494 |
// be converted to an rvalue of type "pointer to char"; a wide |
| 4495 |
// string literal can be converted to an rvalue of type "pointer |
| 4496 |
// to wchar_t" (C++ 4.2p2). |
| 4497 |
if (StringLiteral *StrLit = dyn_cast<StringLiteral>(From->IgnoreParens())) |
| 4498 |
if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) |
| 4499 |
if (const BuiltinType *ToPointeeType |
| 4500 |
= ToPtrType->getPointeeType()->getAs<BuiltinType>()) { |
| 4501 |
// This conversion is considered only when there is an |
| 4502 |
// explicit appropriate pointer target type (C++ 4.2p2). |
| 4503 |
if (!ToPtrType->getPointeeType().hasQualifiers()) { |
| 4504 |
switch (StrLit->getKind()) { |
| 4505 |
case StringLiteralKind::UTF8: |
| 4506 |
case StringLiteralKind::UTF16: |
| 4507 |
case StringLiteralKind::UTF32: |
| 4508 |
// We don't allow UTF literals to be implicitly converted |
| 4509 |
break; |
| 4510 |
case StringLiteralKind::Ordinary: |
| 4511 |
case StringLiteralKind::Binary: |
| 4512 |
return (ToPointeeType->getKind() == BuiltinType::Char_U || |
| 4513 |
ToPointeeType->getKind() == BuiltinType::Char_S); |
| 4514 |
case StringLiteralKind::Wide: |
| 4515 |
return Context.typesAreCompatible(Context.getWideCharType(), |
| 4516 |
QualType(ToPointeeType, 0)); |
| 4517 |
case StringLiteralKind::Unevaluated: |
| 4518 |
assert(false && "Unevaluated string literal in expression"); |
| 4519 |
break; |
| 4520 |
} |
| 4521 |
} |
| 4522 |
} |
| 4523 |
|
| 4524 |
return false; |
| 4525 |
} |
| 4526 |
|
| 4527 |
static ExprResult BuildCXXCastArgument(Sema &S, |
| 4528 |
SourceLocation CastLoc, |
| 4529 |
QualType Ty, |
| 4530 |
CastKind Kind, |
| 4531 |
CXXMethodDecl *Method, |
| 4532 |
DeclAccessPair FoundDecl, |
| 4533 |
bool HadMultipleCandidates, |
| 4534 |
Expr *From) { |
| 4535 |
switch (Kind) { |
| 4536 |
default: llvm_unreachable("Unhandled cast kind!"); |
| 4537 |
case CK_ConstructorConversion: { |
| 4538 |
CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Method); |
| 4539 |
SmallVector<Expr*, 8> ConstructorArgs; |
| 4540 |
|
| 4541 |
if (S.RequireNonAbstractType(CastLoc, Ty, |
| 4542 |
diag::err_allocation_of_abstract_type)) |
| 4543 |
return ExprError(); |
| 4544 |
|
| 4545 |
if (S.CompleteConstructorCall(Constructor, Ty, From, CastLoc, |
| 4546 |
ConstructorArgs)) |
| 4547 |
return ExprError(); |
| 4548 |
|
| 4549 |
S.CheckConstructorAccess(CastLoc, Constructor, FoundDecl, |
| 4550 |
InitializedEntity::InitializeTemporary(Ty)); |
| 4551 |
if (S.DiagnoseUseOfDecl(Method, CastLoc)) |
| 4552 |
return ExprError(); |
| 4553 |
|
| 4554 |
ExprResult Result = S.BuildCXXConstructExpr( |
| 4555 |
CastLoc, Ty, FoundDecl, cast<CXXConstructorDecl>(Method), |
| 4556 |
ConstructorArgs, HadMultipleCandidates, |
| 4557 |
/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, |
| 4558 |
CXXConstructionKind::Complete, SourceRange()); |
| 4559 |
if (Result.isInvalid()) |
| 4560 |
return ExprError(); |
| 4561 |
|
| 4562 |
return S.MaybeBindToTemporary(Result.getAs<Expr>()); |
| 4563 |
} |
| 4564 |
|
| 4565 |
case CK_UserDefinedConversion: { |
| 4566 |
assert(!From->getType()->isPointerType() && "Arg can't have pointer type!"); |
| 4567 |
|
| 4568 |
S.CheckMemberOperatorAccess(CastLoc, From, /*arg*/ nullptr, FoundDecl); |
| 4569 |
if (S.DiagnoseUseOfDecl(Method, CastLoc)) |
| 4570 |
return ExprError(); |
| 4571 |
|
| 4572 |
// Create an implicit call expr that calls it. |
| 4573 |
CXXConversionDecl *Conv = cast<CXXConversionDecl>(Method); |
| 4574 |
ExprResult Result = S.BuildCXXMemberCallExpr(From, FoundDecl, Conv, |
| 4575 |
HadMultipleCandidates); |
| 4576 |
if (Result.isInvalid()) |
| 4577 |
return ExprError(); |
| 4578 |
// Record usage of conversion in an implicit cast. |
| 4579 |
Result = ImplicitCastExpr::Create(S.Context, Result.get()->getType(), |
| 4580 |
CK_UserDefinedConversion, Result.get(), |
| 4581 |
nullptr, Result.get()->getValueKind(), |
| 4582 |
S.CurFPFeatureOverrides()); |
| 4583 |
|
| 4584 |
return S.MaybeBindToTemporary(Result.get()); |
| 4585 |
} |
| 4586 |
} |
| 4587 |
} |
| 4588 |
|
| 4589 |
ExprResult |
| 4590 |
Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
| 4591 |
const ImplicitConversionSequence &ICS, |
| 4592 |
AssignmentAction Action, |
| 4593 |
CheckedConversionKind CCK) { |
| 4594 |
// C++ [over.match.oper]p7: [...] operands of class type are converted [...] |
| 4595 |
if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp && |
| 4596 |
!From->getType()->isRecordType()) |
| 4597 |
return From; |
| 4598 |
|
| 4599 |
switch (ICS.getKind()) { |
| 4600 |
case ImplicitConversionSequence::StandardConversion: { |
| 4601 |
ExprResult Res = PerformImplicitConversion(From, ToType, ICS.Standard, |
| 4602 |
Action, CCK); |
| 4603 |
if (Res.isInvalid()) |
| 4604 |
return ExprError(); |
| 4605 |
From = Res.get(); |
| 4606 |
break; |
| 4607 |
} |
| 4608 |
|
| 4609 |
case ImplicitConversionSequence::UserDefinedConversion: { |
| 4610 |
|
| 4611 |
FunctionDecl *FD = ICS.UserDefined.ConversionFunction; |
| 4612 |
CastKind CastKind; |
| 4613 |
QualType BeforeToType; |
| 4614 |
assert(FD && "no conversion function for user-defined conversion seq"); |
| 4615 |
if (const CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(FD)) { |
| 4616 |
CastKind = CK_UserDefinedConversion; |
| 4617 |
|
| 4618 |
// If the user-defined conversion is specified by a conversion function, |
| 4619 |
// the initial standard conversion sequence converts the source type to |
| 4620 |
// the implicit object parameter of the conversion function. |
| 4621 |
BeforeToType = Context.getCanonicalTagType(Conv->getParent()); |
| 4622 |
} else { |
| 4623 |
const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(FD); |
| 4624 |
CastKind = CK_ConstructorConversion; |
| 4625 |
// Do no conversion if dealing with ... for the first conversion. |
| 4626 |
if (!ICS.UserDefined.EllipsisConversion) { |
| 4627 |
// If the user-defined conversion is specified by a constructor, the |
| 4628 |
// initial standard conversion sequence converts the source type to |
| 4629 |
// the type required by the argument of the constructor |
| 4630 |
BeforeToType = Ctor->getParamDecl(0)->getType().getNonReferenceType(); |
| 4631 |
} |
| 4632 |
} |
| 4633 |
// Watch out for ellipsis conversion. |
| 4634 |
if (!ICS.UserDefined.EllipsisConversion) { |
| 4635 |
ExprResult Res = PerformImplicitConversion( |
| 4636 |
From, BeforeToType, ICS.UserDefined.Before, |
| 4637 |
AssignmentAction::Converting, CCK); |
| 4638 |
if (Res.isInvalid()) |
| 4639 |
return ExprError(); |
| 4640 |
From = Res.get(); |
| 4641 |
} |
| 4642 |
|
| 4643 |
ExprResult CastArg = BuildCXXCastArgument( |
| 4644 |
*this, From->getBeginLoc(), ToType.getNonReferenceType(), CastKind, |
| 4645 |
cast<CXXMethodDecl>(FD), ICS.UserDefined.FoundConversionFunction, |
| 4646 |
ICS.UserDefined.HadMultipleCandidates, From); |
| 4647 |
|
| 4648 |
if (CastArg.isInvalid()) |
| 4649 |
return ExprError(); |
| 4650 |
|
| 4651 |
From = CastArg.get(); |
| 4652 |
|
| 4653 |
// C++ [over.match.oper]p7: |
| 4654 |
// [...] the second standard conversion sequence of a user-defined |
| 4655 |
// conversion sequence is not applied. |
| 4656 |
if (CCK == CheckedConversionKind::ForBuiltinOverloadedOp) |
| 4657 |
return From; |
| 4658 |
|
| 4659 |
return PerformImplicitConversion(From, ToType, ICS.UserDefined.After, |
| 4660 |
AssignmentAction::Converting, CCK); |
| 4661 |
} |
| 4662 |
|
| 4663 |
case ImplicitConversionSequence::AmbiguousConversion: |
| 4664 |
ICS.DiagnoseAmbiguousConversion(*this, From->getExprLoc(), |
| 4665 |
PDiag(diag::err_typecheck_ambiguous_condition) |
| 4666 |
<< From->getSourceRange()); |
| 4667 |
return ExprError(); |
| 4668 |
|
| 4669 |
case ImplicitConversionSequence::EllipsisConversion: |
| 4670 |
case ImplicitConversionSequence::StaticObjectArgumentConversion: |
| 4671 |
llvm_unreachable("bad conversion"); |
| 4672 |
|
| 4673 |
case ImplicitConversionSequence::BadConversion: |
| 4674 |
AssignConvertType ConvTy = |
| 4675 |
CheckAssignmentConstraints(From->getExprLoc(), ToType, From->getType()); |
| 4676 |
bool Diagnosed = DiagnoseAssignmentResult( |
| 4677 |
ConvTy == AssignConvertType::Compatible |
| 4678 |
? AssignConvertType::Incompatible |
| 4679 |
: ConvTy, |
| 4680 |
From->getExprLoc(), ToType, From->getType(), From, Action); |
| 4681 |
assert(Diagnosed && "failed to diagnose bad conversion"); (void)Diagnosed; |
| 4682 |
return ExprError(); |
| 4683 |
} |
| 4684 |
|
| 4685 |
// Everything went well. |
| 4686 |
return From; |
| 4687 |
} |
| 4688 |
|
| 4689 |
// adjustVectorType - Compute the intermediate cast type casting elements of the |
| 4690 |
// from type to the elements of the to type without resizing the vector. |
| 4691 |
static QualType adjustVectorType(ASTContext &Context, QualType FromTy, |
| 4692 |
QualType ToType, QualType *ElTy = nullptr) { |
| 4693 |
QualType ElType = ToType; |
| 4694 |
if (auto *ToVec = ToType->getAs<VectorType>()) |
| 4695 |
ElType = ToVec->getElementType(); |
| 4696 |
|
| 4697 |
if (ElTy) |
| 4698 |
*ElTy = ElType; |
| 4699 |
if (!FromTy->isVectorType()) |
| 4700 |
return ElType; |
| 4701 |
auto *FromVec = FromTy->castAs<VectorType>(); |
| 4702 |
return Context.getExtVectorType(ElType, FromVec->getNumElements()); |
| 4703 |
} |
| 4704 |
|
| 4705 |
ExprResult |
| 4706 |
Sema::PerformImplicitConversion(Expr *From, QualType ToType, |
| 4707 |
const StandardConversionSequence& SCS, |
| 4708 |
AssignmentAction Action, |
| 4709 |
CheckedConversionKind CCK) { |
| 4710 |
bool CStyle = (CCK == CheckedConversionKind::CStyleCast || |
| 4711 |
CCK == CheckedConversionKind::FunctionalCast); |
| 4712 |
|
| 4713 |
// Overall FIXME: we are recomputing too many types here and doing far too |
| 4714 |
// much extra work. What this means is that we need to keep track of more |
| 4715 |
// information that is computed when we try the implicit conversion initially, |
| 4716 |
// so that we don't need to recompute anything here. |
| 4717 |
QualType FromType = From->getType(); |
| 4718 |
|
| 4719 |
if (SCS.CopyConstructor) { |
| 4720 |
// FIXME: When can ToType be a reference type? |
| 4721 |
assert(!ToType->isReferenceType()); |
| 4722 |
if (SCS.Second == ICK_Derived_To_Base) { |
| 4723 |
SmallVector<Expr*, 8> ConstructorArgs; |
| 4724 |
if (CompleteConstructorCall( |
| 4725 |
cast<CXXConstructorDecl>(SCS.CopyConstructor), ToType, From, |
| 4726 |
/*FIXME:ConstructLoc*/ SourceLocation(), ConstructorArgs)) |
| 4727 |
return ExprError(); |
| 4728 |
return BuildCXXConstructExpr( |
| 4729 |
/*FIXME:ConstructLoc*/ SourceLocation(), ToType, |
| 4730 |
SCS.FoundCopyConstructor, SCS.CopyConstructor, ConstructorArgs, |
| 4731 |
/*HadMultipleCandidates*/ false, |
| 4732 |
/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, |
| 4733 |
CXXConstructionKind::Complete, SourceRange()); |
| 4734 |
} |
| 4735 |
return BuildCXXConstructExpr( |
| 4736 |
/*FIXME:ConstructLoc*/ SourceLocation(), ToType, |
| 4737 |
SCS.FoundCopyConstructor, SCS.CopyConstructor, From, |
| 4738 |
/*HadMultipleCandidates*/ false, |
| 4739 |
/*ListInit*/ false, /*StdInitListInit*/ false, /*ZeroInit*/ false, |
| 4740 |
CXXConstructionKind::Complete, SourceRange()); |
| 4741 |
} |
| 4742 |
|
| 4743 |
// Resolve overloaded function references. |
| 4744 |
if (Context.hasSameType(FromType, Context.OverloadTy)) { |
| 4745 |
DeclAccessPair Found; |
| 4746 |
FunctionDecl *Fn = ResolveAddressOfOverloadedFunction(From, ToType, |
| 4747 |
true, Found); |
| 4748 |
if (!Fn) |
| 4749 |
return ExprError(); |
| 4750 |
|
| 4751 |
if (DiagnoseUseOfDecl(Fn, From->getBeginLoc())) |
| 4752 |
return ExprError(); |
| 4753 |
|
| 4754 |
ExprResult Res = FixOverloadedFunctionReference(From, Found, Fn); |
| 4755 |
if (Res.isInvalid()) |
| 4756 |
return ExprError(); |
| 4757 |
|
| 4758 |
// We might get back another placeholder expression if we resolved to a |
| 4759 |
// builtin. |
| 4760 |
Res = CheckPlaceholderExpr(Res.get()); |
| 4761 |
if (Res.isInvalid()) |
| 4762 |
return ExprError(); |
| 4763 |
|
| 4764 |
From = Res.get(); |
| 4765 |
FromType = From->getType(); |
| 4766 |
} |
| 4767 |
|
| 4768 |
// If we're converting to an atomic type, first convert to the corresponding |
| 4769 |
// non-atomic type. |
| 4770 |
QualType ToAtomicType; |
| 4771 |
if (const AtomicType *ToAtomic = ToType->getAs<AtomicType>()) { |
| 4772 |
ToAtomicType = ToType; |
| 4773 |
ToType = ToAtomic->getValueType(); |
| 4774 |
} |
| 4775 |
|
| 4776 |
QualType InitialFromType = FromType; |
| 4777 |
// Perform the first implicit conversion. |
| 4778 |
switch (SCS.First) { |
| 4779 |
case ICK_Identity: |
| 4780 |
if (const AtomicType *FromAtomic = FromType->getAs<AtomicType>()) { |
| 4781 |
FromType = FromAtomic->getValueType().getUnqualifiedType(); |
| 4782 |
From = ImplicitCastExpr::Create(Context, FromType, CK_AtomicToNonAtomic, |
| 4783 |
From, /*BasePath=*/nullptr, VK_PRValue, |
| 4784 |
FPOptionsOverride()); |
| 4785 |
} |
| 4786 |
break; |
| 4787 |
|
| 4788 |
case ICK_Lvalue_To_Rvalue: { |
| 4789 |
assert(From->getObjectKind() != OK_ObjCProperty); |
| 4790 |
ExprResult FromRes = DefaultLvalueConversion(From); |
| 4791 |
if (FromRes.isInvalid()) |
| 4792 |
return ExprError(); |
| 4793 |
|
| 4794 |
From = FromRes.get(); |
| 4795 |
FromType = From->getType(); |
| 4796 |
break; |
| 4797 |
} |
| 4798 |
|
| 4799 |
case ICK_Array_To_Pointer: |
| 4800 |
FromType = Context.getArrayDecayedType(FromType); |
| 4801 |
From = ImpCastExprToType(From, FromType, CK_ArrayToPointerDecay, VK_PRValue, |
| 4802 |
/*BasePath=*/nullptr, CCK) |
| 4803 |
.get(); |
| 4804 |
break; |
| 4805 |
|
| 4806 |
case ICK_HLSL_Array_RValue: |
| 4807 |
if (ToType->isArrayParameterType()) { |
| 4808 |
FromType = Context.getArrayParameterType(FromType); |
| 4809 |
} else if (FromType->isArrayParameterType()) { |
| 4810 |
const ArrayParameterType *APT = cast<ArrayParameterType>(FromType); |
| 4811 |
FromType = APT->getConstantArrayType(Context); |
| 4812 |
} |
| 4813 |
From = ImpCastExprToType(From, FromType, CK_HLSLArrayRValue, VK_PRValue, |
| 4814 |
/*BasePath=*/nullptr, CCK) |
| 4815 |
.get(); |
| 4816 |
break; |
| 4817 |
|
| 4818 |
case ICK_Function_To_Pointer: |
| 4819 |
FromType = Context.getPointerType(FromType); |
| 4820 |
From = ImpCastExprToType(From, FromType, CK_FunctionToPointerDecay, |
| 4821 |
VK_PRValue, /*BasePath=*/nullptr, CCK) |
| 4822 |
.get(); |
| 4823 |
break; |
| 4824 |
|
| 4825 |
default: |
| 4826 |
llvm_unreachable("Improper first standard conversion"); |
| 4827 |
} |
| 4828 |
|
| 4829 |
// Perform the second implicit conversion |
| 4830 |
switch (SCS.Second) { |
| 4831 |
case ICK_Identity: |
| 4832 |
// C++ [except.spec]p5: |
| 4833 |
// [For] assignment to and initialization of pointers to functions, |
| 4834 |
// pointers to member functions, and references to functions: the |
| 4835 |
// target entity shall allow at least the exceptions allowed by the |
| 4836 |
// source value in the assignment or initialization. |
| 4837 |
switch (Action) { |
| 4838 |
case AssignmentAction::Assigning: |
| 4839 |
case AssignmentAction::Initializing: |
| 4840 |
// Note, function argument passing and returning are initialization. |
| 4841 |
case AssignmentAction::Passing: |
| 4842 |
case AssignmentAction::Returning: |
| 4843 |
case AssignmentAction::Sending: |
| 4844 |
case AssignmentAction::Passing_CFAudited: |
| 4845 |
if (CheckExceptionSpecCompatibility(From, ToType)) |
| 4846 |
return ExprError(); |
| 4847 |
break; |
| 4848 |
|
| 4849 |
case AssignmentAction::Casting: |
| 4850 |
case AssignmentAction::Converting: |
| 4851 |
// Casts and implicit conversions are not initialization, so are not |
| 4852 |
// checked for exception specification mismatches. |
| 4853 |
break; |
| 4854 |
} |
| 4855 |
// Nothing else to do. |
| 4856 |
break; |
| 4857 |
|
| 4858 |
case ICK_Integral_Promotion: |
| 4859 |
case ICK_Integral_Conversion: { |
| 4860 |
QualType ElTy = ToType; |
| 4861 |
QualType StepTy = ToType; |
| 4862 |
if (FromType->isVectorType() || ToType->isVectorType()) |
| 4863 |
StepTy = adjustVectorType(Context, FromType, ToType, &ElTy); |
| 4864 |
if (ElTy->isBooleanType()) { |
| 4865 |
assert(FromType->castAsEnumDecl()->isFixed() && |
| 4866 |
SCS.Second == ICK_Integral_Promotion && |
| 4867 |
"only enums with fixed underlying type can promote to bool"); |
| 4868 |
From = ImpCastExprToType(From, StepTy, CK_IntegralToBoolean, VK_PRValue, |
| 4869 |
/*BasePath=*/nullptr, CCK) |
| 4870 |
.get(); |
| 4871 |
} else { |
| 4872 |
From = ImpCastExprToType(From, StepTy, CK_IntegralCast, VK_PRValue, |
| 4873 |
/*BasePath=*/nullptr, CCK) |
| 4874 |
.get(); |
| 4875 |
} |
| 4876 |
break; |
| 4877 |
} |
| 4878 |
|
| 4879 |
case ICK_Floating_Promotion: |
| 4880 |
case ICK_Floating_Conversion: { |
| 4881 |
QualType StepTy = ToType; |
| 4882 |
if (FromType->isVectorType() || ToType->isVectorType()) |
| 4883 |
StepTy = adjustVectorType(Context, FromType, ToType); |
| 4884 |
From = ImpCastExprToType(From, StepTy, CK_FloatingCast, VK_PRValue, |
| 4885 |
/*BasePath=*/nullptr, CCK) |
| 4886 |
.get(); |
| 4887 |
break; |
| 4888 |
} |
| 4889 |
|
| 4890 |
case ICK_Complex_Promotion: |
| 4891 |
case ICK_Complex_Conversion: { |
| 4892 |
QualType FromEl = From->getType()->castAs<ComplexType>()->getElementType(); |
| 4893 |
QualType ToEl = ToType->castAs<ComplexType>()->getElementType(); |
| 4894 |
CastKind CK; |
| 4895 |
if (FromEl->isRealFloatingType()) { |
| 4896 |
if (ToEl->isRealFloatingType()) |
| 4897 |
CK = CK_FloatingComplexCast; |
| 4898 |
else |
| 4899 |
CK = CK_FloatingComplexToIntegralComplex; |
| 4900 |
} else if (ToEl->isRealFloatingType()) { |
| 4901 |
CK = CK_IntegralComplexToFloatingComplex; |
| 4902 |
} else { |
| 4903 |
CK = CK_IntegralComplexCast; |
| 4904 |
} |
| 4905 |
From = ImpCastExprToType(From, ToType, CK, VK_PRValue, /*BasePath=*/nullptr, |
| 4906 |
CCK) |
| 4907 |
.get(); |
| 4908 |
break; |
| 4909 |
} |
| 4910 |
|
| 4911 |
case ICK_Floating_Integral: { |
| 4912 |
QualType ElTy = ToType; |
| 4913 |
QualType StepTy = ToType; |
| 4914 |
if (FromType->isVectorType() || ToType->isVectorType()) |
| 4915 |
StepTy = adjustVectorType(Context, FromType, ToType, &ElTy); |
| 4916 |
if (ElTy->isRealFloatingType()) |
| 4917 |
From = ImpCastExprToType(From, StepTy, CK_IntegralToFloating, VK_PRValue, |
| 4918 |
/*BasePath=*/nullptr, CCK) |
| 4919 |
.get(); |
| 4920 |
else |
| 4921 |
From = ImpCastExprToType(From, StepTy, CK_FloatingToIntegral, VK_PRValue, |
| 4922 |
/*BasePath=*/nullptr, CCK) |
| 4923 |
.get(); |
| 4924 |
break; |
| 4925 |
} |
| 4926 |
|
| 4927 |
case ICK_Fixed_Point_Conversion: |
| 4928 |
assert((FromType->isFixedPointType() || ToType->isFixedPointType()) && |
| 4929 |
"Attempting implicit fixed point conversion without a fixed " |
| 4930 |
"point operand"); |
| 4931 |
if (FromType->isFloatingType()) |
| 4932 |
From = ImpCastExprToType(From, ToType, CK_FloatingToFixedPoint, |
| 4933 |
VK_PRValue, |
| 4934 |
/*BasePath=*/nullptr, CCK).get(); |
| 4935 |
else if (ToType->isFloatingType()) |
| 4936 |
From = ImpCastExprToType(From, ToType, CK_FixedPointToFloating, |
| 4937 |
VK_PRValue, |
| 4938 |
/*BasePath=*/nullptr, CCK).get(); |
| 4939 |
else if (FromType->isIntegralType(Context)) |
| 4940 |
From = ImpCastExprToType(From, ToType, CK_IntegralToFixedPoint, |
| 4941 |
VK_PRValue, |
| 4942 |
/*BasePath=*/nullptr, CCK).get(); |
| 4943 |
else if (ToType->isIntegralType(Context)) |
| 4944 |
From = ImpCastExprToType(From, ToType, CK_FixedPointToIntegral, |
| 4945 |
VK_PRValue, |
| 4946 |
/*BasePath=*/nullptr, CCK).get(); |
| 4947 |
else if (ToType->isBooleanType()) |
| 4948 |
From = ImpCastExprToType(From, ToType, CK_FixedPointToBoolean, |
| 4949 |
VK_PRValue, |
| 4950 |
/*BasePath=*/nullptr, CCK).get(); |
| 4951 |
else |
| 4952 |
From = ImpCastExprToType(From, ToType, CK_FixedPointCast, |
| 4953 |
VK_PRValue, |
| 4954 |
/*BasePath=*/nullptr, CCK).get(); |
| 4955 |
break; |
| 4956 |
|
| 4957 |
case ICK_Compatible_Conversion: |
| 4958 |
From = ImpCastExprToType(From, ToType, CK_NoOp, From->getValueKind(), |
| 4959 |
/*BasePath=*/nullptr, CCK).get(); |
| 4960 |
break; |
| 4961 |
|
| 4962 |
case ICK_Writeback_Conversion: |
| 4963 |
case ICK_Pointer_Conversion: { |
| 4964 |
if (SCS.IncompatibleObjC && Action != AssignmentAction::Casting) { |
| 4965 |
// Diagnose incompatible Objective-C conversions |
| 4966 |
if (Action == AssignmentAction::Initializing || |
| 4967 |
Action == AssignmentAction::Assigning) |
| 4968 |
Diag(From->getBeginLoc(), |
| 4969 |
diag::ext_typecheck_convert_incompatible_pointer) |
| 4970 |
<< ToType << From->getType() << Action << From->getSourceRange() |
| 4971 |
<< 0; |
| 4972 |
else |
| 4973 |
Diag(From->getBeginLoc(), |
| 4974 |
diag::ext_typecheck_convert_incompatible_pointer) |
| 4975 |
<< From->getType() << ToType << Action << From->getSourceRange() |
| 4976 |
<< 0; |
| 4977 |
|
| 4978 |
if (From->getType()->isObjCObjectPointerType() && |
| 4979 |
ToType->isObjCObjectPointerType()) |
| 4980 |
ObjC().EmitRelatedResultTypeNote(From); |
| 4981 |
} else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() && |
| 4982 |
!ObjC().CheckObjCARCUnavailableWeakConversion(ToType, |
| 4983 |
From->getType())) { |
| 4984 |
if (Action == AssignmentAction::Initializing) |
| 4985 |
Diag(From->getBeginLoc(), diag::err_arc_weak_unavailable_assign); |
| 4986 |
else |
| 4987 |
Diag(From->getBeginLoc(), diag::err_arc_convesion_of_weak_unavailable) |
| 4988 |
<< (Action == AssignmentAction::Casting) << From->getType() |
| 4989 |
<< ToType << From->getSourceRange(); |
| 4990 |
} |
| 4991 |
|
| 4992 |
// Defer address space conversion to the third conversion. |
| 4993 |
QualType FromPteeType = From->getType()->getPointeeType(); |
| 4994 |
QualType ToPteeType = ToType->getPointeeType(); |
| 4995 |
QualType NewToType = ToType; |
| 4996 |
if (!FromPteeType.isNull() && !ToPteeType.isNull() && |
| 4997 |
FromPteeType.getAddressSpace() != ToPteeType.getAddressSpace()) { |
| 4998 |
NewToType = Context.removeAddrSpaceQualType(ToPteeType); |
| 4999 |
NewToType = Context.getAddrSpaceQualType(NewToType, |
| 5000 |
FromPteeType.getAddressSpace()); |
| 5001 |
if (ToType->isObjCObjectPointerType()) |
| 5002 |
NewToType = Context.getObjCObjectPointerType(NewToType); |
| 5003 |
else if (ToType->isBlockPointerType()) |
| 5004 |
NewToType = Context.getBlockPointerType(NewToType); |
| 5005 |
else |
| 5006 |
NewToType = Context.getPointerType(NewToType); |
| 5007 |
} |
| 5008 |
|
| 5009 |
CastKind Kind; |
| 5010 |
CXXCastPath BasePath; |
| 5011 |
if (CheckPointerConversion(From, NewToType, Kind, BasePath, CStyle)) |
| 5012 |
return ExprError(); |
| 5013 |
|
| 5014 |
// Make sure we extend blocks if necessary. |
| 5015 |
// FIXME: doing this here is really ugly. |
| 5016 |
if (Kind == CK_BlockPointerToObjCPointerCast) { |
| 5017 |
ExprResult E = From; |
| 5018 |
(void)ObjC().PrepareCastToObjCObjectPointer(E); |
| 5019 |
From = E.get(); |
| 5020 |
} |
| 5021 |
if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) |
| 5022 |
ObjC().CheckObjCConversion(SourceRange(), NewToType, From, CCK); |
| 5023 |
From = ImpCastExprToType(From, NewToType, Kind, VK_PRValue, &BasePath, CCK) |
| 5024 |
.get(); |
| 5025 |
break; |
| 5026 |
} |
| 5027 |
|
| 5028 |
case ICK_Pointer_Member: { |
| 5029 |
CastKind Kind; |
| 5030 |
CXXCastPath BasePath; |
| 5031 |
switch (CheckMemberPointerConversion( |
| 5032 |
From->getType(), ToType->castAs<MemberPointerType>(), Kind, BasePath, |
| 5033 |
From->getExprLoc(), From->getSourceRange(), CStyle, |
| 5034 |
MemberPointerConversionDirection::Downcast)) { |
| 5035 |
case MemberPointerConversionResult::Success: |
| 5036 |
assert((Kind != CK_NullToMemberPointer || |
| 5037 |
From->isNullPointerConstant(Context, |
| 5038 |
Expr::NPC_ValueDependentIsNull)) && |
| 5039 |
"Expr must be null pointer constant!"); |
| 5040 |
break; |
| 5041 |
case MemberPointerConversionResult::Inaccessible: |
| 5042 |
break; |
| 5043 |
case MemberPointerConversionResult::DifferentPointee: |
| 5044 |
llvm_unreachable("unexpected result"); |
| 5045 |
case MemberPointerConversionResult::NotDerived: |
| 5046 |
llvm_unreachable("Should not have been called if derivation isn't OK."); |
| 5047 |
case MemberPointerConversionResult::Ambiguous: |
| 5048 |
case MemberPointerConversionResult::Virtual: |
| 5049 |
return ExprError(); |
| 5050 |
} |
| 5051 |
if (CheckExceptionSpecCompatibility(From, ToType)) |
| 5052 |
return ExprError(); |
| 5053 |
|
| 5054 |
From = |
| 5055 |
ImpCastExprToType(From, ToType, Kind, VK_PRValue, &BasePath, CCK).get(); |
| 5056 |
break; |
| 5057 |
} |
| 5058 |
|
| 5059 |
case ICK_Boolean_Conversion: { |
| 5060 |
// Perform half-to-boolean conversion via float. |
| 5061 |
if (From->getType()->isHalfType()) { |
| 5062 |
From = ImpCastExprToType(From, Context.FloatTy, CK_FloatingCast).get(); |
| 5063 |
FromType = Context.FloatTy; |
| 5064 |
} |
| 5065 |
QualType ElTy = FromType; |
| 5066 |
QualType StepTy = ToType; |
| 5067 |
if (FromType->isVectorType()) |
| 5068 |
ElTy = FromType->castAs<VectorType>()->getElementType(); |
| 5069 |
if (getLangOpts().HLSL && |
| 5070 |
(FromType->isVectorType() || ToType->isVectorType())) |
| 5071 |
StepTy = adjustVectorType(Context, FromType, ToType); |
| 5072 |
|
| 5073 |
From = ImpCastExprToType(From, StepTy, ScalarTypeToBooleanCastKind(ElTy), |
| 5074 |
VK_PRValue, |
| 5075 |
/*BasePath=*/nullptr, CCK) |
| 5076 |
.get(); |
| 5077 |
break; |
| 5078 |
} |
| 5079 |
|
| 5080 |
case ICK_Derived_To_Base: { |
| 5081 |
CXXCastPath BasePath; |
| 5082 |
if (CheckDerivedToBaseConversion( |
| 5083 |
From->getType(), ToType.getNonReferenceType(), From->getBeginLoc(), |
| 5084 |
From->getSourceRange(), &BasePath, CStyle)) |
| 5085 |
return ExprError(); |
| 5086 |
|
| 5087 |
From = ImpCastExprToType(From, ToType.getNonReferenceType(), |
| 5088 |
CK_DerivedToBase, From->getValueKind(), |
| 5089 |
&BasePath, CCK).get(); |
| 5090 |
break; |
| 5091 |
} |
| 5092 |
|
| 5093 |
case ICK_Vector_Conversion: |
| 5094 |
From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, |
| 5095 |
/*BasePath=*/nullptr, CCK) |
| 5096 |
.get(); |
| 5097 |
break; |
| 5098 |
|
| 5099 |
case ICK_SVE_Vector_Conversion: |
| 5100 |
case ICK_RVV_Vector_Conversion: |
| 5101 |
From = ImpCastExprToType(From, ToType, CK_BitCast, VK_PRValue, |
| 5102 |
/*BasePath=*/nullptr, CCK) |
| 5103 |
.get(); |
| 5104 |
break; |
| 5105 |
|
| 5106 |
case ICK_Vector_Splat: { |
| 5107 |
// Vector splat from any arithmetic type to a vector. |
| 5108 |
Expr *Elem = prepareVectorSplat(ToType, From).get(); |
| 5109 |
From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, |
| 5110 |
/*BasePath=*/nullptr, CCK) |
| 5111 |
.get(); |
| 5112 |
break; |
| 5113 |
} |
| 5114 |
|
| 5115 |
case ICK_Complex_Real: |
| 5116 |
// Case 1. x -> _Complex y |
| 5117 |
if (const ComplexType *ToComplex = ToType->getAs<ComplexType>()) { |
| 5118 |
QualType ElType = ToComplex->getElementType(); |
| 5119 |
bool isFloatingComplex = ElType->isRealFloatingType(); |
| 5120 |
|
| 5121 |
// x -> y |
| 5122 |
if (Context.hasSameUnqualifiedType(ElType, From->getType())) { |
| 5123 |
// do nothing |
| 5124 |
} else if (From->getType()->isRealFloatingType()) { |
| 5125 |
From = ImpCastExprToType(From, ElType, |
| 5126 |
isFloatingComplex ? CK_FloatingCast : CK_FloatingToIntegral).get(); |
| 5127 |
} else { |
| 5128 |
assert(From->getType()->isIntegerType()); |
| 5129 |
From = ImpCastExprToType(From, ElType, |
| 5130 |
isFloatingComplex ? CK_IntegralToFloating : CK_IntegralCast).get(); |
| 5131 |
} |
| 5132 |
// y -> _Complex y |
| 5133 |
From = ImpCastExprToType(From, ToType, |
| 5134 |
isFloatingComplex ? CK_FloatingRealToComplex |
| 5135 |
: CK_IntegralRealToComplex).get(); |
| 5136 |
|
| 5137 |
// Case 2. _Complex x -> y |
| 5138 |
} else { |
| 5139 |
auto *FromComplex = From->getType()->castAs<ComplexType>(); |
| 5140 |
QualType ElType = FromComplex->getElementType(); |
| 5141 |
bool isFloatingComplex = ElType->isRealFloatingType(); |
| 5142 |
|
| 5143 |
// _Complex x -> x |
| 5144 |
From = ImpCastExprToType(From, ElType, |
| 5145 |
isFloatingComplex ? CK_FloatingComplexToReal |
| 5146 |
: CK_IntegralComplexToReal, |
| 5147 |
VK_PRValue, /*BasePath=*/nullptr, CCK) |
| 5148 |
.get(); |
| 5149 |
|
| 5150 |
// x -> y |
| 5151 |
if (Context.hasSameUnqualifiedType(ElType, ToType)) { |
| 5152 |
// do nothing |
| 5153 |
} else if (ToType->isRealFloatingType()) { |
| 5154 |
From = ImpCastExprToType(From, ToType, |
| 5155 |
isFloatingComplex ? CK_FloatingCast |
| 5156 |
: CK_IntegralToFloating, |
| 5157 |
VK_PRValue, /*BasePath=*/nullptr, CCK) |
| 5158 |
.get(); |
| 5159 |
} else { |
| 5160 |
assert(ToType->isIntegerType()); |
| 5161 |
From = ImpCastExprToType(From, ToType, |
| 5162 |
isFloatingComplex ? CK_FloatingToIntegral |
| 5163 |
: CK_IntegralCast, |
| 5164 |
VK_PRValue, /*BasePath=*/nullptr, CCK) |
| 5165 |
.get(); |
| 5166 |
} |
| 5167 |
} |
| 5168 |
break; |
| 5169 |
|
| 5170 |
case ICK_Block_Pointer_Conversion: { |
| 5171 |
LangAS AddrSpaceL = |
| 5172 |
ToType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); |
| 5173 |
LangAS AddrSpaceR = |
| 5174 |
FromType->castAs<BlockPointerType>()->getPointeeType().getAddressSpace(); |
| 5175 |
assert(Qualifiers::isAddressSpaceSupersetOf(AddrSpaceL, AddrSpaceR, |
| 5176 |
getASTContext()) && |
| 5177 |
"Invalid cast"); |
| 5178 |
CastKind Kind = |
| 5179 |
AddrSpaceL != AddrSpaceR ? CK_AddressSpaceConversion : CK_BitCast; |
| 5180 |
From = ImpCastExprToType(From, ToType.getUnqualifiedType(), Kind, |
| 5181 |
VK_PRValue, /*BasePath=*/nullptr, CCK) |
| 5182 |
.get(); |
| 5183 |
break; |
| 5184 |
} |
| 5185 |
|
| 5186 |
case ICK_TransparentUnionConversion: { |
| 5187 |
ExprResult FromRes = From; |
| 5188 |
AssignConvertType ConvTy = |
| 5189 |
CheckTransparentUnionArgumentConstraints(ToType, FromRes); |
| 5190 |
if (FromRes.isInvalid()) |
| 5191 |
return ExprError(); |
| 5192 |
From = FromRes.get(); |
| 5193 |
assert((ConvTy == AssignConvertType::Compatible) && |
| 5194 |
"Improper transparent union conversion"); |
| 5195 |
(void)ConvTy; |
| 5196 |
break; |
| 5197 |
} |
| 5198 |
|
| 5199 |
case ICK_Zero_Event_Conversion: |
| 5200 |
case ICK_Zero_Queue_Conversion: |
| 5201 |
From = ImpCastExprToType(From, ToType, |
| 5202 |
CK_ZeroToOCLOpaqueType, |
| 5203 |
From->getValueKind()).get(); |
| 5204 |
break; |
| 5205 |
|
| 5206 |
case ICK_Lvalue_To_Rvalue: |
| 5207 |
case ICK_Array_To_Pointer: |
| 5208 |
case ICK_Function_To_Pointer: |
| 5209 |
case ICK_Function_Conversion: |
| 5210 |
case ICK_Qualification: |
| 5211 |
case ICK_Num_Conversion_Kinds: |
| 5212 |
case ICK_C_Only_Conversion: |
| 5213 |
case ICK_Incompatible_Pointer_Conversion: |
| 5214 |
case ICK_HLSL_Array_RValue: |
| 5215 |
case ICK_HLSL_Vector_Truncation: |
| 5216 |
case ICK_HLSL_Matrix_Truncation: |
| 5217 |
case ICK_HLSL_Vector_Splat: |
| 5218 |
case ICK_HLSL_Matrix_Splat: |
| 5219 |
llvm_unreachable("Improper second standard conversion"); |
| 5220 |
} |
| 5221 |
|
| 5222 |
if (SCS.Dimension != ICK_Identity) { |
| 5223 |
// If SCS.Element is not ICK_Identity the To and From types must be HLSL |
| 5224 |
// vectors or matrices. |
| 5225 |
assert( |
| 5226 |
(ToType->isVectorType() || ToType->isConstantMatrixType() || |
| 5227 |
ToType->isBuiltinType()) && |
| 5228 |
"Dimension conversion output must be vector, matrix, or scalar type."); |
| 5229 |
switch (SCS.Dimension) { |
| 5230 |
case ICK_HLSL_Vector_Splat: { |
| 5231 |
// Vector splat from any arithmetic type to a vector. |
| 5232 |
Expr *Elem = prepareVectorSplat(ToType, From).get(); |
| 5233 |
From = ImpCastExprToType(Elem, ToType, CK_VectorSplat, VK_PRValue, |
| 5234 |
/*BasePath=*/nullptr, CCK) |
| 5235 |
.get(); |
| 5236 |
break; |
| 5237 |
} |
| 5238 |
case ICK_HLSL_Matrix_Splat: { |
| 5239 |
// Matrix splat from any arithmetic type to a matrix. |
| 5240 |
Expr *Elem = prepareMatrixSplat(ToType, From).get(); |
| 5241 |
From = |
| 5242 |
ImpCastExprToType(Elem, ToType, CK_HLSLAggregateSplatCast, VK_PRValue, |
| 5243 |
/*BasePath=*/nullptr, CCK) |
| 5244 |
.get(); |
| 5245 |
break; |
| 5246 |
} |
| 5247 |
case ICK_HLSL_Vector_Truncation: { |
| 5248 |
// Note: HLSL built-in vectors are ExtVectors. Since this truncates a |
| 5249 |
// vector to a smaller vector or to a scalar, this can only operate on |
| 5250 |
// arguments where the source type is an ExtVector and the destination |
| 5251 |
// type is destination type is either an ExtVectorType or a builtin scalar |
| 5252 |
// type. |
| 5253 |
auto *FromVec = From->getType()->castAs<VectorType>(); |
| 5254 |
QualType TruncTy = FromVec->getElementType(); |
| 5255 |
if (auto *ToVec = ToType->getAs<VectorType>()) |
| 5256 |
TruncTy = Context.getExtVectorType(TruncTy, ToVec->getNumElements()); |
| 5257 |
From = ImpCastExprToType(From, TruncTy, CK_HLSLVectorTruncation, |
| 5258 |
From->getValueKind()) |
| 5259 |
.get(); |
| 5260 |
|
| 5261 |
break; |
| 5262 |
} |
| 5263 |
case ICK_HLSL_Matrix_Truncation: { |
| 5264 |
auto *FromMat = From->getType()->castAs<ConstantMatrixType>(); |
| 5265 |
QualType TruncTy = FromMat->getElementType(); |
| 5266 |
if (auto *ToMat = ToType->getAs<ConstantMatrixType>()) |
| 5267 |
TruncTy = Context.getConstantMatrixType(TruncTy, ToMat->getNumRows(), |
| 5268 |
ToMat->getNumColumns()); |
| 5269 |
From = ImpCastExprToType(From, TruncTy, CK_HLSLMatrixTruncation, |
| 5270 |
From->getValueKind()) |
| 5271 |
.get(); |
| 5272 |
break; |
| 5273 |
} |
| 5274 |
case ICK_Identity: |
| 5275 |
default: |
| 5276 |
llvm_unreachable("Improper element standard conversion"); |
| 5277 |
} |
| 5278 |
} |
| 5279 |
|
| 5280 |
switch (SCS.Third) { |
| 5281 |
case ICK_Identity: |
| 5282 |
// Nothing to do. |
| 5283 |
break; |
| 5284 |
|
| 5285 |
case ICK_Function_Conversion: |
| 5286 |
// If both sides are functions (or pointers/references to them), there could |
| 5287 |
// be incompatible exception declarations. |
| 5288 |
if (CheckExceptionSpecCompatibility(From, ToType)) |
| 5289 |
return ExprError(); |
| 5290 |
|
| 5291 |
From = ImpCastExprToType(From, ToType, CK_NoOp, VK_PRValue, |
| 5292 |
/*BasePath=*/nullptr, CCK) |
| 5293 |
.get(); |
| 5294 |
break; |
| 5295 |
|
| 5296 |
case ICK_Qualification: { |
| 5297 |
ExprValueKind VK = From->getValueKind(); |
| 5298 |
CastKind CK = CK_NoOp; |
| 5299 |
|
| 5300 |
if (ToType->isReferenceType() && |
| 5301 |
ToType->getPointeeType().getAddressSpace() != |
| 5302 |
From->getType().getAddressSpace()) |
| 5303 |
CK = CK_AddressSpaceConversion; |
| 5304 |
|
| 5305 |
if (ToType->isPointerType() && |
| 5306 |
ToType->getPointeeType().getAddressSpace() != |
| 5307 |
From->getType()->getPointeeType().getAddressSpace()) |
| 5308 |
CK = CK_AddressSpaceConversion; |
| 5309 |
|
| 5310 |
if (!isCast(CCK) && |
| 5311 |
!ToType->getPointeeType().getQualifiers().hasUnaligned() && |
| 5312 |
From->getType()->getPointeeType().getQualifiers().hasUnaligned()) { |
| 5313 |
Diag(From->getBeginLoc(), diag::warn_imp_cast_drops_unaligned) |
| 5314 |
<< InitialFromType << ToType; |
| 5315 |
} |
| 5316 |
|
| 5317 |
From = ImpCastExprToType(From, ToType.getNonLValueExprType(Context), CK, VK, |
| 5318 |
/*BasePath=*/nullptr, CCK) |
| 5319 |
.get(); |
| 5320 |
|
| 5321 |
if (SCS.DeprecatedStringLiteralToCharPtr && |
| 5322 |
!getLangOpts().WritableStrings) { |
| 5323 |
Diag(From->getBeginLoc(), |
| 5324 |
getLangOpts().CPlusPlus11 |
| 5325 |
? diag::ext_deprecated_string_literal_conversion |
| 5326 |
: diag::warn_deprecated_string_literal_conversion) |
| 5327 |
<< ToType.getNonReferenceType(); |
| 5328 |
} |
| 5329 |
|
| 5330 |
break; |
| 5331 |
} |
| 5332 |
|
| 5333 |
default: |
| 5334 |
llvm_unreachable("Improper third standard conversion"); |
| 5335 |
} |
| 5336 |
|
| 5337 |
// If this conversion sequence involved a scalar -> atomic conversion, perform |
| 5338 |
// that conversion now. |
| 5339 |
if (!ToAtomicType.isNull()) { |
| 5340 |
assert(Context.hasSameType( |
| 5341 |
ToAtomicType->castAs<AtomicType>()->getValueType(), From->getType())); |
| 5342 |
From = ImpCastExprToType(From, ToAtomicType, CK_NonAtomicToAtomic, |
| 5343 |
VK_PRValue, nullptr, CCK) |
| 5344 |
.get(); |
| 5345 |
} |
| 5346 |
|
| 5347 |
// Materialize a temporary if we're implicitly converting to a reference |
| 5348 |
// type. This is not required by the C++ rules but is necessary to maintain |
| 5349 |
// AST invariants. |
| 5350 |
if (ToType->isReferenceType() && From->isPRValue()) { |
| 5351 |
ExprResult Res = TemporaryMaterializationConversion(From); |
| 5352 |
if (Res.isInvalid()) |
| 5353 |
return ExprError(); |
| 5354 |
From = Res.get(); |
| 5355 |
} |
| 5356 |
|
| 5357 |
// If this conversion sequence succeeded and involved implicitly converting a |
| 5358 |
// _Nullable type to a _Nonnull one, complain. |
| 5359 |
if (!isCast(CCK)) |
| 5360 |
diagnoseNullableToNonnullConversion(ToType, InitialFromType, |
| 5361 |
From->getBeginLoc()); |
| 5362 |
|
| 5363 |
return From; |
| 5364 |
} |
| 5365 |
|
| 5366 |
QualType Sema::CheckPointerToMemberOperands(ExprResult &LHS, ExprResult &RHS, |
| 5367 |
ExprValueKind &VK, |
| 5368 |
SourceLocation Loc, |
| 5369 |
bool isIndirect) { |
| 5370 |
assert(!LHS.get()->hasPlaceholderType() && !RHS.get()->hasPlaceholderType() && |
| 5371 |
"placeholders should have been weeded out by now"); |
| 5372 |
|
| 5373 |
// The LHS undergoes lvalue conversions if this is ->*, and undergoes the |
| 5374 |
// temporary materialization conversion otherwise. |
| 5375 |
if (isIndirect) |
| 5376 |
LHS = DefaultLvalueConversion(LHS.get()); |
| 5377 |
else if (LHS.get()->isPRValue()) |
| 5378 |
LHS = TemporaryMaterializationConversion(LHS.get()); |
| 5379 |
if (LHS.isInvalid()) |
| 5380 |
return QualType(); |
| 5381 |
|
| 5382 |
// The RHS always undergoes lvalue conversions. |
| 5383 |
RHS = DefaultLvalueConversion(RHS.get()); |
| 5384 |
if (RHS.isInvalid()) return QualType(); |
| 5385 |
|
| 5386 |
const char *OpSpelling = isIndirect ? "->*" : ".*"; |
| 5387 |
// C++ 5.5p2 |
| 5388 |
// The binary operator .* [p3: ->*] binds its second operand, which shall |
| 5389 |
// be of type "pointer to member of T" (where T is a completely-defined |
| 5390 |
// class type) [...] |
| 5391 |
QualType RHSType = RHS.get()->getType(); |
| 5392 |
const MemberPointerType *MemPtr = RHSType->getAs<MemberPointerType>(); |
| 5393 |
if (!MemPtr) { |
| 5394 |
Diag(Loc, diag::err_bad_memptr_rhs) |
| 5395 |
<< OpSpelling << RHSType << RHS.get()->getSourceRange(); |
| 5396 |
return QualType(); |
| 5397 |
} |
| 5398 |
|
| 5399 |
CXXRecordDecl *RHSClass = MemPtr->getMostRecentCXXRecordDecl(); |
| 5400 |
|
| 5401 |
// Note: C++ [expr.mptr.oper]p2-3 says that the class type into which the |
| 5402 |
// member pointer points must be completely-defined. However, there is no |
| 5403 |
// reason for this semantic distinction, and the rule is not enforced by |
| 5404 |
// other compilers. Therefore, we do not check this property, as it is |
| 5405 |
// likely to be considered a defect. |
| 5406 |
|
| 5407 |
// C++ 5.5p2 |
| 5408 |
// [...] to its first operand, which shall be of class T or of a class of |
| 5409 |
// which T is an unambiguous and accessible base class. [p3: a pointer to |
| 5410 |
// such a class] |
| 5411 |
QualType LHSType = LHS.get()->getType(); |
| 5412 |
if (isIndirect) { |
| 5413 |
if (const PointerType *Ptr = LHSType->getAs<PointerType>()) |
| 5414 |
LHSType = Ptr->getPointeeType(); |
| 5415 |
else { |
| 5416 |
Diag(Loc, diag::err_bad_memptr_lhs) |
| 5417 |
<< OpSpelling << 1 << LHSType |
| 5418 |
<< FixItHint::CreateReplacement(SourceRange(Loc), ".*"); |
| 5419 |
return QualType(); |
| 5420 |
} |
| 5421 |
} |
| 5422 |
CXXRecordDecl *LHSClass = LHSType->getAsCXXRecordDecl(); |
| 5423 |
|
| 5424 |
if (!declaresSameEntity(LHSClass, RHSClass)) { |
| 5425 |
// If we want to check the hierarchy, we need a complete type. |
| 5426 |
if (RequireCompleteType(Loc, LHSType, diag::err_bad_memptr_lhs, |
| 5427 |
OpSpelling, (int)isIndirect)) { |
| 5428 |
return QualType(); |
| 5429 |
} |
| 5430 |
|
| 5431 |
if (!IsDerivedFrom(Loc, LHSClass, RHSClass)) { |
| 5432 |
Diag(Loc, diag::err_bad_memptr_lhs) << OpSpelling |
| 5433 |
<< (int)isIndirect << LHS.get()->getType(); |
| 5434 |
return QualType(); |
| 5435 |
} |
| 5436 |
|
| 5437 |
// FIXME: use sugared type from member pointer. |
| 5438 |
CanQualType RHSClassType = Context.getCanonicalTagType(RHSClass); |
| 5439 |
CXXCastPath BasePath; |
| 5440 |
if (CheckDerivedToBaseConversion( |
| 5441 |
LHSType, RHSClassType, Loc, |
| 5442 |
SourceRange(LHS.get()->getBeginLoc(), RHS.get()->getEndLoc()), |
| 5443 |
&BasePath)) |
| 5444 |
return QualType(); |
| 5445 |
|
| 5446 |
// Cast LHS to type of use. |
| 5447 |
QualType UseType = |
| 5448 |
Context.getQualifiedType(RHSClassType, LHSType.getQualifiers()); |
| 5449 |
if (isIndirect) |
| 5450 |
UseType = Context.getPointerType(UseType); |
| 5451 |
ExprValueKind VK = isIndirect ? VK_PRValue : LHS.get()->getValueKind(); |
| 5452 |
LHS = ImpCastExprToType(LHS.get(), UseType, CK_DerivedToBase, VK, |
| 5453 |
&BasePath); |
| 5454 |
} |
| 5455 |
|
| 5456 |
if (isa<CXXScalarValueInitExpr>(RHS.get()->IgnoreParens())) { |
| 5457 |
// Diagnose use of pointer-to-member type which when used as |
| 5458 |
// the functional cast in a pointer-to-member expression. |
| 5459 |
Diag(Loc, diag::err_pointer_to_member_type) << isIndirect; |
| 5460 |
return QualType(); |
| 5461 |
} |
| 5462 |
|
| 5463 |
// C++ 5.5p2 |
| 5464 |
// The result is an object or a function of the type specified by the |
| 5465 |
// second operand. |
| 5466 |
// The cv qualifiers are the union of those in the pointer and the left side, |
| 5467 |
// in accordance with 5.5p5 and 5.2.5. |
| 5468 |
QualType Result = MemPtr->getPointeeType(); |
| 5469 |
Result = Context.getCVRQualifiedType(Result, LHSType.getCVRQualifiers()); |
| 5470 |
|
| 5471 |
// C++0x [expr.mptr.oper]p6: |
| 5472 |
// In a .* expression whose object expression is an rvalue, the program is |
| 5473 |
// ill-formed if the second operand is a pointer to member function with |
| 5474 |
// ref-qualifier &. In a ->* expression or in a .* expression whose object |
| 5475 |
// expression is an lvalue, the program is ill-formed if the second operand |
| 5476 |
// is a pointer to member function with ref-qualifier &&. |
| 5477 |
if (const FunctionProtoType *Proto = Result->getAs<FunctionProtoType>()) { |
| 5478 |
switch (Proto->getRefQualifier()) { |
| 5479 |
case RQ_None: |
| 5480 |
// Do nothing |
| 5481 |
break; |
| 5482 |
|
| 5483 |
case RQ_LValue: |
| 5484 |
if (!isIndirect && !LHS.get()->Classify(Context).isLValue()) { |
| 5485 |
// C++2a allows functions with ref-qualifier & if their cv-qualifier-seq |
| 5486 |
// is (exactly) 'const'. |
| 5487 |
if (Proto->isConst() && !Proto->isVolatile()) |
| 5488 |
Diag(Loc, getLangOpts().CPlusPlus20 |
| 5489 |
? diag::warn_cxx17_compat_pointer_to_const_ref_member_on_rvalue |
| 5490 |
: diag::ext_pointer_to_const_ref_member_on_rvalue); |
| 5491 |
else |
| 5492 |
Diag(Loc, diag::err_pointer_to_member_oper_value_classify) |
| 5493 |
<< RHSType << 1 << LHS.get()->getSourceRange(); |
| 5494 |
} |
| 5495 |
break; |
| 5496 |
|
| 5497 |
case RQ_RValue: |
| 5498 |
if (isIndirect || !LHS.get()->Classify(Context).isRValue()) |
| 5499 |
Diag(Loc, diag::err_pointer_to_member_oper_value_classify) |
| 5500 |
<< RHSType << 0 << LHS.get()->getSourceRange(); |
| 5501 |
break; |
| 5502 |
} |
| 5503 |
} |
| 5504 |
|
| 5505 |
// C++ [expr.mptr.oper]p6: |
| 5506 |
// The result of a .* expression whose second operand is a pointer |
| 5507 |
// to a data member is of the same value category as its |
| 5508 |
// first operand. The result of a .* expression whose second |
| 5509 |
// operand is a pointer to a member function is a prvalue. The |
| 5510 |
// result of an ->* expression is an lvalue if its second operand |
| 5511 |
// is a pointer to data member and a prvalue otherwise. |
| 5512 |
if (Result->isFunctionType()) { |
| 5513 |
VK = VK_PRValue; |
| 5514 |
return Context.BoundMemberTy; |
| 5515 |
} else if (isIndirect) { |
| 5516 |
VK = VK_LValue; |
| 5517 |
} else { |
| 5518 |
VK = LHS.get()->getValueKind(); |
| 5519 |
} |
| 5520 |
|
| 5521 |
return Result; |
| 5522 |
} |
| 5523 |
|
| 5524 |
/// Try to convert a type to another according to C++11 5.16p3. |
| 5525 |
/// |
| 5526 |
/// This is part of the parameter validation for the ? operator. If either |
| 5527 |
/// value operand is a class type, the two operands are attempted to be |
| 5528 |
/// converted to each other. This function does the conversion in one direction. |
| 5529 |
/// It returns true if the program is ill-formed and has already been diagnosed |
| 5530 |
/// as such. |
| 5531 |
static bool TryClassUnification(Sema &Self, Expr *From, Expr *To, |
| 5532 |
SourceLocation QuestionLoc, |
| 5533 |
bool &HaveConversion, |
| 5534 |
QualType &ToType) { |
| 5535 |
HaveConversion = false; |
| 5536 |
ToType = To->getType(); |
| 5537 |
|
| 5538 |
InitializationKind Kind = |
| 5539 |
InitializationKind::CreateCopy(To->getBeginLoc(), SourceLocation()); |
| 5540 |
// C++11 5.16p3 |
| 5541 |
// The process for determining whether an operand expression E1 of type T1 |
| 5542 |
// can be converted to match an operand expression E2 of type T2 is defined |
| 5543 |
// as follows: |
| 5544 |
// -- If E2 is an lvalue: E1 can be converted to match E2 if E1 can be |
| 5545 |
// implicitly converted to type "lvalue reference to T2", subject to the |
| 5546 |
// constraint that in the conversion the reference must bind directly to |
| 5547 |
// an lvalue. |
| 5548 |
// -- If E2 is an xvalue: E1 can be converted to match E2 if E1 can be |
| 5549 |
// implicitly converted to the type "rvalue reference to R2", subject to |
| 5550 |
// the constraint that the reference must bind directly. |
| 5551 |
if (To->isGLValue()) { |
| 5552 |
QualType T = Self.Context.getReferenceQualifiedType(To); |
| 5553 |
InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); |
| 5554 |
|
| 5555 |
InitializationSequence InitSeq(Self, Entity, Kind, From); |
| 5556 |
if (InitSeq.isDirectReferenceBinding()) { |
| 5557 |
ToType = T; |
| 5558 |
HaveConversion = true; |
| 5559 |
return false; |
| 5560 |
} |
| 5561 |
|
| 5562 |
if (InitSeq.isAmbiguous()) |
| 5563 |
return InitSeq.Diagnose(Self, Entity, Kind, From); |
| 5564 |
} |
| 5565 |
|
| 5566 |
// -- If E2 is an rvalue, or if the conversion above cannot be done: |
| 5567 |
// -- if E1 and E2 have class type, and the underlying class types are |
| 5568 |
// the same or one is a base class of the other: |
| 5569 |
QualType FTy = From->getType(); |
| 5570 |
QualType TTy = To->getType(); |
| 5571 |
const RecordType *FRec = FTy->getAsCanonical<RecordType>(); |
| 5572 |
const RecordType *TRec = TTy->getAsCanonical<RecordType>(); |
| 5573 |
bool FDerivedFromT = FRec && TRec && FRec != TRec && |
| 5574 |
Self.IsDerivedFrom(QuestionLoc, FTy, TTy); |
| 5575 |
if (FRec && TRec && (FRec == TRec || FDerivedFromT || |
| 5576 |
Self.IsDerivedFrom(QuestionLoc, TTy, FTy))) { |
| 5577 |
// E1 can be converted to match E2 if the class of T2 is the |
| 5578 |
// same type as, or a base class of, the class of T1, and |
| 5579 |
// [cv2 > cv1]. |
| 5580 |
if (FRec == TRec || FDerivedFromT) { |
| 5581 |
if (TTy.isAtLeastAsQualifiedAs(FTy, Self.getASTContext())) { |
| 5582 |
InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); |
| 5583 |
InitializationSequence InitSeq(Self, Entity, Kind, From); |
| 5584 |
if (InitSeq) { |
| 5585 |
HaveConversion = true; |
| 5586 |
return false; |
| 5587 |
} |
| 5588 |
|
| 5589 |
if (InitSeq.isAmbiguous()) |
| 5590 |
return InitSeq.Diagnose(Self, Entity, Kind, From); |
| 5591 |
} |
| 5592 |
} |
| 5593 |
|
| 5594 |
return false; |
| 5595 |
} |
| 5596 |
|
| 5597 |
// -- Otherwise: E1 can be converted to match E2 if E1 can be |
| 5598 |
// implicitly converted to the type that expression E2 would have |
| 5599 |
// if E2 were converted to an rvalue (or the type it has, if E2 is |
| 5600 |
// an rvalue). |
| 5601 |
// |
| 5602 |
// This actually refers very narrowly to the lvalue-to-rvalue conversion, not |
| 5603 |
// to the array-to-pointer or function-to-pointer conversions. |
| 5604 |
TTy = TTy.getNonLValueExprType(Self.Context); |
| 5605 |
|
| 5606 |
InitializedEntity Entity = InitializedEntity::InitializeTemporary(TTy); |
| 5607 |
InitializationSequence InitSeq(Self, Entity, Kind, From); |
| 5608 |
HaveConversion = !InitSeq.Failed(); |
| 5609 |
ToType = TTy; |
| 5610 |
if (InitSeq.isAmbiguous()) |
| 5611 |
return InitSeq.Diagnose(Self, Entity, Kind, From); |
| 5612 |
|
| 5613 |
return false; |
| 5614 |
} |
| 5615 |
|
| 5616 |
/// Try to find a common type for two according to C++0x 5.16p5. |
| 5617 |
/// |
| 5618 |
/// This is part of the parameter validation for the ? operator. If either |
| 5619 |
/// value operand is a class type, overload resolution is used to find a |
| 5620 |
/// conversion to a common type. |
| 5621 |
static bool FindConditionalOverload(Sema &Self, ExprResult &LHS, ExprResult &RHS, |
| 5622 |
SourceLocation QuestionLoc) { |
| 5623 |
Expr *Args[2] = { LHS.get(), RHS.get() }; |
| 5624 |
OverloadCandidateSet CandidateSet(QuestionLoc, |
| 5625 |
OverloadCandidateSet::CSK_Operator); |
| 5626 |
Self.AddBuiltinOperatorCandidates(OO_Conditional, QuestionLoc, Args, |
| 5627 |
CandidateSet); |
| 5628 |
|
| 5629 |
OverloadCandidateSet::iterator Best; |
| 5630 |
switch (CandidateSet.BestViableFunction(Self, QuestionLoc, Best)) { |
| 5631 |
case OR_Success: { |
| 5632 |
// We found a match. Perform the conversions on the arguments and move on. |
| 5633 |
ExprResult LHSRes = Self.PerformImplicitConversion( |
| 5634 |
LHS.get(), Best->BuiltinParamTypes[0], Best->Conversions[0], |
| 5635 |
AssignmentAction::Converting); |
| 5636 |
if (LHSRes.isInvalid()) |
| 5637 |
break; |
| 5638 |
LHS = LHSRes; |
| 5639 |
|
| 5640 |
ExprResult RHSRes = Self.PerformImplicitConversion( |
| 5641 |
RHS.get(), Best->BuiltinParamTypes[1], Best->Conversions[1], |
| 5642 |
AssignmentAction::Converting); |
| 5643 |
if (RHSRes.isInvalid()) |
| 5644 |
break; |
| 5645 |
RHS = RHSRes; |
| 5646 |
if (Best->Function) |
| 5647 |
Self.MarkFunctionReferenced(QuestionLoc, Best->Function); |
| 5648 |
return false; |
| 5649 |
} |
| 5650 |
|
| 5651 |
case OR_No_Viable_Function: |
| 5652 |
|
| 5653 |
// Emit a better diagnostic if one of the expressions is a null pointer |
| 5654 |
// constant and the other is a pointer type. In this case, the user most |
| 5655 |
// likely forgot to take the address of the other expression. |
| 5656 |
if (Self.DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) |
| 5657 |
return true; |
| 5658 |
|
| 5659 |
Self.Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
| 5660 |
<< LHS.get()->getType() << RHS.get()->getType() |
| 5661 |
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 5662 |
return true; |
| 5663 |
|
| 5664 |
case OR_Ambiguous: |
| 5665 |
Self.Diag(QuestionLoc, diag::err_conditional_ambiguous_ovl) |
| 5666 |
<< LHS.get()->getType() << RHS.get()->getType() |
| 5667 |
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 5668 |
// FIXME: Print the possible common types by printing the return types of |
| 5669 |
// the viable candidates. |
| 5670 |
break; |
| 5671 |
|
| 5672 |
case OR_Deleted: |
| 5673 |
llvm_unreachable("Conditional operator has only built-in overloads"); |
| 5674 |
} |
| 5675 |
return true; |
| 5676 |
} |
| 5677 |
|
| 5678 |
/// Perform an "extended" implicit conversion as returned by |
| 5679 |
/// TryClassUnification. |
| 5680 |
static bool ConvertForConditional(Sema &Self, ExprResult &E, QualType T) { |
| 5681 |
InitializedEntity Entity = InitializedEntity::InitializeTemporary(T); |
| 5682 |
InitializationKind Kind = |
| 5683 |
InitializationKind::CreateCopy(E.get()->getBeginLoc(), SourceLocation()); |
| 5684 |
Expr *Arg = E.get(); |
| 5685 |
InitializationSequence InitSeq(Self, Entity, Kind, Arg); |
| 5686 |
ExprResult Result = InitSeq.Perform(Self, Entity, Kind, Arg); |
| 5687 |
if (Result.isInvalid()) |
| 5688 |
return true; |
| 5689 |
|
| 5690 |
E = Result; |
| 5691 |
return false; |
| 5692 |
} |
| 5693 |
|
| 5694 |
// Check the condition operand of ?: to see if it is valid for the GCC |
| 5695 |
// extension. |
| 5696 |
static bool isValidVectorForConditionalCondition(ASTContext &Ctx, |
| 5697 |
QualType CondTy) { |
| 5698 |
bool IsSVEVectorType = CondTy->isSveVLSBuiltinType(); |
| 5699 |
if (!CondTy->isVectorType() && !CondTy->isExtVectorType() && !IsSVEVectorType) |
| 5700 |
return false; |
| 5701 |
const QualType EltTy = |
| 5702 |
IsSVEVectorType |
| 5703 |
? cast<BuiltinType>(CondTy.getCanonicalType())->getSveEltType(Ctx) |
| 5704 |
: cast<VectorType>(CondTy.getCanonicalType())->getElementType(); |
| 5705 |
assert(!EltTy->isEnumeralType() && "Vectors cant be enum types"); |
| 5706 |
return EltTy->isIntegralType(Ctx); |
| 5707 |
} |
| 5708 |
|
| 5709 |
QualType Sema::CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, |
| 5710 |
ExprResult &RHS, |
| 5711 |
SourceLocation QuestionLoc) { |
| 5712 |
LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); |
| 5713 |
RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); |
| 5714 |
|
| 5715 |
QualType CondType = Cond.get()->getType(); |
| 5716 |
QualType LHSType = LHS.get()->getType(); |
| 5717 |
QualType RHSType = RHS.get()->getType(); |
| 5718 |
|
| 5719 |
bool LHSSizelessVector = LHSType->isSizelessVectorType(); |
| 5720 |
bool RHSSizelessVector = RHSType->isSizelessVectorType(); |
| 5721 |
bool LHSIsVector = LHSType->isVectorType() || LHSSizelessVector; |
| 5722 |
bool RHSIsVector = RHSType->isVectorType() || RHSSizelessVector; |
| 5723 |
|
| 5724 |
auto GetVectorInfo = |
| 5725 |
[&](QualType Type) -> std::pair<QualType, llvm::ElementCount> { |
| 5726 |
if (const auto *VT = Type->getAs<VectorType>()) |
| 5727 |
return std::make_pair(VT->getElementType(), |
| 5728 |
llvm::ElementCount::getFixed(VT->getNumElements())); |
| 5729 |
ASTContext::BuiltinVectorTypeInfo VectorInfo = |
| 5730 |
Context.getBuiltinVectorTypeInfo(Type->castAs<BuiltinType>()); |
| 5731 |
return std::make_pair(VectorInfo.ElementType, VectorInfo.EC); |
| 5732 |
}; |
| 5733 |
|
| 5734 |
auto [CondElementTy, CondElementCount] = GetVectorInfo(CondType); |
| 5735 |
|
| 5736 |
QualType ResultType; |
| 5737 |
if (LHSIsVector && RHSIsVector) { |
| 5738 |
if (CondType->isExtVectorType() != LHSType->isExtVectorType()) { |
| 5739 |
Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) |
| 5740 |
<< /*isExtVectorNotSizeless=*/1; |
| 5741 |
return {}; |
| 5742 |
} |
| 5743 |
|
| 5744 |
// If both are vector types, they must be the same type. |
| 5745 |
if (!Context.hasSameType(LHSType, RHSType)) { |
| 5746 |
Diag(QuestionLoc, diag::err_conditional_vector_mismatched) |
| 5747 |
<< LHSType << RHSType; |
| 5748 |
return {}; |
| 5749 |
} |
| 5750 |
ResultType = Context.getCommonSugaredType(LHSType, RHSType); |
| 5751 |
} else if (LHSIsVector || RHSIsVector) { |
| 5752 |
bool ResultSizeless = LHSSizelessVector || RHSSizelessVector; |
| 5753 |
if (ResultSizeless != CondType->isSizelessVectorType()) { |
| 5754 |
Diag(QuestionLoc, diag::err_conditional_vector_cond_result_mismatch) |
| 5755 |
<< /*isExtVectorNotSizeless=*/0; |
| 5756 |
return {}; |
| 5757 |
} |
| 5758 |
if (ResultSizeless) |
| 5759 |
ResultType = CheckSizelessVectorOperands(LHS, RHS, QuestionLoc, |
| 5760 |
/*IsCompAssign*/ false, |
| 5761 |
ArithConvKind::Conditional); |
| 5762 |
else |
| 5763 |
ResultType = CheckVectorOperands( |
| 5764 |
LHS, RHS, QuestionLoc, /*isCompAssign*/ false, /*AllowBothBool*/ true, |
| 5765 |
/*AllowBoolConversions*/ false, |
| 5766 |
/*AllowBoolOperation*/ true, |
| 5767 |
/*ReportInvalid*/ true); |
| 5768 |
if (ResultType.isNull()) |
| 5769 |
return {}; |
| 5770 |
} else { |
| 5771 |
// Both are scalar. |
| 5772 |
LHSType = LHSType.getUnqualifiedType(); |
| 5773 |
RHSType = RHSType.getUnqualifiedType(); |
| 5774 |
QualType ResultElementTy = |
| 5775 |
Context.hasSameType(LHSType, RHSType) |
| 5776 |
? Context.getCommonSugaredType(LHSType, RHSType) |
| 5777 |
: UsualArithmeticConversions(LHS, RHS, QuestionLoc, |
| 5778 |
ArithConvKind::Conditional); |
| 5779 |
|
| 5780 |
if (ResultElementTy->isEnumeralType()) { |
| 5781 |
Diag(QuestionLoc, diag::err_conditional_vector_operand_type) |
| 5782 |
<< ResultElementTy; |
| 5783 |
return {}; |
| 5784 |
} |
| 5785 |
if (CondType->isExtVectorType()) { |
| 5786 |
ResultType = Context.getExtVectorType(ResultElementTy, |
| 5787 |
CondElementCount.getFixedValue()); |
| 5788 |
} else if (CondType->isSizelessVectorType()) { |
| 5789 |
ResultType = Context.getScalableVectorType( |
| 5790 |
ResultElementTy, CondElementCount.getKnownMinValue()); |
| 5791 |
// There are not scalable vector type mappings for all element counts. |
| 5792 |
if (ResultType.isNull()) { |
| 5793 |
Diag(QuestionLoc, diag::err_conditional_vector_scalar_type_unsupported) |
| 5794 |
<< ResultElementTy << CondType; |
| 5795 |
return {}; |
| 5796 |
} |
| 5797 |
} else { |
| 5798 |
ResultType = Context.getVectorType(ResultElementTy, |
| 5799 |
CondElementCount.getFixedValue(), |
| 5800 |
VectorKind::Generic); |
| 5801 |
} |
| 5802 |
LHS = ImpCastExprToType(LHS.get(), ResultType, CK_VectorSplat); |
| 5803 |
RHS = ImpCastExprToType(RHS.get(), ResultType, CK_VectorSplat); |
| 5804 |
} |
| 5805 |
|
| 5806 |
assert(!ResultType.isNull() && |
| 5807 |
(ResultType->isVectorType() || ResultType->isSizelessVectorType()) && |
| 5808 |
(!CondType->isExtVectorType() || ResultType->isExtVectorType()) && |
| 5809 |
"Result should have been a vector type"); |
| 5810 |
|
| 5811 |
auto [ResultElementTy, ResultElementCount] = GetVectorInfo(ResultType); |
| 5812 |
if (ResultElementCount != CondElementCount) { |
| 5813 |
Diag(QuestionLoc, diag::err_conditional_vector_size) << CondType |
| 5814 |
<< ResultType; |
| 5815 |
return {}; |
| 5816 |
} |
| 5817 |
|
| 5818 |
// Boolean vectors are permitted outside of OpenCL mode. |
| 5819 |
if (Context.getTypeSize(ResultElementTy) != |
| 5820 |
Context.getTypeSize(CondElementTy) && |
| 5821 |
(!CondElementTy->isBooleanType() || LangOpts.OpenCL)) { |
| 5822 |
Diag(QuestionLoc, diag::err_conditional_vector_element_size) |
| 5823 |
<< CondType << ResultType; |
| 5824 |
return {}; |
| 5825 |
} |
| 5826 |
|
| 5827 |
return ResultType; |
| 5828 |
} |
| 5829 |
|
| 5830 |
QualType Sema::CXXCheckConditionalOperands(ExprResult &Cond, ExprResult &LHS, |
| 5831 |
ExprResult &RHS, ExprValueKind &VK, |
| 5832 |
ExprObjectKind &OK, |
| 5833 |
SourceLocation QuestionLoc) { |
| 5834 |
// FIXME: Handle C99's complex types, block pointers and Obj-C++ interface |
| 5835 |
// pointers. |
| 5836 |
|
| 5837 |
// Assume r-value. |
| 5838 |
VK = VK_PRValue; |
| 5839 |
OK = OK_Ordinary; |
| 5840 |
bool IsVectorConditional = |
| 5841 |
isValidVectorForConditionalCondition(Context, Cond.get()->getType()); |
| 5842 |
|
| 5843 |
// C++11 [expr.cond]p1 |
| 5844 |
// The first expression is contextually converted to bool. |
| 5845 |
if (!Cond.get()->isTypeDependent()) { |
| 5846 |
ExprResult CondRes = IsVectorConditional |
| 5847 |
? DefaultFunctionArrayLvalueConversion(Cond.get()) |
| 5848 |
: CheckCXXBooleanCondition(Cond.get()); |
| 5849 |
if (CondRes.isInvalid()) |
| 5850 |
return QualType(); |
| 5851 |
Cond = CondRes; |
| 5852 |
} else { |
| 5853 |
// To implement C++, the first expression typically doesn't alter the result |
| 5854 |
// type of the conditional, however the GCC compatible vector extension |
| 5855 |
// changes the result type to be that of the conditional. Since we cannot |
| 5856 |
// know if this is a vector extension here, delay the conversion of the |
| 5857 |
// LHS/RHS below until later. |
| 5858 |
return Context.DependentTy; |
| 5859 |
} |
| 5860 |
|
| 5861 |
|
| 5862 |
// Either of the arguments dependent? |
| 5863 |
if (LHS.get()->isTypeDependent() || RHS.get()->isTypeDependent()) |
| 5864 |
return Context.DependentTy; |
| 5865 |
|
| 5866 |
// C++11 [expr.cond]p2 |
| 5867 |
// If either the second or the third operand has type (cv) void, ... |
| 5868 |
QualType LTy = LHS.get()->getType(); |
| 5869 |
QualType RTy = RHS.get()->getType(); |
| 5870 |
bool LVoid = LTy->isVoidType(); |
| 5871 |
bool RVoid = RTy->isVoidType(); |
| 5872 |
if (LVoid || RVoid) { |
| 5873 |
// ... one of the following shall hold: |
| 5874 |
// -- The second or the third operand (but not both) is a (possibly |
| 5875 |
// parenthesized) throw-expression; the result is of the type |
| 5876 |
// and value category of the other. |
| 5877 |
bool LThrow = isa<CXXThrowExpr>(LHS.get()->IgnoreParenImpCasts()); |
| 5878 |
bool RThrow = isa<CXXThrowExpr>(RHS.get()->IgnoreParenImpCasts()); |
| 5879 |
|
| 5880 |
// Void expressions aren't legal in the vector-conditional expressions. |
| 5881 |
if (IsVectorConditional) { |
| 5882 |
SourceRange DiagLoc = |
| 5883 |
LVoid ? LHS.get()->getSourceRange() : RHS.get()->getSourceRange(); |
| 5884 |
bool IsThrow = LVoid ? LThrow : RThrow; |
| 5885 |
Diag(DiagLoc.getBegin(), diag::err_conditional_vector_has_void) |
| 5886 |
<< DiagLoc << IsThrow; |
| 5887 |
return QualType(); |
| 5888 |
} |
| 5889 |
|
| 5890 |
if (LThrow != RThrow) { |
| 5891 |
Expr *NonThrow = LThrow ? RHS.get() : LHS.get(); |
| 5892 |
VK = NonThrow->getValueKind(); |
| 5893 |
// DR (no number yet): the result is a bit-field if the |
| 5894 |
// non-throw-expression operand is a bit-field. |
| 5895 |
OK = NonThrow->getObjectKind(); |
| 5896 |
return NonThrow->getType(); |
| 5897 |
} |
| 5898 |
|
| 5899 |
// -- Both the second and third operands have type void; the result is of |
| 5900 |
// type void and is a prvalue. |
| 5901 |
if (LVoid && RVoid) |
| 5902 |
return Context.getCommonSugaredType(LTy, RTy); |
| 5903 |
|
| 5904 |
// Neither holds, error. |
| 5905 |
Diag(QuestionLoc, diag::err_conditional_void_nonvoid) |
| 5906 |
<< (LVoid ? RTy : LTy) << (LVoid ? 0 : 1) |
| 5907 |
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 5908 |
return QualType(); |
| 5909 |
} |
| 5910 |
|
| 5911 |
// Neither is void. |
| 5912 |
if (IsVectorConditional) |
| 5913 |
return CheckVectorConditionalTypes(Cond, LHS, RHS, QuestionLoc); |
| 5914 |
|
| 5915 |
// WebAssembly tables are not allowed as conditional LHS or RHS. |
| 5916 |
if (LTy->isWebAssemblyTableType() || RTy->isWebAssemblyTableType()) { |
| 5917 |
Diag(QuestionLoc, diag::err_wasm_table_conditional_expression) |
| 5918 |
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 5919 |
return QualType(); |
| 5920 |
} |
| 5921 |
|
| 5922 |
// C++11 [expr.cond]p3 |
| 5923 |
// Otherwise, if the second and third operand have different types, and |
| 5924 |
// either has (cv) class type [...] an attempt is made to convert each of |
| 5925 |
// those operands to the type of the other. |
| 5926 |
if (!Context.hasSameType(LTy, RTy) && |
| 5927 |
(LTy->isRecordType() || RTy->isRecordType())) { |
| 5928 |
// These return true if a single direction is already ambiguous. |
| 5929 |
QualType L2RType, R2LType; |
| 5930 |
bool HaveL2R, HaveR2L; |
| 5931 |
if (TryClassUnification(*this, LHS.get(), RHS.get(), QuestionLoc, HaveL2R, L2RType)) |
| 5932 |
return QualType(); |
| 5933 |
if (TryClassUnification(*this, RHS.get(), LHS.get(), QuestionLoc, HaveR2L, R2LType)) |
| 5934 |
return QualType(); |
| 5935 |
|
| 5936 |
// If both can be converted, [...] the program is ill-formed. |
| 5937 |
if (HaveL2R && HaveR2L) { |
| 5938 |
Diag(QuestionLoc, diag::err_conditional_ambiguous) |
| 5939 |
<< LTy << RTy << LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 5940 |
return QualType(); |
| 5941 |
} |
| 5942 |
|
| 5943 |
// If exactly one conversion is possible, that conversion is applied to |
| 5944 |
// the chosen operand and the converted operands are used in place of the |
| 5945 |
// original operands for the remainder of this section. |
| 5946 |
if (HaveL2R) { |
| 5947 |
if (ConvertForConditional(*this, LHS, L2RType) || LHS.isInvalid()) |
| 5948 |
return QualType(); |
| 5949 |
LTy = LHS.get()->getType(); |
| 5950 |
} else if (HaveR2L) { |
| 5951 |
if (ConvertForConditional(*this, RHS, R2LType) || RHS.isInvalid()) |
| 5952 |
return QualType(); |
| 5953 |
RTy = RHS.get()->getType(); |
| 5954 |
} |
| 5955 |
} |
| 5956 |
|
| 5957 |
// C++11 [expr.cond]p3 |
| 5958 |
// if both are glvalues of the same value category and the same type except |
| 5959 |
// for cv-qualification, an attempt is made to convert each of those |
| 5960 |
// operands to the type of the other. |
| 5961 |
// FIXME: |
| 5962 |
// Resolving a defect in P0012R1: we extend this to cover all cases where |
| 5963 |
// one of the operands is reference-compatible with the other, in order |
| 5964 |
// to support conditionals between functions differing in noexcept. This |
| 5965 |
// will similarly cover difference in array bounds after P0388R4. |
| 5966 |
// FIXME: If LTy and RTy have a composite pointer type, should we convert to |
| 5967 |
// that instead? |
| 5968 |
ExprValueKind LVK = LHS.get()->getValueKind(); |
| 5969 |
ExprValueKind RVK = RHS.get()->getValueKind(); |
| 5970 |
if (!Context.hasSameType(LTy, RTy) && LVK == RVK && LVK != VK_PRValue) { |
| 5971 |
// DerivedToBase was already handled by the class-specific case above. |
| 5972 |
// FIXME: Should we allow ObjC conversions here? |
| 5973 |
const ReferenceConversions AllowedConversions = |
| 5974 |
ReferenceConversions::Qualification | |
| 5975 |
ReferenceConversions::NestedQualification | |
| 5976 |
ReferenceConversions::Function; |
| 5977 |
|
| 5978 |
ReferenceConversions RefConv; |
| 5979 |
if (CompareReferenceRelationship(QuestionLoc, LTy, RTy, &RefConv) == |
| 5980 |
Ref_Compatible && |
| 5981 |
!(RefConv & ~AllowedConversions) && |
| 5982 |
// [...] subject to the constraint that the reference must bind |
| 5983 |
// directly [...] |
| 5984 |
!RHS.get()->refersToBitField() && !RHS.get()->refersToVectorElement()) { |
| 5985 |
RHS = ImpCastExprToType(RHS.get(), LTy, CK_NoOp, RVK); |
| 5986 |
RTy = RHS.get()->getType(); |
| 5987 |
} else if (CompareReferenceRelationship(QuestionLoc, RTy, LTy, &RefConv) == |
| 5988 |
Ref_Compatible && |
| 5989 |
!(RefConv & ~AllowedConversions) && |
| 5990 |
!LHS.get()->refersToBitField() && |
| 5991 |
!LHS.get()->refersToVectorElement()) { |
| 5992 |
LHS = ImpCastExprToType(LHS.get(), RTy, CK_NoOp, LVK); |
| 5993 |
LTy = LHS.get()->getType(); |
| 5994 |
} |
| 5995 |
} |
| 5996 |
|
| 5997 |
// C++11 [expr.cond]p4 |
| 5998 |
// If the second and third operands are glvalues of the same value |
| 5999 |
// category and have the same type, the result is of that type and |
| 6000 |
// value category and it is a bit-field if the second or the third |
| 6001 |
// operand is a bit-field, or if both are bit-fields. |
| 6002 |
// We only extend this to bitfields, not to the crazy other kinds of |
| 6003 |
// l-values. |
| 6004 |
bool Same = Context.hasSameType(LTy, RTy); |
| 6005 |
if (Same && LVK == RVK && LVK != VK_PRValue && |
| 6006 |
LHS.get()->isOrdinaryOrBitFieldObject() && |
| 6007 |
RHS.get()->isOrdinaryOrBitFieldObject()) { |
| 6008 |
VK = LHS.get()->getValueKind(); |
| 6009 |
if (LHS.get()->getObjectKind() == OK_BitField || |
| 6010 |
RHS.get()->getObjectKind() == OK_BitField) |
| 6011 |
OK = OK_BitField; |
| 6012 |
return Context.getCommonSugaredType(LTy, RTy); |
| 6013 |
} |
| 6014 |
|
| 6015 |
// C++11 [expr.cond]p5 |
| 6016 |
// Otherwise, the result is a prvalue. If the second and third operands |
| 6017 |
// do not have the same type, and either has (cv) class type, ... |
| 6018 |
if (!Same && (LTy->isRecordType() || RTy->isRecordType())) { |
| 6019 |
// ... overload resolution is used to determine the conversions (if any) |
| 6020 |
// to be applied to the operands. If the overload resolution fails, the |
| 6021 |
// program is ill-formed. |
| 6022 |
if (FindConditionalOverload(*this, LHS, RHS, QuestionLoc)) |
| 6023 |
return QualType(); |
| 6024 |
} |
| 6025 |
|
| 6026 |
// C++11 [expr.cond]p6 |
| 6027 |
// Lvalue-to-rvalue, array-to-pointer, and function-to-pointer standard |
| 6028 |
// conversions are performed on the second and third operands. |
| 6029 |
LHS = DefaultFunctionArrayLvalueConversion(LHS.get()); |
| 6030 |
RHS = DefaultFunctionArrayLvalueConversion(RHS.get()); |
| 6031 |
if (LHS.isInvalid() || RHS.isInvalid()) |
| 6032 |
return QualType(); |
| 6033 |
LTy = LHS.get()->getType(); |
| 6034 |
RTy = RHS.get()->getType(); |
| 6035 |
|
| 6036 |
// After those conversions, one of the following shall hold: |
| 6037 |
// -- The second and third operands have the same type; the result |
| 6038 |
// is of that type. If the operands have class type, the result |
| 6039 |
// is a prvalue temporary of the result type, which is |
| 6040 |
// copy-initialized from either the second operand or the third |
| 6041 |
// operand depending on the value of the first operand. |
| 6042 |
if (Context.hasSameType(LTy, RTy)) { |
| 6043 |
if (LTy->isRecordType()) { |
| 6044 |
// The operands have class type. Make a temporary copy. |
| 6045 |
ExprResult LHSCopy = PerformCopyInitialization( |
| 6046 |
InitializedEntity::InitializeTemporary(LTy), SourceLocation(), LHS); |
| 6047 |
if (LHSCopy.isInvalid()) |
| 6048 |
return QualType(); |
| 6049 |
|
| 6050 |
ExprResult RHSCopy = PerformCopyInitialization( |
| 6051 |
InitializedEntity::InitializeTemporary(RTy), SourceLocation(), RHS); |
| 6052 |
if (RHSCopy.isInvalid()) |
| 6053 |
return QualType(); |
| 6054 |
|
| 6055 |
LHS = LHSCopy; |
| 6056 |
RHS = RHSCopy; |
| 6057 |
} |
| 6058 |
return Context.getCommonSugaredType(LTy, RTy); |
| 6059 |
} |
| 6060 |
|
| 6061 |
// Extension: conditional operator involving vector types. |
| 6062 |
if (LTy->isVectorType() || RTy->isVectorType()) |
| 6063 |
return CheckVectorOperands(LHS, RHS, QuestionLoc, /*isCompAssign*/ false, |
| 6064 |
/*AllowBothBool*/ true, |
| 6065 |
/*AllowBoolConversions*/ false, |
| 6066 |
/*AllowBoolOperation*/ false, |
| 6067 |
/*ReportInvalid*/ true); |
| 6068 |
|
| 6069 |
// -- The second and third operands have arithmetic or enumeration type; |
| 6070 |
// the usual arithmetic conversions are performed to bring them to a |
| 6071 |
// common type, and the result is of that type. |
| 6072 |
if (LTy->isArithmeticType() && RTy->isArithmeticType()) { |
| 6073 |
QualType ResTy = UsualArithmeticConversions(LHS, RHS, QuestionLoc, |
| 6074 |
ArithConvKind::Conditional); |
| 6075 |
if (LHS.isInvalid() || RHS.isInvalid()) |
| 6076 |
return QualType(); |
| 6077 |
if (ResTy.isNull()) { |
| 6078 |
Diag(QuestionLoc, |
| 6079 |
diag::err_typecheck_cond_incompatible_operands) << LTy << RTy |
| 6080 |
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 6081 |
return QualType(); |
| 6082 |
} |
| 6083 |
|
| 6084 |
LHS = ImpCastExprToType(LHS.get(), ResTy, PrepareScalarCast(LHS, ResTy)); |
| 6085 |
RHS = ImpCastExprToType(RHS.get(), ResTy, PrepareScalarCast(RHS, ResTy)); |
| 6086 |
|
| 6087 |
return ResTy; |
| 6088 |
} |
| 6089 |
|
| 6090 |
// -- The second and third operands have pointer type, or one has pointer |
| 6091 |
// type and the other is a null pointer constant, or both are null |
| 6092 |
// pointer constants, at least one of which is non-integral; pointer |
| 6093 |
// conversions and qualification conversions are performed to bring them |
| 6094 |
// to their composite pointer type. The result is of the composite |
| 6095 |
// pointer type. |
| 6096 |
// -- The second and third operands have pointer to member type, or one has |
| 6097 |
// pointer to member type and the other is a null pointer constant; |
| 6098 |
// pointer to member conversions and qualification conversions are |
| 6099 |
// performed to bring them to a common type, whose cv-qualification |
| 6100 |
// shall match the cv-qualification of either the second or the third |
| 6101 |
// operand. The result is of the common type. |
| 6102 |
QualType Composite = FindCompositePointerType(QuestionLoc, LHS, RHS); |
| 6103 |
if (!Composite.isNull()) |
| 6104 |
return Composite; |
| 6105 |
|
| 6106 |
// Similarly, attempt to find composite type of two objective-c pointers. |
| 6107 |
Composite = ObjC().FindCompositeObjCPointerType(LHS, RHS, QuestionLoc); |
| 6108 |
if (LHS.isInvalid() || RHS.isInvalid()) |
| 6109 |
return QualType(); |
| 6110 |
if (!Composite.isNull()) |
| 6111 |
return Composite; |
| 6112 |
|
| 6113 |
// Check if we are using a null with a non-pointer type. |
| 6114 |
if (DiagnoseConditionalForNull(LHS.get(), RHS.get(), QuestionLoc)) |
| 6115 |
return QualType(); |
| 6116 |
|
| 6117 |
Diag(QuestionLoc, diag::err_typecheck_cond_incompatible_operands) |
| 6118 |
<< LHS.get()->getType() << RHS.get()->getType() |
| 6119 |
<< LHS.get()->getSourceRange() << RHS.get()->getSourceRange(); |
| 6120 |
return QualType(); |
| 6121 |
} |
| 6122 |
|
| 6123 |
QualType Sema::FindCompositePointerType(SourceLocation Loc, |
| 6124 |
Expr *&E1, Expr *&E2, |
| 6125 |
bool ConvertArgs) { |
| 6126 |
assert(getLangOpts().CPlusPlus && "This function assumes C++"); |
| 6127 |
|
| 6128 |
// C++1z [expr]p14: |
| 6129 |
// The composite pointer type of two operands p1 and p2 having types T1 |
| 6130 |
// and T2 |
| 6131 |
QualType T1 = E1->getType(), T2 = E2->getType(); |
| 6132 |
|
| 6133 |
// where at least one is a pointer or pointer to member type or |
| 6134 |
// std::nullptr_t is: |
| 6135 |
bool T1IsPointerLike = T1->isAnyPointerType() || T1->isMemberPointerType() || |
| 6136 |
T1->isNullPtrType(); |
| 6137 |
bool T2IsPointerLike = T2->isAnyPointerType() || T2->isMemberPointerType() || |
| 6138 |
T2->isNullPtrType(); |
| 6139 |
if (!T1IsPointerLike && !T2IsPointerLike) |
| 6140 |
return QualType(); |
| 6141 |
|
| 6142 |
// - if both p1 and p2 are null pointer constants, std::nullptr_t; |
| 6143 |
// This can't actually happen, following the standard, but we also use this |
| 6144 |
// to implement the end of [expr.conv], which hits this case. |
| 6145 |
// |
| 6146 |
// - if either p1 or p2 is a null pointer constant, T2 or T1, respectively; |
| 6147 |
if (T1IsPointerLike && |
| 6148 |
E2->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { |
| 6149 |
if (ConvertArgs) |
| 6150 |
E2 = ImpCastExprToType(E2, T1, T1->isMemberPointerType() |
| 6151 |
? CK_NullToMemberPointer |
| 6152 |
: CK_NullToPointer).get(); |
| 6153 |
return T1; |
| 6154 |
} |
| 6155 |
if (T2IsPointerLike && |
| 6156 |
E1->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) { |
| 6157 |
if (ConvertArgs) |
| 6158 |
E1 = ImpCastExprToType(E1, T2, T2->isMemberPointerType() |
| 6159 |
? CK_NullToMemberPointer |
| 6160 |
: CK_NullToPointer).get(); |
| 6161 |
return T2; |
| 6162 |
} |
| 6163 |
|
| 6164 |
// Now both have to be pointers or member pointers. |
| 6165 |
if (!T1IsPointerLike || !T2IsPointerLike) |
| 6166 |
return QualType(); |
| 6167 |
assert(!T1->isNullPtrType() && !T2->isNullPtrType() && |
| 6168 |
"nullptr_t should be a null pointer constant"); |
| 6169 |
|
| 6170 |
struct Step { |
| 6171 |
enum Kind { Pointer, ObjCPointer, MemberPointer, Array } K; |
| 6172 |
// Qualifiers to apply under the step kind. |
| 6173 |
Qualifiers Quals; |
| 6174 |
/// The class for a pointer-to-member; a constant array type with a bound |
| 6175 |
/// (if any) for an array. |
| 6176 |
/// FIXME: Store Qualifier for pointer-to-member. |
| 6177 |
const Type *ClassOrBound; |
| 6178 |
|
| 6179 |
Step(Kind K, const Type *ClassOrBound = nullptr) |
| 6180 |
: K(K), ClassOrBound(ClassOrBound) {} |
| 6181 |
QualType rebuild(ASTContext &Ctx, QualType T) const { |
| 6182 |
T = Ctx.getQualifiedType(T, Quals); |
| 6183 |
switch (K) { |
| 6184 |
case Pointer: |
| 6185 |
return Ctx.getPointerType(T); |
| 6186 |
case MemberPointer: |
| 6187 |
return Ctx.getMemberPointerType(T, /*Qualifier=*/std::nullopt, |
| 6188 |
ClassOrBound->getAsCXXRecordDecl()); |
| 6189 |
case ObjCPointer: |
| 6190 |
return Ctx.getObjCObjectPointerType(T); |
| 6191 |
case Array: |
| 6192 |
if (auto *CAT = cast_or_null<ConstantArrayType>(ClassOrBound)) |
| 6193 |
return Ctx.getConstantArrayType(T, CAT->getSize(), nullptr, |
| 6194 |
ArraySizeModifier::Normal, 0); |
| 6195 |
else |
| 6196 |
return Ctx.getIncompleteArrayType(T, ArraySizeModifier::Normal, 0); |
| 6197 |
} |
| 6198 |
llvm_unreachable("unknown step kind"); |
| 6199 |
} |
| 6200 |
}; |
| 6201 |
|
| 6202 |
SmallVector<Step, 8> Steps; |
| 6203 |
|
| 6204 |
// - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 |
| 6205 |
// is reference-related to C2 or C2 is reference-related to C1 (8.6.3), |
| 6206 |
// the cv-combined type of T1 and T2 or the cv-combined type of T2 and T1, |
| 6207 |
// respectively; |
| 6208 |
// - if T1 is "pointer to member of C1 of type cv1 U1" and T2 is "pointer |
| 6209 |
// to member of C2 of type cv2 U2" for some non-function type U, where |
| 6210 |
// C1 is reference-related to C2 or C2 is reference-related to C1, the |
| 6211 |
// cv-combined type of T2 and T1 or the cv-combined type of T1 and T2, |
| 6212 |
// respectively; |
| 6213 |
// - if T1 and T2 are similar types (4.5), the cv-combined type of T1 and |
| 6214 |
// T2; |
| 6215 |
// |
| 6216 |
// Dismantle T1 and T2 to simultaneously determine whether they are similar |
| 6217 |
// and to prepare to form the cv-combined type if so. |
| 6218 |
QualType Composite1 = T1; |
| 6219 |
QualType Composite2 = T2; |
| 6220 |
unsigned NeedConstBefore = 0; |
| 6221 |
while (true) { |
| 6222 |
assert(!Composite1.isNull() && !Composite2.isNull()); |
| 6223 |
|
| 6224 |
Qualifiers Q1, Q2; |
| 6225 |
Composite1 = Context.getUnqualifiedArrayType(Composite1, Q1); |
| 6226 |
Composite2 = Context.getUnqualifiedArrayType(Composite2, Q2); |
| 6227 |
|
| 6228 |
// Top-level qualifiers are ignored. Merge at all lower levels. |
| 6229 |
if (!Steps.empty()) { |
| 6230 |
// Find the qualifier union: (approximately) the unique minimal set of |
| 6231 |
// qualifiers that is compatible with both types. |
| 6232 |
Qualifiers Quals = Qualifiers::fromCVRUMask(Q1.getCVRUQualifiers() | |
| 6233 |
Q2.getCVRUQualifiers()); |
| 6234 |
|
| 6235 |
// Under one level of pointer or pointer-to-member, we can change to an |
| 6236 |
// unambiguous compatible address space. |
| 6237 |
if (Q1.getAddressSpace() == Q2.getAddressSpace()) { |
| 6238 |
Quals.setAddressSpace(Q1.getAddressSpace()); |
| 6239 |
} else if (Steps.size() == 1) { |
| 6240 |
bool MaybeQ1 = Q1.isAddressSpaceSupersetOf(Q2, getASTContext()); |
| 6241 |
bool MaybeQ2 = Q2.isAddressSpaceSupersetOf(Q1, getASTContext()); |
| 6242 |
if (MaybeQ1 == MaybeQ2) { |
| 6243 |
// Exception for ptr size address spaces. Should be able to choose |
| 6244 |
// either address space during comparison. |
| 6245 |
if (isPtrSizeAddressSpace(Q1.getAddressSpace()) || |
| 6246 |
isPtrSizeAddressSpace(Q2.getAddressSpace())) |
| 6247 |
MaybeQ1 = true; |
| 6248 |
else |
| 6249 |
return QualType(); // No unique best address space. |
| 6250 |
} |
| 6251 |
Quals.setAddressSpace(MaybeQ1 ? Q1.getAddressSpace() |
| 6252 |
: Q2.getAddressSpace()); |
| 6253 |
} else { |
| 6254 |
return QualType(); |
| 6255 |
} |
| 6256 |
|
| 6257 |
// FIXME: In C, we merge __strong and none to __strong at the top level. |
| 6258 |
if (Q1.getObjCGCAttr() == Q2.getObjCGCAttr()) |
| 6259 |
Quals.setObjCGCAttr(Q1.getObjCGCAttr()); |
| 6260 |
else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
| 6261 |
assert(Steps.size() == 1); |
| 6262 |
else |
| 6263 |
return QualType(); |
| 6264 |
|
| 6265 |
// Mismatched lifetime qualifiers never compatibly include each other. |
| 6266 |
if (Q1.getObjCLifetime() == Q2.getObjCLifetime()) |
| 6267 |
Quals.setObjCLifetime(Q1.getObjCLifetime()); |
| 6268 |
else if (T1->isVoidPointerType() || T2->isVoidPointerType()) |
| 6269 |
assert(Steps.size() == 1); |
| 6270 |
else |
| 6271 |
return QualType(); |
| 6272 |
|
| 6273 |
if (Q1.getPointerAuth().isEquivalent(Q2.getPointerAuth())) |
| 6274 |
Quals.setPointerAuth(Q1.getPointerAuth()); |
| 6275 |
else |
| 6276 |
return QualType(); |
| 6277 |
|
| 6278 |
Steps.back().Quals = Quals; |
| 6279 |
if (Q1 != Quals || Q2 != Quals) |
| 6280 |
NeedConstBefore = Steps.size() - 1; |
| 6281 |
} |
| 6282 |
|
| 6283 |
// FIXME: Can we unify the following with UnwrapSimilarTypes? |
| 6284 |
|
| 6285 |
const ArrayType *Arr1, *Arr2; |
| 6286 |
if ((Arr1 = Context.getAsArrayType(Composite1)) && |
| 6287 |
(Arr2 = Context.getAsArrayType(Composite2))) { |
| 6288 |
auto *CAT1 = dyn_cast<ConstantArrayType>(Arr1); |
| 6289 |
auto *CAT2 = dyn_cast<ConstantArrayType>(Arr2); |
| 6290 |
if (CAT1 && CAT2 && CAT1->getSize() == CAT2->getSize()) { |
| 6291 |
Composite1 = Arr1->getElementType(); |
| 6292 |
Composite2 = Arr2->getElementType(); |
| 6293 |
Steps.emplace_back(Step::Array, CAT1); |
| 6294 |
continue; |
| 6295 |
} |
| 6296 |
bool IAT1 = isa<IncompleteArrayType>(Arr1); |
| 6297 |
bool IAT2 = isa<IncompleteArrayType>(Arr2); |
| 6298 |
if ((IAT1 && IAT2) || |
| 6299 |
(getLangOpts().CPlusPlus20 && (IAT1 != IAT2) && |
| 6300 |
((bool)CAT1 != (bool)CAT2) && |
| 6301 |
(Steps.empty() || Steps.back().K != Step::Array))) { |
| 6302 |
// In C++20 onwards, we can unify an array of N T with an array of |
| 6303 |
// a different or unknown bound. But we can't form an array whose |
| 6304 |
// element type is an array of unknown bound by doing so. |
| 6305 |
Composite1 = Arr1->getElementType(); |
| 6306 |
Composite2 = Arr2->getElementType(); |
| 6307 |
Steps.emplace_back(Step::Array); |
| 6308 |
if (CAT1 || CAT2) |
| 6309 |
NeedConstBefore = Steps.size(); |
| 6310 |
continue; |
| 6311 |
} |
| 6312 |
} |
| 6313 |
|
| 6314 |
const PointerType *Ptr1, *Ptr2; |
| 6315 |
if ((Ptr1 = Composite1->getAs<PointerType>()) && |
| 6316 |
(Ptr2 = Composite2->getAs<PointerType>())) { |
| 6317 |
Composite1 = Ptr1->getPointeeType(); |
| 6318 |
Composite2 = Ptr2->getPointeeType(); |
| 6319 |
Steps.emplace_back(Step::Pointer); |
| 6320 |
continue; |
| 6321 |
} |
| 6322 |
|
| 6323 |
const ObjCObjectPointerType *ObjPtr1, *ObjPtr2; |
| 6324 |
if ((ObjPtr1 = Composite1->getAs<ObjCObjectPointerType>()) && |
| 6325 |
(ObjPtr2 = Composite2->getAs<ObjCObjectPointerType>())) { |
| 6326 |
Composite1 = ObjPtr1->getPointeeType(); |
| 6327 |
Composite2 = ObjPtr2->getPointeeType(); |
| 6328 |
Steps.emplace_back(Step::ObjCPointer); |
| 6329 |
continue; |
| 6330 |
} |
| 6331 |
|
| 6332 |
const MemberPointerType *MemPtr1, *MemPtr2; |
| 6333 |
if ((MemPtr1 = Composite1->getAs<MemberPointerType>()) && |
| 6334 |
(MemPtr2 = Composite2->getAs<MemberPointerType>())) { |
| 6335 |
Composite1 = MemPtr1->getPointeeType(); |
| 6336 |
Composite2 = MemPtr2->getPointeeType(); |
| 6337 |
|
| 6338 |
// At the top level, we can perform a base-to-derived pointer-to-member |
| 6339 |
// conversion: |
| 6340 |
// |
| 6341 |
// - [...] where C1 is reference-related to C2 or C2 is |
| 6342 |
// reference-related to C1 |
| 6343 |
// |
| 6344 |
// (Note that the only kinds of reference-relatedness in scope here are |
| 6345 |
// "same type or derived from".) At any other level, the class must |
| 6346 |
// exactly match. |
| 6347 |
CXXRecordDecl *Cls = nullptr, |
| 6348 |
*Cls1 = MemPtr1->getMostRecentCXXRecordDecl(), |
| 6349 |
*Cls2 = MemPtr2->getMostRecentCXXRecordDecl(); |
| 6350 |
if (declaresSameEntity(Cls1, Cls2)) |
| 6351 |
Cls = Cls1; |
| 6352 |
else if (Steps.empty()) |
| 6353 |
Cls = IsDerivedFrom(Loc, Cls1, Cls2) ? Cls1 |
| 6354 |
: IsDerivedFrom(Loc, Cls2, Cls1) ? Cls2 |
| 6355 |
: nullptr; |
| 6356 |
if (!Cls) |
| 6357 |
return QualType(); |
| 6358 |
|
| 6359 |
Steps.emplace_back(Step::MemberPointer, |
| 6360 |
Context.getCanonicalTagType(Cls).getTypePtr()); |
| 6361 |
continue; |
| 6362 |
} |
| 6363 |
|
| 6364 |
// Special case: at the top level, we can decompose an Objective-C pointer |
| 6365 |
// and a 'cv void *'. Unify the qualifiers. |
| 6366 |
if (Steps.empty() && ((Composite1->isVoidPointerType() && |
| 6367 |
Composite2->isObjCObjectPointerType()) || |
| 6368 |
(Composite1->isObjCObjectPointerType() && |
| 6369 |
Composite2->isVoidPointerType()))) { |
| 6370 |
Composite1 = Composite1->getPointeeType(); |
| 6371 |
Composite2 = Composite2->getPointeeType(); |
| 6372 |
Steps.emplace_back(Step::Pointer); |
| 6373 |
continue; |
| 6374 |
} |
| 6375 |
|
| 6376 |
// FIXME: block pointer types? |
| 6377 |
|
| 6378 |
// Cannot unwrap any more types. |
| 6379 |
break; |
| 6380 |
} |
| 6381 |
|
| 6382 |
// - if T1 or T2 is "pointer to noexcept function" and the other type is |
| 6383 |
// "pointer to function", where the function types are otherwise the same, |
| 6384 |
// "pointer to function"; |
| 6385 |
// - if T1 or T2 is "pointer to member of C1 of type function", the other |
| 6386 |
// type is "pointer to member of C2 of type noexcept function", and C1 |
| 6387 |
// is reference-related to C2 or C2 is reference-related to C1, where |
| 6388 |
// the function types are otherwise the same, "pointer to member of C2 of |
| 6389 |
// type function" or "pointer to member of C1 of type function", |
| 6390 |
// respectively; |
| 6391 |
// |
| 6392 |
// We also support 'noreturn' here, so as a Clang extension we generalize the |
| 6393 |
// above to: |
| 6394 |
// |
| 6395 |
// - [Clang] If T1 and T2 are both of type "pointer to function" or |
| 6396 |
// "pointer to member function" and the pointee types can be unified |
| 6397 |
// by a function pointer conversion, that conversion is applied |
| 6398 |
// before checking the following rules. |
| 6399 |
// |
| 6400 |
// We've already unwrapped down to the function types, and we want to merge |
| 6401 |
// rather than just convert, so do this ourselves rather than calling |
| 6402 |
// IsFunctionConversion. |
| 6403 |
// |
| 6404 |
// FIXME: In order to match the standard wording as closely as possible, we |
| 6405 |
// currently only do this under a single level of pointers. Ideally, we would |
| 6406 |
// allow this in general, and set NeedConstBefore to the relevant depth on |
| 6407 |
// the side(s) where we changed anything. If we permit that, we should also |
| 6408 |
// consider this conversion when determining type similarity and model it as |
| 6409 |
// a qualification conversion. |
| 6410 |
if (Steps.size() == 1) { |
| 6411 |
if (auto *FPT1 = Composite1->getAs<FunctionProtoType>()) { |
| 6412 |
if (auto *FPT2 = Composite2->getAs<FunctionProtoType>()) { |
| 6413 |
FunctionProtoType::ExtProtoInfo EPI1 = FPT1->getExtProtoInfo(); |
| 6414 |
FunctionProtoType::ExtProtoInfo EPI2 = FPT2->getExtProtoInfo(); |
| 6415 |
|
| 6416 |
// The result is noreturn if both operands are. |
| 6417 |
bool Noreturn = |
| 6418 |
EPI1.ExtInfo.getNoReturn() && EPI2.ExtInfo.getNoReturn(); |
| 6419 |
EPI1.ExtInfo = EPI1.ExtInfo.withNoReturn(Noreturn); |
| 6420 |
EPI2.ExtInfo = EPI2.ExtInfo.withNoReturn(Noreturn); |
| 6421 |
|
| 6422 |
bool CFIUncheckedCallee = |
| 6423 |
EPI1.CFIUncheckedCallee || EPI2.CFIUncheckedCallee; |
| 6424 |
EPI1.CFIUncheckedCallee = CFIUncheckedCallee; |
| 6425 |
EPI2.CFIUncheckedCallee = CFIUncheckedCallee; |
| 6426 |
|
| 6427 |
// The result is nothrow if both operands are. |
| 6428 |
SmallVector<QualType, 8> ExceptionTypeStorage; |
| 6429 |
EPI1.ExceptionSpec = EPI2.ExceptionSpec = Context.mergeExceptionSpecs( |
| 6430 |
EPI1.ExceptionSpec, EPI2.ExceptionSpec, ExceptionTypeStorage, |
| 6431 |
getLangOpts().CPlusPlus17); |
| 6432 |
|
| 6433 |
Composite1 = Context.getFunctionType(FPT1->getReturnType(), |
| 6434 |
FPT1->getParamTypes(), EPI1); |
| 6435 |
Composite2 = Context.getFunctionType(FPT2->getReturnType(), |
| 6436 |
FPT2->getParamTypes(), EPI2); |
| 6437 |
} |
| 6438 |
} |
| 6439 |
} |
| 6440 |
|
| 6441 |
// There are some more conversions we can perform under exactly one pointer. |
| 6442 |
if (Steps.size() == 1 && Steps.front().K == Step::Pointer && |
| 6443 |
!Context.hasSameType(Composite1, Composite2)) { |
| 6444 |
// - if T1 or T2 is "pointer to cv1 void" and the other type is |
| 6445 |
// "pointer to cv2 T", where T is an object type or void, |
| 6446 |
// "pointer to cv12 void", where cv12 is the union of cv1 and cv2; |
| 6447 |
if (Composite1->isVoidType() && Composite2->isObjectType()) |
| 6448 |
Composite2 = Composite1; |
| 6449 |
else if (Composite2->isVoidType() && Composite1->isObjectType()) |
| 6450 |
Composite1 = Composite2; |
| 6451 |
// - if T1 is "pointer to cv1 C1" and T2 is "pointer to cv2 C2", where C1 |
| 6452 |
// is reference-related to C2 or C2 is reference-related to C1 (8.6.3), |
| 6453 |
// the cv-combined type of T1 and T2 or the cv-combined type of T2 and |
| 6454 |
// T1, respectively; |
| 6455 |
// |
| 6456 |
// The "similar type" handling covers all of this except for the "T1 is a |
| 6457 |
// base class of T2" case in the definition of reference-related. |
| 6458 |
else if (IsDerivedFrom(Loc, Composite1, Composite2)) |
| 6459 |
Composite1 = Composite2; |
| 6460 |
else if (IsDerivedFrom(Loc, Composite2, Composite1)) |
| 6461 |
Composite2 = Composite1; |
| 6462 |
} |
| 6463 |
|
| 6464 |
// At this point, either the inner types are the same or we have failed to |
| 6465 |
// find a composite pointer type. |
| 6466 |
if (!Context.hasSameType(Composite1, Composite2)) |
| 6467 |
return QualType(); |
| 6468 |
|
| 6469 |
// Per C++ [conv.qual]p3, add 'const' to every level before the last |
| 6470 |
// differing qualifier. |
| 6471 |
for (unsigned I = 0; I != NeedConstBefore; ++I) |
| 6472 |
Steps[I].Quals.addConst(); |
| 6473 |
|
| 6474 |
// Rebuild the composite type. |
| 6475 |
QualType Composite = Context.getCommonSugaredType(Composite1, Composite2); |
| 6476 |
for (auto &S : llvm::reverse(Steps)) |
| 6477 |
Composite = S.rebuild(Context, Composite); |
| 6478 |
|
| 6479 |
if (ConvertArgs) { |
| 6480 |
// Convert the expressions to the composite pointer type. |
| 6481 |
InitializedEntity Entity = |
| 6482 |
InitializedEntity::InitializeTemporary(Composite); |
| 6483 |
InitializationKind Kind = |
| 6484 |
InitializationKind::CreateCopy(Loc, SourceLocation()); |
| 6485 |
|
| 6486 |
InitializationSequence E1ToC(*this, Entity, Kind, E1); |
| 6487 |
if (!E1ToC) |
| 6488 |
return QualType(); |
| 6489 |
|
| 6490 |
InitializationSequence E2ToC(*this, Entity, Kind, E2); |
| 6491 |
if (!E2ToC) |
| 6492 |
return QualType(); |
| 6493 |
|
| 6494 |
// FIXME: Let the caller know if these fail to avoid duplicate diagnostics. |
| 6495 |
ExprResult E1Result = E1ToC.Perform(*this, Entity, Kind, E1); |
| 6496 |
if (E1Result.isInvalid()) |
| 6497 |
return QualType(); |
| 6498 |
E1 = E1Result.get(); |
| 6499 |
|
| 6500 |
ExprResult E2Result = E2ToC.Perform(*this, Entity, Kind, E2); |
| 6501 |
if (E2Result.isInvalid()) |
| 6502 |
return QualType(); |
| 6503 |
E2 = E2Result.get(); |
| 6504 |
} |
| 6505 |
|
| 6506 |
return Composite; |
| 6507 |
} |
| 6508 |
|
| 6509 |
ExprResult Sema::MaybeBindToTemporary(Expr *E) { |
| 6510 |
if (!E) |
| 6511 |
return ExprError(); |
| 6512 |
|
| 6513 |
assert(!isa<CXXBindTemporaryExpr>(E) && "Double-bound temporary?"); |
| 6514 |
|
| 6515 |
// If the result is a glvalue, we shouldn't bind it. |
| 6516 |
if (E->isGLValue()) |
| 6517 |
return E; |
| 6518 |
|
| 6519 |
// In ARC, calls that return a retainable type can return retained, |
| 6520 |
// in which case we have to insert a consuming cast. |
| 6521 |
if (getLangOpts().ObjCAutoRefCount && |
| 6522 |
E->getType()->isObjCRetainableType()) { |
| 6523 |
|
| 6524 |
bool ReturnsRetained; |
| 6525 |
|
| 6526 |
// For actual calls, we compute this by examining the type of the |
| 6527 |
// called value. |
| 6528 |
if (CallExpr *Call = dyn_cast<CallExpr>(E)) { |
| 6529 |
Expr *Callee = Call->getCallee()->IgnoreParens(); |
| 6530 |
QualType T = Callee->getType(); |
| 6531 |
|
| 6532 |
if (T == Context.BoundMemberTy) { |
| 6533 |
// Handle pointer-to-members. |
| 6534 |
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Callee)) |
| 6535 |
T = BinOp->getRHS()->getType(); |
| 6536 |
else if (MemberExpr *Mem = dyn_cast<MemberExpr>(Callee)) |
| 6537 |
T = Mem->getMemberDecl()->getType(); |
| 6538 |
} |
| 6539 |
|
| 6540 |
if (const PointerType *Ptr = T->getAs<PointerType>()) |
| 6541 |
T = Ptr->getPointeeType(); |
| 6542 |
else if (const BlockPointerType *Ptr = T->getAs<BlockPointerType>()) |
| 6543 |
T = Ptr->getPointeeType(); |
| 6544 |
else if (const MemberPointerType *MemPtr = T->getAs<MemberPointerType>()) |
| 6545 |
T = MemPtr->getPointeeType(); |
| 6546 |
|
| 6547 |
auto *FTy = T->castAs<FunctionType>(); |
| 6548 |
ReturnsRetained = FTy->getExtInfo().getProducesResult(); |
| 6549 |
|
| 6550 |
// ActOnStmtExpr arranges things so that StmtExprs of retainable |
| 6551 |
// type always produce a +1 object. |
| 6552 |
} else if (isa<StmtExpr>(E)) { |
| 6553 |
ReturnsRetained = true; |
| 6554 |
|
| 6555 |
// We hit this case with the lambda conversion-to-block optimization; |
| 6556 |
// we don't want any extra casts here. |
| 6557 |
} else if (isa<CastExpr>(E) && |
| 6558 |
isa<BlockExpr>(cast<CastExpr>(E)->getSubExpr())) { |
| 6559 |
return E; |
| 6560 |
|
| 6561 |
// For message sends and property references, we try to find an |
| 6562 |
// actual method. FIXME: we should infer retention by selector in |
| 6563 |
// cases where we don't have an actual method. |
| 6564 |
} else { |
| 6565 |
ObjCMethodDecl *D = nullptr; |
| 6566 |
if (ObjCMessageExpr *Send = dyn_cast<ObjCMessageExpr>(E)) { |
| 6567 |
D = Send->getMethodDecl(); |
| 6568 |
} else if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) { |
| 6569 |
D = BoxedExpr->getBoxingMethod(); |
| 6570 |
} else if (ObjCArrayLiteral *ArrayLit = dyn_cast<ObjCArrayLiteral>(E)) { |
| 6571 |
// Don't do reclaims if we're using the zero-element array |
| 6572 |
// constant. |
| 6573 |
if (ArrayLit->getNumElements() == 0 && |
| 6574 |
Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) |
| 6575 |
return E; |
| 6576 |
|
| 6577 |
D = ArrayLit->getArrayWithObjectsMethod(); |
| 6578 |
} else if (ObjCDictionaryLiteral *DictLit |
| 6579 |
= dyn_cast<ObjCDictionaryLiteral>(E)) { |
| 6580 |
// Don't do reclaims if we're using the zero-element dictionary |
| 6581 |
// constant. |
| 6582 |
if (DictLit->getNumElements() == 0 && |
| 6583 |
Context.getLangOpts().ObjCRuntime.hasEmptyCollections()) |
| 6584 |
return E; |
| 6585 |
|
| 6586 |
D = DictLit->getDictWithObjectsMethod(); |
| 6587 |
} |
| 6588 |
|
| 6589 |
ReturnsRetained = (D && D->hasAttr<NSReturnsRetainedAttr>()); |
| 6590 |
|
| 6591 |
// Don't do reclaims on performSelector calls; despite their |
| 6592 |
// return type, the invoked method doesn't necessarily actually |
| 6593 |
// return an object. |
| 6594 |
if (!ReturnsRetained && |
| 6595 |
D && D->getMethodFamily() == OMF_performSelector) |
| 6596 |
return E; |
| 6597 |
} |
| 6598 |
|
| 6599 |
// Don't reclaim an object of Class type. |
| 6600 |
if (!ReturnsRetained && E->getType()->isObjCARCImplicitlyUnretainedType()) |
| 6601 |
return E; |
| 6602 |
|
| 6603 |
Cleanup.setExprNeedsCleanups(true); |
| 6604 |
|
| 6605 |
CastKind ck = (ReturnsRetained ? CK_ARCConsumeObject |
| 6606 |
: CK_ARCReclaimReturnedObject); |
| 6607 |
return ImplicitCastExpr::Create(Context, E->getType(), ck, E, nullptr, |
| 6608 |
VK_PRValue, FPOptionsOverride()); |
| 6609 |
} |
| 6610 |
|
| 6611 |
if (E->getType().isDestructedType() == QualType::DK_nontrivial_c_struct) |
| 6612 |
Cleanup.setExprNeedsCleanups(true); |
| 6613 |
|
| 6614 |
if (!getLangOpts().CPlusPlus) |
| 6615 |
return E; |
| 6616 |
|
| 6617 |
// Search for the base element type (cf. ASTContext::getBaseElementType) with |
| 6618 |
// a fast path for the common case that the type is directly a RecordType. |
| 6619 |
const Type *T = Context.getCanonicalType(E->getType().getTypePtr()); |
| 6620 |
const RecordType *RT = nullptr; |
| 6621 |
while (!RT) { |
| 6622 |
switch (T->getTypeClass()) { |
| 6623 |
case Type::Record: |
| 6624 |
RT = cast<RecordType>(T); |
| 6625 |
break; |
| 6626 |
case Type::ConstantArray: |
| 6627 |
case Type::IncompleteArray: |
| 6628 |
case Type::VariableArray: |
| 6629 |
case Type::DependentSizedArray: |
| 6630 |
T = cast<ArrayType>(T)->getElementType().getTypePtr(); |
| 6631 |
break; |
| 6632 |
default: |
| 6633 |
return E; |
| 6634 |
} |
| 6635 |
} |
| 6636 |
|
| 6637 |
// That should be enough to guarantee that this type is complete, if we're |
| 6638 |
// not processing a decltype expression. |
| 6639 |
auto *RD = cast<CXXRecordDecl>(RT->getDecl())->getDefinitionOrSelf(); |
| 6640 |
if (RD->isInvalidDecl() || RD->isDependentContext()) |
| 6641 |
return E; |
| 6642 |
|
| 6643 |
bool IsDecltype = ExprEvalContexts.back().ExprContext == |
| 6644 |
ExpressionEvaluationContextRecord::EK_Decltype; |
| 6645 |
CXXDestructorDecl *Destructor = IsDecltype ? nullptr : LookupDestructor(RD); |
| 6646 |
|
| 6647 |
if (Destructor) { |
| 6648 |
MarkFunctionReferenced(E->getExprLoc(), Destructor); |
| 6649 |
CheckDestructorAccess(E->getExprLoc(), Destructor, |
| 6650 |
PDiag(diag::err_access_dtor_temp) |
| 6651 |
<< E->getType()); |
| 6652 |
if (DiagnoseUseOfDecl(Destructor, E->getExprLoc())) |
| 6653 |
return ExprError(); |
| 6654 |
|
| 6655 |
// If destructor is trivial, we can avoid the extra copy. |
| 6656 |
if (Destructor->isTrivial()) |
| 6657 |
return E; |
| 6658 |
|
| 6659 |
// We need a cleanup, but we don't need to remember the temporary. |
| 6660 |
Cleanup.setExprNeedsCleanups(true); |
| 6661 |
} |
| 6662 |
|
| 6663 |
CXXTemporary *Temp = CXXTemporary::Create(Context, Destructor); |
| 6664 |
CXXBindTemporaryExpr *Bind = CXXBindTemporaryExpr::Create(Context, Temp, E); |
| 6665 |
|
| 6666 |
if (IsDecltype) |
| 6667 |
ExprEvalContexts.back().DelayedDecltypeBinds.push_back(Bind); |
| 6668 |
|
| 6669 |
return Bind; |
| 6670 |
} |
| 6671 |
|
| 6672 |
ExprResult |
| 6673 |
Sema::MaybeCreateExprWithCleanups(ExprResult SubExpr) { |
| 6674 |
if (SubExpr.isInvalid()) |
| 6675 |
return ExprError(); |
| 6676 |
|
| 6677 |
return MaybeCreateExprWithCleanups(SubExpr.get()); |
| 6678 |
} |
| 6679 |
|
| 6680 |
Expr *Sema::MaybeCreateExprWithCleanups(Expr *SubExpr) { |
| 6681 |
assert(SubExpr && "subexpression can't be null!"); |
| 6682 |
|
| 6683 |
CleanupVarDeclMarking(); |
| 6684 |
|
| 6685 |
unsigned FirstCleanup = ExprEvalContexts.back().NumCleanupObjects; |
| 6686 |
assert(ExprCleanupObjects.size() >= FirstCleanup); |
| 6687 |
assert(Cleanup.exprNeedsCleanups() || |
| 6688 |
ExprCleanupObjects.size() == FirstCleanup); |
| 6689 |
if (!Cleanup.exprNeedsCleanups()) |
| 6690 |
return SubExpr; |
| 6691 |
|
| 6692 |
auto Cleanups = llvm::ArrayRef(ExprCleanupObjects.begin() + FirstCleanup, |
| 6693 |
ExprCleanupObjects.size() - FirstCleanup); |
| 6694 |
|
| 6695 |
auto *E = ExprWithCleanups::Create( |
| 6696 |
Context, SubExpr, Cleanup.cleanupsHaveSideEffects(), Cleanups); |
| 6697 |
DiscardCleanupsInEvaluationContext(); |
| 6698 |
|
| 6699 |
return E; |
| 6700 |
} |
| 6701 |
|
| 6702 |
Stmt *Sema::MaybeCreateStmtWithCleanups(Stmt *SubStmt) { |
| 6703 |
assert(SubStmt && "sub-statement can't be null!"); |
| 6704 |
|
| 6705 |
CleanupVarDeclMarking(); |
| 6706 |
|
| 6707 |
if (!Cleanup.exprNeedsCleanups()) |
| 6708 |
return SubStmt; |
| 6709 |
|
| 6710 |
// FIXME: In order to attach the temporaries, wrap the statement into |
| 6711 |
// a StmtExpr; currently this is only used for asm statements. |
| 6712 |
// This is hacky, either create a new CXXStmtWithTemporaries statement or |
| 6713 |
// a new AsmStmtWithTemporaries. |
| 6714 |
CompoundStmt *CompStmt = |
| 6715 |
CompoundStmt::Create(Context, SubStmt, FPOptionsOverride(), |
| 6716 |
SourceLocation(), SourceLocation()); |
| 6717 |
Expr *E = new (Context) |
| 6718 |
StmtExpr(CompStmt, Context.VoidTy, SourceLocation(), SourceLocation(), |
| 6719 |
/*FIXME TemplateDepth=*/0); |
| 6720 |
return MaybeCreateExprWithCleanups(E); |
| 6721 |
} |
| 6722 |
|
| 6723 |
ExprResult Sema::ActOnDecltypeExpression(Expr *E) { |
| 6724 |
assert(ExprEvalContexts.back().ExprContext == |
| 6725 |
ExpressionEvaluationContextRecord::EK_Decltype && |
| 6726 |
"not in a decltype expression"); |
| 6727 |
|
| 6728 |
ExprResult Result = CheckPlaceholderExpr(E); |
| 6729 |
if (Result.isInvalid()) |
| 6730 |
return ExprError(); |
| 6731 |
E = Result.get(); |
| 6732 |
|
| 6733 |
// C++11 [expr.call]p11: |
| 6734 |
// If a function call is a prvalue of object type, |
| 6735 |
// -- if the function call is either |
| 6736 |
// -- the operand of a decltype-specifier, or |
| 6737 |
// -- the right operand of a comma operator that is the operand of a |
| 6738 |
// decltype-specifier, |
| 6739 |
// a temporary object is not introduced for the prvalue. |
| 6740 |
|
| 6741 |
// Recursively rebuild ParenExprs and comma expressions to strip out the |
| 6742 |
// outermost CXXBindTemporaryExpr, if any. |
| 6743 |
if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { |
| 6744 |
ExprResult SubExpr = ActOnDecltypeExpression(PE->getSubExpr()); |
| 6745 |
if (SubExpr.isInvalid()) |
| 6746 |
return ExprError(); |
| 6747 |
if (SubExpr.get() == PE->getSubExpr()) |
| 6748 |
return E; |
| 6749 |
return ActOnParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get()); |
| 6750 |
} |
| 6751 |
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { |
| 6752 |
if (BO->getOpcode() == BO_Comma) { |
| 6753 |
ExprResult RHS = ActOnDecltypeExpression(BO->getRHS()); |
| 6754 |
if (RHS.isInvalid()) |
| 6755 |
return ExprError(); |
| 6756 |
if (RHS.get() == BO->getRHS()) |
| 6757 |
return E; |
| 6758 |
return BinaryOperator::Create(Context, BO->getLHS(), RHS.get(), BO_Comma, |
| 6759 |
BO->getType(), BO->getValueKind(), |
| 6760 |
BO->getObjectKind(), BO->getOperatorLoc(), |
| 6761 |
BO->getFPFeatures()); |
| 6762 |
} |
| 6763 |
} |
| 6764 |
|
| 6765 |
CXXBindTemporaryExpr *TopBind = dyn_cast<CXXBindTemporaryExpr>(E); |
| 6766 |
CallExpr *TopCall = TopBind ? dyn_cast<CallExpr>(TopBind->getSubExpr()) |
| 6767 |
: nullptr; |
| 6768 |
if (TopCall) |
| 6769 |
E = TopCall; |
| 6770 |
else |
| 6771 |
TopBind = nullptr; |
| 6772 |
|
| 6773 |
// Disable the special decltype handling now. |
| 6774 |
ExprEvalContexts.back().ExprContext = |
| 6775 |
ExpressionEvaluationContextRecord::EK_Other; |
| 6776 |
|
| 6777 |
Result = CheckUnevaluatedOperand(E); |
| 6778 |
if (Result.isInvalid()) |
| 6779 |
return ExprError(); |
| 6780 |
E = Result.get(); |
| 6781 |
|
| 6782 |
// In MS mode, don't perform any extra checking of call return types within a |
| 6783 |
// decltype expression. |
| 6784 |
if (getLangOpts().MSVCCompat) |
| 6785 |
return E; |
| 6786 |
|
| 6787 |
// Perform the semantic checks we delayed until this point. |
| 6788 |
for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeCalls.size(); |
| 6789 |
I != N; ++I) { |
| 6790 |
CallExpr *Call = ExprEvalContexts.back().DelayedDecltypeCalls[I]; |
| 6791 |
if (Call == TopCall) |
| 6792 |
continue; |
| 6793 |
|
| 6794 |
if (CheckCallReturnType(Call->getCallReturnType(Context), |
| 6795 |
Call->getBeginLoc(), Call, Call->getDirectCallee())) |
| 6796 |
return ExprError(); |
| 6797 |
} |
| 6798 |
|
| 6799 |
// Now all relevant types are complete, check the destructors are accessible |
| 6800 |
// and non-deleted, and annotate them on the temporaries. |
| 6801 |
for (unsigned I = 0, N = ExprEvalContexts.back().DelayedDecltypeBinds.size(); |
| 6802 |
I != N; ++I) { |
| 6803 |
CXXBindTemporaryExpr *Bind = |
| 6804 |
ExprEvalContexts.back().DelayedDecltypeBinds[I]; |
| 6805 |
if (Bind == TopBind) |
| 6806 |
continue; |
| 6807 |
|
| 6808 |
CXXTemporary *Temp = Bind->getTemporary(); |
| 6809 |
|
| 6810 |
CXXRecordDecl *RD = |
| 6811 |
Bind->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
| 6812 |
CXXDestructorDecl *Destructor = LookupDestructor(RD); |
| 6813 |
Temp->setDestructor(Destructor); |
| 6814 |
|
| 6815 |
MarkFunctionReferenced(Bind->getExprLoc(), Destructor); |
| 6816 |
CheckDestructorAccess(Bind->getExprLoc(), Destructor, |
| 6817 |
PDiag(diag::err_access_dtor_temp) |
| 6818 |
<< Bind->getType()); |
| 6819 |
if (DiagnoseUseOfDecl(Destructor, Bind->getExprLoc())) |
| 6820 |
return ExprError(); |
| 6821 |
|
| 6822 |
// We need a cleanup, but we don't need to remember the temporary. |
| 6823 |
Cleanup.setExprNeedsCleanups(true); |
| 6824 |
} |
| 6825 |
|
| 6826 |
// Possibly strip off the top CXXBindTemporaryExpr. |
| 6827 |
return E; |
| 6828 |
} |
| 6829 |
|
| 6830 |
/// Note a set of 'operator->' functions that were used for a member access. |
| 6831 |
static void noteOperatorArrows(Sema &S, |
| 6832 |
ArrayRef<FunctionDecl *> OperatorArrows) { |
| 6833 |
unsigned SkipStart = OperatorArrows.size(), SkipCount = 0; |
| 6834 |
// FIXME: Make this configurable? |
| 6835 |
unsigned Limit = 9; |
| 6836 |
if (OperatorArrows.size() > Limit) { |
| 6837 |
// Produce Limit-1 normal notes and one 'skipping' note. |
| 6838 |
SkipStart = (Limit - 1) / 2 + (Limit - 1) % 2; |
| 6839 |
SkipCount = OperatorArrows.size() - (Limit - 1); |
| 6840 |
} |
| 6841 |
|
| 6842 |
for (unsigned I = 0; I < OperatorArrows.size(); /**/) { |
| 6843 |
if (I == SkipStart) { |
| 6844 |
S.Diag(OperatorArrows[I]->getLocation(), |
| 6845 |
diag::note_operator_arrows_suppressed) |
| 6846 |
<< SkipCount; |
| 6847 |
I += SkipCount; |
| 6848 |
} else { |
| 6849 |
S.Diag(OperatorArrows[I]->getLocation(), diag::note_operator_arrow_here) |
| 6850 |
<< OperatorArrows[I]->getCallResultType(); |
| 6851 |
++I; |
| 6852 |
} |
| 6853 |
} |
| 6854 |
} |
| 6855 |
|
| 6856 |
ExprResult Sema::ActOnStartCXXMemberReference(Scope *S, Expr *Base, |
| 6857 |
SourceLocation OpLoc, |
| 6858 |
tok::TokenKind OpKind, |
| 6859 |
ParsedType &ObjectType, |
| 6860 |
bool &MayBePseudoDestructor) { |
| 6861 |
// Since this might be a postfix expression, get rid of ParenListExprs. |
| 6862 |
ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); |
| 6863 |
if (Result.isInvalid()) return ExprError(); |
| 6864 |
Base = Result.get(); |
| 6865 |
|
| 6866 |
Result = CheckPlaceholderExpr(Base); |
| 6867 |
if (Result.isInvalid()) return ExprError(); |
| 6868 |
Base = Result.get(); |
| 6869 |
|
| 6870 |
QualType BaseType = Base->getType(); |
| 6871 |
MayBePseudoDestructor = false; |
| 6872 |
if (BaseType->isDependentType()) { |
| 6873 |
// If we have a pointer to a dependent type and are using the -> operator, |
| 6874 |
// the object type is the type that the pointer points to. We might still |
| 6875 |
// have enough information about that type to do something useful. |
| 6876 |
if (OpKind == tok::arrow) |
| 6877 |
if (const PointerType *Ptr = BaseType->getAs<PointerType>()) |
| 6878 |
BaseType = Ptr->getPointeeType(); |
| 6879 |
|
| 6880 |
ObjectType = ParsedType::make(BaseType); |
| 6881 |
MayBePseudoDestructor = true; |
| 6882 |
return Base; |
| 6883 |
} |
| 6884 |
|
| 6885 |
// C++ [over.match.oper]p8: |
| 6886 |
// [...] When operator->returns, the operator-> is applied to the value |
| 6887 |
// returned, with the original second operand. |
| 6888 |
if (OpKind == tok::arrow) { |
| 6889 |
QualType StartingType = BaseType; |
| 6890 |
bool NoArrowOperatorFound = false; |
| 6891 |
bool FirstIteration = true; |
| 6892 |
FunctionDecl *CurFD = dyn_cast<FunctionDecl>(CurContext); |
| 6893 |
// The set of types we've considered so far. |
| 6894 |
llvm::SmallPtrSet<CanQualType,8> CTypes; |
| 6895 |
SmallVector<FunctionDecl*, 8> OperatorArrows; |
| 6896 |
CTypes.insert(Context.getCanonicalType(BaseType)); |
| 6897 |
|
| 6898 |
while (BaseType->isRecordType()) { |
| 6899 |
if (OperatorArrows.size() >= getLangOpts().ArrowDepth) { |
| 6900 |
Diag(OpLoc, diag::err_operator_arrow_depth_exceeded) |
| 6901 |
<< StartingType << getLangOpts().ArrowDepth << Base->getSourceRange(); |
| 6902 |
noteOperatorArrows(*this, OperatorArrows); |
| 6903 |
Diag(OpLoc, diag::note_operator_arrow_depth) |
| 6904 |
<< getLangOpts().ArrowDepth; |
| 6905 |
return ExprError(); |
| 6906 |
} |
| 6907 |
|
| 6908 |
Result = BuildOverloadedArrowExpr( |
| 6909 |
S, Base, OpLoc, |
| 6910 |
// When in a template specialization and on the first loop iteration, |
| 6911 |
// potentially give the default diagnostic (with the fixit in a |
| 6912 |
// separate note) instead of having the error reported back to here |
| 6913 |
// and giving a diagnostic with a fixit attached to the error itself. |
| 6914 |
(FirstIteration && CurFD && CurFD->isFunctionTemplateSpecialization()) |
| 6915 |
? nullptr |
| 6916 |
: &NoArrowOperatorFound); |
| 6917 |
if (Result.isInvalid()) { |
| 6918 |
if (NoArrowOperatorFound) { |
| 6919 |
if (FirstIteration) { |
| 6920 |
Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
| 6921 |
<< BaseType << 1 << Base->getSourceRange() |
| 6922 |
<< FixItHint::CreateReplacement(OpLoc, "."); |
| 6923 |
OpKind = tok::period; |
| 6924 |
break; |
| 6925 |
} |
| 6926 |
Diag(OpLoc, diag::err_typecheck_member_reference_arrow) |
| 6927 |
<< BaseType << Base->getSourceRange(); |
| 6928 |
CallExpr *CE = dyn_cast<CallExpr>(Base); |
| 6929 |
if (Decl *CD = (CE ? CE->getCalleeDecl() : nullptr)) { |
| 6930 |
Diag(CD->getBeginLoc(), |
| 6931 |
diag::note_member_reference_arrow_from_operator_arrow); |
| 6932 |
} |
| 6933 |
} |
| 6934 |
return ExprError(); |
| 6935 |
} |
| 6936 |
Base = Result.get(); |
| 6937 |
if (CXXOperatorCallExpr *OpCall = dyn_cast<CXXOperatorCallExpr>(Base)) |
| 6938 |
OperatorArrows.push_back(OpCall->getDirectCallee()); |
| 6939 |
BaseType = Base->getType(); |
| 6940 |
CanQualType CBaseType = Context.getCanonicalType(BaseType); |
| 6941 |
if (!CTypes.insert(CBaseType).second) { |
| 6942 |
Diag(OpLoc, diag::err_operator_arrow_circular) << StartingType; |
| 6943 |
noteOperatorArrows(*this, OperatorArrows); |
| 6944 |
return ExprError(); |
| 6945 |
} |
| 6946 |
FirstIteration = false; |
| 6947 |
} |
| 6948 |
|
| 6949 |
if (OpKind == tok::arrow) { |
| 6950 |
if (BaseType->isPointerType()) |
| 6951 |
BaseType = BaseType->getPointeeType(); |
| 6952 |
else if (auto *AT = Context.getAsArrayType(BaseType)) |
| 6953 |
BaseType = AT->getElementType(); |
| 6954 |
} |
| 6955 |
} |
| 6956 |
|
| 6957 |
// Objective-C properties allow "." access on Objective-C pointer types, |
| 6958 |
// so adjust the base type to the object type itself. |
| 6959 |
if (BaseType->isObjCObjectPointerType()) |
| 6960 |
BaseType = BaseType->getPointeeType(); |
| 6961 |
|
| 6962 |
// C++ [basic.lookup.classref]p2: |
| 6963 |
// [...] If the type of the object expression is of pointer to scalar |
| 6964 |
// type, the unqualified-id is looked up in the context of the complete |
| 6965 |
// postfix-expression. |
| 6966 |
// |
| 6967 |
// This also indicates that we could be parsing a pseudo-destructor-name. |
| 6968 |
// Note that Objective-C class and object types can be pseudo-destructor |
| 6969 |
// expressions or normal member (ivar or property) access expressions, and |
| 6970 |
// it's legal for the type to be incomplete if this is a pseudo-destructor |
| 6971 |
// call. We'll do more incomplete-type checks later in the lookup process, |
| 6972 |
// so just skip this check for ObjC types. |
| 6973 |
if (!BaseType->isRecordType()) { |
| 6974 |
ObjectType = ParsedType::make(BaseType); |
| 6975 |
MayBePseudoDestructor = true; |
| 6976 |
return Base; |
| 6977 |
} |
| 6978 |
|
| 6979 |
// The object type must be complete (or dependent), or |
| 6980 |
// C++11 [expr.prim.general]p3: |
| 6981 |
// Unlike the object expression in other contexts, *this is not required to |
| 6982 |
// be of complete type for purposes of class member access (5.2.5) outside |
| 6983 |
// the member function body. |
| 6984 |
if (!BaseType->isDependentType() && |
| 6985 |
!isThisOutsideMemberFunctionBody(BaseType) && |
| 6986 |
RequireCompleteType(OpLoc, BaseType, |
| 6987 |
diag::err_incomplete_member_access)) { |
| 6988 |
return CreateRecoveryExpr(Base->getBeginLoc(), Base->getEndLoc(), {Base}); |
| 6989 |
} |
| 6990 |
|
| 6991 |
// C++ [basic.lookup.classref]p2: |
| 6992 |
// If the id-expression in a class member access (5.2.5) is an |
| 6993 |
// unqualified-id, and the type of the object expression is of a class |
| 6994 |
// type C (or of pointer to a class type C), the unqualified-id is looked |
| 6995 |
// up in the scope of class C. [...] |
| 6996 |
ObjectType = ParsedType::make(BaseType); |
| 6997 |
return Base; |
| 6998 |
} |
| 6999 |
|
| 7000 |
static bool CheckArrow(Sema &S, QualType &ObjectType, Expr *&Base, |
| 7001 |
tok::TokenKind &OpKind, SourceLocation OpLoc) { |
| 7002 |
if (Base->hasPlaceholderType()) { |
| 7003 |
ExprResult result = S.CheckPlaceholderExpr(Base); |
| 7004 |
if (result.isInvalid()) return true; |
| 7005 |
Base = result.get(); |
| 7006 |
} |
| 7007 |
ObjectType = Base->getType(); |
| 7008 |
|
| 7009 |
// C++ [expr.pseudo]p2: |
| 7010 |
// The left-hand side of the dot operator shall be of scalar type. The |
| 7011 |
// left-hand side of the arrow operator shall be of pointer to scalar type. |
| 7012 |
// This scalar type is the object type. |
| 7013 |
// Note that this is rather different from the normal handling for the |
| 7014 |
// arrow operator. |
| 7015 |
if (OpKind == tok::arrow) { |
| 7016 |
// The operator requires a prvalue, so perform lvalue conversions. |
| 7017 |
// Only do this if we might plausibly end with a pointer, as otherwise |
| 7018 |
// this was likely to be intended to be a '.'. |
| 7019 |
if (ObjectType->isPointerType() || ObjectType->isArrayType() || |
| 7020 |
ObjectType->isFunctionType()) { |
| 7021 |
ExprResult BaseResult = S.DefaultFunctionArrayLvalueConversion(Base); |
| 7022 |
if (BaseResult.isInvalid()) |
| 7023 |
return true; |
| 7024 |
Base = BaseResult.get(); |
| 7025 |
ObjectType = Base->getType(); |
| 7026 |
} |
| 7027 |
|
| 7028 |
if (const PointerType *Ptr = ObjectType->getAs<PointerType>()) { |
| 7029 |
ObjectType = Ptr->getPointeeType(); |
| 7030 |
} else if (!Base->isTypeDependent()) { |
| 7031 |
// The user wrote "p->" when they probably meant "p."; fix it. |
| 7032 |
S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
| 7033 |
<< ObjectType << true |
| 7034 |
<< FixItHint::CreateReplacement(OpLoc, "."); |
| 7035 |
if (S.isSFINAEContext()) |
| 7036 |
return true; |
| 7037 |
|
| 7038 |
OpKind = tok::period; |
| 7039 |
} |
| 7040 |
} |
| 7041 |
|
| 7042 |
return false; |
| 7043 |
} |
| 7044 |
|
| 7045 |
/// Check if it's ok to try and recover dot pseudo destructor calls on |
| 7046 |
/// pointer objects. |
| 7047 |
static bool |
| 7048 |
canRecoverDotPseudoDestructorCallsOnPointerObjects(Sema &SemaRef, |
| 7049 |
QualType DestructedType) { |
| 7050 |
// If this is a record type, check if its destructor is callable. |
| 7051 |
if (auto *RD = DestructedType->getAsCXXRecordDecl()) { |
| 7052 |
if (RD->hasDefinition()) |
| 7053 |
if (CXXDestructorDecl *D = SemaRef.LookupDestructor(RD)) |
| 7054 |
return SemaRef.CanUseDecl(D, /*TreatUnavailableAsInvalid=*/false); |
| 7055 |
return false; |
| 7056 |
} |
| 7057 |
|
| 7058 |
// Otherwise, check if it's a type for which it's valid to use a pseudo-dtor. |
| 7059 |
return DestructedType->isDependentType() || DestructedType->isScalarType() || |
| 7060 |
DestructedType->isVectorType(); |
| 7061 |
} |
| 7062 |
|
| 7063 |
ExprResult Sema::BuildPseudoDestructorExpr(Expr *Base, |
| 7064 |
SourceLocation OpLoc, |
| 7065 |
tok::TokenKind OpKind, |
| 7066 |
const CXXScopeSpec &SS, |
| 7067 |
TypeSourceInfo *ScopeTypeInfo, |
| 7068 |
SourceLocation CCLoc, |
| 7069 |
SourceLocation TildeLoc, |
| 7070 |
PseudoDestructorTypeStorage Destructed) { |
| 7071 |
TypeSourceInfo *DestructedTypeInfo = Destructed.getTypeSourceInfo(); |
| 7072 |
|
| 7073 |
QualType ObjectType; |
| 7074 |
if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) |
| 7075 |
return ExprError(); |
| 7076 |
|
| 7077 |
if (!ObjectType->isDependentType() && !ObjectType->isScalarType() && |
| 7078 |
!ObjectType->isVectorType() && !ObjectType->isMatrixType()) { |
| 7079 |
if (getLangOpts().MSVCCompat && ObjectType->isVoidType()) |
| 7080 |
Diag(OpLoc, diag::ext_pseudo_dtor_on_void) << Base->getSourceRange(); |
| 7081 |
else { |
| 7082 |
Diag(OpLoc, diag::err_pseudo_dtor_base_not_scalar) |
| 7083 |
<< ObjectType << Base->getSourceRange(); |
| 7084 |
return ExprError(); |
| 7085 |
} |
| 7086 |
} |
| 7087 |
|
| 7088 |
// C++ [expr.pseudo]p2: |
| 7089 |
// [...] The cv-unqualified versions of the object type and of the type |
| 7090 |
// designated by the pseudo-destructor-name shall be the same type. |
| 7091 |
if (DestructedTypeInfo) { |
| 7092 |
QualType DestructedType = DestructedTypeInfo->getType(); |
| 7093 |
SourceLocation DestructedTypeStart = |
| 7094 |
DestructedTypeInfo->getTypeLoc().getBeginLoc(); |
| 7095 |
if (!DestructedType->isDependentType() && !ObjectType->isDependentType()) { |
| 7096 |
if (!Context.hasSameUnqualifiedType(DestructedType, ObjectType)) { |
| 7097 |
// Detect dot pseudo destructor calls on pointer objects, e.g.: |
| 7098 |
// Foo *foo; |
| 7099 |
// foo.~Foo(); |
| 7100 |
if (OpKind == tok::period && ObjectType->isPointerType() && |
| 7101 |
Context.hasSameUnqualifiedType(DestructedType, |
| 7102 |
ObjectType->getPointeeType())) { |
| 7103 |
auto Diagnostic = |
| 7104 |
Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) |
| 7105 |
<< ObjectType << /*IsArrow=*/0 << Base->getSourceRange(); |
| 7106 |
|
| 7107 |
// Issue a fixit only when the destructor is valid. |
| 7108 |
if (canRecoverDotPseudoDestructorCallsOnPointerObjects( |
| 7109 |
*this, DestructedType)) |
| 7110 |
Diagnostic << FixItHint::CreateReplacement(OpLoc, "->"); |
| 7111 |
|
| 7112 |
// Recover by setting the object type to the destructed type and the |
| 7113 |
// operator to '->'. |
| 7114 |
ObjectType = DestructedType; |
| 7115 |
OpKind = tok::arrow; |
| 7116 |
} else { |
| 7117 |
Diag(DestructedTypeStart, diag::err_pseudo_dtor_type_mismatch) |
| 7118 |
<< ObjectType << DestructedType << Base->getSourceRange() |
| 7119 |
<< DestructedTypeInfo->getTypeLoc().getSourceRange(); |
| 7120 |
|
| 7121 |
// Recover by setting the destructed type to the object type. |
| 7122 |
DestructedType = ObjectType; |
| 7123 |
DestructedTypeInfo = |
| 7124 |
Context.getTrivialTypeSourceInfo(ObjectType, DestructedTypeStart); |
| 7125 |
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
| 7126 |
} |
| 7127 |
} else if (DestructedType.getObjCLifetime() != |
| 7128 |
ObjectType.getObjCLifetime()) { |
| 7129 |
|
| 7130 |
if (DestructedType.getObjCLifetime() == Qualifiers::OCL_None) { |
| 7131 |
// Okay: just pretend that the user provided the correctly-qualified |
| 7132 |
// type. |
| 7133 |
} else { |
| 7134 |
Diag(DestructedTypeStart, diag::err_arc_pseudo_dtor_inconstant_quals) |
| 7135 |
<< ObjectType << DestructedType << Base->getSourceRange() |
| 7136 |
<< DestructedTypeInfo->getTypeLoc().getSourceRange(); |
| 7137 |
} |
| 7138 |
|
| 7139 |
// Recover by setting the destructed type to the object type. |
| 7140 |
DestructedType = ObjectType; |
| 7141 |
DestructedTypeInfo = Context.getTrivialTypeSourceInfo(ObjectType, |
| 7142 |
DestructedTypeStart); |
| 7143 |
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
| 7144 |
} |
| 7145 |
} |
| 7146 |
} |
| 7147 |
|
| 7148 |
// C++ [expr.pseudo]p2: |
| 7149 |
// [...] Furthermore, the two type-names in a pseudo-destructor-name of the |
| 7150 |
// form |
| 7151 |
// |
| 7152 |
// ::[opt] nested-name-specifier[opt] type-name :: ~ type-name |
| 7153 |
// |
| 7154 |
// shall designate the same scalar type. |
| 7155 |
if (ScopeTypeInfo) { |
| 7156 |
QualType ScopeType = ScopeTypeInfo->getType(); |
| 7157 |
if (!ScopeType->isDependentType() && !ObjectType->isDependentType() && |
| 7158 |
!Context.hasSameUnqualifiedType(ScopeType, ObjectType)) { |
| 7159 |
|
| 7160 |
Diag(ScopeTypeInfo->getTypeLoc().getSourceRange().getBegin(), |
| 7161 |
diag::err_pseudo_dtor_type_mismatch) |
| 7162 |
<< ObjectType << ScopeType << Base->getSourceRange() |
| 7163 |
<< ScopeTypeInfo->getTypeLoc().getSourceRange(); |
| 7164 |
|
| 7165 |
ScopeType = QualType(); |
| 7166 |
ScopeTypeInfo = nullptr; |
| 7167 |
} |
| 7168 |
} |
| 7169 |
|
| 7170 |
Expr *Result |
| 7171 |
= new (Context) CXXPseudoDestructorExpr(Context, Base, |
| 7172 |
OpKind == tok::arrow, OpLoc, |
| 7173 |
SS.getWithLocInContext(Context), |
| 7174 |
ScopeTypeInfo, |
| 7175 |
CCLoc, |
| 7176 |
TildeLoc, |
| 7177 |
Destructed); |
| 7178 |
|
| 7179 |
return Result; |
| 7180 |
} |
| 7181 |
|
| 7182 |
ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
| 7183 |
SourceLocation OpLoc, |
| 7184 |
tok::TokenKind OpKind, |
| 7185 |
CXXScopeSpec &SS, |
| 7186 |
UnqualifiedId &FirstTypeName, |
| 7187 |
SourceLocation CCLoc, |
| 7188 |
SourceLocation TildeLoc, |
| 7189 |
UnqualifiedId &SecondTypeName) { |
| 7190 |
assert((FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
| 7191 |
FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
| 7192 |
"Invalid first type name in pseudo-destructor"); |
| 7193 |
assert((SecondTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
| 7194 |
SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) && |
| 7195 |
"Invalid second type name in pseudo-destructor"); |
| 7196 |
|
| 7197 |
QualType ObjectType; |
| 7198 |
if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc)) |
| 7199 |
return ExprError(); |
| 7200 |
|
| 7201 |
// Compute the object type that we should use for name lookup purposes. Only |
| 7202 |
// record types and dependent types matter. |
| 7203 |
ParsedType ObjectTypePtrForLookup; |
| 7204 |
if (!SS.isSet()) { |
| 7205 |
if (ObjectType->isRecordType()) |
| 7206 |
ObjectTypePtrForLookup = ParsedType::make(ObjectType); |
| 7207 |
else if (ObjectType->isDependentType()) |
| 7208 |
ObjectTypePtrForLookup = ParsedType::make(Context.DependentTy); |
| 7209 |
} |
| 7210 |
|
| 7211 |
// Convert the name of the type being destructed (following the ~) into a |
| 7212 |
// type (with source-location information). |
| 7213 |
QualType DestructedType; |
| 7214 |
TypeSourceInfo *DestructedTypeInfo = nullptr; |
| 7215 |
PseudoDestructorTypeStorage Destructed; |
| 7216 |
if (SecondTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { |
| 7217 |
ParsedType T = getTypeName(*SecondTypeName.Identifier, |
| 7218 |
SecondTypeName.StartLocation, |
| 7219 |
S, &SS, true, false, ObjectTypePtrForLookup, |
| 7220 |
/*IsCtorOrDtorName*/true); |
| 7221 |
if (!T && |
| 7222 |
((SS.isSet() && !computeDeclContext(SS, false)) || |
| 7223 |
(!SS.isSet() && ObjectType->isDependentType()))) { |
| 7224 |
// The name of the type being destroyed is a dependent name, and we |
| 7225 |
// couldn't find anything useful in scope. Just store the identifier and |
| 7226 |
// it's location, and we'll perform (qualified) name lookup again at |
| 7227 |
// template instantiation time. |
| 7228 |
Destructed = PseudoDestructorTypeStorage(SecondTypeName.Identifier, |
| 7229 |
SecondTypeName.StartLocation); |
| 7230 |
} else if (!T) { |
| 7231 |
Diag(SecondTypeName.StartLocation, |
| 7232 |
diag::err_pseudo_dtor_destructor_non_type) |
| 7233 |
<< SecondTypeName.Identifier << ObjectType; |
| 7234 |
if (isSFINAEContext()) |
| 7235 |
return ExprError(); |
| 7236 |
|
| 7237 |
// Recover by assuming we had the right type all along. |
| 7238 |
DestructedType = ObjectType; |
| 7239 |
} else |
| 7240 |
DestructedType = GetTypeFromParser(T, &DestructedTypeInfo); |
| 7241 |
} else { |
| 7242 |
// Resolve the template-id to a type. |
| 7243 |
TemplateIdAnnotation *TemplateId = SecondTypeName.TemplateId; |
| 7244 |
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
| 7245 |
TemplateId->NumArgs); |
| 7246 |
TypeResult T = ActOnTemplateIdType( |
| 7247 |
S, ElaboratedTypeKeyword::None, |
| 7248 |
/*ElaboratedKeywordLoc=*/SourceLocation(), SS, |
| 7249 |
TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name, |
| 7250 |
TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, |
| 7251 |
TemplateId->RAngleLoc, |
| 7252 |
/*IsCtorOrDtorName*/ true); |
| 7253 |
if (T.isInvalid() || !T.get()) { |
| 7254 |
// Recover by assuming we had the right type all along. |
| 7255 |
DestructedType = ObjectType; |
| 7256 |
} else |
| 7257 |
DestructedType = GetTypeFromParser(T.get(), &DestructedTypeInfo); |
| 7258 |
} |
| 7259 |
|
| 7260 |
// If we've performed some kind of recovery, (re-)build the type source |
| 7261 |
// information. |
| 7262 |
if (!DestructedType.isNull()) { |
| 7263 |
if (!DestructedTypeInfo) |
| 7264 |
DestructedTypeInfo = Context.getTrivialTypeSourceInfo(DestructedType, |
| 7265 |
SecondTypeName.StartLocation); |
| 7266 |
Destructed = PseudoDestructorTypeStorage(DestructedTypeInfo); |
| 7267 |
} |
| 7268 |
|
| 7269 |
// Convert the name of the scope type (the type prior to '::') into a type. |
| 7270 |
TypeSourceInfo *ScopeTypeInfo = nullptr; |
| 7271 |
QualType ScopeType; |
| 7272 |
if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_TemplateId || |
| 7273 |
FirstTypeName.Identifier) { |
| 7274 |
if (FirstTypeName.getKind() == UnqualifiedIdKind::IK_Identifier) { |
| 7275 |
ParsedType T = getTypeName(*FirstTypeName.Identifier, |
| 7276 |
FirstTypeName.StartLocation, |
| 7277 |
S, &SS, true, false, ObjectTypePtrForLookup, |
| 7278 |
/*IsCtorOrDtorName*/true); |
| 7279 |
if (!T) { |
| 7280 |
Diag(FirstTypeName.StartLocation, |
| 7281 |
diag::err_pseudo_dtor_destructor_non_type) |
| 7282 |
<< FirstTypeName.Identifier << ObjectType; |
| 7283 |
|
| 7284 |
if (isSFINAEContext()) |
| 7285 |
return ExprError(); |
| 7286 |
|
| 7287 |
// Just drop this type. It's unnecessary anyway. |
| 7288 |
ScopeType = QualType(); |
| 7289 |
} else |
| 7290 |
ScopeType = GetTypeFromParser(T, &ScopeTypeInfo); |
| 7291 |
} else { |
| 7292 |
// Resolve the template-id to a type. |
| 7293 |
TemplateIdAnnotation *TemplateId = FirstTypeName.TemplateId; |
| 7294 |
ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(), |
| 7295 |
TemplateId->NumArgs); |
| 7296 |
TypeResult T = ActOnTemplateIdType( |
| 7297 |
S, ElaboratedTypeKeyword::None, |
| 7298 |
/*ElaboratedKeywordLoc=*/SourceLocation(), SS, |
| 7299 |
TemplateId->TemplateKWLoc, TemplateId->Template, TemplateId->Name, |
| 7300 |
TemplateId->TemplateNameLoc, TemplateId->LAngleLoc, TemplateArgsPtr, |
| 7301 |
TemplateId->RAngleLoc, |
| 7302 |
/*IsCtorOrDtorName*/ true); |
| 7303 |
if (T.isInvalid() || !T.get()) { |
| 7304 |
// Recover by dropping this type. |
| 7305 |
ScopeType = QualType(); |
| 7306 |
} else |
| 7307 |
ScopeType = GetTypeFromParser(T.get(), &ScopeTypeInfo); |
| 7308 |
} |
| 7309 |
} |
| 7310 |
|
| 7311 |
if (!ScopeType.isNull() && !ScopeTypeInfo) |
| 7312 |
ScopeTypeInfo = Context.getTrivialTypeSourceInfo(ScopeType, |
| 7313 |
FirstTypeName.StartLocation); |
| 7314 |
|
| 7315 |
|
| 7316 |
return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, SS, |
| 7317 |
ScopeTypeInfo, CCLoc, TildeLoc, |
| 7318 |
Destructed); |
| 7319 |
} |
| 7320 |
|
| 7321 |
ExprResult Sema::ActOnPseudoDestructorExpr(Scope *S, Expr *Base, |
| 7322 |
SourceLocation OpLoc, |
| 7323 |
tok::TokenKind OpKind, |
| 7324 |
SourceLocation TildeLoc, |
| 7325 |
const DeclSpec& DS) { |
| 7326 |
QualType ObjectType; |
| 7327 |
QualType T; |
| 7328 |
TypeLocBuilder TLB; |
| 7329 |
if (CheckArrow(*this, ObjectType, Base, OpKind, OpLoc) || |
| 7330 |
DS.getTypeSpecType() == DeclSpec::TST_error) |
| 7331 |
return ExprError(); |
| 7332 |
|
| 7333 |
switch (DS.getTypeSpecType()) { |
| 7334 |
case DeclSpec::TST_decltype_auto: { |
| 7335 |
Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid); |
| 7336 |
return true; |
| 7337 |
} |
| 7338 |
case DeclSpec::TST_decltype: { |
| 7339 |
T = BuildDecltypeType(DS.getRepAsExpr(), /*AsUnevaluated=*/false); |
| 7340 |
DecltypeTypeLoc DecltypeTL = TLB.push<DecltypeTypeLoc>(T); |
| 7341 |
DecltypeTL.setDecltypeLoc(DS.getTypeSpecTypeLoc()); |
| 7342 |
DecltypeTL.setRParenLoc(DS.getTypeofParensRange().getEnd()); |
| 7343 |
break; |
| 7344 |
} |
| 7345 |
case DeclSpec::TST_typename_pack_indexing: { |
| 7346 |
T = ActOnPackIndexingType(DS.getRepAsType().get(), DS.getPackIndexingExpr(), |
| 7347 |
DS.getBeginLoc(), DS.getEllipsisLoc()); |
| 7348 |
TLB.pushTrivial(getASTContext(), |
| 7349 |
cast<PackIndexingType>(T.getTypePtr())->getPattern(), |
| 7350 |
DS.getBeginLoc()); |
| 7351 |
PackIndexingTypeLoc PITL = TLB.push<PackIndexingTypeLoc>(T); |
| 7352 |
PITL.setEllipsisLoc(DS.getEllipsisLoc()); |
| 7353 |
break; |
| 7354 |
} |
| 7355 |
default: |
| 7356 |
llvm_unreachable("Unsupported type in pseudo destructor"); |
| 7357 |
} |
| 7358 |
TypeSourceInfo *DestructedTypeInfo = TLB.getTypeSourceInfo(Context, T); |
| 7359 |
PseudoDestructorTypeStorage Destructed(DestructedTypeInfo); |
| 7360 |
|
| 7361 |
return BuildPseudoDestructorExpr(Base, OpLoc, OpKind, CXXScopeSpec(), |
| 7362 |
nullptr, SourceLocation(), TildeLoc, |
| 7363 |
Destructed); |
| 7364 |
} |
| 7365 |
|
| 7366 |
ExprResult Sema::BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, |
| 7367 |
SourceLocation RParen) { |
| 7368 |
// If the operand is an unresolved lookup expression, the expression is ill- |
| 7369 |
// formed per [over.over]p1, because overloaded function names cannot be used |
| 7370 |
// without arguments except in explicit contexts. |
| 7371 |
ExprResult R = CheckPlaceholderExpr(Operand); |
| 7372 |
if (R.isInvalid()) |
| 7373 |
return R; |
| 7374 |
|
| 7375 |
R = CheckUnevaluatedOperand(R.get()); |
| 7376 |
if (R.isInvalid()) |
| 7377 |
return ExprError(); |
| 7378 |
|
| 7379 |
Operand = R.get(); |
| 7380 |
|
| 7381 |
if (!inTemplateInstantiation() && !Operand->isInstantiationDependent() && |
| 7382 |
Operand->HasSideEffects(Context, false)) { |
| 7383 |
// The expression operand for noexcept is in an unevaluated expression |
| 7384 |
// context, so side effects could result in unintended consequences. |
| 7385 |
Diag(Operand->getExprLoc(), diag::warn_side_effects_unevaluated_context); |
| 7386 |
} |
| 7387 |
|
| 7388 |
CanThrowResult CanThrow = canThrow(Operand); |
| 7389 |
return new (Context) |
| 7390 |
CXXNoexceptExpr(Context.BoolTy, Operand, CanThrow, KeyLoc, RParen); |
| 7391 |
} |
| 7392 |
|
| 7393 |
ExprResult Sema::ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation, |
| 7394 |
Expr *Operand, SourceLocation RParen) { |
| 7395 |
return BuildCXXNoexceptExpr(KeyLoc, Operand, RParen); |
| 7396 |
} |
| 7397 |
|
| 7398 |
static void MaybeDecrementCount( |
| 7399 |
Expr *E, llvm::DenseMap<const VarDecl *, int> &RefsMinusAssignments) { |
| 7400 |
DeclRefExpr *LHS = nullptr; |
| 7401 |
bool IsCompoundAssign = false; |
| 7402 |
bool isIncrementDecrementUnaryOp = false; |
| 7403 |
if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { |
| 7404 |
if (BO->getLHS()->getType()->isDependentType() || |
| 7405 |
BO->getRHS()->getType()->isDependentType()) { |
| 7406 |
if (BO->getOpcode() != BO_Assign) |
| 7407 |
return; |
| 7408 |
} else if (!BO->isAssignmentOp()) |
| 7409 |
return; |
| 7410 |
else |
| 7411 |
IsCompoundAssign = BO->isCompoundAssignmentOp(); |
| 7412 |
LHS = dyn_cast<DeclRefExpr>(BO->getLHS()); |
| 7413 |
} else if (CXXOperatorCallExpr *COCE = dyn_cast<CXXOperatorCallExpr>(E)) { |
| 7414 |
if (COCE->getOperator() != OO_Equal) |
| 7415 |
return; |
| 7416 |
LHS = dyn_cast<DeclRefExpr>(COCE->getArg(0)); |
| 7417 |
} else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { |
| 7418 |
if (!UO->isIncrementDecrementOp()) |
| 7419 |
return; |
| 7420 |
isIncrementDecrementUnaryOp = true; |
| 7421 |
LHS = dyn_cast<DeclRefExpr>(UO->getSubExpr()); |
| 7422 |
} |
| 7423 |
if (!LHS) |
| 7424 |
return; |
| 7425 |
VarDecl *VD = dyn_cast<VarDecl>(LHS->getDecl()); |
| 7426 |
if (!VD) |
| 7427 |
return; |
| 7428 |
// Don't decrement RefsMinusAssignments if volatile variable with compound |
| 7429 |
// assignment (+=, ...) or increment/decrement unary operator to avoid |
| 7430 |
// potential unused-but-set-variable warning. |
| 7431 |
if ((IsCompoundAssign || isIncrementDecrementUnaryOp) && |
| 7432 |
VD->getType().isVolatileQualified()) |
| 7433 |
return; |
| 7434 |
auto iter = RefsMinusAssignments.find(VD); |
| 7435 |
if (iter == RefsMinusAssignments.end()) |
| 7436 |
return; |
| 7437 |
iter->getSecond()--; |
| 7438 |
} |
| 7439 |
|
| 7440 |
/// Perform the conversions required for an expression used in a |
| 7441 |
/// context that ignores the result. |
| 7442 |
ExprResult Sema::IgnoredValueConversions(Expr *E) { |
| 7443 |
MaybeDecrementCount(E, RefsMinusAssignments); |
| 7444 |
|
| 7445 |
if (E->hasPlaceholderType()) { |
| 7446 |
ExprResult result = CheckPlaceholderExpr(E); |
| 7447 |
if (result.isInvalid()) return E; |
| 7448 |
E = result.get(); |
| 7449 |
} |
| 7450 |
|
| 7451 |
if (getLangOpts().CPlusPlus) { |
| 7452 |
// The C++11 standard defines the notion of a discarded-value expression; |
| 7453 |
// normally, we don't need to do anything to handle it, but if it is a |
| 7454 |
// volatile lvalue with a special form, we perform an lvalue-to-rvalue |
| 7455 |
// conversion. |
| 7456 |
if (getLangOpts().CPlusPlus11 && E->isReadIfDiscardedInCPlusPlus11()) { |
| 7457 |
ExprResult Res = DefaultLvalueConversion(E); |
| 7458 |
if (Res.isInvalid()) |
| 7459 |
return E; |
| 7460 |
E = Res.get(); |
| 7461 |
} else { |
| 7462 |
// Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if |
| 7463 |
// it occurs as a discarded-value expression. |
| 7464 |
CheckUnusedVolatileAssignment(E); |
| 7465 |
} |
| 7466 |
|
| 7467 |
// C++1z: |
| 7468 |
// If the expression is a prvalue after this optional conversion, the |
| 7469 |
// temporary materialization conversion is applied. |
| 7470 |
// |
| 7471 |
// We do not materialize temporaries by default in order to avoid creating |
| 7472 |
// unnecessary temporary objects. If we skip this step, IR generation is |
| 7473 |
// able to synthesize the storage for itself in the aggregate case, and |
| 7474 |
// adding the extra node to the AST is just clutter. |
| 7475 |
if (isInLifetimeExtendingContext() && getLangOpts().CPlusPlus17 && |
| 7476 |
E->isPRValue() && !E->getType()->isVoidType()) { |
| 7477 |
ExprResult Res = TemporaryMaterializationConversion(E); |
| 7478 |
if (Res.isInvalid()) |
| 7479 |
return E; |
| 7480 |
E = Res.get(); |
| 7481 |
} |
| 7482 |
return E; |
| 7483 |
} |
| 7484 |
|
| 7485 |
// C99 6.3.2.1: |
| 7486 |
// [Except in specific positions,] an lvalue that does not have |
| 7487 |
// array type is converted to the value stored in the |
| 7488 |
// designated object (and is no longer an lvalue). |
| 7489 |
if (E->isPRValue()) { |
| 7490 |
// In C, function designators (i.e. expressions of function type) |
| 7491 |
// are r-values, but we still want to do function-to-pointer decay |
| 7492 |
// on them. This is both technically correct and convenient for |
| 7493 |
// some clients. |
| 7494 |
if (!getLangOpts().CPlusPlus && E->getType()->isFunctionType()) |
| 7495 |
return DefaultFunctionArrayConversion(E); |
| 7496 |
|
| 7497 |
return E; |
| 7498 |
} |
| 7499 |
|
| 7500 |
// GCC seems to also exclude expressions of incomplete enum type. |
| 7501 |
if (const auto *ED = E->getType()->getAsEnumDecl(); ED && !ED->isComplete()) { |
| 7502 |
// FIXME: stupid workaround for a codegen bug! |
| 7503 |
E = ImpCastExprToType(E, Context.VoidTy, CK_ToVoid).get(); |
| 7504 |
return E; |
| 7505 |
} |
| 7506 |
|
| 7507 |
ExprResult Res = DefaultFunctionArrayLvalueConversion(E); |
| 7508 |
if (Res.isInvalid()) |
| 7509 |
return E; |
| 7510 |
E = Res.get(); |
| 7511 |
|
| 7512 |
if (!E->getType()->isVoidType()) |
| 7513 |
RequireCompleteType(E->getExprLoc(), E->getType(), |
| 7514 |
diag::err_incomplete_type); |
| 7515 |
return E; |
| 7516 |
} |
| 7517 |
|
| 7518 |
ExprResult Sema::CheckUnevaluatedOperand(Expr *E) { |
| 7519 |
// Per C++2a [expr.ass]p5, a volatile assignment is not deprecated if |
| 7520 |
// it occurs as an unevaluated operand. |
| 7521 |
CheckUnusedVolatileAssignment(E); |
| 7522 |
|
| 7523 |
return E; |
| 7524 |
} |
| 7525 |
|
| 7526 |
// If we can unambiguously determine whether Var can never be used |
| 7527 |
// in a constant expression, return true. |
| 7528 |
// - if the variable and its initializer are non-dependent, then |
| 7529 |
// we can unambiguously check if the variable is a constant expression. |
| 7530 |
// - if the initializer is not value dependent - we can determine whether |
| 7531 |
// it can be used to initialize a constant expression. If Init can not |
| 7532 |
// be used to initialize a constant expression we conclude that Var can |
| 7533 |
// never be a constant expression. |
| 7534 |
// - FXIME: if the initializer is dependent, we can still do some analysis and |
| 7535 |
// identify certain cases unambiguously as non-const by using a Visitor: |
| 7536 |
// - such as those that involve odr-use of a ParmVarDecl, involve a new |
| 7537 |
// delete, lambda-expr, dynamic-cast, reinterpret-cast etc... |
| 7538 |
static inline bool VariableCanNeverBeAConstantExpression(VarDecl *Var, |
| 7539 |
ASTContext &Context) { |
| 7540 |
if (isa<ParmVarDecl>(Var)) return true; |
| 7541 |
const VarDecl *DefVD = nullptr; |
| 7542 |
|
| 7543 |
// If there is no initializer - this can not be a constant expression. |
| 7544 |
const Expr *Init = Var->getAnyInitializer(DefVD); |
| 7545 |
if (!Init) |
| 7546 |
return true; |
| 7547 |
assert(DefVD); |
| 7548 |
if (DefVD->isWeak()) |
| 7549 |
return false; |
| 7550 |
|
| 7551 |
if (Var->getType()->isDependentType() || Init->isValueDependent()) { |
| 7552 |
// FIXME: Teach the constant evaluator to deal with the non-dependent parts |
| 7553 |
// of value-dependent expressions, and use it here to determine whether the |
| 7554 |
// initializer is a potential constant expression. |
| 7555 |
return false; |
| 7556 |
} |
| 7557 |
|
| 7558 |
return !Var->isUsableInConstantExpressions(Context); |
| 7559 |
} |
| 7560 |
|
| 7561 |
/// Check if the current lambda has any potential captures |
| 7562 |
/// that must be captured by any of its enclosing lambdas that are ready to |
| 7563 |
/// capture. If there is a lambda that can capture a nested |
| 7564 |
/// potential-capture, go ahead and do so. Also, check to see if any |
| 7565 |
/// variables are uncaptureable or do not involve an odr-use so do not |
| 7566 |
/// need to be captured. |
| 7567 |
|
| 7568 |
static void CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures( |
| 7569 |
Expr *const FE, LambdaScopeInfo *const CurrentLSI, Sema &S) { |
| 7570 |
|
| 7571 |
assert(!S.isUnevaluatedContext()); |
| 7572 |
assert(S.CurContext->isDependentContext()); |
| 7573 |
#ifndef NDEBUG |
| 7574 |
DeclContext *DC = S.CurContext; |
| 7575 |
while (isa_and_nonnull<CapturedDecl>(DC)) |
| 7576 |
DC = DC->getParent(); |
| 7577 |
assert( |
| 7578 |
(CurrentLSI->CallOperator == DC || !CurrentLSI->AfterParameterList) && |
| 7579 |
"The current call operator must be synchronized with Sema's CurContext"); |
| 7580 |
#endif // NDEBUG |
| 7581 |
|
| 7582 |
const bool IsFullExprInstantiationDependent = FE->isInstantiationDependent(); |
| 7583 |
|
| 7584 |
// All the potentially captureable variables in the current nested |
| 7585 |
// lambda (within a generic outer lambda), must be captured by an |
| 7586 |
// outer lambda that is enclosed within a non-dependent context. |
| 7587 |
CurrentLSI->visitPotentialCaptures([&](ValueDecl *Var, Expr *VarExpr) { |
| 7588 |
// If the variable is clearly identified as non-odr-used and the full |
| 7589 |
// expression is not instantiation dependent, only then do we not |
| 7590 |
// need to check enclosing lambda's for speculative captures. |
| 7591 |
// For e.g.: |
| 7592 |
// Even though 'x' is not odr-used, it should be captured. |
| 7593 |
// int test() { |
| 7594 |
// const int x = 10; |
| 7595 |
// auto L = [=](auto a) { |
| 7596 |
// (void) +x + a; |
| 7597 |
// }; |
| 7598 |
// } |
| 7599 |
if (CurrentLSI->isVariableExprMarkedAsNonODRUsed(VarExpr) && |
| 7600 |
!IsFullExprInstantiationDependent) |
| 7601 |
return; |
| 7602 |
|
| 7603 |
VarDecl *UnderlyingVar = Var->getPotentiallyDecomposedVarDecl(); |
| 7604 |
if (!UnderlyingVar) |
| 7605 |
return; |
| 7606 |
|
| 7607 |
// If we have a capture-capable lambda for the variable, go ahead and |
| 7608 |
// capture the variable in that lambda (and all its enclosing lambdas). |
| 7609 |
if (const UnsignedOrNone Index = |
| 7610 |
getStackIndexOfNearestEnclosingCaptureCapableLambda( |
| 7611 |
S.FunctionScopes, Var, S)) |
| 7612 |
S.MarkCaptureUsedInEnclosingContext(Var, VarExpr->getExprLoc(), *Index); |
| 7613 |
const bool IsVarNeverAConstantExpression = |
| 7614 |
VariableCanNeverBeAConstantExpression(UnderlyingVar, S.Context); |
| 7615 |
if (!IsFullExprInstantiationDependent || IsVarNeverAConstantExpression) { |
| 7616 |
// This full expression is not instantiation dependent or the variable |
| 7617 |
// can not be used in a constant expression - which means |
| 7618 |
// this variable must be odr-used here, so diagnose a |
| 7619 |
// capture violation early, if the variable is un-captureable. |
| 7620 |
// This is purely for diagnosing errors early. Otherwise, this |
| 7621 |
// error would get diagnosed when the lambda becomes capture ready. |
| 7622 |
QualType CaptureType, DeclRefType; |
| 7623 |
SourceLocation ExprLoc = VarExpr->getExprLoc(); |
| 7624 |
if (S.tryCaptureVariable(Var, ExprLoc, TryCaptureKind::Implicit, |
| 7625 |
/*EllipsisLoc*/ SourceLocation(), |
| 7626 |
/*BuildAndDiagnose*/ false, CaptureType, |
| 7627 |
DeclRefType, nullptr)) { |
| 7628 |
// We will never be able to capture this variable, and we need |
| 7629 |
// to be able to in any and all instantiations, so diagnose it. |
| 7630 |
S.tryCaptureVariable(Var, ExprLoc, TryCaptureKind::Implicit, |
| 7631 |
/*EllipsisLoc*/ SourceLocation(), |
| 7632 |
/*BuildAndDiagnose*/ true, CaptureType, |
| 7633 |
DeclRefType, nullptr); |
| 7634 |
} |
| 7635 |
} |
| 7636 |
}); |
| 7637 |
|
| 7638 |
// Check if 'this' needs to be captured. |
| 7639 |
if (CurrentLSI->hasPotentialThisCapture()) { |
| 7640 |
// If we have a capture-capable lambda for 'this', go ahead and capture |
| 7641 |
// 'this' in that lambda (and all its enclosing lambdas). |
| 7642 |
if (const UnsignedOrNone Index = |
| 7643 |
getStackIndexOfNearestEnclosingCaptureCapableLambda( |
| 7644 |
S.FunctionScopes, /*0 is 'this'*/ nullptr, S)) { |
| 7645 |
const unsigned FunctionScopeIndexOfCapturableLambda = *Index; |
| 7646 |
S.CheckCXXThisCapture(CurrentLSI->PotentialThisCaptureLocation, |
| 7647 |
/*Explicit*/ false, /*BuildAndDiagnose*/ true, |
| 7648 |
&FunctionScopeIndexOfCapturableLambda); |
| 7649 |
} |
| 7650 |
} |
| 7651 |
|
| 7652 |
// Reset all the potential captures at the end of each full-expression. |
| 7653 |
CurrentLSI->clearPotentialCaptures(); |
| 7654 |
} |
| 7655 |
|
| 7656 |
ExprResult Sema::ActOnFinishFullExpr(Expr *FE, SourceLocation CC, |
| 7657 |
bool DiscardedValue, bool IsConstexpr, |
| 7658 |
bool IsTemplateArgument) { |
| 7659 |
ExprResult FullExpr = FE; |
| 7660 |
|
| 7661 |
if (!FullExpr.get()) |
| 7662 |
return ExprError(); |
| 7663 |
|
| 7664 |
if (!IsTemplateArgument && DiagnoseUnexpandedParameterPack(FullExpr.get())) |
| 7665 |
return ExprError(); |
| 7666 |
|
| 7667 |
if (DiscardedValue) { |
| 7668 |
// Top-level expressions default to 'id' when we're in a debugger. |
| 7669 |
if (getLangOpts().DebuggerCastResultToId && |
| 7670 |
FullExpr.get()->getType() == Context.UnknownAnyTy) { |
| 7671 |
FullExpr = forceUnknownAnyToType(FullExpr.get(), Context.getObjCIdType()); |
| 7672 |
if (FullExpr.isInvalid()) |
| 7673 |
return ExprError(); |
| 7674 |
} |
| 7675 |
|
| 7676 |
FullExpr = CheckPlaceholderExpr(FullExpr.get()); |
| 7677 |
if (FullExpr.isInvalid()) |
| 7678 |
return ExprError(); |
| 7679 |
|
| 7680 |
FullExpr = IgnoredValueConversions(FullExpr.get()); |
| 7681 |
if (FullExpr.isInvalid()) |
| 7682 |
return ExprError(); |
| 7683 |
|
| 7684 |
DiagnoseUnusedExprResult(FullExpr.get(), diag::warn_unused_expr); |
| 7685 |
} |
| 7686 |
|
| 7687 |
if (FullExpr.isInvalid()) |
| 7688 |
return ExprError(); |
| 7689 |
|
| 7690 |
CheckCompletedExpr(FullExpr.get(), CC, IsConstexpr); |
| 7691 |
|
| 7692 |
// At the end of this full expression (which could be a deeply nested |
| 7693 |
// lambda), if there is a potential capture within the nested lambda, |
| 7694 |
// have the outer capture-able lambda try and capture it. |
| 7695 |
// Consider the following code: |
| 7696 |
// void f(int, int); |
| 7697 |
// void f(const int&, double); |
| 7698 |
// void foo() { |
| 7699 |
// const int x = 10, y = 20; |
| 7700 |
// auto L = [=](auto a) { |
| 7701 |
// auto M = [=](auto b) { |
| 7702 |
// f(x, b); <-- requires x to be captured by L and M |
| 7703 |
// f(y, a); <-- requires y to be captured by L, but not all Ms |
| 7704 |
// }; |
| 7705 |
// }; |
| 7706 |
// } |
| 7707 |
|
| 7708 |
// FIXME: Also consider what happens for something like this that involves |
| 7709 |
// the gnu-extension statement-expressions or even lambda-init-captures: |
| 7710 |
// void f() { |
| 7711 |
// const int n = 0; |
| 7712 |
// auto L = [&](auto a) { |
| 7713 |
// +n + ({ 0; a; }); |
| 7714 |
// }; |
| 7715 |
// } |
| 7716 |
// |
| 7717 |
// Here, we see +n, and then the full-expression 0; ends, so we don't |
| 7718 |
// capture n (and instead remove it from our list of potential captures), |
| 7719 |
// and then the full-expression +n + ({ 0; }); ends, but it's too late |
| 7720 |
// for us to see that we need to capture n after all. |
| 7721 |
|
| 7722 |
LambdaScopeInfo *const CurrentLSI = |
| 7723 |
getCurLambda(/*IgnoreCapturedRegions=*/true); |
| 7724 |
// FIXME: PR 17877 showed that getCurLambda() can return a valid pointer |
| 7725 |
// even if CurContext is not a lambda call operator. Refer to that Bug Report |
| 7726 |
// for an example of the code that might cause this asynchrony. |
| 7727 |
// By ensuring we are in the context of a lambda's call operator |
| 7728 |
// we can fix the bug (we only need to check whether we need to capture |
| 7729 |
// if we are within a lambda's body); but per the comments in that |
| 7730 |
// PR, a proper fix would entail : |
| 7731 |
// "Alternative suggestion: |
| 7732 |
// - Add to Sema an integer holding the smallest (outermost) scope |
| 7733 |
// index that we are *lexically* within, and save/restore/set to |
| 7734 |
// FunctionScopes.size() in InstantiatingTemplate's |
| 7735 |
// constructor/destructor. |
| 7736 |
// - Teach the handful of places that iterate over FunctionScopes to |
| 7737 |
// stop at the outermost enclosing lexical scope." |
| 7738 |
DeclContext *DC = CurContext; |
| 7739 |
while (isa_and_nonnull<CapturedDecl>(DC)) |
| 7740 |
DC = DC->getParent(); |
| 7741 |
const bool IsInLambdaDeclContext = isLambdaCallOperator(DC); |
| 7742 |
if (IsInLambdaDeclContext && CurrentLSI && |
| 7743 |
CurrentLSI->hasPotentialCaptures() && !FullExpr.isInvalid()) |
| 7744 |
CheckIfAnyEnclosingLambdasMustCaptureAnyPotentialCaptures(FE, CurrentLSI, |
| 7745 |
*this); |
| 7746 |
return MaybeCreateExprWithCleanups(FullExpr); |
| 7747 |
} |
| 7748 |
|
| 7749 |
StmtResult Sema::ActOnFinishFullStmt(Stmt *FullStmt) { |
| 7750 |
if (!FullStmt) return StmtError(); |
| 7751 |
|
| 7752 |
return MaybeCreateStmtWithCleanups(FullStmt); |
| 7753 |
} |
| 7754 |
|
| 7755 |
IfExistsResult |
| 7756 |
Sema::CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, |
| 7757 |
const DeclarationNameInfo &TargetNameInfo) { |
| 7758 |
DeclarationName TargetName = TargetNameInfo.getName(); |
| 7759 |
if (!TargetName) |
| 7760 |
return IfExistsResult::DoesNotExist; |
| 7761 |
|
| 7762 |
// If the name itself is dependent, then the result is dependent. |
| 7763 |
if (TargetName.isDependentName()) |
| 7764 |
return IfExistsResult::Dependent; |
| 7765 |
|
| 7766 |
// Do the redeclaration lookup in the current scope. |
| 7767 |
LookupResult R(*this, TargetNameInfo, Sema::LookupAnyName, |
| 7768 |
RedeclarationKind::NotForRedeclaration); |
| 7769 |
LookupParsedName(R, S, &SS, /*ObjectType=*/QualType()); |
| 7770 |
R.suppressDiagnostics(); |
| 7771 |
|
| 7772 |
switch (R.getResultKind()) { |
| 7773 |
case LookupResultKind::Found: |
| 7774 |
case LookupResultKind::FoundOverloaded: |
| 7775 |
case LookupResultKind::FoundUnresolvedValue: |
| 7776 |
case LookupResultKind::Ambiguous: |
| 7777 |
return IfExistsResult::Exists; |
| 7778 |
|
| 7779 |
case LookupResultKind::NotFound: |
| 7780 |
return IfExistsResult::DoesNotExist; |
| 7781 |
|
| 7782 |
case LookupResultKind::NotFoundInCurrentInstantiation: |
| 7783 |
return IfExistsResult::Dependent; |
| 7784 |
} |
| 7785 |
|
| 7786 |
llvm_unreachable("Invalid LookupResult Kind!"); |
| 7787 |
} |
| 7788 |
|
| 7789 |
IfExistsResult Sema::CheckMicrosoftIfExistsSymbol(Scope *S, |
| 7790 |
SourceLocation KeywordLoc, |
| 7791 |
bool IsIfExists, |
| 7792 |
CXXScopeSpec &SS, |
| 7793 |
UnqualifiedId &Name) { |
| 7794 |
DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name); |
| 7795 |
|
| 7796 |
// Check for an unexpanded parameter pack. |
| 7797 |
auto UPPC = IsIfExists ? UPPC_IfExists : UPPC_IfNotExists; |
| 7798 |
if (DiagnoseUnexpandedParameterPack(SS, UPPC) || |
| 7799 |
DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC)) |
| 7800 |
return IfExistsResult::Error; |
| 7801 |
|
| 7802 |
return CheckMicrosoftIfExistsSymbol(S, SS, TargetNameInfo); |
| 7803 |
} |
| 7804 |
|
| 7805 |
concepts::Requirement *Sema::ActOnSimpleRequirement(Expr *E) { |
| 7806 |
return BuildExprRequirement(E, /*IsSimple=*/true, |
| 7807 |
/*NoexceptLoc=*/SourceLocation(), |
| 7808 |
/*ReturnTypeRequirement=*/{}); |
| 7809 |
} |
| 7810 |
|
| 7811 |
concepts::Requirement *Sema::ActOnTypeRequirement( |
| 7812 |
SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, |
| 7813 |
const IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId) { |
| 7814 |
assert(((!TypeName && TemplateId) || (TypeName && !TemplateId)) && |
| 7815 |
"Exactly one of TypeName and TemplateId must be specified."); |
| 7816 |
TypeSourceInfo *TSI = nullptr; |
| 7817 |
if (TypeName) { |
| 7818 |
QualType T = |
| 7819 |
CheckTypenameType(ElaboratedTypeKeyword::Typename, TypenameKWLoc, |
| 7820 |
SS.getWithLocInContext(Context), *TypeName, NameLoc, |
| 7821 |
&TSI, /*DeducedTSTContext=*/false); |
| 7822 |
if (T.isNull()) |
| 7823 |
return nullptr; |
| 7824 |
} else { |
| 7825 |
ASTTemplateArgsPtr ArgsPtr(TemplateId->getTemplateArgs(), |
| 7826 |
TemplateId->NumArgs); |
| 7827 |
TypeResult T = ActOnTypenameType(CurScope, TypenameKWLoc, SS, |
| 7828 |
TemplateId->TemplateKWLoc, |
| 7829 |
TemplateId->Template, TemplateId->Name, |
| 7830 |
TemplateId->TemplateNameLoc, |
| 7831 |
TemplateId->LAngleLoc, ArgsPtr, |
| 7832 |
TemplateId->RAngleLoc); |
| 7833 |
if (T.isInvalid()) |
| 7834 |
return nullptr; |
| 7835 |
if (GetTypeFromParser(T.get(), &TSI).isNull()) |
| 7836 |
return nullptr; |
| 7837 |
} |
| 7838 |
return BuildTypeRequirement(TSI); |
| 7839 |
} |
| 7840 |
|
| 7841 |
concepts::Requirement * |
| 7842 |
Sema::ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc) { |
| 7843 |
return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, |
| 7844 |
/*ReturnTypeRequirement=*/{}); |
| 7845 |
} |
| 7846 |
|
| 7847 |
concepts::Requirement * |
| 7848 |
Sema::ActOnCompoundRequirement( |
| 7849 |
Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, |
| 7850 |
TemplateIdAnnotation *TypeConstraint, unsigned Depth) { |
| 7851 |
// C++2a [expr.prim.req.compound] p1.3.3 |
| 7852 |
// [..] the expression is deduced against an invented function template |
| 7853 |
// F [...] F is a void function template with a single type template |
| 7854 |
// parameter T declared with the constrained-parameter. Form a new |
| 7855 |
// cv-qualifier-seq cv by taking the union of const and volatile specifiers |
| 7856 |
// around the constrained-parameter. F has a single parameter whose |
| 7857 |
// type-specifier is cv T followed by the abstract-declarator. [...] |
| 7858 |
// |
| 7859 |
// The cv part is done in the calling function - we get the concept with |
| 7860 |
// arguments and the abstract declarator with the correct CV qualification and |
| 7861 |
// have to synthesize T and the single parameter of F. |
| 7862 |
auto &II = Context.Idents.get("expr-type"); |
| 7863 |
auto *TParam = TemplateTypeParmDecl::Create(Context, CurContext, |
| 7864 |
SourceLocation(), |
| 7865 |
SourceLocation(), Depth, |
| 7866 |
/*Index=*/0, &II, |
| 7867 |
/*Typename=*/true, |
| 7868 |
/*ParameterPack=*/false, |
| 7869 |
/*HasTypeConstraint=*/true); |
| 7870 |
|
| 7871 |
if (BuildTypeConstraint(SS, TypeConstraint, TParam, |
| 7872 |
/*EllipsisLoc=*/SourceLocation(), |
| 7873 |
/*AllowUnexpandedPack=*/true)) |
| 7874 |
// Just produce a requirement with no type requirements. |
| 7875 |
return BuildExprRequirement(E, /*IsSimple=*/false, NoexceptLoc, {}); |
| 7876 |
|
| 7877 |
auto *TPL = TemplateParameterList::Create(Context, SourceLocation(), |
| 7878 |
SourceLocation(), |
| 7879 |
ArrayRef<NamedDecl *>(TParam), |
| 7880 |
SourceLocation(), |
| 7881 |
/*RequiresClause=*/nullptr); |
| 7882 |
return BuildExprRequirement( |
| 7883 |
E, /*IsSimple=*/false, NoexceptLoc, |
| 7884 |
concepts::ExprRequirement::ReturnTypeRequirement(TPL)); |
| 7885 |
} |
| 7886 |
|
| 7887 |
concepts::ExprRequirement * |
| 7888 |
Sema::BuildExprRequirement( |
| 7889 |
Expr *E, bool IsSimple, SourceLocation NoexceptLoc, |
| 7890 |
concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { |
| 7891 |
auto Status = concepts::ExprRequirement::SS_Satisfied; |
| 7892 |
ConceptSpecializationExpr *SubstitutedConstraintExpr = nullptr; |
| 7893 |
if (E->isInstantiationDependent() || E->getType()->isPlaceholderType() || |
| 7894 |
ReturnTypeRequirement.isDependent()) |
| 7895 |
Status = concepts::ExprRequirement::SS_Dependent; |
| 7896 |
else if (NoexceptLoc.isValid() && canThrow(E) == CanThrowResult::CT_Can) |
| 7897 |
Status = concepts::ExprRequirement::SS_NoexceptNotMet; |
| 7898 |
else if (ReturnTypeRequirement.isSubstitutionFailure()) |
| 7899 |
Status = concepts::ExprRequirement::SS_TypeRequirementSubstitutionFailure; |
| 7900 |
else if (ReturnTypeRequirement.isTypeConstraint()) { |
| 7901 |
// C++2a [expr.prim.req]p1.3.3 |
| 7902 |
// The immediately-declared constraint ([temp]) of decltype((E)) shall |
| 7903 |
// be satisfied. |
| 7904 |
TemplateParameterList *TPL = |
| 7905 |
ReturnTypeRequirement.getTypeConstraintTemplateParameterList(); |
| 7906 |
QualType MatchedType = Context.getReferenceQualifiedType(E); |
| 7907 |
llvm::SmallVector<TemplateArgument, 1> Args; |
| 7908 |
Args.push_back(TemplateArgument(MatchedType)); |
| 7909 |
|
| 7910 |
auto *Param = cast<TemplateTypeParmDecl>(TPL->getParam(0)); |
| 7911 |
|
| 7912 |
MultiLevelTemplateArgumentList MLTAL(Param, Args, /*Final=*/true); |
| 7913 |
MLTAL.addOuterRetainedLevels(TPL->getDepth()); |
| 7914 |
const TypeConstraint *TC = Param->getTypeConstraint(); |
| 7915 |
assert(TC && "Type Constraint cannot be null here"); |
| 7916 |
auto *IDC = TC->getImmediatelyDeclaredConstraint(); |
| 7917 |
assert(IDC && "ImmediatelyDeclaredConstraint can't be null here."); |
| 7918 |
ExprResult Constraint = SubstExpr(IDC, MLTAL); |
| 7919 |
bool HasError = Constraint.isInvalid(); |
| 7920 |
if (!HasError) { |
| 7921 |
SubstitutedConstraintExpr = |
| 7922 |
cast<ConceptSpecializationExpr>(Constraint.get()); |
| 7923 |
if (SubstitutedConstraintExpr->getSatisfaction().ContainsErrors) |
| 7924 |
HasError = true; |
| 7925 |
} |
| 7926 |
if (HasError) { |
| 7927 |
return new (Context) concepts::ExprRequirement( |
| 7928 |
createSubstDiagAt(IDC->getExprLoc(), |
| 7929 |
[&](llvm::raw_ostream &OS) { |
| 7930 |
IDC->printPretty(OS, /*Helper=*/nullptr, |
| 7931 |
getPrintingPolicy()); |
| 7932 |
}), |
| 7933 |
IsSimple, NoexceptLoc, ReturnTypeRequirement); |
| 7934 |
} |
| 7935 |
if (!SubstitutedConstraintExpr->isSatisfied()) |
| 7936 |
Status = concepts::ExprRequirement::SS_ConstraintsNotSatisfied; |
| 7937 |
} |
| 7938 |
return new (Context) concepts::ExprRequirement(E, IsSimple, NoexceptLoc, |
| 7939 |
ReturnTypeRequirement, Status, |
| 7940 |
SubstitutedConstraintExpr); |
| 7941 |
} |
| 7942 |
|
| 7943 |
concepts::ExprRequirement * |
| 7944 |
Sema::BuildExprRequirement( |
| 7945 |
concepts::Requirement::SubstitutionDiagnostic *ExprSubstitutionDiagnostic, |
| 7946 |
bool IsSimple, SourceLocation NoexceptLoc, |
| 7947 |
concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement) { |
| 7948 |
return new (Context) concepts::ExprRequirement(ExprSubstitutionDiagnostic, |
| 7949 |
IsSimple, NoexceptLoc, |
| 7950 |
ReturnTypeRequirement); |
| 7951 |
} |
| 7952 |
|
| 7953 |
concepts::TypeRequirement * |
| 7954 |
Sema::BuildTypeRequirement(TypeSourceInfo *Type) { |
| 7955 |
return new (Context) concepts::TypeRequirement(Type); |
| 7956 |
} |
| 7957 |
|
| 7958 |
concepts::TypeRequirement * |
| 7959 |
Sema::BuildTypeRequirement( |
| 7960 |
concepts::Requirement::SubstitutionDiagnostic *SubstDiag) { |
| 7961 |
return new (Context) concepts::TypeRequirement(SubstDiag); |
| 7962 |
} |
| 7963 |
|
| 7964 |
concepts::Requirement *Sema::ActOnNestedRequirement(Expr *Constraint) { |
| 7965 |
return BuildNestedRequirement(Constraint); |
| 7966 |
} |
| 7967 |
|
| 7968 |
concepts::NestedRequirement * |
| 7969 |
Sema::BuildNestedRequirement(Expr *Constraint) { |
| 7970 |
ConstraintSatisfaction Satisfaction; |
| 7971 |
LocalInstantiationScope Scope(*this); |
| 7972 |
if (!Constraint->isInstantiationDependent() && |
| 7973 |
!Constraint->isValueDependent() && |
| 7974 |
CheckConstraintSatisfaction(nullptr, AssociatedConstraint(Constraint), |
| 7975 |
/*TemplateArgs=*/{}, |
| 7976 |
Constraint->getSourceRange(), Satisfaction)) |
| 7977 |
return nullptr; |
| 7978 |
return new (Context) concepts::NestedRequirement(Context, Constraint, |
| 7979 |
Satisfaction); |
| 7980 |
} |
| 7981 |
|
| 7982 |
concepts::NestedRequirement * |
| 7983 |
Sema::BuildNestedRequirement(StringRef InvalidConstraintEntity, |
| 7984 |
const ASTConstraintSatisfaction &Satisfaction) { |
| 7985 |
return new (Context) concepts::NestedRequirement( |
| 7986 |
InvalidConstraintEntity, |
| 7987 |
ASTConstraintSatisfaction::Rebuild(Context, Satisfaction)); |
| 7988 |
} |
| 7989 |
|
| 7990 |
RequiresExprBodyDecl * |
| 7991 |
Sema::ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, |
| 7992 |
ArrayRef<ParmVarDecl *> LocalParameters, |
| 7993 |
Scope *BodyScope) { |
| 7994 |
assert(BodyScope); |
| 7995 |
|
| 7996 |
RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(Context, CurContext, |
| 7997 |
RequiresKWLoc); |
| 7998 |
|
| 7999 |
PushDeclContext(BodyScope, Body); |
| 8000 |
|
| 8001 |
for (ParmVarDecl *Param : LocalParameters) { |
| 8002 |
if (Param->getType()->isVoidType()) { |
| 8003 |
if (LocalParameters.size() > 1) { |
| 8004 |
Diag(Param->getBeginLoc(), diag::err_void_only_param); |
| 8005 |
Param->setType(Context.IntTy); |
| 8006 |
} else if (Param->getIdentifier()) { |
| 8007 |
Diag(Param->getBeginLoc(), diag::err_param_with_void_type); |
| 8008 |
Param->setType(Context.IntTy); |
| 8009 |
} else if (Param->getType().hasQualifiers()) { |
| 8010 |
Diag(Param->getBeginLoc(), diag::err_void_param_qualified); |
| 8011 |
} |
| 8012 |
} else if (Param->hasDefaultArg()) { |
| 8013 |
// C++2a [expr.prim.req] p4 |
| 8014 |
// [...] A local parameter of a requires-expression shall not have a |
| 8015 |
// default argument. [...] |
| 8016 |
Diag(Param->getDefaultArgRange().getBegin(), |
| 8017 |
diag::err_requires_expr_local_parameter_default_argument); |
| 8018 |
// Ignore default argument and move on |
| 8019 |
} else if (Param->isExplicitObjectParameter()) { |
| 8020 |
// C++23 [dcl.fct]p6: |
| 8021 |
// An explicit-object-parameter-declaration is a parameter-declaration |
| 8022 |
// with a this specifier. An explicit-object-parameter-declaration |
| 8023 |
// shall appear only as the first parameter-declaration of a |
| 8024 |
// parameter-declaration-list of either: |
| 8025 |
// - a member-declarator that declares a member function, or |
| 8026 |
// - a lambda-declarator. |
| 8027 |
// |
| 8028 |
// The parameter-declaration-list of a requires-expression is not such |
| 8029 |
// a context. |
| 8030 |
Diag(Param->getExplicitObjectParamThisLoc(), |
| 8031 |
diag::err_requires_expr_explicit_object_parameter); |
| 8032 |
Param->setExplicitObjectParameterLoc(SourceLocation()); |
| 8033 |
} |
| 8034 |
|
| 8035 |
Param->setDeclContext(Body); |
| 8036 |
// If this has an identifier, add it to the scope stack. |
| 8037 |
if (Param->getIdentifier()) { |
| 8038 |
CheckShadow(BodyScope, Param); |
| 8039 |
PushOnScopeChains(Param, BodyScope); |
| 8040 |
} |
| 8041 |
} |
| 8042 |
return Body; |
| 8043 |
} |
| 8044 |
|
| 8045 |
void Sema::ActOnFinishRequiresExpr() { |
| 8046 |
assert(CurContext && "DeclContext imbalance!"); |
| 8047 |
CurContext = CurContext->getLexicalParent(); |
| 8048 |
assert(CurContext && "Popped translation unit!"); |
| 8049 |
} |
| 8050 |
|
| 8051 |
ExprResult Sema::ActOnRequiresExpr( |
| 8052 |
SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, |
| 8053 |
SourceLocation LParenLoc, ArrayRef<ParmVarDecl *> LocalParameters, |
| 8054 |
SourceLocation RParenLoc, ArrayRef<concepts::Requirement *> Requirements, |
| 8055 |
SourceLocation ClosingBraceLoc) { |
| 8056 |
auto *RE = RequiresExpr::Create(Context, RequiresKWLoc, Body, LParenLoc, |
| 8057 |
LocalParameters, RParenLoc, Requirements, |
| 8058 |
ClosingBraceLoc); |
| 8059 |
if (DiagnoseUnexpandedParameterPackInRequiresExpr(RE)) |
| 8060 |
return ExprError(); |
| 8061 |
return RE; |
| 8062 |
} |