| 1 | //===--- SemaInit.cpp - Semantic Analysis for Initializers ----------------===// |
| 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 | // This file implements semantic analysis for initializers. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "CheckExprLifetime.h" |
| 14 | #include "clang/AST/ASTContext.h" |
| 15 | #include "clang/AST/DeclObjC.h" |
| 16 | #include "clang/AST/Expr.h" |
| 17 | #include "clang/AST/ExprCXX.h" |
| 18 | #include "clang/AST/ExprObjC.h" |
| 19 | #include "clang/AST/IgnoreExpr.h" |
| 20 | #include "clang/AST/TypeBase.h" |
| 21 | #include "clang/AST/TypeLoc.h" |
| 22 | #include "clang/Basic/SourceManager.h" |
| 23 | #include "clang/Basic/Specifiers.h" |
| 24 | #include "clang/Basic/TargetInfo.h" |
| 25 | #include "clang/Lex/Preprocessor.h" |
| 26 | #include "clang/Sema/Designator.h" |
| 27 | #include "clang/Sema/EnterExpressionEvaluationContext.h" |
| 28 | #include "clang/Sema/Initialization.h" |
| 29 | #include "clang/Sema/Lookup.h" |
| 30 | #include "clang/Sema/Ownership.h" |
| 31 | #include "clang/Sema/SemaHLSL.h" |
| 32 | #include "clang/Sema/SemaObjC.h" |
| 33 | #include "llvm/ADT/APInt.h" |
| 34 | #include "llvm/ADT/DenseMap.h" |
| 35 | #include "llvm/ADT/FoldingSet.h" |
| 36 | #include "llvm/ADT/PointerIntPair.h" |
| 37 | #include "llvm/ADT/SmallString.h" |
| 38 | #include "llvm/ADT/SmallVector.h" |
| 39 | #include "llvm/ADT/StringExtras.h" |
| 40 | #include "llvm/Support/ErrorHandling.h" |
| 41 | #include "llvm/Support/raw_ostream.h" |
| 42 | |
| 43 | using namespace clang; |
| 44 | |
| 45 | //===----------------------------------------------------------------------===// |
| 46 | // Sema Initialization Checking |
| 47 | //===----------------------------------------------------------------------===// |
| 48 | |
| 49 | /// Check whether T is compatible with a wide character type (wchar_t, |
| 50 | /// char16_t or char32_t). |
| 51 | static bool IsWideCharCompatible(QualType T, ASTContext &Context) { |
| 52 | if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: T)) |
| 53 | return true; |
| 54 | if (Context.getLangOpts().CPlusPlus || Context.getLangOpts().C11) { |
| 55 | return Context.typesAreCompatible(T1: Context.Char16Ty, T2: T) || |
| 56 | Context.typesAreCompatible(T1: Context.Char32Ty, T2: T); |
| 57 | } |
| 58 | return false; |
| 59 | } |
| 60 | |
| 61 | enum StringInitFailureKind { |
| 62 | SIF_None, |
| 63 | SIF_NarrowStringIntoWideChar, |
| 64 | SIF_WideStringIntoChar, |
| 65 | SIF_IncompatWideStringIntoWideChar, |
| 66 | SIF_UTF8StringIntoPlainChar, |
| 67 | SIF_PlainStringIntoUTF8Char, |
| 68 | SIF_Other |
| 69 | }; |
| 70 | |
| 71 | /// Check whether the array of type AT can be initialized by the Init |
| 72 | /// expression by means of string initialization. Returns SIF_None if so, |
| 73 | /// otherwise returns a StringInitFailureKind that describes why the |
| 74 | /// initialization would not work. |
| 75 | static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT, |
| 76 | ASTContext &Context) { |
| 77 | if (!isa<ConstantArrayType>(Val: AT) && !isa<IncompleteArrayType>(Val: AT)) |
| 78 | return SIF_Other; |
| 79 | |
| 80 | // See if this is a string literal or @encode. |
| 81 | Init = Init->IgnoreParens(); |
| 82 | |
| 83 | // Handle @encode, which is a narrow string. |
| 84 | if (isa<ObjCEncodeExpr>(Val: Init) && AT->getElementType()->isCharType()) |
| 85 | return SIF_None; |
| 86 | |
| 87 | // Otherwise we can only handle string literals. |
| 88 | StringLiteral *SL = dyn_cast<StringLiteral>(Val: Init); |
| 89 | if (!SL) |
| 90 | return SIF_Other; |
| 91 | |
| 92 | const QualType ElemTy = |
| 93 | Context.getCanonicalType(T: AT->getElementType()).getUnqualifiedType(); |
| 94 | |
| 95 | auto IsCharOrUnsignedChar = [](const QualType &T) { |
| 96 | const BuiltinType *BT = dyn_cast<BuiltinType>(Val: T.getTypePtr()); |
| 97 | return BT && BT->isCharType() && BT->getKind() != BuiltinType::SChar; |
| 98 | }; |
| 99 | |
| 100 | switch (SL->getKind()) { |
| 101 | case StringLiteralKind::UTF8: |
| 102 | // char8_t array can be initialized with a UTF-8 string. |
| 103 | // - C++20 [dcl.init.string] (DR) |
| 104 | // Additionally, an array of char or unsigned char may be initialized |
| 105 | // by a UTF-8 string literal. |
| 106 | if (ElemTy->isChar8Type() || |
| 107 | (Context.getLangOpts().Char8 && |
| 108 | IsCharOrUnsignedChar(ElemTy.getCanonicalType()))) |
| 109 | return SIF_None; |
| 110 | [[fallthrough]]; |
| 111 | case StringLiteralKind::Ordinary: |
| 112 | case StringLiteralKind::Binary: |
| 113 | // char array can be initialized with a narrow string. |
| 114 | // Only allow char x[] = "foo"; not char x[] = L"foo"; |
| 115 | if (ElemTy->isCharType()) |
| 116 | return (SL->getKind() == StringLiteralKind::UTF8 && |
| 117 | Context.getLangOpts().Char8) |
| 118 | ? SIF_UTF8StringIntoPlainChar |
| 119 | : SIF_None; |
| 120 | if (ElemTy->isChar8Type()) |
| 121 | return SIF_PlainStringIntoUTF8Char; |
| 122 | if (IsWideCharCompatible(T: ElemTy, Context)) |
| 123 | return SIF_NarrowStringIntoWideChar; |
| 124 | return SIF_Other; |
| 125 | // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15: |
| 126 | // "An array with element type compatible with a qualified or unqualified |
| 127 | // version of wchar_t, char16_t, or char32_t may be initialized by a wide |
| 128 | // string literal with the corresponding encoding prefix (L, u, or U, |
| 129 | // respectively), optionally enclosed in braces. |
| 130 | case StringLiteralKind::UTF16: |
| 131 | if (Context.typesAreCompatible(T1: Context.Char16Ty, T2: ElemTy)) |
| 132 | return SIF_None; |
| 133 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
| 134 | return SIF_WideStringIntoChar; |
| 135 | if (IsWideCharCompatible(T: ElemTy, Context)) |
| 136 | return SIF_IncompatWideStringIntoWideChar; |
| 137 | return SIF_Other; |
| 138 | case StringLiteralKind::UTF32: |
| 139 | if (Context.typesAreCompatible(T1: Context.Char32Ty, T2: ElemTy)) |
| 140 | return SIF_None; |
| 141 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
| 142 | return SIF_WideStringIntoChar; |
| 143 | if (IsWideCharCompatible(T: ElemTy, Context)) |
| 144 | return SIF_IncompatWideStringIntoWideChar; |
| 145 | return SIF_Other; |
| 146 | case StringLiteralKind::Wide: |
| 147 | if (Context.typesAreCompatible(T1: Context.getWideCharType(), T2: ElemTy)) |
| 148 | return SIF_None; |
| 149 | if (ElemTy->isCharType() || ElemTy->isChar8Type()) |
| 150 | return SIF_WideStringIntoChar; |
| 151 | if (IsWideCharCompatible(T: ElemTy, Context)) |
| 152 | return SIF_IncompatWideStringIntoWideChar; |
| 153 | return SIF_Other; |
| 154 | case StringLiteralKind::Unevaluated: |
| 155 | assert(false && "Unevaluated string literal in initialization" ); |
| 156 | break; |
| 157 | } |
| 158 | |
| 159 | llvm_unreachable("missed a StringLiteral kind?" ); |
| 160 | } |
| 161 | |
| 162 | static StringInitFailureKind IsStringInit(Expr *init, QualType declType, |
| 163 | ASTContext &Context) { |
| 164 | const ArrayType *arrayType = Context.getAsArrayType(T: declType); |
| 165 | if (!arrayType) |
| 166 | return SIF_Other; |
| 167 | return IsStringInit(Init: init, AT: arrayType, Context); |
| 168 | } |
| 169 | |
| 170 | bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) { |
| 171 | return ::IsStringInit(Init, AT, Context) == SIF_None; |
| 172 | } |
| 173 | |
| 174 | /// Update the type of a string literal, including any surrounding parentheses, |
| 175 | /// to match the type of the object which it is initializing. |
| 176 | static void updateStringLiteralType(Expr *E, QualType Ty) { |
| 177 | while (true) { |
| 178 | E->setType(Ty); |
| 179 | E->setValueKind(VK_PRValue); |
| 180 | if (isa<StringLiteral>(Val: E) || isa<ObjCEncodeExpr>(Val: E)) |
| 181 | break; |
| 182 | E = IgnoreParensSingleStep(E); |
| 183 | } |
| 184 | } |
| 185 | |
| 186 | /// Fix a compound literal initializing an array so it's correctly marked |
| 187 | /// as an rvalue. |
| 188 | static void updateGNUCompoundLiteralRValue(Expr *E) { |
| 189 | while (true) { |
| 190 | E->setValueKind(VK_PRValue); |
| 191 | if (isa<CompoundLiteralExpr>(Val: E)) |
| 192 | break; |
| 193 | E = IgnoreParensSingleStep(E); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | static bool initializingConstexprVariable(const InitializedEntity &Entity) { |
| 198 | Decl *D = Entity.getDecl(); |
| 199 | const InitializedEntity *Parent = &Entity; |
| 200 | |
| 201 | while (Parent) { |
| 202 | D = Parent->getDecl(); |
| 203 | Parent = Parent->getParent(); |
| 204 | } |
| 205 | |
| 206 | if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: D); VD && VD->isConstexpr()) |
| 207 | return true; |
| 208 | |
| 209 | return false; |
| 210 | } |
| 211 | |
| 212 | static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, |
| 213 | Sema &SemaRef, QualType &TT); |
| 214 | |
| 215 | static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT, |
| 216 | Sema &S, const InitializedEntity &Entity, |
| 217 | bool CheckC23ConstexprInit = false) { |
| 218 | // Get the length of the string as parsed. |
| 219 | auto *ConstantArrayTy = |
| 220 | cast<ConstantArrayType>(Val: Str->getType()->getAsArrayTypeUnsafe()); |
| 221 | uint64_t StrLength = ConstantArrayTy->getZExtSize(); |
| 222 | |
| 223 | if (CheckC23ConstexprInit) |
| 224 | if (const StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) |
| 225 | CheckC23ConstexprInitStringLiteral(SE: SL, SemaRef&: S, TT&: DeclT); |
| 226 | |
| 227 | if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(Val: AT)) { |
| 228 | // C99 6.7.8p14. We have an array of character type with unknown size |
| 229 | // being initialized to a string literal. |
| 230 | llvm::APInt ConstVal(32, StrLength); |
| 231 | // Return a new array type (C99 6.7.8p22). |
| 232 | DeclT = S.Context.getConstantArrayType( |
| 233 | EltTy: IAT->getElementType(), ArySize: ConstVal, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 234 | updateStringLiteralType(E: Str, Ty: DeclT); |
| 235 | return; |
| 236 | } |
| 237 | |
| 238 | const ConstantArrayType *CAT = cast<ConstantArrayType>(Val: AT); |
| 239 | uint64_t ArrayLen = CAT->getZExtSize(); |
| 240 | |
| 241 | // We have an array of character type with known size. However, |
| 242 | // the size may be smaller or larger than the string we are initializing. |
| 243 | // FIXME: Avoid truncation for 64-bit length strings. |
| 244 | if (S.getLangOpts().CPlusPlus) { |
| 245 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens())) { |
| 246 | // For Pascal strings it's OK to strip off the terminating null character, |
| 247 | // so the example below is valid: |
| 248 | // |
| 249 | // unsigned char a[2] = "\pa"; |
| 250 | if (SL->isPascal()) |
| 251 | StrLength--; |
| 252 | } |
| 253 | |
| 254 | // [dcl.init.string]p2 |
| 255 | if (StrLength > ArrayLen) |
| 256 | S.Diag(Loc: Str->getBeginLoc(), |
| 257 | DiagID: diag::err_initializer_string_for_char_array_too_long) |
| 258 | << ArrayLen << StrLength << Str->getSourceRange(); |
| 259 | } else { |
| 260 | // C99 6.7.8p14. |
| 261 | if (StrLength - 1 > ArrayLen) |
| 262 | S.Diag(Loc: Str->getBeginLoc(), |
| 263 | DiagID: diag::ext_initializer_string_for_char_array_too_long) |
| 264 | << Str->getSourceRange(); |
| 265 | else if (StrLength - 1 == ArrayLen) { |
| 266 | // In C, if the string literal is null-terminated explicitly, e.g., `char |
| 267 | // a[4] = "ABC\0"`, there should be no warning: |
| 268 | const auto *SL = dyn_cast<StringLiteral>(Val: Str->IgnoreParens()); |
| 269 | bool IsSLSafe = SL && SL->getLength() > 0 && |
| 270 | SL->getCodeUnit(i: SL->getLength() - 1) == 0; |
| 271 | |
| 272 | if (!IsSLSafe) { |
| 273 | // If the entity being initialized has the nonstring attribute, then |
| 274 | // silence the "missing nonstring" diagnostic. If there's no entity, |
| 275 | // check whether we're initializing an array of arrays; if so, walk the |
| 276 | // parents to find an entity. |
| 277 | auto FindCorrectEntity = |
| 278 | [](const InitializedEntity *Entity) -> const ValueDecl * { |
| 279 | while (Entity) { |
| 280 | if (const ValueDecl *VD = Entity->getDecl()) |
| 281 | return VD; |
| 282 | if (!Entity->getType()->isArrayType()) |
| 283 | return nullptr; |
| 284 | Entity = Entity->getParent(); |
| 285 | } |
| 286 | |
| 287 | return nullptr; |
| 288 | }; |
| 289 | if (const ValueDecl *D = FindCorrectEntity(&Entity); |
| 290 | !D || !D->hasAttr<NonStringAttr>()) |
| 291 | S.Diag( |
| 292 | Loc: Str->getBeginLoc(), |
| 293 | DiagID: diag:: |
| 294 | warn_initializer_string_for_char_array_too_long_no_nonstring) |
| 295 | << ArrayLen << StrLength << Str->getSourceRange(); |
| 296 | } |
| 297 | // Always emit the C++ compatibility diagnostic. |
| 298 | S.Diag(Loc: Str->getBeginLoc(), |
| 299 | DiagID: diag::warn_initializer_string_for_char_array_too_long_for_cpp) |
| 300 | << ArrayLen << StrLength << Str->getSourceRange(); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // Set the type to the actual size that we are initializing. If we have |
| 305 | // something like: |
| 306 | // char x[1] = "foo"; |
| 307 | // then this will set the string literal's type to char[1]. |
| 308 | updateStringLiteralType(E: Str, Ty: DeclT); |
| 309 | } |
| 310 | |
| 311 | void emitUninitializedExplicitInitFields(Sema &S, const RecordDecl *R) { |
| 312 | for (const FieldDecl *Field : R->fields()) { |
| 313 | if (Field->hasAttr<ExplicitInitAttr>()) |
| 314 | S.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at) << Field; |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | //===----------------------------------------------------------------------===// |
| 319 | // Semantic checking for initializer lists. |
| 320 | //===----------------------------------------------------------------------===// |
| 321 | |
| 322 | namespace { |
| 323 | |
| 324 | /// Semantic checking for initializer lists. |
| 325 | /// |
| 326 | /// The InitListChecker class contains a set of routines that each |
| 327 | /// handle the initialization of a certain kind of entity, e.g., |
| 328 | /// arrays, vectors, struct/union types, scalars, etc. The |
| 329 | /// InitListChecker itself performs a recursive walk of the subobject |
| 330 | /// structure of the type to be initialized, while stepping through |
| 331 | /// the initializer list one element at a time. The IList and Index |
| 332 | /// parameters to each of the Check* routines contain the active |
| 333 | /// (syntactic) initializer list and the index into that initializer |
| 334 | /// list that represents the current initializer. Each routine is |
| 335 | /// responsible for moving that Index forward as it consumes elements. |
| 336 | /// |
| 337 | /// Each Check* routine also has a StructuredList/StructuredIndex |
| 338 | /// arguments, which contains the current "structured" (semantic) |
| 339 | /// initializer list and the index into that initializer list where we |
| 340 | /// are copying initializers as we map them over to the semantic |
| 341 | /// list. Once we have completed our recursive walk of the subobject |
| 342 | /// structure, we will have constructed a full semantic initializer |
| 343 | /// list. |
| 344 | /// |
| 345 | /// C99 designators cause changes in the initializer list traversal, |
| 346 | /// because they make the initialization "jump" into a specific |
| 347 | /// subobject and then continue the initialization from that |
| 348 | /// point. CheckDesignatedInitializer() recursively steps into the |
| 349 | /// designated subobject and manages backing out the recursion to |
| 350 | /// initialize the subobjects after the one designated. |
| 351 | /// |
| 352 | /// If an initializer list contains any designators, we build a placeholder |
| 353 | /// structured list even in 'verify only' mode, so that we can track which |
| 354 | /// elements need 'empty' initializtion. |
| 355 | class InitListChecker { |
| 356 | Sema &SemaRef; |
| 357 | bool hadError = false; |
| 358 | bool VerifyOnly; // No diagnostics. |
| 359 | bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode. |
| 360 | bool InOverloadResolution; |
| 361 | InitListExpr *FullyStructuredList = nullptr; |
| 362 | NoInitExpr *DummyExpr = nullptr; |
| 363 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr; |
| 364 | EmbedExpr *CurEmbed = nullptr; // Save current embed we're processing. |
| 365 | unsigned CurEmbedIndex = 0; |
| 366 | |
| 367 | NoInitExpr *getDummyInit() { |
| 368 | if (!DummyExpr) |
| 369 | DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy); |
| 370 | return DummyExpr; |
| 371 | } |
| 372 | |
| 373 | void CheckImplicitInitList(const InitializedEntity &Entity, |
| 374 | InitListExpr *ParentIList, QualType T, |
| 375 | unsigned &Index, InitListExpr *StructuredList, |
| 376 | unsigned &StructuredIndex); |
| 377 | void CheckExplicitInitList(const InitializedEntity &Entity, |
| 378 | InitListExpr *IList, QualType &T, |
| 379 | InitListExpr *StructuredList, |
| 380 | bool TopLevelObject = false); |
| 381 | void CheckListElementTypes(const InitializedEntity &Entity, |
| 382 | InitListExpr *IList, QualType &DeclType, |
| 383 | bool SubobjectIsDesignatorContext, |
| 384 | unsigned &Index, |
| 385 | InitListExpr *StructuredList, |
| 386 | unsigned &StructuredIndex, |
| 387 | bool TopLevelObject = false); |
| 388 | void CheckSubElementType(const InitializedEntity &Entity, |
| 389 | InitListExpr *IList, QualType ElemType, |
| 390 | unsigned &Index, |
| 391 | InitListExpr *StructuredList, |
| 392 | unsigned &StructuredIndex, |
| 393 | bool DirectlyDesignated = false); |
| 394 | void CheckComplexType(const InitializedEntity &Entity, |
| 395 | InitListExpr *IList, QualType DeclType, |
| 396 | unsigned &Index, |
| 397 | InitListExpr *StructuredList, |
| 398 | unsigned &StructuredIndex); |
| 399 | void CheckScalarType(const InitializedEntity &Entity, |
| 400 | InitListExpr *IList, QualType DeclType, |
| 401 | unsigned &Index, |
| 402 | InitListExpr *StructuredList, |
| 403 | unsigned &StructuredIndex); |
| 404 | void CheckReferenceType(const InitializedEntity &Entity, |
| 405 | InitListExpr *IList, QualType DeclType, |
| 406 | unsigned &Index, |
| 407 | InitListExpr *StructuredList, |
| 408 | unsigned &StructuredIndex); |
| 409 | void CheckMatrixType(const InitializedEntity &Entity, InitListExpr *IList, |
| 410 | QualType DeclType, unsigned &Index, |
| 411 | InitListExpr *StructuredList, unsigned &StructuredIndex); |
| 412 | void CheckVectorType(const InitializedEntity &Entity, |
| 413 | InitListExpr *IList, QualType DeclType, unsigned &Index, |
| 414 | InitListExpr *StructuredList, |
| 415 | unsigned &StructuredIndex); |
| 416 | void CheckStructUnionTypes(const InitializedEntity &Entity, |
| 417 | InitListExpr *IList, QualType DeclType, |
| 418 | CXXRecordDecl::base_class_const_range Bases, |
| 419 | RecordDecl::field_iterator Field, |
| 420 | bool SubobjectIsDesignatorContext, unsigned &Index, |
| 421 | InitListExpr *StructuredList, |
| 422 | unsigned &StructuredIndex, |
| 423 | bool TopLevelObject = false); |
| 424 | void CheckArrayType(const InitializedEntity &Entity, |
| 425 | InitListExpr *IList, QualType &DeclType, |
| 426 | llvm::APSInt elementIndex, |
| 427 | bool SubobjectIsDesignatorContext, unsigned &Index, |
| 428 | InitListExpr *StructuredList, |
| 429 | unsigned &StructuredIndex); |
| 430 | bool CheckDesignatedInitializer(const InitializedEntity &Entity, |
| 431 | InitListExpr *IList, DesignatedInitExpr *DIE, |
| 432 | unsigned DesigIdx, |
| 433 | QualType &CurrentObjectType, |
| 434 | RecordDecl::field_iterator *NextField, |
| 435 | llvm::APSInt *NextElementIndex, |
| 436 | unsigned &Index, |
| 437 | InitListExpr *StructuredList, |
| 438 | unsigned &StructuredIndex, |
| 439 | bool FinishSubobjectInit, |
| 440 | bool TopLevelObject); |
| 441 | InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, |
| 442 | QualType CurrentObjectType, |
| 443 | InitListExpr *StructuredList, |
| 444 | unsigned StructuredIndex, |
| 445 | SourceRange InitRange, |
| 446 | bool IsFullyOverwritten = false); |
| 447 | void UpdateStructuredListElement(InitListExpr *StructuredList, |
| 448 | unsigned &StructuredIndex, |
| 449 | Expr *expr); |
| 450 | InitListExpr *createInitListExpr(QualType CurrentObjectType, |
| 451 | SourceRange InitRange, |
| 452 | unsigned ExpectedNumInits, bool IsExplicit); |
| 453 | int numArrayElements(QualType DeclType); |
| 454 | int numStructUnionElements(QualType DeclType); |
| 455 | |
| 456 | ExprResult PerformEmptyInit(SourceLocation Loc, |
| 457 | const InitializedEntity &Entity); |
| 458 | |
| 459 | /// Diagnose that OldInit (or part thereof) has been overridden by NewInit. |
| 460 | void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange, |
| 461 | bool UnionOverride = false, |
| 462 | bool FullyOverwritten = true) { |
| 463 | // Overriding an initializer via a designator is valid with C99 designated |
| 464 | // initializers, but ill-formed with C++20 designated initializers. |
| 465 | unsigned DiagID = |
| 466 | SemaRef.getLangOpts().CPlusPlus |
| 467 | ? (UnionOverride ? diag::ext_initializer_union_overrides |
| 468 | : diag::ext_initializer_overrides) |
| 469 | : diag::warn_initializer_overrides; |
| 470 | |
| 471 | if (InOverloadResolution && SemaRef.getLangOpts().CPlusPlus) { |
| 472 | // In overload resolution, we have to strictly enforce the rules, and so |
| 473 | // don't allow any overriding of prior initializers. This matters for a |
| 474 | // case such as: |
| 475 | // |
| 476 | // union U { int a, b; }; |
| 477 | // struct S { int a, b; }; |
| 478 | // void f(U), f(S); |
| 479 | // |
| 480 | // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For |
| 481 | // consistency, we disallow all overriding of prior initializers in |
| 482 | // overload resolution, not only overriding of union members. |
| 483 | hadError = true; |
| 484 | } else if (OldInit->getType().isDestructedType() && !FullyOverwritten) { |
| 485 | // If we'll be keeping around the old initializer but overwriting part of |
| 486 | // the object it initialized, and that object is not trivially |
| 487 | // destructible, this can leak. Don't allow that, not even as an |
| 488 | // extension. |
| 489 | // |
| 490 | // FIXME: It might be reasonable to allow this in cases where the part of |
| 491 | // the initializer that we're overriding has trivial destruction. |
| 492 | DiagID = diag::err_initializer_overrides_destructed; |
| 493 | } else if (!OldInit->getSourceRange().isValid()) { |
| 494 | // We need to check on source range validity because the previous |
| 495 | // initializer does not have to be an explicit initializer. e.g., |
| 496 | // |
| 497 | // struct P { int a, b; }; |
| 498 | // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 }; |
| 499 | // |
| 500 | // There is an overwrite taking place because the first braced initializer |
| 501 | // list "{ .a = 2 }" already provides value for .p.b (which is zero). |
| 502 | // |
| 503 | // Such overwrites are harmless, so we don't diagnose them. (Note that in |
| 504 | // C++, this cannot be reached unless we've already seen and diagnosed a |
| 505 | // different conformance issue, such as a mixture of designated and |
| 506 | // non-designated initializers or a multi-level designator.) |
| 507 | return; |
| 508 | } |
| 509 | |
| 510 | if (!VerifyOnly) { |
| 511 | SemaRef.Diag(Loc: NewInitRange.getBegin(), DiagID) |
| 512 | << NewInitRange << FullyOverwritten << OldInit->getType(); |
| 513 | SemaRef.Diag(Loc: OldInit->getBeginLoc(), DiagID: diag::note_previous_initializer) |
| 514 | << (OldInit->HasSideEffects(Ctx: SemaRef.Context) && FullyOverwritten) |
| 515 | << OldInit->getSourceRange(); |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | // Explanation on the "FillWithNoInit" mode: |
| 520 | // |
| 521 | // Assume we have the following definitions (Case#1): |
| 522 | // struct P { char x[6][6]; } xp = { .x[1] = "bar" }; |
| 523 | // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' }; |
| 524 | // |
| 525 | // l.lp.x[1][0..1] should not be filled with implicit initializers because the |
| 526 | // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf". |
| 527 | // |
| 528 | // But if we have (Case#2): |
| 529 | // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } }; |
| 530 | // |
| 531 | // l.lp.x[1][0..1] are implicitly initialized and do not use values from the |
| 532 | // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0". |
| 533 | // |
| 534 | // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes" |
| 535 | // in the InitListExpr, the "holes" in Case#1 are filled not with empty |
| 536 | // initializers but with special "NoInitExpr" place holders, which tells the |
| 537 | // CodeGen not to generate any initializers for these parts. |
| 538 | void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base, |
| 539 | const InitializedEntity &ParentEntity, |
| 540 | InitListExpr *ILE, bool &RequiresSecondPass, |
| 541 | bool FillWithNoInit); |
| 542 | void FillInEmptyInitForField(unsigned Init, FieldDecl *Field, |
| 543 | const InitializedEntity &ParentEntity, |
| 544 | InitListExpr *ILE, bool &RequiresSecondPass, |
| 545 | bool FillWithNoInit = false); |
| 546 | void FillInEmptyInitializations(const InitializedEntity &Entity, |
| 547 | InitListExpr *ILE, bool &RequiresSecondPass, |
| 548 | InitListExpr *OuterILE, unsigned OuterIndex, |
| 549 | bool FillWithNoInit = false); |
| 550 | bool CheckFlexibleArrayInit(const InitializedEntity &Entity, |
| 551 | Expr *InitExpr, FieldDecl *Field, |
| 552 | bool TopLevelObject); |
| 553 | void CheckEmptyInitializable(const InitializedEntity &Entity, |
| 554 | SourceLocation Loc); |
| 555 | |
| 556 | Expr *HandleEmbed(EmbedExpr *Embed, const InitializedEntity &Entity) { |
| 557 | Expr *Result = nullptr; |
| 558 | // Undrestand which part of embed we'd like to reference. |
| 559 | if (!CurEmbed) { |
| 560 | CurEmbed = Embed; |
| 561 | CurEmbedIndex = 0; |
| 562 | } |
| 563 | // Reference just one if we're initializing a single scalar. |
| 564 | uint64_t ElsCount = 1; |
| 565 | // Otherwise try to fill whole array with embed data. |
| 566 | if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { |
| 567 | unsigned ArrIndex = Entity.getElementIndex(); |
| 568 | auto *AType = |
| 569 | SemaRef.Context.getAsArrayType(T: Entity.getParent()->getType()); |
| 570 | assert(AType && "expected array type when initializing array" ); |
| 571 | ElsCount = Embed->getDataElementCount(); |
| 572 | if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType)) |
| 573 | ElsCount = std::min(a: CAType->getSize().getZExtValue() - ArrIndex, |
| 574 | b: ElsCount - CurEmbedIndex); |
| 575 | if (ElsCount == Embed->getDataElementCount()) { |
| 576 | CurEmbed = nullptr; |
| 577 | CurEmbedIndex = 0; |
| 578 | return Embed; |
| 579 | } |
| 580 | } |
| 581 | |
| 582 | Result = new (SemaRef.Context) |
| 583 | EmbedExpr(SemaRef.Context, Embed->getLocation(), Embed->getData(), |
| 584 | CurEmbedIndex, ElsCount); |
| 585 | CurEmbedIndex += ElsCount; |
| 586 | if (CurEmbedIndex >= Embed->getDataElementCount()) { |
| 587 | CurEmbed = nullptr; |
| 588 | CurEmbedIndex = 0; |
| 589 | } |
| 590 | return Result; |
| 591 | } |
| 592 | |
| 593 | public: |
| 594 | InitListChecker( |
| 595 | Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, |
| 596 | bool VerifyOnly, bool TreatUnavailableAsInvalid, |
| 597 | bool InOverloadResolution = false, |
| 598 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes = nullptr); |
| 599 | InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL, |
| 600 | QualType &T, |
| 601 | SmallVectorImpl<QualType> &AggrDeductionCandidateParamTypes) |
| 602 | : InitListChecker(S, Entity, IL, T, /*VerifyOnly=*/true, |
| 603 | /*TreatUnavailableAsInvalid=*/false, |
| 604 | /*InOverloadResolution=*/false, |
| 605 | &AggrDeductionCandidateParamTypes) {} |
| 606 | |
| 607 | bool HadError() { return hadError; } |
| 608 | |
| 609 | // Retrieves the fully-structured initializer list used for |
| 610 | // semantic analysis and code generation. |
| 611 | InitListExpr *getFullyStructuredList() const { return FullyStructuredList; } |
| 612 | }; |
| 613 | |
| 614 | } // end anonymous namespace |
| 615 | |
| 616 | ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc, |
| 617 | const InitializedEntity &Entity) { |
| 618 | InitializationKind Kind = InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, |
| 619 | isImplicit: true); |
| 620 | MultiExprArg SubInit; |
| 621 | Expr *InitExpr; |
| 622 | InitListExpr DummyInitList(SemaRef.Context, Loc, {}, Loc, |
| 623 | /*isExplicit=*/false); |
| 624 | |
| 625 | // C++ [dcl.init.aggr]p7: |
| 626 | // If there are fewer initializer-clauses in the list than there are |
| 627 | // members in the aggregate, then each member not explicitly initialized |
| 628 | // ... |
| 629 | bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 && |
| 630 | Entity.getType()->getBaseElementTypeUnsafe()->isRecordType(); |
| 631 | if (EmptyInitList) { |
| 632 | // C++1y / DR1070: |
| 633 | // shall be initialized [...] from an empty initializer list. |
| 634 | // |
| 635 | // We apply the resolution of this DR to C++11 but not C++98, since C++98 |
| 636 | // does not have useful semantics for initialization from an init list. |
| 637 | // We treat this as copy-initialization, because aggregate initialization |
| 638 | // always performs copy-initialization on its elements. |
| 639 | // |
| 640 | // Only do this if we're initializing a class type, to avoid filling in |
| 641 | // the initializer list where possible. |
| 642 | InitExpr = VerifyOnly ? &DummyInitList |
| 643 | : new (SemaRef.Context) |
| 644 | InitListExpr(SemaRef.Context, Loc, {}, Loc, |
| 645 | /*isExplicit=*/false); |
| 646 | InitExpr->setType(SemaRef.Context.VoidTy); |
| 647 | SubInit = InitExpr; |
| 648 | Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc); |
| 649 | } else { |
| 650 | // C++03: |
| 651 | // shall be value-initialized. |
| 652 | } |
| 653 | |
| 654 | InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit); |
| 655 | // HACK: libstdc++ prior to 4.9 marks the vector default constructor |
| 656 | // as explicit in _GLIBCXX_DEBUG mode, so recover using the C++03 logic |
| 657 | // in that case. stlport does so too. |
| 658 | // Look for std::__debug for libstdc++, and for std:: for stlport. |
| 659 | // This is effectively a compiler-side implementation of LWG2193. |
| 660 | if (!InitSeq && EmptyInitList && |
| 661 | InitSeq.getFailureKind() == |
| 662 | InitializationSequence::FK_ExplicitConstructor && |
| 663 | SemaRef.getPreprocessor().NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2014'04'22)) { |
| 664 | OverloadCandidateSet::iterator Best; |
| 665 | OverloadingResult O = |
| 666 | InitSeq.getFailedCandidateSet() |
| 667 | .BestViableFunction(S&: SemaRef, Loc: Kind.getLocation(), Best); |
| 668 | (void)O; |
| 669 | assert(O == OR_Success && "Inconsistent overload resolution" ); |
| 670 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
| 671 | CXXRecordDecl *R = CtorDecl->getParent(); |
| 672 | |
| 673 | if (CtorDecl->getMinRequiredArguments() == 0 && |
| 674 | CtorDecl->isExplicit() && R->getDeclName() && |
| 675 | SemaRef.SourceMgr.isInSystemHeader(Loc: CtorDecl->getLocation())) { |
| 676 | bool IsInStd = false; |
| 677 | for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Val: R->getDeclContext()); |
| 678 | ND && !IsInStd; ND = dyn_cast<NamespaceDecl>(Val: ND->getParent())) { |
| 679 | if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(NS: ND)) |
| 680 | IsInStd = true; |
| 681 | } |
| 682 | |
| 683 | if (IsInStd && |
| 684 | llvm::StringSwitch<bool>(R->getName()) |
| 685 | .Cases(CaseStrings: {"basic_string" , "deque" , "forward_list" }, Value: true) |
| 686 | .Cases(CaseStrings: {"list" , "map" , "multimap" , "multiset" }, Value: true) |
| 687 | .Cases(CaseStrings: {"priority_queue" , "queue" , "set" , "stack" }, Value: true) |
| 688 | .Cases(CaseStrings: {"unordered_map" , "unordered_set" , "vector" }, Value: true) |
| 689 | .Default(Value: false)) { |
| 690 | InitSeq.InitializeFrom( |
| 691 | S&: SemaRef, Entity, |
| 692 | Kind: InitializationKind::CreateValue(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc, isImplicit: true), |
| 693 | Args: MultiExprArg(), /*TopLevelOfInitList=*/false, |
| 694 | TreatUnavailableAsInvalid); |
| 695 | // Emit a warning for this. System header warnings aren't shown |
| 696 | // by default, but people working on system headers should see it. |
| 697 | if (!VerifyOnly) { |
| 698 | SemaRef.Diag(Loc: CtorDecl->getLocation(), |
| 699 | DiagID: diag::warn_invalid_initializer_from_system_header); |
| 700 | if (Entity.getKind() == InitializedEntity::EK_Member) |
| 701 | SemaRef.Diag(Loc: Entity.getDecl()->getLocation(), |
| 702 | DiagID: diag::note_used_in_initialization_here); |
| 703 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) |
| 704 | SemaRef.Diag(Loc, DiagID: diag::note_used_in_initialization_here); |
| 705 | } |
| 706 | } |
| 707 | } |
| 708 | } |
| 709 | if (!InitSeq) { |
| 710 | if (!VerifyOnly) { |
| 711 | InitSeq.Diagnose(S&: SemaRef, Entity, Kind, Args: SubInit); |
| 712 | if (Entity.getKind() == InitializedEntity::EK_Member) |
| 713 | SemaRef.Diag(Loc: Entity.getDecl()->getLocation(), |
| 714 | DiagID: diag::note_in_omitted_aggregate_initializer) |
| 715 | << /*field*/1 << Entity.getDecl(); |
| 716 | else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) { |
| 717 | bool IsTrailingArrayNewMember = |
| 718 | Entity.getParent() && |
| 719 | Entity.getParent()->isVariableLengthArrayNew(); |
| 720 | SemaRef.Diag(Loc, DiagID: diag::note_in_omitted_aggregate_initializer) |
| 721 | << (IsTrailingArrayNewMember ? 2 : /*array element*/0) |
| 722 | << Entity.getElementIndex(); |
| 723 | } |
| 724 | } |
| 725 | hadError = true; |
| 726 | return ExprError(); |
| 727 | } |
| 728 | |
| 729 | return VerifyOnly ? ExprResult() |
| 730 | : InitSeq.Perform(S&: SemaRef, Entity, Kind, Args: SubInit); |
| 731 | } |
| 732 | |
| 733 | void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity, |
| 734 | SourceLocation Loc) { |
| 735 | // If we're building a fully-structured list, we'll check this at the end |
| 736 | // once we know which elements are actually initialized. Otherwise, we know |
| 737 | // that there are no designators so we can just check now. |
| 738 | if (FullyStructuredList) |
| 739 | return; |
| 740 | PerformEmptyInit(Loc, Entity); |
| 741 | } |
| 742 | |
| 743 | void InitListChecker::FillInEmptyInitForBase( |
| 744 | unsigned Init, const CXXBaseSpecifier &Base, |
| 745 | const InitializedEntity &ParentEntity, InitListExpr *ILE, |
| 746 | bool &RequiresSecondPass, bool FillWithNoInit) { |
| 747 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( |
| 748 | Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &ParentEntity); |
| 749 | |
| 750 | if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) { |
| 751 | ExprResult BaseInit = FillWithNoInit |
| 752 | ? new (SemaRef.Context) NoInitExpr(Base.getType()) |
| 753 | : PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: BaseEntity); |
| 754 | if (BaseInit.isInvalid()) { |
| 755 | hadError = true; |
| 756 | return; |
| 757 | } |
| 758 | |
| 759 | if (!VerifyOnly) { |
| 760 | assert(Init < ILE->getNumInits() && "should have been expanded" ); |
| 761 | ILE->setInit(Init, expr: BaseInit.getAs<Expr>()); |
| 762 | } |
| 763 | } else if (InitListExpr *InnerILE = |
| 764 | dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) { |
| 765 | FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerILE, RequiresSecondPass, |
| 766 | OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
| 767 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
| 768 | dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) { |
| 769 | FillInEmptyInitializations(Entity: BaseEntity, ILE: InnerDIUE->getUpdater(), |
| 770 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
| 771 | /*FillWithNoInit =*/true); |
| 772 | } |
| 773 | } |
| 774 | |
| 775 | void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field, |
| 776 | const InitializedEntity &ParentEntity, |
| 777 | InitListExpr *ILE, |
| 778 | bool &RequiresSecondPass, |
| 779 | bool FillWithNoInit) { |
| 780 | SourceLocation Loc = ILE->getEndLoc(); |
| 781 | unsigned NumInits = ILE->getNumInits(); |
| 782 | InitializedEntity MemberEntity |
| 783 | = InitializedEntity::InitializeMember(Member: Field, Parent: &ParentEntity); |
| 784 | |
| 785 | if (Init >= NumInits || !ILE->getInit(Init)) { |
| 786 | if (const RecordType *RType = ILE->getType()->getAsCanonical<RecordType>()) |
| 787 | if (!RType->getDecl()->isUnion()) |
| 788 | assert((Init < NumInits || VerifyOnly) && |
| 789 | "This ILE should have been expanded" ); |
| 790 | |
| 791 | if (FillWithNoInit) { |
| 792 | assert(!VerifyOnly && "should not fill with no-init in verify-only mode" ); |
| 793 | Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType()); |
| 794 | if (Init < NumInits) |
| 795 | ILE->setInit(Init, expr: Filler); |
| 796 | else |
| 797 | ILE->updateInit(C: SemaRef.Context, Init, expr: Filler); |
| 798 | return; |
| 799 | } |
| 800 | |
| 801 | if (!VerifyOnly && Field->hasAttr<ExplicitInitAttr>() && |
| 802 | !SemaRef.isUnevaluatedContext()) { |
| 803 | SemaRef.Diag(Loc: ILE->getExprLoc(), DiagID: diag::warn_field_requires_explicit_init) |
| 804 | << /* Var-in-Record */ 0 << Field; |
| 805 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_entity_declared_at) |
| 806 | << Field; |
| 807 | } |
| 808 | |
| 809 | // C++1y [dcl.init.aggr]p7: |
| 810 | // If there are fewer initializer-clauses in the list than there are |
| 811 | // members in the aggregate, then each member not explicitly initialized |
| 812 | // shall be initialized from its brace-or-equal-initializer [...] |
| 813 | if (Field->hasInClassInitializer()) { |
| 814 | if (VerifyOnly) |
| 815 | return; |
| 816 | |
| 817 | ExprResult DIE; |
| 818 | { |
| 819 | // Enter a default initializer rebuild context, then we can support |
| 820 | // lifetime extension of temporary created by aggregate initialization |
| 821 | // using a default member initializer. |
| 822 | // CWG1815 (https://wg21.link/CWG1815). |
| 823 | EnterExpressionEvaluationContext RebuildDefaultInit( |
| 824 | SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated); |
| 825 | SemaRef.currentEvaluationContext().RebuildDefaultArgOrDefaultInit = |
| 826 | true; |
| 827 | SemaRef.currentEvaluationContext().DelayedDefaultInitializationContext = |
| 828 | SemaRef.parentEvaluationContext() |
| 829 | .DelayedDefaultInitializationContext; |
| 830 | SemaRef.currentEvaluationContext().InLifetimeExtendingContext = |
| 831 | SemaRef.parentEvaluationContext().InLifetimeExtendingContext; |
| 832 | DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field); |
| 833 | } |
| 834 | if (DIE.isInvalid()) { |
| 835 | hadError = true; |
| 836 | return; |
| 837 | } |
| 838 | SemaRef.checkInitializerLifetime(Entity: MemberEntity, Init: DIE.get()); |
| 839 | if (Init < NumInits) |
| 840 | ILE->setInit(Init, expr: DIE.get()); |
| 841 | else { |
| 842 | ILE->updateInit(C: SemaRef.Context, Init, expr: DIE.get()); |
| 843 | RequiresSecondPass = true; |
| 844 | } |
| 845 | return; |
| 846 | } |
| 847 | |
| 848 | if (Field->getType()->isReferenceType()) { |
| 849 | if (!VerifyOnly) { |
| 850 | // C++ [dcl.init.aggr]p9: |
| 851 | // If an incomplete or empty initializer-list leaves a |
| 852 | // member of reference type uninitialized, the program is |
| 853 | // ill-formed. |
| 854 | SemaRef.Diag(Loc, DiagID: diag::err_init_reference_member_uninitialized) |
| 855 | << Field->getType() |
| 856 | << (ILE->isSyntacticForm() ? ILE : ILE->getSyntacticForm()) |
| 857 | ->getSourceRange(); |
| 858 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_uninit_reference_member); |
| 859 | } |
| 860 | hadError = true; |
| 861 | return; |
| 862 | } |
| 863 | |
| 864 | ExprResult MemberInit = PerformEmptyInit(Loc, Entity: MemberEntity); |
| 865 | if (MemberInit.isInvalid()) { |
| 866 | hadError = true; |
| 867 | return; |
| 868 | } |
| 869 | |
| 870 | if (hadError || VerifyOnly) { |
| 871 | // Do nothing |
| 872 | } else if (Init < NumInits) { |
| 873 | ILE->setInit(Init, expr: MemberInit.getAs<Expr>()); |
| 874 | } else if (!isa<ImplicitValueInitExpr>(Val: MemberInit.get())) { |
| 875 | // Empty initialization requires a constructor call, so |
| 876 | // extend the initializer list to include the constructor |
| 877 | // call and make a note that we'll need to take another pass |
| 878 | // through the initializer list. |
| 879 | ILE->updateInit(C: SemaRef.Context, Init, expr: MemberInit.getAs<Expr>()); |
| 880 | RequiresSecondPass = true; |
| 881 | } |
| 882 | } else if (InitListExpr *InnerILE |
| 883 | = dyn_cast<InitListExpr>(Val: ILE->getInit(Init))) { |
| 884 | FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerILE, |
| 885 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
| 886 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
| 887 | dyn_cast<DesignatedInitUpdateExpr>(Val: ILE->getInit(Init))) { |
| 888 | FillInEmptyInitializations(Entity: MemberEntity, ILE: InnerDIUE->getUpdater(), |
| 889 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
| 890 | /*FillWithNoInit =*/true); |
| 891 | } |
| 892 | } |
| 893 | |
| 894 | /// Recursively replaces NULL values within the given initializer list |
| 895 | /// with expressions that perform value-initialization of the |
| 896 | /// appropriate type, and finish off the InitListExpr formation. |
| 897 | void |
| 898 | InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity, |
| 899 | InitListExpr *ILE, |
| 900 | bool &RequiresSecondPass, |
| 901 | InitListExpr *OuterILE, |
| 902 | unsigned OuterIndex, |
| 903 | bool FillWithNoInit) { |
| 904 | assert((ILE->getType() != SemaRef.Context.VoidTy) && |
| 905 | "Should not have void type" ); |
| 906 | |
| 907 | // We don't need to do any checks when just filling NoInitExprs; that can't |
| 908 | // fail. |
| 909 | if (FillWithNoInit && VerifyOnly) |
| 910 | return; |
| 911 | |
| 912 | // If this is a nested initializer list, we might have changed its contents |
| 913 | // (and therefore some of its properties, such as instantiation-dependence) |
| 914 | // while filling it in. Inform the outer initializer list so that its state |
| 915 | // can be updated to match. |
| 916 | // FIXME: We should fully build the inner initializers before constructing |
| 917 | // the outer InitListExpr instead of mutating AST nodes after they have |
| 918 | // been used as subexpressions of other nodes. |
| 919 | struct UpdateOuterILEWithUpdatedInit { |
| 920 | InitListExpr *Outer; |
| 921 | unsigned OuterIndex; |
| 922 | ~UpdateOuterILEWithUpdatedInit() { |
| 923 | if (Outer) |
| 924 | Outer->setInit(Init: OuterIndex, expr: Outer->getInit(Init: OuterIndex)); |
| 925 | } |
| 926 | } UpdateOuterRAII = {.Outer: OuterILE, .OuterIndex: OuterIndex}; |
| 927 | |
| 928 | // A transparent ILE is not performing aggregate initialization and should |
| 929 | // not be filled in. |
| 930 | if (ILE->isTransparent()) |
| 931 | return; |
| 932 | |
| 933 | if (const auto *RDecl = ILE->getType()->getAsRecordDecl()) { |
| 934 | if (RDecl->isUnion() && ILE->getInitializedFieldInUnion()) { |
| 935 | FillInEmptyInitForField(Init: 0, Field: ILE->getInitializedFieldInUnion(), ParentEntity: Entity, ILE, |
| 936 | RequiresSecondPass, FillWithNoInit); |
| 937 | } else { |
| 938 | assert((!RDecl->isUnion() || !isa<CXXRecordDecl>(RDecl) || |
| 939 | !cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()) && |
| 940 | "We should have computed initialized fields already" ); |
| 941 | // The fields beyond ILE->getNumInits() are default initialized, so in |
| 942 | // order to leave them uninitialized, the ILE is expanded and the extra |
| 943 | // fields are then filled with NoInitExpr. |
| 944 | unsigned NumElems = numStructUnionElements(DeclType: ILE->getType()); |
| 945 | if (!RDecl->isUnion() && RDecl->hasFlexibleArrayMember()) |
| 946 | ++NumElems; |
| 947 | if (!VerifyOnly && ILE->getNumInits() < NumElems) |
| 948 | ILE->resizeInits(Context: SemaRef.Context, NumInits: NumElems); |
| 949 | |
| 950 | unsigned Init = 0; |
| 951 | |
| 952 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RDecl)) { |
| 953 | for (auto &Base : CXXRD->bases()) { |
| 954 | if (hadError) |
| 955 | return; |
| 956 | |
| 957 | FillInEmptyInitForBase(Init, Base, ParentEntity: Entity, ILE, RequiresSecondPass, |
| 958 | FillWithNoInit); |
| 959 | ++Init; |
| 960 | } |
| 961 | } |
| 962 | |
| 963 | for (auto *Field : RDecl->fields()) { |
| 964 | if (Field->isUnnamedBitField()) |
| 965 | continue; |
| 966 | |
| 967 | if (hadError) |
| 968 | return; |
| 969 | |
| 970 | FillInEmptyInitForField(Init, Field, ParentEntity: Entity, ILE, RequiresSecondPass, |
| 971 | FillWithNoInit); |
| 972 | if (hadError) |
| 973 | return; |
| 974 | |
| 975 | ++Init; |
| 976 | |
| 977 | // Only look at the first initialization of a union. |
| 978 | if (RDecl->isUnion()) |
| 979 | break; |
| 980 | } |
| 981 | } |
| 982 | |
| 983 | return; |
| 984 | } |
| 985 | |
| 986 | QualType ElementType; |
| 987 | |
| 988 | InitializedEntity ElementEntity = Entity; |
| 989 | unsigned NumInits = ILE->getNumInits(); |
| 990 | uint64_t NumElements = NumInits; |
| 991 | if (const ArrayType *AType = SemaRef.Context.getAsArrayType(T: ILE->getType())) { |
| 992 | ElementType = AType->getElementType(); |
| 993 | if (const auto *CAType = dyn_cast<ConstantArrayType>(Val: AType)) |
| 994 | NumElements = CAType->getZExtSize(); |
| 995 | // For an array new with an unknown bound, ask for one additional element |
| 996 | // in order to populate the array filler. |
| 997 | if (Entity.isVariableLengthArrayNew()) |
| 998 | ++NumElements; |
| 999 | ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context, |
| 1000 | Index: 0, Parent: Entity); |
| 1001 | } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) { |
| 1002 | ElementType = VType->getElementType(); |
| 1003 | NumElements = VType->getNumElements(); |
| 1004 | ElementEntity = InitializedEntity::InitializeElement(Context&: SemaRef.Context, |
| 1005 | Index: 0, Parent: Entity); |
| 1006 | } else |
| 1007 | ElementType = ILE->getType(); |
| 1008 | |
| 1009 | bool SkipEmptyInitChecks = false; |
| 1010 | for (uint64_t Init = 0; Init != NumElements; ++Init) { |
| 1011 | if (hadError) |
| 1012 | return; |
| 1013 | |
| 1014 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement || |
| 1015 | ElementEntity.getKind() == InitializedEntity::EK_VectorElement || |
| 1016 | ElementEntity.getKind() == InitializedEntity::EK_MatrixElement) |
| 1017 | ElementEntity.setElementIndex(Init); |
| 1018 | |
| 1019 | if (Init >= NumInits && (ILE->hasArrayFiller() || SkipEmptyInitChecks)) |
| 1020 | return; |
| 1021 | |
| 1022 | Expr *InitExpr = (Init < NumInits ? ILE->getInit(Init) : nullptr); |
| 1023 | if (!InitExpr && Init < NumInits && ILE->hasArrayFiller()) |
| 1024 | ILE->setInit(Init, expr: ILE->getArrayFiller()); |
| 1025 | else if (!InitExpr && !ILE->hasArrayFiller()) { |
| 1026 | // In VerifyOnly mode, there's no point performing empty initialization |
| 1027 | // more than once. |
| 1028 | if (SkipEmptyInitChecks) |
| 1029 | continue; |
| 1030 | |
| 1031 | Expr *Filler = nullptr; |
| 1032 | |
| 1033 | if (FillWithNoInit) |
| 1034 | Filler = new (SemaRef.Context) NoInitExpr(ElementType); |
| 1035 | else { |
| 1036 | ExprResult ElementInit = |
| 1037 | PerformEmptyInit(Loc: ILE->getEndLoc(), Entity: ElementEntity); |
| 1038 | if (ElementInit.isInvalid()) { |
| 1039 | hadError = true; |
| 1040 | return; |
| 1041 | } |
| 1042 | |
| 1043 | Filler = ElementInit.getAs<Expr>(); |
| 1044 | } |
| 1045 | |
| 1046 | if (hadError) { |
| 1047 | // Do nothing |
| 1048 | } else if (VerifyOnly) { |
| 1049 | SkipEmptyInitChecks = true; |
| 1050 | } else if (Init < NumInits) { |
| 1051 | // For arrays, just set the expression used for value-initialization |
| 1052 | // of the "holes" in the array. |
| 1053 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) |
| 1054 | ILE->setArrayFiller(Filler); |
| 1055 | else |
| 1056 | ILE->setInit(Init, expr: Filler); |
| 1057 | } else { |
| 1058 | // For arrays, just set the expression used for value-initialization |
| 1059 | // of the rest of elements and exit. |
| 1060 | if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) { |
| 1061 | ILE->setArrayFiller(Filler); |
| 1062 | return; |
| 1063 | } |
| 1064 | |
| 1065 | if (!isa<ImplicitValueInitExpr>(Val: Filler) && !isa<NoInitExpr>(Val: Filler)) { |
| 1066 | // Empty initialization requires a constructor call, so |
| 1067 | // extend the initializer list to include the constructor |
| 1068 | // call and make a note that we'll need to take another pass |
| 1069 | // through the initializer list. |
| 1070 | ILE->updateInit(C: SemaRef.Context, Init, expr: Filler); |
| 1071 | RequiresSecondPass = true; |
| 1072 | } |
| 1073 | } |
| 1074 | } else if (InitListExpr *InnerILE |
| 1075 | = dyn_cast_or_null<InitListExpr>(Val: InitExpr)) { |
| 1076 | FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerILE, RequiresSecondPass, |
| 1077 | OuterILE: ILE, OuterIndex: Init, FillWithNoInit); |
| 1078 | } else if (DesignatedInitUpdateExpr *InnerDIUE = |
| 1079 | dyn_cast_or_null<DesignatedInitUpdateExpr>(Val: InitExpr)) { |
| 1080 | FillInEmptyInitializations(Entity: ElementEntity, ILE: InnerDIUE->getUpdater(), |
| 1081 | RequiresSecondPass, OuterILE: ILE, OuterIndex: Init, |
| 1082 | /*FillWithNoInit =*/true); |
| 1083 | } |
| 1084 | } |
| 1085 | } |
| 1086 | |
| 1087 | static bool hasAnyDesignatedInits(const InitListExpr *IL) { |
| 1088 | for (const Stmt *Init : *IL) |
| 1089 | if (isa_and_nonnull<DesignatedInitExpr>(Val: Init)) |
| 1090 | return true; |
| 1091 | return false; |
| 1092 | } |
| 1093 | |
| 1094 | InitListChecker::InitListChecker( |
| 1095 | Sema &S, const InitializedEntity &Entity, InitListExpr *IL, QualType &T, |
| 1096 | bool VerifyOnly, bool TreatUnavailableAsInvalid, bool InOverloadResolution, |
| 1097 | SmallVectorImpl<QualType> *AggrDeductionCandidateParamTypes) |
| 1098 | : SemaRef(S), VerifyOnly(VerifyOnly), |
| 1099 | TreatUnavailableAsInvalid(TreatUnavailableAsInvalid), |
| 1100 | InOverloadResolution(InOverloadResolution), |
| 1101 | AggrDeductionCandidateParamTypes(AggrDeductionCandidateParamTypes) { |
| 1102 | if (!VerifyOnly || hasAnyDesignatedInits(IL)) { |
| 1103 | FullyStructuredList = createInitListExpr( |
| 1104 | CurrentObjectType: T, InitRange: IL->getSourceRange(), ExpectedNumInits: IL->getNumInits(), IsExplicit: IL->isExplicit()); |
| 1105 | |
| 1106 | // FIXME: Check that IL isn't already the semantic form of some other |
| 1107 | // InitListExpr. If it is, we'd create a broken AST. |
| 1108 | if (!VerifyOnly) |
| 1109 | FullyStructuredList->setSyntacticForm(IL); |
| 1110 | } |
| 1111 | |
| 1112 | CheckExplicitInitList(Entity, IList: IL, T, StructuredList: FullyStructuredList, |
| 1113 | /*TopLevelObject=*/true); |
| 1114 | |
| 1115 | if (!hadError && !AggrDeductionCandidateParamTypes && FullyStructuredList) { |
| 1116 | bool RequiresSecondPass = false; |
| 1117 | FillInEmptyInitializations(Entity, ILE: FullyStructuredList, RequiresSecondPass, |
| 1118 | /*OuterILE=*/nullptr, /*OuterIndex=*/0); |
| 1119 | if (RequiresSecondPass && !hadError) |
| 1120 | FillInEmptyInitializations(Entity, ILE: FullyStructuredList, |
| 1121 | RequiresSecondPass, OuterILE: nullptr, OuterIndex: 0); |
| 1122 | } |
| 1123 | if (hadError && FullyStructuredList) |
| 1124 | FullyStructuredList->markError(); |
| 1125 | } |
| 1126 | |
| 1127 | int InitListChecker::numArrayElements(QualType DeclType) { |
| 1128 | // FIXME: use a proper constant |
| 1129 | int maxElements = 0x7FFFFFFF; |
| 1130 | if (const ConstantArrayType *CAT = |
| 1131 | SemaRef.Context.getAsConstantArrayType(T: DeclType)) { |
| 1132 | maxElements = static_cast<int>(CAT->getZExtSize()); |
| 1133 | } |
| 1134 | return maxElements; |
| 1135 | } |
| 1136 | |
| 1137 | int InitListChecker::numStructUnionElements(QualType DeclType) { |
| 1138 | auto *structDecl = DeclType->castAsRecordDecl(); |
| 1139 | int InitializableMembers = 0; |
| 1140 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: structDecl)) |
| 1141 | InitializableMembers += CXXRD->getNumBases(); |
| 1142 | for (const auto *Field : structDecl->fields()) |
| 1143 | if (!Field->isUnnamedBitField()) |
| 1144 | ++InitializableMembers; |
| 1145 | |
| 1146 | if (structDecl->isUnion()) |
| 1147 | return std::min(a: InitializableMembers, b: 1); |
| 1148 | return InitializableMembers - structDecl->hasFlexibleArrayMember(); |
| 1149 | } |
| 1150 | |
| 1151 | /// Determine whether Entity is an entity for which it is idiomatic to elide |
| 1152 | /// the braces in aggregate initialization. |
| 1153 | static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) { |
| 1154 | // Recursive initialization of the one and only field within an aggregate |
| 1155 | // class is considered idiomatic. This case arises in particular for |
| 1156 | // initialization of std::array, where the C++ standard suggests the idiom of |
| 1157 | // |
| 1158 | // std::array<T, N> arr = {1, 2, 3}; |
| 1159 | // |
| 1160 | // (where std::array is an aggregate struct containing a single array field. |
| 1161 | |
| 1162 | if (!Entity.getParent()) |
| 1163 | return false; |
| 1164 | |
| 1165 | // Allows elide brace initialization for aggregates with empty base. |
| 1166 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
| 1167 | auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl(); |
| 1168 | CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(Val: ParentRD); |
| 1169 | return CXXRD->getNumBases() == 1 && CXXRD->field_empty(); |
| 1170 | } |
| 1171 | |
| 1172 | // Allow brace elision if the only subobject is a field. |
| 1173 | if (Entity.getKind() == InitializedEntity::EK_Member) { |
| 1174 | auto *ParentRD = Entity.getParent()->getType()->castAsRecordDecl(); |
| 1175 | if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(Val: ParentRD)) { |
| 1176 | if (CXXRD->getNumBases()) { |
| 1177 | return false; |
| 1178 | } |
| 1179 | } |
| 1180 | auto FieldIt = ParentRD->field_begin(); |
| 1181 | assert(FieldIt != ParentRD->field_end() && |
| 1182 | "no fields but have initializer for member?" ); |
| 1183 | return ++FieldIt == ParentRD->field_end(); |
| 1184 | } |
| 1185 | |
| 1186 | return false; |
| 1187 | } |
| 1188 | |
| 1189 | /// Check whether the range of the initializer \p ParentIList from element |
| 1190 | /// \p Index onwards can be used to initialize an object of type \p T. Update |
| 1191 | /// \p Index to indicate how many elements of the list were consumed. |
| 1192 | /// |
| 1193 | /// This also fills in \p StructuredList, from element \p StructuredIndex |
| 1194 | /// onwards, with the fully-braced, desugared form of the initialization. |
| 1195 | void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity, |
| 1196 | InitListExpr *ParentIList, |
| 1197 | QualType T, unsigned &Index, |
| 1198 | InitListExpr *StructuredList, |
| 1199 | unsigned &StructuredIndex) { |
| 1200 | int maxElements = 0; |
| 1201 | |
| 1202 | if (T->isArrayType()) |
| 1203 | maxElements = numArrayElements(DeclType: T); |
| 1204 | else if (T->isRecordType()) |
| 1205 | maxElements = numStructUnionElements(DeclType: T); |
| 1206 | else if (T->isVectorType()) |
| 1207 | maxElements = T->castAs<VectorType>()->getNumElements(); |
| 1208 | else |
| 1209 | llvm_unreachable("CheckImplicitInitList(): Illegal type" ); |
| 1210 | |
| 1211 | if (maxElements == 0) { |
| 1212 | if (!VerifyOnly) |
| 1213 | SemaRef.Diag(Loc: ParentIList->getInit(Init: Index)->getBeginLoc(), |
| 1214 | DiagID: diag::err_implicit_empty_initializer); |
| 1215 | ++Index; |
| 1216 | hadError = true; |
| 1217 | return; |
| 1218 | } |
| 1219 | |
| 1220 | // Build a structured initializer list corresponding to this subobject. |
| 1221 | InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit( |
| 1222 | IList: ParentIList, Index, CurrentObjectType: T, StructuredList, StructuredIndex, |
| 1223 | InitRange: SourceRange(ParentIList->getInit(Init: Index)->getBeginLoc(), |
| 1224 | ParentIList->getSourceRange().getEnd())); |
| 1225 | unsigned StructuredSubobjectInitIndex = 0; |
| 1226 | |
| 1227 | // Check the element types and build the structural subobject. |
| 1228 | unsigned StartIndex = Index; |
| 1229 | CheckListElementTypes(Entity, IList: ParentIList, DeclType&: T, |
| 1230 | /*SubobjectIsDesignatorContext=*/false, Index, |
| 1231 | StructuredList: StructuredSubobjectInitList, |
| 1232 | StructuredIndex&: StructuredSubobjectInitIndex); |
| 1233 | |
| 1234 | if (StructuredSubobjectInitList) { |
| 1235 | StructuredSubobjectInitList->setType(T); |
| 1236 | |
| 1237 | unsigned EndIndex = (Index == StartIndex? StartIndex : Index - 1); |
| 1238 | // Update the structured sub-object initializer so that it's ending |
| 1239 | // range corresponds with the end of the last initializer it used. |
| 1240 | if (EndIndex < ParentIList->getNumInits() && |
| 1241 | ParentIList->getInit(Init: EndIndex)) { |
| 1242 | SourceLocation EndLoc |
| 1243 | = ParentIList->getInit(Init: EndIndex)->getSourceRange().getEnd(); |
| 1244 | StructuredSubobjectInitList->setRBraceLoc(EndLoc); |
| 1245 | } |
| 1246 | |
| 1247 | // Complain about missing braces. |
| 1248 | if (!VerifyOnly && (T->isArrayType() || T->isRecordType()) && |
| 1249 | !ParentIList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) && |
| 1250 | !isIdiomaticBraceElisionEntity(Entity)) { |
| 1251 | SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(), |
| 1252 | DiagID: diag::warn_missing_braces) |
| 1253 | << StructuredSubobjectInitList->getSourceRange() |
| 1254 | << FixItHint::CreateInsertion( |
| 1255 | InsertionLoc: StructuredSubobjectInitList->getBeginLoc(), Code: "{" ) |
| 1256 | << FixItHint::CreateInsertion( |
| 1257 | InsertionLoc: SemaRef.getLocForEndOfToken( |
| 1258 | Loc: StructuredSubobjectInitList->getEndLoc()), |
| 1259 | Code: "}" ); |
| 1260 | } |
| 1261 | |
| 1262 | // Warn if this type won't be an aggregate in future versions of C++. |
| 1263 | auto *CXXRD = T->getAsCXXRecordDecl(); |
| 1264 | if (!VerifyOnly && CXXRD && CXXRD->hasUserDeclaredConstructor()) { |
| 1265 | SemaRef.Diag(Loc: StructuredSubobjectInitList->getBeginLoc(), |
| 1266 | DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors) |
| 1267 | << StructuredSubobjectInitList->getSourceRange() << T; |
| 1268 | } |
| 1269 | } |
| 1270 | } |
| 1271 | |
| 1272 | /// Warn that \p Entity was of scalar type and was initialized by a |
| 1273 | /// single-element braced initializer list. |
| 1274 | static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity, |
| 1275 | SourceRange Braces) { |
| 1276 | // Don't warn during template instantiation. If the initialization was |
| 1277 | // non-dependent, we warned during the initial parse; otherwise, the |
| 1278 | // type might not be scalar in some uses of the template. |
| 1279 | if (S.inTemplateInstantiation()) |
| 1280 | return; |
| 1281 | |
| 1282 | unsigned DiagID = 0; |
| 1283 | |
| 1284 | switch (Entity.getKind()) { |
| 1285 | case InitializedEntity::EK_VectorElement: |
| 1286 | case InitializedEntity::EK_MatrixElement: |
| 1287 | case InitializedEntity::EK_ComplexElement: |
| 1288 | case InitializedEntity::EK_ArrayElement: |
| 1289 | case InitializedEntity::EK_Parameter: |
| 1290 | case InitializedEntity::EK_Parameter_CF_Audited: |
| 1291 | case InitializedEntity::EK_TemplateParameter: |
| 1292 | case InitializedEntity::EK_Result: |
| 1293 | case InitializedEntity::EK_ParenAggInitMember: |
| 1294 | // Extra braces here are suspicious. |
| 1295 | DiagID = diag::warn_braces_around_init; |
| 1296 | break; |
| 1297 | |
| 1298 | case InitializedEntity::EK_Member: |
| 1299 | // Warn on aggregate initialization but not on ctor init list or |
| 1300 | // default member initializer. |
| 1301 | if (Entity.getParent()) |
| 1302 | DiagID = diag::warn_braces_around_init; |
| 1303 | break; |
| 1304 | |
| 1305 | case InitializedEntity::EK_Variable: |
| 1306 | case InitializedEntity::EK_LambdaCapture: |
| 1307 | // No warning, might be direct-list-initialization. |
| 1308 | // FIXME: Should we warn for copy-list-initialization in these cases? |
| 1309 | break; |
| 1310 | |
| 1311 | case InitializedEntity::EK_New: |
| 1312 | case InitializedEntity::EK_Temporary: |
| 1313 | case InitializedEntity::EK_CompoundLiteralInit: |
| 1314 | // No warning, braces are part of the syntax of the underlying construct. |
| 1315 | break; |
| 1316 | |
| 1317 | case InitializedEntity::EK_RelatedResult: |
| 1318 | // No warning, we already warned when initializing the result. |
| 1319 | break; |
| 1320 | |
| 1321 | case InitializedEntity::EK_Exception: |
| 1322 | case InitializedEntity::EK_Base: |
| 1323 | case InitializedEntity::EK_Delegating: |
| 1324 | case InitializedEntity::EK_BlockElement: |
| 1325 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
| 1326 | case InitializedEntity::EK_Binding: |
| 1327 | case InitializedEntity::EK_StmtExprResult: |
| 1328 | llvm_unreachable("unexpected braced scalar init" ); |
| 1329 | } |
| 1330 | |
| 1331 | if (DiagID) { |
| 1332 | S.Diag(Loc: Braces.getBegin(), DiagID) |
| 1333 | << Entity.getType()->isSizelessBuiltinType() << Braces |
| 1334 | << FixItHint::CreateRemoval(RemoveRange: Braces.getBegin()) |
| 1335 | << FixItHint::CreateRemoval(RemoveRange: Braces.getEnd()); |
| 1336 | } |
| 1337 | } |
| 1338 | |
| 1339 | /// Check whether the initializer \p IList (that was written with explicit |
| 1340 | /// braces) can be used to initialize an object of type \p T. |
| 1341 | /// |
| 1342 | /// This also fills in \p StructuredList with the fully-braced, desugared |
| 1343 | /// form of the initialization. |
| 1344 | void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity, |
| 1345 | InitListExpr *IList, QualType &T, |
| 1346 | InitListExpr *StructuredList, |
| 1347 | bool TopLevelObject) { |
| 1348 | unsigned Index = 0, StructuredIndex = 0; |
| 1349 | CheckListElementTypes(Entity, IList, DeclType&: T, /*SubobjectIsDesignatorContext=*/true, |
| 1350 | Index, StructuredList, StructuredIndex, TopLevelObject); |
| 1351 | if (StructuredList) { |
| 1352 | QualType ExprTy = T; |
| 1353 | if (!ExprTy->isArrayType()) |
| 1354 | ExprTy = ExprTy.getNonLValueExprType(Context: SemaRef.Context); |
| 1355 | if (!VerifyOnly) |
| 1356 | IList->setType(ExprTy); |
| 1357 | StructuredList->setType(ExprTy); |
| 1358 | } |
| 1359 | if (hadError) |
| 1360 | return; |
| 1361 | |
| 1362 | // Don't complain for incomplete types, since we'll get an error elsewhere. |
| 1363 | if ((Index < IList->getNumInits() || CurEmbed) && !T->isIncompleteType()) { |
| 1364 | // We have leftover initializers |
| 1365 | bool = SemaRef.getLangOpts().CPlusPlus || |
| 1366 | (SemaRef.getLangOpts().OpenCL && T->isVectorType()); |
| 1367 | hadError = ExtraInitsIsError; |
| 1368 | if (VerifyOnly) { |
| 1369 | return; |
| 1370 | } else if (StructuredIndex == 1 && |
| 1371 | IsStringInit(init: StructuredList->getInit(Init: 0), declType: T, Context&: SemaRef.Context) == |
| 1372 | SIF_None) { |
| 1373 | unsigned DK = |
| 1374 | ExtraInitsIsError |
| 1375 | ? diag::err_excess_initializers_in_char_array_initializer |
| 1376 | : diag::ext_excess_initializers_in_char_array_initializer; |
| 1377 | SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK) |
| 1378 | << IList->getInit(Init: Index)->getSourceRange(); |
| 1379 | } else if (T->isSizelessBuiltinType()) { |
| 1380 | unsigned DK = ExtraInitsIsError |
| 1381 | ? diag::err_excess_initializers_for_sizeless_type |
| 1382 | : diag::ext_excess_initializers_for_sizeless_type; |
| 1383 | SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK) |
| 1384 | << T << IList->getInit(Init: Index)->getSourceRange(); |
| 1385 | } else { |
| 1386 | int initKind = T->isArrayType() ? 0 |
| 1387 | : T->isVectorType() ? 1 |
| 1388 | : T->isMatrixType() ? 2 |
| 1389 | : T->isScalarType() ? 3 |
| 1390 | : T->isUnionType() ? 4 |
| 1391 | : 5; |
| 1392 | |
| 1393 | unsigned DK = ExtraInitsIsError ? diag::err_excess_initializers |
| 1394 | : diag::ext_excess_initializers; |
| 1395 | SemaRef.Diag(Loc: IList->getInit(Init: Index)->getBeginLoc(), DiagID: DK) |
| 1396 | << initKind << IList->getInit(Init: Index)->getSourceRange(); |
| 1397 | } |
| 1398 | } |
| 1399 | |
| 1400 | if (!VerifyOnly) { |
| 1401 | if (T->isScalarType() && IList->getNumInits() == 1 && |
| 1402 | !isa<InitListExpr>(Val: IList->getInit(Init: 0))) |
| 1403 | warnBracedScalarInit(S&: SemaRef, Entity, Braces: IList->getSourceRange()); |
| 1404 | |
| 1405 | // Warn if this is a class type that won't be an aggregate in future |
| 1406 | // versions of C++. |
| 1407 | auto *CXXRD = T->getAsCXXRecordDecl(); |
| 1408 | if (CXXRD && CXXRD->hasUserDeclaredConstructor()) { |
| 1409 | // Don't warn if there's an equivalent default constructor that would be |
| 1410 | // used instead. |
| 1411 | bool HasEquivCtor = false; |
| 1412 | if (IList->getNumInits() == 0) { |
| 1413 | auto *CD = SemaRef.LookupDefaultConstructor(Class: CXXRD); |
| 1414 | HasEquivCtor = CD && !CD->isDeleted(); |
| 1415 | } |
| 1416 | |
| 1417 | if (!HasEquivCtor) { |
| 1418 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
| 1419 | DiagID: diag::warn_cxx20_compat_aggregate_init_with_ctors) |
| 1420 | << IList->getSourceRange() << T; |
| 1421 | } |
| 1422 | } |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity, |
| 1427 | InitListExpr *IList, |
| 1428 | QualType &DeclType, |
| 1429 | bool SubobjectIsDesignatorContext, |
| 1430 | unsigned &Index, |
| 1431 | InitListExpr *StructuredList, |
| 1432 | unsigned &StructuredIndex, |
| 1433 | bool TopLevelObject) { |
| 1434 | if (DeclType->isAnyComplexType() && SubobjectIsDesignatorContext) { |
| 1435 | // Explicitly braced initializer for complex type can be real+imaginary |
| 1436 | // parts. |
| 1437 | CheckComplexType(Entity, IList, DeclType, Index, |
| 1438 | StructuredList, StructuredIndex); |
| 1439 | } else if (DeclType->isScalarType()) { |
| 1440 | CheckScalarType(Entity, IList, DeclType, Index, |
| 1441 | StructuredList, StructuredIndex); |
| 1442 | } else if (DeclType->isVectorType()) { |
| 1443 | CheckVectorType(Entity, IList, DeclType, Index, |
| 1444 | StructuredList, StructuredIndex); |
| 1445 | } else if (DeclType->isMatrixType()) { |
| 1446 | CheckMatrixType(Entity, IList, DeclType, Index, StructuredList, |
| 1447 | StructuredIndex); |
| 1448 | } else if (const RecordDecl *RD = DeclType->getAsRecordDecl()) { |
| 1449 | auto Bases = |
| 1450 | CXXRecordDecl::base_class_const_range(CXXRecordDecl::base_class_const_iterator(), |
| 1451 | CXXRecordDecl::base_class_const_iterator()); |
| 1452 | if (DeclType->isRecordType()) { |
| 1453 | assert(DeclType->isAggregateType() && |
| 1454 | "non-aggregate records should be handed in CheckSubElementType" ); |
| 1455 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
| 1456 | Bases = CXXRD->bases(); |
| 1457 | } else { |
| 1458 | Bases = cast<CXXRecordDecl>(Val: RD)->bases(); |
| 1459 | } |
| 1460 | CheckStructUnionTypes(Entity, IList, DeclType, Bases, Field: RD->field_begin(), |
| 1461 | SubobjectIsDesignatorContext, Index, StructuredList, |
| 1462 | StructuredIndex, TopLevelObject); |
| 1463 | } else if (DeclType->isArrayType()) { |
| 1464 | llvm::APSInt Zero( |
| 1465 | SemaRef.Context.getTypeSize(T: SemaRef.Context.getSizeType()), |
| 1466 | false); |
| 1467 | CheckArrayType(Entity, IList, DeclType, elementIndex: Zero, |
| 1468 | SubobjectIsDesignatorContext, Index, |
| 1469 | StructuredList, StructuredIndex); |
| 1470 | } else if (DeclType->isVoidType() || DeclType->isFunctionType()) { |
| 1471 | // This type is invalid, issue a diagnostic. |
| 1472 | ++Index; |
| 1473 | if (!VerifyOnly) |
| 1474 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type) |
| 1475 | << DeclType; |
| 1476 | hadError = true; |
| 1477 | } else if (DeclType->isReferenceType()) { |
| 1478 | CheckReferenceType(Entity, IList, DeclType, Index, |
| 1479 | StructuredList, StructuredIndex); |
| 1480 | } else if (DeclType->isObjCObjectType()) { |
| 1481 | if (!VerifyOnly) |
| 1482 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_objc_class) << DeclType; |
| 1483 | hadError = true; |
| 1484 | } else if (DeclType->isOCLIntelSubgroupAVCType() || |
| 1485 | DeclType->isSizelessBuiltinType()) { |
| 1486 | // Checks for scalar type are sufficient for these types too. |
| 1487 | CheckScalarType(Entity, IList, DeclType, Index, StructuredList, |
| 1488 | StructuredIndex); |
| 1489 | } else if (DeclType->isDependentType()) { |
| 1490 | // C++ [over.match.class.deduct]p1.5: |
| 1491 | // brace elision is not considered for any aggregate element that has a |
| 1492 | // dependent non-array type or an array type with a value-dependent bound |
| 1493 | ++Index; |
| 1494 | assert(AggrDeductionCandidateParamTypes); |
| 1495 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
| 1496 | } else { |
| 1497 | if (!VerifyOnly) |
| 1498 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_illegal_initializer_type) |
| 1499 | << DeclType; |
| 1500 | hadError = true; |
| 1501 | } |
| 1502 | } |
| 1503 | |
| 1504 | void InitListChecker::CheckSubElementType(const InitializedEntity &Entity, |
| 1505 | InitListExpr *IList, |
| 1506 | QualType ElemType, |
| 1507 | unsigned &Index, |
| 1508 | InitListExpr *StructuredList, |
| 1509 | unsigned &StructuredIndex, |
| 1510 | bool DirectlyDesignated) { |
| 1511 | Expr *expr = IList->getInit(Init: Index); |
| 1512 | |
| 1513 | if (ElemType->isReferenceType()) |
| 1514 | return CheckReferenceType(Entity, IList, DeclType: ElemType, Index, |
| 1515 | StructuredList, StructuredIndex); |
| 1516 | |
| 1517 | if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(Val: expr)) { |
| 1518 | if (SubInitList->getNumInits() == 1 && |
| 1519 | IsStringInit(init: SubInitList->getInit(Init: 0), declType: ElemType, Context&: SemaRef.Context) == |
| 1520 | SIF_None) { |
| 1521 | // FIXME: It would be more faithful and no less correct to include an |
| 1522 | // InitListExpr in the semantic form of the initializer list in this case. |
| 1523 | expr = SubInitList->getInit(Init: 0); |
| 1524 | } |
| 1525 | // Nested aggregate initialization and C++ initialization are handled later. |
| 1526 | } else if (isa<ImplicitValueInitExpr>(Val: expr)) { |
| 1527 | // This happens during template instantiation when we see an InitListExpr |
| 1528 | // that we've already checked once. |
| 1529 | assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) && |
| 1530 | "found implicit initialization for the wrong type" ); |
| 1531 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
| 1532 | ++Index; |
| 1533 | return; |
| 1534 | } |
| 1535 | |
| 1536 | if (SemaRef.getLangOpts().CPlusPlus || isa<InitListExpr>(Val: expr)) { |
| 1537 | // C++ [dcl.init.aggr]p2: |
| 1538 | // Each member is copy-initialized from the corresponding |
| 1539 | // initializer-clause. |
| 1540 | |
| 1541 | // FIXME: Better EqualLoc? |
| 1542 | InitializationKind Kind = |
| 1543 | InitializationKind::CreateCopy(InitLoc: expr->getBeginLoc(), EqualLoc: SourceLocation()); |
| 1544 | |
| 1545 | // Vector elements can be initialized from other vectors in which case |
| 1546 | // we need initialization entity with a type of a vector (and not a vector |
| 1547 | // element!) initializing multiple vector elements. |
| 1548 | auto TmpEntity = |
| 1549 | (ElemType->isExtVectorType() && !Entity.getType()->isExtVectorType()) |
| 1550 | ? InitializedEntity::InitializeTemporary(Type: ElemType) |
| 1551 | : Entity; |
| 1552 | |
| 1553 | if (TmpEntity.getType()->isDependentType()) { |
| 1554 | // C++ [over.match.class.deduct]p1.5: |
| 1555 | // brace elision is not considered for any aggregate element that has a |
| 1556 | // dependent non-array type or an array type with a value-dependent |
| 1557 | // bound |
| 1558 | assert(AggrDeductionCandidateParamTypes); |
| 1559 | |
| 1560 | // In the presence of a braced-init-list within the initializer, we should |
| 1561 | // not perform brace-elision, even if brace elision would otherwise be |
| 1562 | // applicable. For example, given: |
| 1563 | // |
| 1564 | // template <class T> struct Foo { |
| 1565 | // T t[2]; |
| 1566 | // }; |
| 1567 | // |
| 1568 | // Foo t = {{1, 2}}; |
| 1569 | // |
| 1570 | // we don't want the (T, T) but rather (T [2]) in terms of the initializer |
| 1571 | // {{1, 2}}. |
| 1572 | if (isa<InitListExpr, DesignatedInitExpr>(Val: expr) || |
| 1573 | !isa_and_present<ConstantArrayType>( |
| 1574 | Val: SemaRef.Context.getAsArrayType(T: ElemType))) { |
| 1575 | ++Index; |
| 1576 | AggrDeductionCandidateParamTypes->push_back(Elt: ElemType); |
| 1577 | return; |
| 1578 | } |
| 1579 | } else { |
| 1580 | InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr, |
| 1581 | /*TopLevelOfInitList*/ true); |
| 1582 | // C++14 [dcl.init.aggr]p13: |
| 1583 | // If the assignment-expression can initialize a member, the member is |
| 1584 | // initialized. Otherwise [...] brace elision is assumed |
| 1585 | // |
| 1586 | // Brace elision is never performed if the element is not an |
| 1587 | // assignment-expression. |
| 1588 | if (Seq || isa<InitListExpr>(Val: expr)) { |
| 1589 | if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) { |
| 1590 | expr = HandleEmbed(Embed, Entity); |
| 1591 | } |
| 1592 | if (!VerifyOnly) { |
| 1593 | ExprResult Result = Seq.Perform(S&: SemaRef, Entity: TmpEntity, Kind, Args: expr); |
| 1594 | if (Result.isInvalid()) |
| 1595 | hadError = true; |
| 1596 | |
| 1597 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
| 1598 | expr: Result.getAs<Expr>()); |
| 1599 | } else if (!Seq) { |
| 1600 | hadError = true; |
| 1601 | } else if (StructuredList) { |
| 1602 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
| 1603 | expr: getDummyInit()); |
| 1604 | } |
| 1605 | if (!CurEmbed) |
| 1606 | ++Index; |
| 1607 | if (AggrDeductionCandidateParamTypes) |
| 1608 | AggrDeductionCandidateParamTypes->push_back(Elt: ElemType); |
| 1609 | return; |
| 1610 | } |
| 1611 | } |
| 1612 | |
| 1613 | // Fall through for subaggregate initialization |
| 1614 | } else if (ElemType->isScalarType() || ElemType->isAtomicType()) { |
| 1615 | // FIXME: Need to handle atomic aggregate types with implicit init lists. |
| 1616 | return CheckScalarType(Entity, IList, DeclType: ElemType, Index, |
| 1617 | StructuredList, StructuredIndex); |
| 1618 | } else if (const ArrayType *arrayType = |
| 1619 | SemaRef.Context.getAsArrayType(T: ElemType)) { |
| 1620 | // arrayType can be incomplete if we're initializing a flexible |
| 1621 | // array member. There's nothing we can do with the completed |
| 1622 | // type here, though. |
| 1623 | |
| 1624 | if (IsStringInit(Init: expr, AT: arrayType, Context&: SemaRef.Context) == SIF_None) { |
| 1625 | // FIXME: Should we do this checking in verify-only mode? |
| 1626 | if (!VerifyOnly) |
| 1627 | CheckStringInit(Str: expr, DeclT&: ElemType, AT: arrayType, S&: SemaRef, Entity, |
| 1628 | CheckC23ConstexprInit: SemaRef.getLangOpts().C23 && |
| 1629 | initializingConstexprVariable(Entity)); |
| 1630 | if (StructuredList) |
| 1631 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
| 1632 | ++Index; |
| 1633 | return; |
| 1634 | } |
| 1635 | |
| 1636 | // Fall through for subaggregate initialization. |
| 1637 | |
| 1638 | } else { |
| 1639 | assert((ElemType->isRecordType() || ElemType->isVectorType() || |
| 1640 | ElemType->isOpenCLSpecificType() || ElemType->isMFloat8Type()) && |
| 1641 | "Unexpected type" ); |
| 1642 | |
| 1643 | // C99 6.7.8p13: |
| 1644 | // |
| 1645 | // The initializer for a structure or union object that has |
| 1646 | // automatic storage duration shall be either an initializer |
| 1647 | // list as described below, or a single expression that has |
| 1648 | // compatible structure or union type. In the latter case, the |
| 1649 | // initial value of the object, including unnamed members, is |
| 1650 | // that of the expression. |
| 1651 | ExprResult ExprRes = expr; |
| 1652 | if (SemaRef.CheckSingleAssignmentConstraints(LHSType: ElemType, RHS&: ExprRes, |
| 1653 | Diagnose: !VerifyOnly) != |
| 1654 | AssignConvertType::Incompatible) { |
| 1655 | if (ExprRes.isInvalid()) |
| 1656 | hadError = true; |
| 1657 | else { |
| 1658 | ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(E: ExprRes.get()); |
| 1659 | if (ExprRes.isInvalid()) |
| 1660 | hadError = true; |
| 1661 | } |
| 1662 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
| 1663 | expr: ExprRes.getAs<Expr>()); |
| 1664 | ++Index; |
| 1665 | return; |
| 1666 | } |
| 1667 | ExprRes.get(); |
| 1668 | // Fall through for subaggregate initialization |
| 1669 | } |
| 1670 | |
| 1671 | // C++ [dcl.init.aggr]p12: |
| 1672 | // |
| 1673 | // [...] Otherwise, if the member is itself a non-empty |
| 1674 | // subaggregate, brace elision is assumed and the initializer is |
| 1675 | // considered for the initialization of the first member of |
| 1676 | // the subaggregate. |
| 1677 | // OpenCL vector initializer is handled elsewhere. |
| 1678 | if ((!SemaRef.getLangOpts().OpenCL && ElemType->isVectorType()) || |
| 1679 | ElemType->isAggregateType()) { |
| 1680 | CheckImplicitInitList(Entity, ParentIList: IList, T: ElemType, Index, StructuredList, |
| 1681 | StructuredIndex); |
| 1682 | ++StructuredIndex; |
| 1683 | |
| 1684 | // In C++20, brace elision is not permitted for a designated initializer. |
| 1685 | if (DirectlyDesignated && SemaRef.getLangOpts().CPlusPlus && !hadError) { |
| 1686 | if (InOverloadResolution) |
| 1687 | hadError = true; |
| 1688 | if (!VerifyOnly) { |
| 1689 | SemaRef.Diag(Loc: expr->getBeginLoc(), |
| 1690 | DiagID: diag::ext_designated_init_brace_elision) |
| 1691 | << expr->getSourceRange() |
| 1692 | << FixItHint::CreateInsertion(InsertionLoc: expr->getBeginLoc(), Code: "{" ) |
| 1693 | << FixItHint::CreateInsertion( |
| 1694 | InsertionLoc: SemaRef.getLocForEndOfToken(Loc: expr->getEndLoc()), Code: "}" ); |
| 1695 | } |
| 1696 | } |
| 1697 | } else { |
| 1698 | if (!VerifyOnly) { |
| 1699 | // We cannot initialize this element, so let PerformCopyInitialization |
| 1700 | // produce the appropriate diagnostic. We already checked that this |
| 1701 | // initialization will fail. |
| 1702 | ExprResult Copy = |
| 1703 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: SourceLocation(), Init: expr, |
| 1704 | /*TopLevelOfInitList=*/true); |
| 1705 | (void)Copy; |
| 1706 | assert(Copy.isInvalid() && |
| 1707 | "expected non-aggregate initialization to fail" ); |
| 1708 | } |
| 1709 | hadError = true; |
| 1710 | ++Index; |
| 1711 | ++StructuredIndex; |
| 1712 | } |
| 1713 | } |
| 1714 | |
| 1715 | void InitListChecker::CheckComplexType(const InitializedEntity &Entity, |
| 1716 | InitListExpr *IList, QualType DeclType, |
| 1717 | unsigned &Index, |
| 1718 | InitListExpr *StructuredList, |
| 1719 | unsigned &StructuredIndex) { |
| 1720 | assert(Index == 0 && "Index in explicit init list must be zero" ); |
| 1721 | |
| 1722 | // As an extension, clang supports complex initializers, which initialize |
| 1723 | // a complex number component-wise. When an explicit initializer list for |
| 1724 | // a complex number contains two initializers, this extension kicks in: |
| 1725 | // it expects the initializer list to contain two elements convertible to |
| 1726 | // the element type of the complex type. The first element initializes |
| 1727 | // the real part, and the second element intitializes the imaginary part. |
| 1728 | |
| 1729 | if (IList->getNumInits() < 2) |
| 1730 | return CheckScalarType(Entity, IList, DeclType, Index, StructuredList, |
| 1731 | StructuredIndex); |
| 1732 | |
| 1733 | // This is an extension in C. (The builtin _Complex type does not exist |
| 1734 | // in the C++ standard.) |
| 1735 | if (!SemaRef.getLangOpts().CPlusPlus && !VerifyOnly) |
| 1736 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_complex_component_init) |
| 1737 | << IList->getSourceRange(); |
| 1738 | |
| 1739 | // Initialize the complex number. |
| 1740 | QualType elementType = DeclType->castAs<ComplexType>()->getElementType(); |
| 1741 | InitializedEntity ElementEntity = |
| 1742 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
| 1743 | |
| 1744 | for (unsigned i = 0; i < 2; ++i) { |
| 1745 | ElementEntity.setElementIndex(Index); |
| 1746 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
| 1747 | StructuredList, StructuredIndex); |
| 1748 | } |
| 1749 | } |
| 1750 | |
| 1751 | void InitListChecker::CheckScalarType(const InitializedEntity &Entity, |
| 1752 | InitListExpr *IList, QualType DeclType, |
| 1753 | unsigned &Index, |
| 1754 | InitListExpr *StructuredList, |
| 1755 | unsigned &StructuredIndex) { |
| 1756 | if (Index >= IList->getNumInits()) { |
| 1757 | if (!VerifyOnly) { |
| 1758 | if (SemaRef.getLangOpts().CPlusPlus) { |
| 1759 | if (DeclType->isSizelessBuiltinType()) |
| 1760 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
| 1761 | DiagID: SemaRef.getLangOpts().CPlusPlus11 |
| 1762 | ? diag::warn_cxx98_compat_empty_sizeless_initializer |
| 1763 | : diag::err_empty_sizeless_initializer) |
| 1764 | << DeclType << IList->getSourceRange(); |
| 1765 | else |
| 1766 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
| 1767 | DiagID: SemaRef.getLangOpts().CPlusPlus11 |
| 1768 | ? diag::warn_cxx98_compat_empty_scalar_initializer |
| 1769 | : diag::err_empty_scalar_initializer) |
| 1770 | << IList->getSourceRange(); |
| 1771 | } |
| 1772 | } |
| 1773 | hadError = |
| 1774 | SemaRef.getLangOpts().CPlusPlus && !SemaRef.getLangOpts().CPlusPlus11; |
| 1775 | ++Index; |
| 1776 | ++StructuredIndex; |
| 1777 | return; |
| 1778 | } |
| 1779 | |
| 1780 | Expr *expr = IList->getInit(Init: Index); |
| 1781 | if (InitListExpr *SubIList = dyn_cast<InitListExpr>(Val: expr)) { |
| 1782 | // FIXME: This is invalid, and accepting it causes overload resolution |
| 1783 | // to pick the wrong overload in some corner cases. |
| 1784 | if (!VerifyOnly) |
| 1785 | SemaRef.Diag(Loc: SubIList->getBeginLoc(), DiagID: diag::ext_many_braces_around_init) |
| 1786 | << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange(); |
| 1787 | |
| 1788 | CheckScalarType(Entity, IList: SubIList, DeclType, Index, StructuredList, |
| 1789 | StructuredIndex); |
| 1790 | return; |
| 1791 | } else if (isa<DesignatedInitExpr>(Val: expr)) { |
| 1792 | if (!VerifyOnly) |
| 1793 | SemaRef.Diag(Loc: expr->getBeginLoc(), |
| 1794 | DiagID: diag::err_designator_for_scalar_or_sizeless_init) |
| 1795 | << DeclType->isSizelessBuiltinType() << DeclType |
| 1796 | << expr->getSourceRange(); |
| 1797 | hadError = true; |
| 1798 | ++Index; |
| 1799 | ++StructuredIndex; |
| 1800 | return; |
| 1801 | } else if (auto *Embed = dyn_cast<EmbedExpr>(Val: expr)) { |
| 1802 | expr = HandleEmbed(Embed, Entity); |
| 1803 | } |
| 1804 | |
| 1805 | ExprResult Result; |
| 1806 | if (VerifyOnly) { |
| 1807 | if (SemaRef.CanPerformCopyInitialization(Entity, Init: expr)) |
| 1808 | Result = getDummyInit(); |
| 1809 | else |
| 1810 | Result = ExprError(); |
| 1811 | } else { |
| 1812 | Result = |
| 1813 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr, |
| 1814 | /*TopLevelOfInitList=*/true); |
| 1815 | } |
| 1816 | |
| 1817 | Expr *ResultExpr = nullptr; |
| 1818 | |
| 1819 | if (Result.isInvalid()) |
| 1820 | hadError = true; // types weren't compatible. |
| 1821 | else { |
| 1822 | ResultExpr = Result.getAs<Expr>(); |
| 1823 | |
| 1824 | if (ResultExpr != expr && !VerifyOnly && !CurEmbed) { |
| 1825 | // The type was promoted, update initializer list. |
| 1826 | // FIXME: Why are we updating the syntactic init list? |
| 1827 | IList->setInit(Init: Index, expr: ResultExpr); |
| 1828 | } |
| 1829 | } |
| 1830 | |
| 1831 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr); |
| 1832 | if (!CurEmbed) |
| 1833 | ++Index; |
| 1834 | if (AggrDeductionCandidateParamTypes) |
| 1835 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
| 1836 | } |
| 1837 | |
| 1838 | void InitListChecker::CheckReferenceType(const InitializedEntity &Entity, |
| 1839 | InitListExpr *IList, QualType DeclType, |
| 1840 | unsigned &Index, |
| 1841 | InitListExpr *StructuredList, |
| 1842 | unsigned &StructuredIndex) { |
| 1843 | if (Index >= IList->getNumInits()) { |
| 1844 | // FIXME: It would be wonderful if we could point at the actual member. In |
| 1845 | // general, it would be useful to pass location information down the stack, |
| 1846 | // so that we know the location (or decl) of the "current object" being |
| 1847 | // initialized. |
| 1848 | if (!VerifyOnly) |
| 1849 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
| 1850 | DiagID: diag::err_init_reference_member_uninitialized) |
| 1851 | << DeclType << IList->getSourceRange(); |
| 1852 | hadError = true; |
| 1853 | ++Index; |
| 1854 | ++StructuredIndex; |
| 1855 | return; |
| 1856 | } |
| 1857 | |
| 1858 | Expr *expr = IList->getInit(Init: Index); |
| 1859 | if (isa<InitListExpr>(Val: expr) && !SemaRef.getLangOpts().CPlusPlus11) { |
| 1860 | if (!VerifyOnly) |
| 1861 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::err_init_non_aggr_init_list) |
| 1862 | << DeclType << IList->getSourceRange(); |
| 1863 | hadError = true; |
| 1864 | ++Index; |
| 1865 | ++StructuredIndex; |
| 1866 | return; |
| 1867 | } |
| 1868 | |
| 1869 | ExprResult Result; |
| 1870 | if (VerifyOnly) { |
| 1871 | if (SemaRef.CanPerformCopyInitialization(Entity,Init: expr)) |
| 1872 | Result = getDummyInit(); |
| 1873 | else |
| 1874 | Result = ExprError(); |
| 1875 | } else { |
| 1876 | Result = |
| 1877 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: expr->getBeginLoc(), Init: expr, |
| 1878 | /*TopLevelOfInitList=*/true); |
| 1879 | } |
| 1880 | |
| 1881 | if (Result.isInvalid()) |
| 1882 | hadError = true; |
| 1883 | |
| 1884 | expr = Result.getAs<Expr>(); |
| 1885 | // FIXME: Why are we updating the syntactic init list? |
| 1886 | if (!VerifyOnly && expr) |
| 1887 | IList->setInit(Init: Index, expr); |
| 1888 | |
| 1889 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr); |
| 1890 | ++Index; |
| 1891 | if (AggrDeductionCandidateParamTypes) |
| 1892 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
| 1893 | } |
| 1894 | |
| 1895 | void InitListChecker::CheckMatrixType(const InitializedEntity &Entity, |
| 1896 | InitListExpr *IList, QualType DeclType, |
| 1897 | unsigned &Index, |
| 1898 | InitListExpr *StructuredList, |
| 1899 | unsigned &StructuredIndex) { |
| 1900 | if (!SemaRef.getLangOpts().HLSL) |
| 1901 | return; |
| 1902 | |
| 1903 | const ConstantMatrixType *MT = DeclType->castAs<ConstantMatrixType>(); |
| 1904 | |
| 1905 | // For HLSL, the error reporting for this case is handled in SemaHLSL's |
| 1906 | // initializer list diagnostics. That means the execution should require |
| 1907 | // getNumElementsFlattened to equal getNumInits. In other words the execution |
| 1908 | // should never reach this point if this condition is not true". |
| 1909 | assert(IList->getNumInits() == MT->getNumElementsFlattened() && |
| 1910 | "Inits must equal Matrix element count" ); |
| 1911 | |
| 1912 | QualType ElemTy = MT->getElementType(); |
| 1913 | |
| 1914 | Index = 0; |
| 1915 | InitializedEntity Element = |
| 1916 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
| 1917 | |
| 1918 | while (Index < IList->getNumInits()) { |
| 1919 | // Not a sublist: just consume directly. |
| 1920 | // Note: In HLSL, elements of the InitListExpr are in row-major order, so no |
| 1921 | // change is needed to the Index. |
| 1922 | Element.setElementIndex(Index); |
| 1923 | CheckSubElementType(Entity: Element, IList, ElemType: ElemTy, Index, StructuredList, |
| 1924 | StructuredIndex); |
| 1925 | } |
| 1926 | } |
| 1927 | |
| 1928 | void InitListChecker::CheckVectorType(const InitializedEntity &Entity, |
| 1929 | InitListExpr *IList, QualType DeclType, |
| 1930 | unsigned &Index, |
| 1931 | InitListExpr *StructuredList, |
| 1932 | unsigned &StructuredIndex) { |
| 1933 | const VectorType *VT = DeclType->castAs<VectorType>(); |
| 1934 | unsigned maxElements = VT->getNumElements(); |
| 1935 | unsigned numEltsInit = 0; |
| 1936 | QualType elementType = VT->getElementType(); |
| 1937 | |
| 1938 | if (Index >= IList->getNumInits()) { |
| 1939 | // Make sure the element type can be value-initialized. |
| 1940 | CheckEmptyInitializable( |
| 1941 | Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity), |
| 1942 | Loc: IList->getEndLoc()); |
| 1943 | return; |
| 1944 | } |
| 1945 | |
| 1946 | if (!SemaRef.getLangOpts().OpenCL && !SemaRef.getLangOpts().HLSL ) { |
| 1947 | // If the initializing element is a vector, try to copy-initialize |
| 1948 | // instead of breaking it apart (which is doomed to failure anyway). |
| 1949 | Expr *Init = IList->getInit(Init: Index); |
| 1950 | if (!isa<InitListExpr>(Val: Init) && Init->getType()->isVectorType()) { |
| 1951 | ExprResult Result; |
| 1952 | if (VerifyOnly) { |
| 1953 | if (SemaRef.CanPerformCopyInitialization(Entity, Init)) |
| 1954 | Result = getDummyInit(); |
| 1955 | else |
| 1956 | Result = ExprError(); |
| 1957 | } else { |
| 1958 | Result = |
| 1959 | SemaRef.PerformCopyInitialization(Entity, EqualLoc: Init->getBeginLoc(), Init, |
| 1960 | /*TopLevelOfInitList=*/true); |
| 1961 | } |
| 1962 | |
| 1963 | Expr *ResultExpr = nullptr; |
| 1964 | if (Result.isInvalid()) |
| 1965 | hadError = true; // types weren't compatible. |
| 1966 | else { |
| 1967 | ResultExpr = Result.getAs<Expr>(); |
| 1968 | |
| 1969 | if (ResultExpr != Init && !VerifyOnly) { |
| 1970 | // The type was promoted, update initializer list. |
| 1971 | // FIXME: Why are we updating the syntactic init list? |
| 1972 | IList->setInit(Init: Index, expr: ResultExpr); |
| 1973 | } |
| 1974 | } |
| 1975 | UpdateStructuredListElement(StructuredList, StructuredIndex, expr: ResultExpr); |
| 1976 | ++Index; |
| 1977 | if (AggrDeductionCandidateParamTypes) |
| 1978 | AggrDeductionCandidateParamTypes->push_back(Elt: elementType); |
| 1979 | return; |
| 1980 | } |
| 1981 | |
| 1982 | InitializedEntity ElementEntity = |
| 1983 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
| 1984 | |
| 1985 | for (unsigned i = 0; i < maxElements; ++i, ++numEltsInit) { |
| 1986 | // Don't attempt to go past the end of the init list |
| 1987 | if (Index >= IList->getNumInits()) { |
| 1988 | CheckEmptyInitializable(Entity: ElementEntity, Loc: IList->getEndLoc()); |
| 1989 | break; |
| 1990 | } |
| 1991 | |
| 1992 | ElementEntity.setElementIndex(Index); |
| 1993 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
| 1994 | StructuredList, StructuredIndex); |
| 1995 | } |
| 1996 | |
| 1997 | if (VerifyOnly) |
| 1998 | return; |
| 1999 | |
| 2000 | bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian(); |
| 2001 | const VectorType *T = Entity.getType()->castAs<VectorType>(); |
| 2002 | if (isBigEndian && (T->getVectorKind() == VectorKind::Neon || |
| 2003 | T->getVectorKind() == VectorKind::NeonPoly)) { |
| 2004 | // The ability to use vector initializer lists is a GNU vector extension |
| 2005 | // and is unrelated to the NEON intrinsics in arm_neon.h. On little |
| 2006 | // endian machines it works fine, however on big endian machines it |
| 2007 | // exhibits surprising behaviour: |
| 2008 | // |
| 2009 | // uint32x2_t x = {42, 64}; |
| 2010 | // return vget_lane_u32(x, 0); // Will return 64. |
| 2011 | // |
| 2012 | // Because of this, explicitly call out that it is non-portable. |
| 2013 | // |
| 2014 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
| 2015 | DiagID: diag::warn_neon_vector_initializer_non_portable); |
| 2016 | |
| 2017 | const char *typeCode; |
| 2018 | unsigned typeSize = SemaRef.Context.getTypeSize(T: elementType); |
| 2019 | |
| 2020 | if (elementType->isFloatingType()) |
| 2021 | typeCode = "f" ; |
| 2022 | else if (elementType->isSignedIntegerType()) |
| 2023 | typeCode = "s" ; |
| 2024 | else if (elementType->isUnsignedIntegerType()) |
| 2025 | typeCode = "u" ; |
| 2026 | else if (elementType->isMFloat8Type()) |
| 2027 | typeCode = "mf" ; |
| 2028 | else |
| 2029 | llvm_unreachable("Invalid element type!" ); |
| 2030 | |
| 2031 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
| 2032 | DiagID: SemaRef.Context.getTypeSize(T: VT) > 64 |
| 2033 | ? diag::note_neon_vector_initializer_non_portable_q |
| 2034 | : diag::note_neon_vector_initializer_non_portable) |
| 2035 | << typeCode << typeSize; |
| 2036 | } |
| 2037 | |
| 2038 | return; |
| 2039 | } |
| 2040 | |
| 2041 | InitializedEntity ElementEntity = |
| 2042 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
| 2043 | |
| 2044 | // OpenCL and HLSL initializers allow vectors to be constructed from vectors. |
| 2045 | for (unsigned i = 0; i < maxElements; ++i) { |
| 2046 | // Don't attempt to go past the end of the init list |
| 2047 | if (Index >= IList->getNumInits()) |
| 2048 | break; |
| 2049 | |
| 2050 | ElementEntity.setElementIndex(Index); |
| 2051 | |
| 2052 | QualType IType = IList->getInit(Init: Index)->getType(); |
| 2053 | if (!IType->isVectorType()) { |
| 2054 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
| 2055 | StructuredList, StructuredIndex); |
| 2056 | ++numEltsInit; |
| 2057 | } else { |
| 2058 | QualType VecType; |
| 2059 | const VectorType *IVT = IType->castAs<VectorType>(); |
| 2060 | unsigned numIElts = IVT->getNumElements(); |
| 2061 | |
| 2062 | if (IType->isExtVectorType()) |
| 2063 | VecType = SemaRef.Context.getExtVectorType(VectorType: elementType, NumElts: numIElts); |
| 2064 | else |
| 2065 | VecType = SemaRef.Context.getVectorType(VectorType: elementType, NumElts: numIElts, |
| 2066 | VecKind: IVT->getVectorKind()); |
| 2067 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: VecType, Index, |
| 2068 | StructuredList, StructuredIndex); |
| 2069 | numEltsInit += numIElts; |
| 2070 | } |
| 2071 | } |
| 2072 | |
| 2073 | // OpenCL and HLSL require all elements to be initialized. |
| 2074 | if (numEltsInit != maxElements) { |
| 2075 | if (!VerifyOnly) |
| 2076 | SemaRef.Diag(Loc: IList->getBeginLoc(), |
| 2077 | DiagID: diag::err_vector_incorrect_num_elements) |
| 2078 | << (numEltsInit < maxElements) << maxElements << numEltsInit |
| 2079 | << /*initialization*/ 0; |
| 2080 | hadError = true; |
| 2081 | } |
| 2082 | } |
| 2083 | |
| 2084 | /// Check if the type of a class element has an accessible destructor, and marks |
| 2085 | /// it referenced. Returns true if we shouldn't form a reference to the |
| 2086 | /// destructor. |
| 2087 | /// |
| 2088 | /// Aggregate initialization requires a class element's destructor be |
| 2089 | /// accessible per 11.6.1 [dcl.init.aggr]: |
| 2090 | /// |
| 2091 | /// The destructor for each element of class type is potentially invoked |
| 2092 | /// (15.4 [class.dtor]) from the context where the aggregate initialization |
| 2093 | /// occurs. |
| 2094 | static bool checkDestructorReference(QualType ElementType, SourceLocation Loc, |
| 2095 | Sema &SemaRef) { |
| 2096 | auto *CXXRD = ElementType->getAsCXXRecordDecl(); |
| 2097 | // Bail out on incomplete record types: a forward-declared class has no |
| 2098 | // destructor to look up, and `LookupDestructor` (via `LookupSpecialMember`) |
| 2099 | // asserts that the record is fully defined. Error recovery for init lists |
| 2100 | // of incomplete element types reaches this point even after the parser has |
| 2101 | // already diagnosed the incompleteness. |
| 2102 | if (!CXXRD || !CXXRD->hasDefinition()) |
| 2103 | return false; |
| 2104 | |
| 2105 | CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Class: CXXRD); |
| 2106 | if (!Destructor) |
| 2107 | return false; |
| 2108 | |
| 2109 | SemaRef.CheckDestructorAccess(Loc, Dtor: Destructor, |
| 2110 | PDiag: SemaRef.PDiag(DiagID: diag::err_access_dtor_temp) |
| 2111 | << ElementType); |
| 2112 | SemaRef.MarkFunctionReferenced(Loc, Func: Destructor); |
| 2113 | return SemaRef.DiagnoseUseOfDecl(D: Destructor, Locs: Loc); |
| 2114 | } |
| 2115 | |
| 2116 | static bool |
| 2117 | canInitializeArrayWithEmbedDataString(ArrayRef<Expr *> ExprList, |
| 2118 | const InitializedEntity &Entity, |
| 2119 | ASTContext &Context) { |
| 2120 | QualType InitType = Entity.getType(); |
| 2121 | const InitializedEntity *Parent = &Entity; |
| 2122 | |
| 2123 | while (Parent) { |
| 2124 | InitType = Parent->getType(); |
| 2125 | Parent = Parent->getParent(); |
| 2126 | } |
| 2127 | |
| 2128 | // Only one initializer, it's an embed and the types match; |
| 2129 | EmbedExpr *EE = |
| 2130 | ExprList.size() == 1 |
| 2131 | ? dyn_cast_if_present<EmbedExpr>(Val: ExprList[0]->IgnoreParens()) |
| 2132 | : nullptr; |
| 2133 | if (!EE) |
| 2134 | return false; |
| 2135 | |
| 2136 | if (InitType->isArrayType()) { |
| 2137 | const ArrayType *InitArrayType = InitType->getAsArrayTypeUnsafe(); |
| 2138 | StringLiteral *SL = EE->getDataStringLiteral(); |
| 2139 | return IsStringInit(Init: SL, AT: InitArrayType, Context) == SIF_None; |
| 2140 | } |
| 2141 | return false; |
| 2142 | } |
| 2143 | |
| 2144 | void InitListChecker::CheckArrayType(const InitializedEntity &Entity, |
| 2145 | InitListExpr *IList, QualType &DeclType, |
| 2146 | llvm::APSInt elementIndex, |
| 2147 | bool SubobjectIsDesignatorContext, |
| 2148 | unsigned &Index, |
| 2149 | InitListExpr *StructuredList, |
| 2150 | unsigned &StructuredIndex) { |
| 2151 | const ArrayType *arrayType = SemaRef.Context.getAsArrayType(T: DeclType); |
| 2152 | |
| 2153 | if (!VerifyOnly) { |
| 2154 | if (checkDestructorReference(ElementType: arrayType->getElementType(), |
| 2155 | Loc: IList->getEndLoc(), SemaRef)) { |
| 2156 | hadError = true; |
| 2157 | return; |
| 2158 | } |
| 2159 | } |
| 2160 | |
| 2161 | if (canInitializeArrayWithEmbedDataString(ExprList: IList->inits(), Entity, |
| 2162 | Context&: SemaRef.Context)) { |
| 2163 | EmbedExpr *Embed = cast<EmbedExpr>(Val: IList->inits()[0]); |
| 2164 | IList->setInit(Init: 0, expr: Embed->getDataStringLiteral()); |
| 2165 | } |
| 2166 | |
| 2167 | // Check for the special-case of initializing an array with a string. |
| 2168 | if (Index < IList->getNumInits()) { |
| 2169 | if (IsStringInit(Init: IList->getInit(Init: Index), AT: arrayType, Context&: SemaRef.Context) == |
| 2170 | SIF_None) { |
| 2171 | // We place the string literal directly into the resulting |
| 2172 | // initializer list. This is the only place where the structure |
| 2173 | // of the structured initializer list doesn't match exactly, |
| 2174 | // because doing so would involve allocating one character |
| 2175 | // constant for each string. |
| 2176 | // FIXME: Should we do these checks in verify-only mode too? |
| 2177 | if (!VerifyOnly) |
| 2178 | CheckStringInit( |
| 2179 | Str: IList->getInit(Init: Index), DeclT&: DeclType, AT: arrayType, S&: SemaRef, Entity, |
| 2180 | CheckC23ConstexprInit: SemaRef.getLangOpts().C23 && initializingConstexprVariable(Entity)); |
| 2181 | if (StructuredList) { |
| 2182 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
| 2183 | expr: IList->getInit(Init: Index)); |
| 2184 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: StructuredIndex); |
| 2185 | } |
| 2186 | ++Index; |
| 2187 | if (AggrDeductionCandidateParamTypes) |
| 2188 | AggrDeductionCandidateParamTypes->push_back(Elt: DeclType); |
| 2189 | return; |
| 2190 | } |
| 2191 | } |
| 2192 | if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(Val: arrayType)) { |
| 2193 | // Check for VLAs; in standard C it would be possible to check this |
| 2194 | // earlier, but I don't know where clang accepts VLAs (gcc accepts |
| 2195 | // them in all sorts of strange places). |
| 2196 | bool HasErr = IList->getNumInits() != 0 || SemaRef.getLangOpts().CPlusPlus; |
| 2197 | if (!VerifyOnly) { |
| 2198 | // C23 6.7.10p4: An entity of variable length array type shall not be |
| 2199 | // initialized except by an empty initializer. |
| 2200 | // |
| 2201 | // The C extension warnings are issued from ParseBraceInitializer() and |
| 2202 | // do not need to be issued here. However, we continue to issue an error |
| 2203 | // in the case there are initializers or we are compiling C++. We allow |
| 2204 | // use of VLAs in C++, but it's not clear we want to allow {} to zero |
| 2205 | // init a VLA in C++ in all cases (such as with non-trivial constructors). |
| 2206 | // FIXME: should we allow this construct in C++ when it makes sense to do |
| 2207 | // so? |
| 2208 | if (HasErr) |
| 2209 | SemaRef.Diag(Loc: VAT->getSizeExpr()->getBeginLoc(), |
| 2210 | DiagID: diag::err_variable_object_no_init) |
| 2211 | << VAT->getSizeExpr()->getSourceRange(); |
| 2212 | } |
| 2213 | hadError = HasErr; |
| 2214 | ++Index; |
| 2215 | ++StructuredIndex; |
| 2216 | return; |
| 2217 | } |
| 2218 | |
| 2219 | // We might know the maximum number of elements in advance. |
| 2220 | llvm::APSInt maxElements(elementIndex.getBitWidth(), |
| 2221 | elementIndex.isUnsigned()); |
| 2222 | bool maxElementsKnown = false; |
| 2223 | if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(Val: arrayType)) { |
| 2224 | maxElements = CAT->getSize(); |
| 2225 | elementIndex = elementIndex.extOrTrunc(width: maxElements.getBitWidth()); |
| 2226 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); |
| 2227 | maxElementsKnown = true; |
| 2228 | } |
| 2229 | |
| 2230 | QualType elementType = arrayType->getElementType(); |
| 2231 | while (Index < IList->getNumInits()) { |
| 2232 | Expr *Init = IList->getInit(Init: Index); |
| 2233 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) { |
| 2234 | // If we're not the subobject that matches up with the '{' for |
| 2235 | // the designator, we shouldn't be handling the |
| 2236 | // designator. Return immediately. |
| 2237 | if (!SubobjectIsDesignatorContext) |
| 2238 | return; |
| 2239 | |
| 2240 | // Handle this designated initializer. elementIndex will be |
| 2241 | // updated to be the next array element we'll initialize. |
| 2242 | if (CheckDesignatedInitializer(Entity, IList, DIE, DesigIdx: 0, |
| 2243 | CurrentObjectType&: DeclType, NextField: nullptr, NextElementIndex: &elementIndex, Index, |
| 2244 | StructuredList, StructuredIndex, FinishSubobjectInit: true, |
| 2245 | TopLevelObject: false)) { |
| 2246 | hadError = true; |
| 2247 | continue; |
| 2248 | } |
| 2249 | |
| 2250 | if (elementIndex.getBitWidth() > maxElements.getBitWidth()) |
| 2251 | maxElements = maxElements.extend(width: elementIndex.getBitWidth()); |
| 2252 | else if (elementIndex.getBitWidth() < maxElements.getBitWidth()) |
| 2253 | elementIndex = elementIndex.extend(width: maxElements.getBitWidth()); |
| 2254 | elementIndex.setIsUnsigned(maxElements.isUnsigned()); |
| 2255 | |
| 2256 | // If the array is of incomplete type, keep track of the number of |
| 2257 | // elements in the initializer. |
| 2258 | if (!maxElementsKnown && elementIndex > maxElements) |
| 2259 | maxElements = elementIndex; |
| 2260 | |
| 2261 | continue; |
| 2262 | } |
| 2263 | |
| 2264 | // If we know the maximum number of elements, and we've already |
| 2265 | // hit it, stop consuming elements in the initializer list. |
| 2266 | if (maxElementsKnown && elementIndex == maxElements) |
| 2267 | break; |
| 2268 | |
| 2269 | InitializedEntity ElementEntity = InitializedEntity::InitializeElement( |
| 2270 | Context&: SemaRef.Context, Index: StructuredIndex, Parent: Entity); |
| 2271 | ElementEntity.setElementIndex(elementIndex.getExtValue()); |
| 2272 | |
| 2273 | unsigned EmbedElementIndexBeforeInit = CurEmbedIndex; |
| 2274 | // Check this element. |
| 2275 | CheckSubElementType(Entity: ElementEntity, IList, ElemType: elementType, Index, |
| 2276 | StructuredList, StructuredIndex); |
| 2277 | ++elementIndex; |
| 2278 | if ((CurEmbed || isa<EmbedExpr>(Val: Init)) && elementType->isScalarType()) { |
| 2279 | if (CurEmbed) { |
| 2280 | elementIndex = |
| 2281 | elementIndex + CurEmbedIndex - EmbedElementIndexBeforeInit - 1; |
| 2282 | } else { |
| 2283 | auto Embed = cast<EmbedExpr>(Val: Init); |
| 2284 | elementIndex = elementIndex + Embed->getDataElementCount() - |
| 2285 | EmbedElementIndexBeforeInit - 1; |
| 2286 | } |
| 2287 | } |
| 2288 | |
| 2289 | // If the array is of incomplete type, keep track of the number of |
| 2290 | // elements in the initializer. |
| 2291 | if (!maxElementsKnown && elementIndex > maxElements) |
| 2292 | maxElements = elementIndex; |
| 2293 | } |
| 2294 | if (!hadError && DeclType->isIncompleteArrayType() && !VerifyOnly) { |
| 2295 | // If this is an incomplete array type, the actual type needs to |
| 2296 | // be calculated here. |
| 2297 | llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned()); |
| 2298 | if (maxElements == Zero && !Entity.isVariableLengthArrayNew()) { |
| 2299 | // Sizing an array implicitly to zero is not allowed by ISO C, |
| 2300 | // but is supported by GNU. |
| 2301 | SemaRef.Diag(Loc: IList->getBeginLoc(), DiagID: diag::ext_typecheck_zero_array_size); |
| 2302 | } |
| 2303 | |
| 2304 | DeclType = SemaRef.Context.getConstantArrayType( |
| 2305 | EltTy: elementType, ArySize: maxElements, SizeExpr: nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 2306 | } |
| 2307 | if (!hadError) { |
| 2308 | // If there are any members of the array that get value-initialized, check |
| 2309 | // that is possible. That happens if we know the bound and don't have |
| 2310 | // enough elements, or if we're performing an array new with an unknown |
| 2311 | // bound. |
| 2312 | if ((maxElementsKnown && elementIndex < maxElements) || |
| 2313 | Entity.isVariableLengthArrayNew()) |
| 2314 | CheckEmptyInitializable( |
| 2315 | Entity: InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity), |
| 2316 | Loc: IList->getEndLoc()); |
| 2317 | } |
| 2318 | } |
| 2319 | |
| 2320 | bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity, |
| 2321 | Expr *InitExpr, |
| 2322 | FieldDecl *Field, |
| 2323 | bool TopLevelObject) { |
| 2324 | // Handle GNU flexible array initializers. |
| 2325 | unsigned FlexArrayDiag; |
| 2326 | if (isa<InitListExpr>(Val: InitExpr) && |
| 2327 | cast<InitListExpr>(Val: InitExpr)->getNumInits() == 0) { |
| 2328 | // Empty flexible array init always allowed as an extension |
| 2329 | FlexArrayDiag = diag::ext_flexible_array_init; |
| 2330 | } else if (!TopLevelObject) { |
| 2331 | // Disallow flexible array init on non-top-level object |
| 2332 | FlexArrayDiag = diag::err_flexible_array_init; |
| 2333 | } else if (Entity.getKind() != InitializedEntity::EK_Variable) { |
| 2334 | // Disallow flexible array init on anything which is not a variable. |
| 2335 | FlexArrayDiag = diag::err_flexible_array_init; |
| 2336 | } else if (cast<VarDecl>(Val: Entity.getDecl())->hasLocalStorage()) { |
| 2337 | // Disallow flexible array init on local variables. |
| 2338 | FlexArrayDiag = diag::err_flexible_array_init; |
| 2339 | } else { |
| 2340 | // Allow other cases. |
| 2341 | FlexArrayDiag = diag::ext_flexible_array_init; |
| 2342 | } |
| 2343 | |
| 2344 | if (!VerifyOnly) { |
| 2345 | SemaRef.Diag(Loc: InitExpr->getBeginLoc(), DiagID: FlexArrayDiag) |
| 2346 | << InitExpr->getBeginLoc(); |
| 2347 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member) |
| 2348 | << Field; |
| 2349 | } |
| 2350 | |
| 2351 | return FlexArrayDiag != diag::ext_flexible_array_init; |
| 2352 | } |
| 2353 | |
| 2354 | static bool isInitializedStructuredList(const InitListExpr *StructuredList) { |
| 2355 | return StructuredList && StructuredList->getNumInits() == 1U; |
| 2356 | } |
| 2357 | |
| 2358 | void InitListChecker::CheckStructUnionTypes( |
| 2359 | const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType, |
| 2360 | CXXRecordDecl::base_class_const_range Bases, RecordDecl::field_iterator Field, |
| 2361 | bool SubobjectIsDesignatorContext, unsigned &Index, |
| 2362 | InitListExpr *StructuredList, unsigned &StructuredIndex, |
| 2363 | bool TopLevelObject) { |
| 2364 | const RecordDecl *RD = DeclType->getAsRecordDecl(); |
| 2365 | |
| 2366 | // If the record is invalid, some of it's members are invalid. To avoid |
| 2367 | // confusion, we forgo checking the initializer for the entire record. |
| 2368 | if (RD->isInvalidDecl()) { |
| 2369 | // Assume it was supposed to consume a single initializer. |
| 2370 | ++Index; |
| 2371 | hadError = true; |
| 2372 | return; |
| 2373 | } |
| 2374 | |
| 2375 | if (RD->isUnion() && IList->getNumInits() == 0) { |
| 2376 | if (!VerifyOnly) |
| 2377 | for (FieldDecl *FD : RD->fields()) { |
| 2378 | QualType ET = SemaRef.Context.getBaseElementType(QT: FD->getType()); |
| 2379 | if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) { |
| 2380 | hadError = true; |
| 2381 | return; |
| 2382 | } |
| 2383 | } |
| 2384 | |
| 2385 | // If there's a default initializer, use it. |
| 2386 | if (isa<CXXRecordDecl>(Val: RD) && |
| 2387 | cast<CXXRecordDecl>(Val: RD)->hasInClassInitializer()) { |
| 2388 | if (!StructuredList) |
| 2389 | return; |
| 2390 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); |
| 2391 | Field != FieldEnd; ++Field) { |
| 2392 | if (Field->hasInClassInitializer() || |
| 2393 | (Field->isAnonymousStructOrUnion() && |
| 2394 | Field->getType() |
| 2395 | ->castAsCXXRecordDecl() |
| 2396 | ->hasInClassInitializer())) { |
| 2397 | StructuredList->setInitializedFieldInUnion(*Field); |
| 2398 | // FIXME: Actually build a CXXDefaultInitExpr? |
| 2399 | return; |
| 2400 | } |
| 2401 | } |
| 2402 | llvm_unreachable("Couldn't find in-class initializer" ); |
| 2403 | } |
| 2404 | |
| 2405 | // Value-initialize the first member of the union that isn't an unnamed |
| 2406 | // bitfield. |
| 2407 | for (RecordDecl::field_iterator FieldEnd = RD->field_end(); |
| 2408 | Field != FieldEnd; ++Field) { |
| 2409 | if (!Field->isUnnamedBitField()) { |
| 2410 | CheckEmptyInitializable( |
| 2411 | Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity), |
| 2412 | Loc: IList->getEndLoc()); |
| 2413 | if (StructuredList) |
| 2414 | StructuredList->setInitializedFieldInUnion(*Field); |
| 2415 | break; |
| 2416 | } |
| 2417 | } |
| 2418 | return; |
| 2419 | } |
| 2420 | |
| 2421 | bool InitializedSomething = false; |
| 2422 | |
| 2423 | // If we have any base classes, they are initialized prior to the fields. |
| 2424 | for (auto I = Bases.begin(), E = Bases.end(); I != E; ++I) { |
| 2425 | auto &Base = *I; |
| 2426 | Expr *Init = Index < IList->getNumInits() ? IList->getInit(Init: Index) : nullptr; |
| 2427 | |
| 2428 | // Designated inits always initialize fields, so if we see one, all |
| 2429 | // remaining base classes have no explicit initializer. |
| 2430 | if (isa_and_nonnull<DesignatedInitExpr>(Val: Init)) |
| 2431 | Init = nullptr; |
| 2432 | |
| 2433 | // C++ [over.match.class.deduct]p1.6: |
| 2434 | // each non-trailing aggregate element that is a pack expansion is assumed |
| 2435 | // to correspond to no elements of the initializer list, and (1.7) a |
| 2436 | // trailing aggregate element that is a pack expansion is assumed to |
| 2437 | // correspond to all remaining elements of the initializer list (if any). |
| 2438 | |
| 2439 | // C++ [over.match.class.deduct]p1.9: |
| 2440 | // ... except that additional parameter packs of the form P_j... are |
| 2441 | // inserted into the parameter list in their original aggregate element |
| 2442 | // position corresponding to each non-trailing aggregate element of |
| 2443 | // type P_j that was skipped because it was a parameter pack, and the |
| 2444 | // trailing sequence of parameters corresponding to a trailing |
| 2445 | // aggregate element that is a pack expansion (if any) is replaced |
| 2446 | // by a single parameter of the form T_n.... |
| 2447 | if (AggrDeductionCandidateParamTypes && Base.isPackExpansion()) { |
| 2448 | AggrDeductionCandidateParamTypes->push_back( |
| 2449 | Elt: SemaRef.Context.getPackExpansionType(Pattern: Base.getType(), NumExpansions: std::nullopt)); |
| 2450 | |
| 2451 | // Trailing pack expansion |
| 2452 | if (I + 1 == E && RD->field_empty()) { |
| 2453 | if (Index < IList->getNumInits()) |
| 2454 | Index = IList->getNumInits(); |
| 2455 | return; |
| 2456 | } |
| 2457 | |
| 2458 | continue; |
| 2459 | } |
| 2460 | |
| 2461 | SourceLocation InitLoc = Init ? Init->getBeginLoc() : IList->getEndLoc(); |
| 2462 | InitializedEntity BaseEntity = InitializedEntity::InitializeBase( |
| 2463 | Context&: SemaRef.Context, Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity); |
| 2464 | if (Init) { |
| 2465 | CheckSubElementType(Entity: BaseEntity, IList, ElemType: Base.getType(), Index, |
| 2466 | StructuredList, StructuredIndex); |
| 2467 | InitializedSomething = true; |
| 2468 | } else { |
| 2469 | CheckEmptyInitializable(Entity: BaseEntity, Loc: InitLoc); |
| 2470 | } |
| 2471 | |
| 2472 | if (!VerifyOnly) |
| 2473 | if (checkDestructorReference(ElementType: Base.getType(), Loc: InitLoc, SemaRef)) { |
| 2474 | hadError = true; |
| 2475 | return; |
| 2476 | } |
| 2477 | } |
| 2478 | |
| 2479 | // If structDecl is a forward declaration, this loop won't do |
| 2480 | // anything except look at designated initializers; That's okay, |
| 2481 | // because an error should get printed out elsewhere. It might be |
| 2482 | // worthwhile to skip over the rest of the initializer, though. |
| 2483 | RecordDecl::field_iterator FieldEnd = RD->field_end(); |
| 2484 | size_t NumRecordDecls = llvm::count_if(Range: RD->decls(), P: [&](const Decl *D) { |
| 2485 | return isa<FieldDecl>(Val: D) || isa<RecordDecl>(Val: D); |
| 2486 | }); |
| 2487 | bool HasDesignatedInit = false; |
| 2488 | |
| 2489 | llvm::SmallPtrSet<FieldDecl *, 4> InitializedFields; |
| 2490 | |
| 2491 | while (Index < IList->getNumInits()) { |
| 2492 | Expr *Init = IList->getInit(Init: Index); |
| 2493 | SourceLocation InitLoc = Init->getBeginLoc(); |
| 2494 | |
| 2495 | if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Val: Init)) { |
| 2496 | // If we're not the subobject that matches up with the '{' for |
| 2497 | // the designator, we shouldn't be handling the |
| 2498 | // designator. Return immediately. |
| 2499 | if (!SubobjectIsDesignatorContext) |
| 2500 | return; |
| 2501 | |
| 2502 | HasDesignatedInit = true; |
| 2503 | |
| 2504 | // Handle this designated initializer. Field will be updated to |
| 2505 | // the next field that we'll be initializing. |
| 2506 | bool DesignatedInitFailed = CheckDesignatedInitializer( |
| 2507 | Entity, IList, DIE, DesigIdx: 0, CurrentObjectType&: DeclType, NextField: &Field, NextElementIndex: nullptr, Index, |
| 2508 | StructuredList, StructuredIndex, FinishSubobjectInit: true, TopLevelObject); |
| 2509 | if (DesignatedInitFailed) |
| 2510 | hadError = true; |
| 2511 | |
| 2512 | // Find the field named by the designated initializer. |
| 2513 | DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: 0); |
| 2514 | if (!VerifyOnly && D->isFieldDesignator()) { |
| 2515 | FieldDecl *F = D->getFieldDecl(); |
| 2516 | InitializedFields.insert(Ptr: F); |
| 2517 | if (!DesignatedInitFailed) { |
| 2518 | QualType ET = SemaRef.Context.getBaseElementType(QT: F->getType()); |
| 2519 | if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) { |
| 2520 | hadError = true; |
| 2521 | return; |
| 2522 | } |
| 2523 | } |
| 2524 | } |
| 2525 | |
| 2526 | InitializedSomething = true; |
| 2527 | continue; |
| 2528 | } |
| 2529 | |
| 2530 | // Check if this is an initializer of forms: |
| 2531 | // |
| 2532 | // struct foo f = {}; |
| 2533 | // struct foo g = {0}; |
| 2534 | // |
| 2535 | // These are okay for randomized structures. [C99 6.7.8p19] |
| 2536 | // |
| 2537 | // Also, if there is only one element in the structure, we allow something |
| 2538 | // like this, because it's really not randomized in the traditional sense. |
| 2539 | // |
| 2540 | // struct foo h = {bar}; |
| 2541 | auto IsZeroInitializer = [&](const Expr *I) { |
| 2542 | if (IList->getNumInits() == 1) { |
| 2543 | if (NumRecordDecls == 1) |
| 2544 | return true; |
| 2545 | if (const auto *IL = dyn_cast<IntegerLiteral>(Val: I)) |
| 2546 | return IL->getValue().isZero(); |
| 2547 | } |
| 2548 | return false; |
| 2549 | }; |
| 2550 | |
| 2551 | // Don't allow non-designated initializers on randomized structures. |
| 2552 | if (RD->isRandomized() && !IsZeroInitializer(Init)) { |
| 2553 | if (!VerifyOnly) |
| 2554 | SemaRef.Diag(Loc: InitLoc, DiagID: diag::err_non_designated_init_used); |
| 2555 | hadError = true; |
| 2556 | break; |
| 2557 | } |
| 2558 | |
| 2559 | if (Field == FieldEnd) { |
| 2560 | // We've run out of fields. We're done. |
| 2561 | break; |
| 2562 | } |
| 2563 | |
| 2564 | // We've already initialized a member of a union. We can stop entirely. |
| 2565 | if (InitializedSomething && RD->isUnion()) |
| 2566 | return; |
| 2567 | |
| 2568 | // Stop if we've hit a flexible array member. |
| 2569 | if (Field->getType()->isIncompleteArrayType()) |
| 2570 | break; |
| 2571 | |
| 2572 | if (Field->isUnnamedBitField()) { |
| 2573 | // Don't initialize unnamed bitfields, e.g. "int : 20;" |
| 2574 | ++Field; |
| 2575 | continue; |
| 2576 | } |
| 2577 | |
| 2578 | // Make sure we can use this declaration. |
| 2579 | bool InvalidUse; |
| 2580 | if (VerifyOnly) |
| 2581 | InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid); |
| 2582 | else |
| 2583 | InvalidUse = SemaRef.DiagnoseUseOfDecl( |
| 2584 | D: *Field, Locs: IList->getInit(Init: Index)->getBeginLoc()); |
| 2585 | if (InvalidUse) { |
| 2586 | ++Index; |
| 2587 | ++Field; |
| 2588 | hadError = true; |
| 2589 | continue; |
| 2590 | } |
| 2591 | |
| 2592 | if (!VerifyOnly) { |
| 2593 | QualType ET = SemaRef.Context.getBaseElementType(QT: Field->getType()); |
| 2594 | if (checkDestructorReference(ElementType: ET, Loc: InitLoc, SemaRef)) { |
| 2595 | hadError = true; |
| 2596 | return; |
| 2597 | } |
| 2598 | } |
| 2599 | |
| 2600 | InitializedEntity MemberEntity = |
| 2601 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
| 2602 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
| 2603 | StructuredList, StructuredIndex); |
| 2604 | InitializedSomething = true; |
| 2605 | InitializedFields.insert(Ptr: *Field); |
| 2606 | if (RD->isUnion() && isInitializedStructuredList(StructuredList)) { |
| 2607 | // Initialize the first field within the union. |
| 2608 | StructuredList->setInitializedFieldInUnion(*Field); |
| 2609 | } |
| 2610 | |
| 2611 | ++Field; |
| 2612 | } |
| 2613 | |
| 2614 | // Emit warnings for missing struct field initializers. |
| 2615 | // This check is disabled for designated initializers in C. |
| 2616 | // This matches gcc behaviour. |
| 2617 | bool IsCDesignatedInitializer = |
| 2618 | HasDesignatedInit && !SemaRef.getLangOpts().CPlusPlus; |
| 2619 | if (!VerifyOnly && InitializedSomething && !RD->isUnion() && |
| 2620 | !IList->isIdiomaticZeroInitializer(LangOpts: SemaRef.getLangOpts()) && |
| 2621 | !IsCDesignatedInitializer) { |
| 2622 | // It is possible we have one or more unnamed bitfields remaining. |
| 2623 | // Find first (if any) named field and emit warning. |
| 2624 | for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin() |
| 2625 | : Field, |
| 2626 | end = RD->field_end(); |
| 2627 | it != end; ++it) { |
| 2628 | if (HasDesignatedInit && InitializedFields.count(Ptr: *it)) |
| 2629 | continue; |
| 2630 | |
| 2631 | if (!it->isUnnamedBitField() && !it->hasInClassInitializer() && |
| 2632 | !it->getType()->isIncompleteArrayType()) { |
| 2633 | auto Diag = HasDesignatedInit |
| 2634 | ? diag::warn_missing_designated_field_initializers |
| 2635 | : diag::warn_missing_field_initializers; |
| 2636 | SemaRef.Diag(Loc: IList->getSourceRange().getEnd(), DiagID: Diag) << *it; |
| 2637 | break; |
| 2638 | } |
| 2639 | } |
| 2640 | } |
| 2641 | |
| 2642 | // Check that any remaining fields can be value-initialized if we're not |
| 2643 | // building a structured list. (If we are, we'll check this later.) |
| 2644 | if (!StructuredList && Field != FieldEnd && !RD->isUnion() && |
| 2645 | !Field->getType()->isIncompleteArrayType()) { |
| 2646 | for (; Field != FieldEnd && !hadError; ++Field) { |
| 2647 | if (!Field->isUnnamedBitField() && !Field->hasInClassInitializer()) |
| 2648 | CheckEmptyInitializable( |
| 2649 | Entity: InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity), |
| 2650 | Loc: IList->getEndLoc()); |
| 2651 | } |
| 2652 | } |
| 2653 | |
| 2654 | // Check that the types of the remaining fields have accessible destructors. |
| 2655 | if (!VerifyOnly) { |
| 2656 | // If the initializer expression has a designated initializer, check the |
| 2657 | // elements for which a designated initializer is not provided too. |
| 2658 | RecordDecl::field_iterator I = HasDesignatedInit ? RD->field_begin() |
| 2659 | : Field; |
| 2660 | for (RecordDecl::field_iterator E = RD->field_end(); I != E; ++I) { |
| 2661 | QualType ET = SemaRef.Context.getBaseElementType(QT: I->getType()); |
| 2662 | if (checkDestructorReference(ElementType: ET, Loc: IList->getEndLoc(), SemaRef)) { |
| 2663 | hadError = true; |
| 2664 | return; |
| 2665 | } |
| 2666 | } |
| 2667 | } |
| 2668 | |
| 2669 | if (Field == FieldEnd || !Field->getType()->isIncompleteArrayType() || |
| 2670 | Index >= IList->getNumInits()) |
| 2671 | return; |
| 2672 | |
| 2673 | if (CheckFlexibleArrayInit(Entity, InitExpr: IList->getInit(Init: Index), Field: *Field, |
| 2674 | TopLevelObject)) { |
| 2675 | hadError = true; |
| 2676 | ++Index; |
| 2677 | return; |
| 2678 | } |
| 2679 | |
| 2680 | InitializedEntity MemberEntity = |
| 2681 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
| 2682 | |
| 2683 | if (isa<InitListExpr>(Val: IList->getInit(Init: Index)) || |
| 2684 | AggrDeductionCandidateParamTypes) |
| 2685 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
| 2686 | StructuredList, StructuredIndex); |
| 2687 | else |
| 2688 | CheckImplicitInitList(Entity: MemberEntity, ParentIList: IList, T: Field->getType(), Index, |
| 2689 | StructuredList, StructuredIndex); |
| 2690 | |
| 2691 | if (RD->isUnion() && isInitializedStructuredList(StructuredList)) { |
| 2692 | // Initialize the first field within the union. |
| 2693 | StructuredList->setInitializedFieldInUnion(*Field); |
| 2694 | } |
| 2695 | } |
| 2696 | |
| 2697 | /// Expand a field designator that refers to a member of an |
| 2698 | /// anonymous struct or union into a series of field designators that |
| 2699 | /// refers to the field within the appropriate subobject. |
| 2700 | /// |
| 2701 | static void ExpandAnonymousFieldDesignator(Sema &SemaRef, |
| 2702 | DesignatedInitExpr *DIE, |
| 2703 | unsigned DesigIdx, |
| 2704 | IndirectFieldDecl *IndirectField) { |
| 2705 | typedef DesignatedInitExpr::Designator Designator; |
| 2706 | |
| 2707 | // Build the replacement designators. |
| 2708 | SmallVector<Designator, 4> Replacements; |
| 2709 | for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(), |
| 2710 | PE = IndirectField->chain_end(); PI != PE; ++PI) { |
| 2711 | if (PI + 1 == PE) |
| 2712 | Replacements.push_back(Elt: Designator::CreateFieldDesignator( |
| 2713 | FieldName: (IdentifierInfo *)nullptr, DotLoc: DIE->getDesignator(Idx: DesigIdx)->getDotLoc(), |
| 2714 | FieldLoc: DIE->getDesignator(Idx: DesigIdx)->getFieldLoc())); |
| 2715 | else |
| 2716 | Replacements.push_back(Elt: Designator::CreateFieldDesignator( |
| 2717 | FieldName: (IdentifierInfo *)nullptr, DotLoc: SourceLocation(), FieldLoc: SourceLocation())); |
| 2718 | assert(isa<FieldDecl>(*PI)); |
| 2719 | Replacements.back().setFieldDecl(cast<FieldDecl>(Val: *PI)); |
| 2720 | } |
| 2721 | |
| 2722 | // Expand the current designator into the set of replacement |
| 2723 | // designators, so we have a full subobject path down to where the |
| 2724 | // member of the anonymous struct/union is actually stored. |
| 2725 | DIE->ExpandDesignator(C: SemaRef.Context, Idx: DesigIdx, First: &Replacements[0], |
| 2726 | Last: &Replacements[0] + Replacements.size()); |
| 2727 | } |
| 2728 | |
| 2729 | static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef, |
| 2730 | DesignatedInitExpr *DIE) { |
| 2731 | unsigned NumIndexExprs = DIE->getNumSubExprs() - 1; |
| 2732 | SmallVector<Expr*, 4> IndexExprs(NumIndexExprs); |
| 2733 | for (unsigned I = 0; I < NumIndexExprs; ++I) |
| 2734 | IndexExprs[I] = DIE->getSubExpr(Idx: I + 1); |
| 2735 | return DesignatedInitExpr::Create(C: SemaRef.Context, Designators: DIE->designators(), |
| 2736 | IndexExprs, |
| 2737 | EqualOrColonLoc: DIE->getEqualOrColonLoc(), |
| 2738 | GNUSyntax: DIE->usesGNUSyntax(), Init: DIE->getInit()); |
| 2739 | } |
| 2740 | |
| 2741 | namespace { |
| 2742 | |
| 2743 | // Callback to only accept typo corrections that are for field members of |
| 2744 | // the given struct or union. |
| 2745 | class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback { |
| 2746 | public: |
| 2747 | explicit FieldInitializerValidatorCCC(const RecordDecl *RD) |
| 2748 | : Record(RD) {} |
| 2749 | |
| 2750 | bool ValidateCandidate(const TypoCorrection &candidate) override { |
| 2751 | FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>(); |
| 2752 | return FD && FD->getDeclContext()->getRedeclContext()->Equals(DC: Record); |
| 2753 | } |
| 2754 | |
| 2755 | std::unique_ptr<CorrectionCandidateCallback> clone() override { |
| 2756 | return std::make_unique<FieldInitializerValidatorCCC>(args&: *this); |
| 2757 | } |
| 2758 | |
| 2759 | private: |
| 2760 | const RecordDecl *Record; |
| 2761 | }; |
| 2762 | |
| 2763 | } // end anonymous namespace |
| 2764 | |
| 2765 | /// Check the well-formedness of a C99 designated initializer. |
| 2766 | /// |
| 2767 | /// Determines whether the designated initializer @p DIE, which |
| 2768 | /// resides at the given @p Index within the initializer list @p |
| 2769 | /// IList, is well-formed for a current object of type @p DeclType |
| 2770 | /// (C99 6.7.8). The actual subobject that this designator refers to |
| 2771 | /// within the current subobject is returned in either |
| 2772 | /// @p NextField or @p NextElementIndex (whichever is appropriate). |
| 2773 | /// |
| 2774 | /// @param IList The initializer list in which this designated |
| 2775 | /// initializer occurs. |
| 2776 | /// |
| 2777 | /// @param DIE The designated initializer expression. |
| 2778 | /// |
| 2779 | /// @param DesigIdx The index of the current designator. |
| 2780 | /// |
| 2781 | /// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17), |
| 2782 | /// into which the designation in @p DIE should refer. |
| 2783 | /// |
| 2784 | /// @param NextField If non-NULL and the first designator in @p DIE is |
| 2785 | /// a field, this will be set to the field declaration corresponding |
| 2786 | /// to the field named by the designator. On input, this is expected to be |
| 2787 | /// the next field that would be initialized in the absence of designation, |
| 2788 | /// if the complete object being initialized is a struct. |
| 2789 | /// |
| 2790 | /// @param NextElementIndex If non-NULL and the first designator in @p |
| 2791 | /// DIE is an array designator or GNU array-range designator, this |
| 2792 | /// will be set to the last index initialized by this designator. |
| 2793 | /// |
| 2794 | /// @param Index Index into @p IList where the designated initializer |
| 2795 | /// @p DIE occurs. |
| 2796 | /// |
| 2797 | /// @param StructuredList The initializer list expression that |
| 2798 | /// describes all of the subobject initializers in the order they'll |
| 2799 | /// actually be initialized. |
| 2800 | /// |
| 2801 | /// @returns true if there was an error, false otherwise. |
| 2802 | bool |
| 2803 | InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity, |
| 2804 | InitListExpr *IList, |
| 2805 | DesignatedInitExpr *DIE, |
| 2806 | unsigned DesigIdx, |
| 2807 | QualType &CurrentObjectType, |
| 2808 | RecordDecl::field_iterator *NextField, |
| 2809 | llvm::APSInt *NextElementIndex, |
| 2810 | unsigned &Index, |
| 2811 | InitListExpr *StructuredList, |
| 2812 | unsigned &StructuredIndex, |
| 2813 | bool FinishSubobjectInit, |
| 2814 | bool TopLevelObject) { |
| 2815 | if (DesigIdx == DIE->size()) { |
| 2816 | // C++20 designated initialization can result in direct-list-initialization |
| 2817 | // of the designated subobject. This is the only way that we can end up |
| 2818 | // performing direct initialization as part of aggregate initialization, so |
| 2819 | // it needs special handling. |
| 2820 | if (DIE->isDirectInit()) { |
| 2821 | Expr *Init = DIE->getInit(); |
| 2822 | assert(isa<InitListExpr>(Init) && |
| 2823 | "designator result in direct non-list initialization?" ); |
| 2824 | InitializationKind Kind = InitializationKind::CreateDirectList( |
| 2825 | InitLoc: DIE->getBeginLoc(), LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc()); |
| 2826 | InitializationSequence Seq(SemaRef, Entity, Kind, Init, |
| 2827 | /*TopLevelOfInitList*/ true); |
| 2828 | if (StructuredList) { |
| 2829 | ExprResult Result = VerifyOnly |
| 2830 | ? getDummyInit() |
| 2831 | : Seq.Perform(S&: SemaRef, Entity, Kind, Args: Init); |
| 2832 | UpdateStructuredListElement(StructuredList, StructuredIndex, |
| 2833 | expr: Result.get()); |
| 2834 | } |
| 2835 | ++Index; |
| 2836 | if (AggrDeductionCandidateParamTypes) |
| 2837 | AggrDeductionCandidateParamTypes->push_back(Elt: CurrentObjectType); |
| 2838 | return !Seq; |
| 2839 | } |
| 2840 | |
| 2841 | // Check the actual initialization for the designated object type. |
| 2842 | bool prevHadError = hadError; |
| 2843 | |
| 2844 | // Temporarily remove the designator expression from the |
| 2845 | // initializer list that the child calls see, so that we don't try |
| 2846 | // to re-process the designator. |
| 2847 | unsigned OldIndex = Index; |
| 2848 | auto *OldDIE = |
| 2849 | dyn_cast_if_present<DesignatedInitExpr>(Val: IList->getInit(Init: OldIndex)); |
| 2850 | if (!OldDIE) |
| 2851 | OldDIE = DIE; |
| 2852 | IList->setInit(Init: OldIndex, expr: OldDIE->getInit()); |
| 2853 | |
| 2854 | CheckSubElementType(Entity, IList, ElemType: CurrentObjectType, Index, StructuredList, |
| 2855 | StructuredIndex, /*DirectlyDesignated=*/true); |
| 2856 | |
| 2857 | // Restore the designated initializer expression in the syntactic |
| 2858 | // form of the initializer list. |
| 2859 | if (IList->getInit(Init: OldIndex) != OldDIE->getInit()) |
| 2860 | OldDIE->setInit(IList->getInit(Init: OldIndex)); |
| 2861 | IList->setInit(Init: OldIndex, expr: OldDIE); |
| 2862 | |
| 2863 | return hadError && !prevHadError; |
| 2864 | } |
| 2865 | |
| 2866 | DesignatedInitExpr::Designator *D = DIE->getDesignator(Idx: DesigIdx); |
| 2867 | bool IsFirstDesignator = (DesigIdx == 0); |
| 2868 | if (IsFirstDesignator ? FullyStructuredList : StructuredList) { |
| 2869 | // Determine the structural initializer list that corresponds to the |
| 2870 | // current subobject. |
| 2871 | if (IsFirstDesignator) |
| 2872 | StructuredList = FullyStructuredList; |
| 2873 | else { |
| 2874 | Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ? |
| 2875 | StructuredList->getInit(Init: StructuredIndex) : nullptr; |
| 2876 | if (!ExistingInit && StructuredList->hasArrayFiller()) |
| 2877 | ExistingInit = StructuredList->getArrayFiller(); |
| 2878 | |
| 2879 | if (!ExistingInit) |
| 2880 | StructuredList = getStructuredSubobjectInit( |
| 2881 | IList, Index, CurrentObjectType, StructuredList, StructuredIndex, |
| 2882 | InitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc())); |
| 2883 | else if (InitListExpr *Result = dyn_cast<InitListExpr>(Val: ExistingInit)) |
| 2884 | StructuredList = Result; |
| 2885 | else { |
| 2886 | // We are creating an initializer list that initializes the |
| 2887 | // subobjects of the current object, but there was already an |
| 2888 | // initialization that completely initialized the current |
| 2889 | // subobject, e.g., by a compound literal: |
| 2890 | // |
| 2891 | // struct X { int a, b; }; |
| 2892 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; |
| 2893 | // |
| 2894 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, |
| 2895 | // designated initializer re-initializes only its current object |
| 2896 | // subobject [0].b. |
| 2897 | diagnoseInitOverride(OldInit: ExistingInit, |
| 2898 | NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()), |
| 2899 | /*UnionOverride=*/false, |
| 2900 | /*FullyOverwritten=*/false); |
| 2901 | |
| 2902 | if (!VerifyOnly) { |
| 2903 | if (DesignatedInitUpdateExpr *E = |
| 2904 | dyn_cast<DesignatedInitUpdateExpr>(Val: ExistingInit)) |
| 2905 | StructuredList = E->getUpdater(); |
| 2906 | else { |
| 2907 | DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context) |
| 2908 | DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(), |
| 2909 | ExistingInit, DIE->getEndLoc()); |
| 2910 | StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: DIUE); |
| 2911 | StructuredList = DIUE->getUpdater(); |
| 2912 | } |
| 2913 | } else { |
| 2914 | // We don't need to track the structured representation of a |
| 2915 | // designated init update of an already-fully-initialized object in |
| 2916 | // verify-only mode. The only reason we would need the structure is |
| 2917 | // to determine where the uninitialized "holes" are, and in this |
| 2918 | // case, we know there aren't any and we can't introduce any. |
| 2919 | StructuredList = nullptr; |
| 2920 | } |
| 2921 | } |
| 2922 | } |
| 2923 | } |
| 2924 | |
| 2925 | if (D->isFieldDesignator()) { |
| 2926 | // C99 6.7.8p7: |
| 2927 | // |
| 2928 | // If a designator has the form |
| 2929 | // |
| 2930 | // . identifier |
| 2931 | // |
| 2932 | // then the current object (defined below) shall have |
| 2933 | // structure or union type and the identifier shall be the |
| 2934 | // name of a member of that type. |
| 2935 | RecordDecl *RD = CurrentObjectType->getAsRecordDecl(); |
| 2936 | if (!RD) { |
| 2937 | SourceLocation Loc = D->getDotLoc(); |
| 2938 | if (Loc.isInvalid()) |
| 2939 | Loc = D->getFieldLoc(); |
| 2940 | if (!VerifyOnly) |
| 2941 | SemaRef.Diag(Loc, DiagID: diag::err_field_designator_non_aggr) |
| 2942 | << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType; |
| 2943 | ++Index; |
| 2944 | return true; |
| 2945 | } |
| 2946 | |
| 2947 | FieldDecl *KnownField = D->getFieldDecl(); |
| 2948 | if (!KnownField) { |
| 2949 | const IdentifierInfo *FieldName = D->getFieldName(); |
| 2950 | ValueDecl *VD = SemaRef.tryLookupUnambiguousFieldDecl(ClassDecl: RD, MemberOrBase: FieldName); |
| 2951 | if (auto *FD = dyn_cast_if_present<FieldDecl>(Val: VD)) { |
| 2952 | KnownField = FD; |
| 2953 | } else if (auto *IFD = dyn_cast_if_present<IndirectFieldDecl>(Val: VD)) { |
| 2954 | // In verify mode, don't modify the original. |
| 2955 | if (VerifyOnly) |
| 2956 | DIE = CloneDesignatedInitExpr(SemaRef, DIE); |
| 2957 | ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IndirectField: IFD); |
| 2958 | D = DIE->getDesignator(Idx: DesigIdx); |
| 2959 | KnownField = cast<FieldDecl>(Val: *IFD->chain_begin()); |
| 2960 | } |
| 2961 | if (!KnownField) { |
| 2962 | if (VerifyOnly) { |
| 2963 | ++Index; |
| 2964 | return true; // No typo correction when just trying this out. |
| 2965 | } |
| 2966 | |
| 2967 | // We found a placeholder variable |
| 2968 | if (SemaRef.DiagRedefinedPlaceholderFieldDecl(Loc: DIE->getBeginLoc(), ClassDecl: RD, |
| 2969 | Name: FieldName)) { |
| 2970 | ++Index; |
| 2971 | return true; |
| 2972 | } |
| 2973 | // Name lookup found something, but it wasn't a field. |
| 2974 | if (DeclContextLookupResult Lookup = RD->lookup(Name: FieldName); |
| 2975 | !Lookup.empty()) { |
| 2976 | SemaRef.Diag(Loc: D->getFieldLoc(), DiagID: diag::err_field_designator_nonfield) |
| 2977 | << FieldName; |
| 2978 | SemaRef.Diag(Loc: Lookup.front()->getLocation(), |
| 2979 | DiagID: diag::note_field_designator_found); |
| 2980 | ++Index; |
| 2981 | return true; |
| 2982 | } |
| 2983 | |
| 2984 | // Name lookup didn't find anything. |
| 2985 | // Determine whether this was a typo for another field name. |
| 2986 | FieldInitializerValidatorCCC CCC(RD); |
| 2987 | if (TypoCorrection Corrected = SemaRef.CorrectTypo( |
| 2988 | Typo: DeclarationNameInfo(FieldName, D->getFieldLoc()), |
| 2989 | LookupKind: Sema::LookupMemberName, /*Scope=*/S: nullptr, /*SS=*/nullptr, CCC, |
| 2990 | Mode: CorrectTypoKind::ErrorRecovery, MemberContext: RD)) { |
| 2991 | SemaRef.diagnoseTypo( |
| 2992 | Correction: Corrected, |
| 2993 | TypoDiag: SemaRef.PDiag(DiagID: diag::err_field_designator_unknown_suggest) |
| 2994 | << FieldName << CurrentObjectType); |
| 2995 | KnownField = Corrected.getCorrectionDeclAs<FieldDecl>(); |
| 2996 | hadError = true; |
| 2997 | } else { |
| 2998 | // Typo correction didn't find anything. |
| 2999 | SourceLocation Loc = D->getFieldLoc(); |
| 3000 | |
| 3001 | // The loc can be invalid with a "null" designator (i.e. an anonymous |
| 3002 | // union/struct). Do our best to approximate the location. |
| 3003 | if (Loc.isInvalid()) |
| 3004 | Loc = IList->getBeginLoc(); |
| 3005 | |
| 3006 | SemaRef.Diag(Loc, DiagID: diag::err_field_designator_unknown) |
| 3007 | << FieldName << CurrentObjectType << DIE->getSourceRange(); |
| 3008 | ++Index; |
| 3009 | return true; |
| 3010 | } |
| 3011 | } |
| 3012 | } |
| 3013 | |
| 3014 | unsigned NumBases = 0; |
| 3015 | if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD)) |
| 3016 | NumBases = CXXRD->getNumBases(); |
| 3017 | |
| 3018 | unsigned FieldIndex = NumBases; |
| 3019 | |
| 3020 | for (auto *FI : RD->fields()) { |
| 3021 | if (FI->isUnnamedBitField()) |
| 3022 | continue; |
| 3023 | if (declaresSameEntity(D1: KnownField, D2: FI)) { |
| 3024 | KnownField = FI; |
| 3025 | break; |
| 3026 | } |
| 3027 | ++FieldIndex; |
| 3028 | } |
| 3029 | |
| 3030 | RecordDecl::field_iterator Field = |
| 3031 | RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField)); |
| 3032 | |
| 3033 | // All of the fields of a union are located at the same place in |
| 3034 | // the initializer list. |
| 3035 | if (RD->isUnion()) { |
| 3036 | FieldIndex = 0; |
| 3037 | if (StructuredList) { |
| 3038 | FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion(); |
| 3039 | if (CurrentField && !declaresSameEntity(D1: CurrentField, D2: *Field)) { |
| 3040 | assert(StructuredList->getNumInits() == 1 |
| 3041 | && "A union should never have more than one initializer!" ); |
| 3042 | |
| 3043 | Expr *ExistingInit = StructuredList->getInit(Init: 0); |
| 3044 | if (ExistingInit) { |
| 3045 | // We're about to throw away an initializer, emit warning. |
| 3046 | diagnoseInitOverride( |
| 3047 | OldInit: ExistingInit, NewInitRange: SourceRange(D->getBeginLoc(), DIE->getEndLoc()), |
| 3048 | /*UnionOverride=*/true, |
| 3049 | /*FullyOverwritten=*/SemaRef.getLangOpts().CPlusPlus ? false |
| 3050 | : true); |
| 3051 | } |
| 3052 | |
| 3053 | // remove existing initializer |
| 3054 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: 0); |
| 3055 | StructuredList->setInitializedFieldInUnion(nullptr); |
| 3056 | } |
| 3057 | |
| 3058 | StructuredList->setInitializedFieldInUnion(*Field); |
| 3059 | } |
| 3060 | } |
| 3061 | |
| 3062 | // Make sure we can use this declaration. |
| 3063 | bool InvalidUse; |
| 3064 | if (VerifyOnly) |
| 3065 | InvalidUse = !SemaRef.CanUseDecl(D: *Field, TreatUnavailableAsInvalid); |
| 3066 | else |
| 3067 | InvalidUse = SemaRef.DiagnoseUseOfDecl(D: *Field, Locs: D->getFieldLoc()); |
| 3068 | if (InvalidUse) { |
| 3069 | ++Index; |
| 3070 | return true; |
| 3071 | } |
| 3072 | |
| 3073 | // C++20 [dcl.init.list]p3: |
| 3074 | // The ordered identifiers in the designators of the designated- |
| 3075 | // initializer-list shall form a subsequence of the ordered identifiers |
| 3076 | // in the direct non-static data members of T. |
| 3077 | // |
| 3078 | // Note that this is not a condition on forming the aggregate |
| 3079 | // initialization, only on actually performing initialization, |
| 3080 | // so it is not checked in VerifyOnly mode. |
| 3081 | // |
| 3082 | // FIXME: This is the only reordering diagnostic we produce, and it only |
| 3083 | // catches cases where we have a top-level field designator that jumps |
| 3084 | // backwards. This is the only such case that is reachable in an |
| 3085 | // otherwise-valid C++20 program, so is the only case that's required for |
| 3086 | // conformance, but for consistency, we should diagnose all the other |
| 3087 | // cases where a designator takes us backwards too. |
| 3088 | if (IsFirstDesignator && !VerifyOnly && SemaRef.getLangOpts().CPlusPlus && |
| 3089 | NextField && |
| 3090 | (*NextField == RD->field_end() || |
| 3091 | (*NextField)->getFieldIndex() > Field->getFieldIndex() + 1)) { |
| 3092 | // Find the field that we just initialized. |
| 3093 | FieldDecl *PrevField = nullptr; |
| 3094 | for (auto FI = RD->field_begin(); FI != RD->field_end(); ++FI) { |
| 3095 | if (FI->isUnnamedBitField()) |
| 3096 | continue; |
| 3097 | if (*NextField != RD->field_end() && |
| 3098 | declaresSameEntity(D1: *FI, D2: **NextField)) |
| 3099 | break; |
| 3100 | PrevField = *FI; |
| 3101 | } |
| 3102 | |
| 3103 | const auto GenerateDesignatedInitReorderingFixit = |
| 3104 | [&](SemaBase::SemaDiagnosticBuilder &Diag) { |
| 3105 | struct ReorderInfo { |
| 3106 | int Pos{}; |
| 3107 | const Expr *InitExpr{}; |
| 3108 | }; |
| 3109 | |
| 3110 | llvm::SmallDenseMap<IdentifierInfo *, int> MemberNameInx{}; |
| 3111 | llvm::SmallVector<ReorderInfo, 16> ReorderedInitExprs{}; |
| 3112 | |
| 3113 | const auto *CxxRecord = |
| 3114 | IList->getSemanticForm()->getType()->getAsCXXRecordDecl(); |
| 3115 | |
| 3116 | for (const FieldDecl *Field : CxxRecord->fields()) |
| 3117 | MemberNameInx[Field->getIdentifier()] = Field->getFieldIndex(); |
| 3118 | |
| 3119 | for (const Expr *Init : IList->inits()) { |
| 3120 | if (const auto *DI = |
| 3121 | dyn_cast_if_present<DesignatedInitExpr>(Val: Init)) { |
| 3122 | // We expect only one Designator |
| 3123 | if (DI->size() != 1) |
| 3124 | return; |
| 3125 | |
| 3126 | const IdentifierInfo *const FieldName = |
| 3127 | DI->getDesignator(Idx: 0)->getFieldName(); |
| 3128 | // In case we have an unknown initializer in the source, not in |
| 3129 | // the record |
| 3130 | if (MemberNameInx.contains(Val: FieldName)) |
| 3131 | ReorderedInitExprs.emplace_back( |
| 3132 | Args: ReorderInfo{.Pos: MemberNameInx.at(Val: FieldName), .InitExpr: Init}); |
| 3133 | } |
| 3134 | } |
| 3135 | |
| 3136 | llvm::sort(C&: ReorderedInitExprs, |
| 3137 | Comp: [](const ReorderInfo &A, const ReorderInfo &B) { |
| 3138 | return A.Pos < B.Pos; |
| 3139 | }); |
| 3140 | |
| 3141 | llvm::SmallString<128> FixedInitList{}; |
| 3142 | SourceManager &SM = SemaRef.getSourceManager(); |
| 3143 | const LangOptions &LangOpts = SemaRef.getLangOpts(); |
| 3144 | |
| 3145 | // In a derived Record, first n base-classes are initialized first. |
| 3146 | // They do not use designated init, so skip them |
| 3147 | const ArrayRef<clang::Expr *> IListInits = |
| 3148 | IList->inits().drop_front(N: CxxRecord->getNumBases()); |
| 3149 | // loop over each existing expressions and apply replacement |
| 3150 | for (const auto &[OrigExpr, Repl] : |
| 3151 | llvm::zip(t: IListInits, u&: ReorderedInitExprs)) { |
| 3152 | CharSourceRange CharRange = CharSourceRange::getTokenRange( |
| 3153 | R: Repl.InitExpr->getSourceRange()); |
| 3154 | const StringRef InitText = |
| 3155 | Lexer::getSourceText(Range: CharRange, SM, LangOpts); |
| 3156 | |
| 3157 | Diag << FixItHint::CreateReplacement(RemoveRange: OrigExpr->getSourceRange(), |
| 3158 | Code: InitText.str()); |
| 3159 | } |
| 3160 | }; |
| 3161 | |
| 3162 | if (PrevField && |
| 3163 | PrevField->getFieldIndex() > KnownField->getFieldIndex()) { |
| 3164 | SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(), |
| 3165 | DiagID: diag::ext_designated_init_reordered) |
| 3166 | << KnownField << PrevField << DIE->getSourceRange(); |
| 3167 | |
| 3168 | unsigned OldIndex = StructuredIndex - 1; |
| 3169 | if (StructuredList && OldIndex <= StructuredList->getNumInits()) { |
| 3170 | if (Expr *PrevInit = StructuredList->getInit(Init: OldIndex)) { |
| 3171 | auto Diag = SemaRef.Diag(Loc: PrevInit->getBeginLoc(), |
| 3172 | DiagID: diag::note_previous_field_init) |
| 3173 | << PrevField << PrevInit->getSourceRange(); |
| 3174 | GenerateDesignatedInitReorderingFixit(Diag); |
| 3175 | } |
| 3176 | } |
| 3177 | } |
| 3178 | } |
| 3179 | |
| 3180 | |
| 3181 | // Update the designator with the field declaration. |
| 3182 | if (!VerifyOnly) |
| 3183 | D->setFieldDecl(*Field); |
| 3184 | |
| 3185 | // Make sure that our non-designated initializer list has space |
| 3186 | // for a subobject corresponding to this field. |
| 3187 | if (StructuredList && FieldIndex >= StructuredList->getNumInits()) |
| 3188 | StructuredList->resizeInits(Context: SemaRef.Context, NumInits: FieldIndex + 1); |
| 3189 | |
| 3190 | // This designator names a flexible array member. |
| 3191 | if (Field->getType()->isIncompleteArrayType()) { |
| 3192 | bool Invalid = false; |
| 3193 | if ((DesigIdx + 1) != DIE->size()) { |
| 3194 | // We can't designate an object within the flexible array |
| 3195 | // member (because GCC doesn't allow it). |
| 3196 | if (!VerifyOnly) { |
| 3197 | DesignatedInitExpr::Designator *NextD |
| 3198 | = DIE->getDesignator(Idx: DesigIdx + 1); |
| 3199 | SemaRef.Diag(Loc: NextD->getBeginLoc(), |
| 3200 | DiagID: diag::err_designator_into_flexible_array_member) |
| 3201 | << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc()); |
| 3202 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member) |
| 3203 | << *Field; |
| 3204 | } |
| 3205 | Invalid = true; |
| 3206 | } |
| 3207 | |
| 3208 | if (!hadError && !isa<InitListExpr>(Val: DIE->getInit()) && |
| 3209 | !isa<StringLiteral>(Val: DIE->getInit())) { |
| 3210 | // The initializer is not an initializer list. |
| 3211 | if (!VerifyOnly) { |
| 3212 | SemaRef.Diag(Loc: DIE->getInit()->getBeginLoc(), |
| 3213 | DiagID: diag::err_flexible_array_init_needs_braces) |
| 3214 | << DIE->getInit()->getSourceRange(); |
| 3215 | SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_flexible_array_member) |
| 3216 | << *Field; |
| 3217 | } |
| 3218 | Invalid = true; |
| 3219 | } |
| 3220 | |
| 3221 | // Check GNU flexible array initializer. |
| 3222 | if (!Invalid && CheckFlexibleArrayInit(Entity, InitExpr: DIE->getInit(), Field: *Field, |
| 3223 | TopLevelObject)) |
| 3224 | Invalid = true; |
| 3225 | |
| 3226 | if (Invalid) { |
| 3227 | ++Index; |
| 3228 | return true; |
| 3229 | } |
| 3230 | |
| 3231 | // Initialize the array. |
| 3232 | bool prevHadError = hadError; |
| 3233 | unsigned newStructuredIndex = FieldIndex; |
| 3234 | unsigned OldIndex = Index; |
| 3235 | IList->setInit(Init: Index, expr: DIE->getInit()); |
| 3236 | |
| 3237 | InitializedEntity MemberEntity = |
| 3238 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
| 3239 | CheckSubElementType(Entity: MemberEntity, IList, ElemType: Field->getType(), Index, |
| 3240 | StructuredList, StructuredIndex&: newStructuredIndex); |
| 3241 | |
| 3242 | IList->setInit(Init: OldIndex, expr: DIE); |
| 3243 | if (hadError && !prevHadError) { |
| 3244 | ++Field; |
| 3245 | ++FieldIndex; |
| 3246 | if (NextField) |
| 3247 | *NextField = Field; |
| 3248 | StructuredIndex = FieldIndex; |
| 3249 | return true; |
| 3250 | } |
| 3251 | } else { |
| 3252 | // Recurse to check later designated subobjects. |
| 3253 | QualType FieldType = Field->getType(); |
| 3254 | unsigned newStructuredIndex = FieldIndex; |
| 3255 | |
| 3256 | InitializedEntity MemberEntity = |
| 3257 | InitializedEntity::InitializeMember(Member: *Field, Parent: &Entity); |
| 3258 | if (CheckDesignatedInitializer(Entity: MemberEntity, IList, DIE, DesigIdx: DesigIdx + 1, |
| 3259 | CurrentObjectType&: FieldType, NextField: nullptr, NextElementIndex: nullptr, Index, |
| 3260 | StructuredList, StructuredIndex&: newStructuredIndex, |
| 3261 | FinishSubobjectInit, TopLevelObject: false)) |
| 3262 | return true; |
| 3263 | } |
| 3264 | |
| 3265 | // Find the position of the next field to be initialized in this |
| 3266 | // subobject. |
| 3267 | ++Field; |
| 3268 | ++FieldIndex; |
| 3269 | |
| 3270 | // If this the first designator, our caller will continue checking |
| 3271 | // the rest of this struct/class/union subobject. |
| 3272 | if (IsFirstDesignator) { |
| 3273 | if (Field != RD->field_end() && Field->isUnnamedBitField()) |
| 3274 | ++Field; |
| 3275 | |
| 3276 | if (NextField) |
| 3277 | *NextField = Field; |
| 3278 | |
| 3279 | StructuredIndex = FieldIndex; |
| 3280 | return false; |
| 3281 | } |
| 3282 | |
| 3283 | if (!FinishSubobjectInit) |
| 3284 | return false; |
| 3285 | |
| 3286 | // We've already initialized something in the union; we're done. |
| 3287 | if (RD->isUnion()) |
| 3288 | return hadError; |
| 3289 | |
| 3290 | // Check the remaining fields within this class/struct/union subobject. |
| 3291 | bool prevHadError = hadError; |
| 3292 | |
| 3293 | auto NoBases = |
| 3294 | CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(), |
| 3295 | CXXRecordDecl::base_class_iterator()); |
| 3296 | CheckStructUnionTypes(Entity, IList, DeclType: CurrentObjectType, Bases: NoBases, Field, |
| 3297 | SubobjectIsDesignatorContext: false, Index, StructuredList, StructuredIndex&: FieldIndex); |
| 3298 | return hadError && !prevHadError; |
| 3299 | } |
| 3300 | |
| 3301 | // C99 6.7.8p6: |
| 3302 | // |
| 3303 | // If a designator has the form |
| 3304 | // |
| 3305 | // [ constant-expression ] |
| 3306 | // |
| 3307 | // then the current object (defined below) shall have array |
| 3308 | // type and the expression shall be an integer constant |
| 3309 | // expression. If the array is of unknown size, any |
| 3310 | // nonnegative value is valid. |
| 3311 | // |
| 3312 | // Additionally, cope with the GNU extension that permits |
| 3313 | // designators of the form |
| 3314 | // |
| 3315 | // [ constant-expression ... constant-expression ] |
| 3316 | const ArrayType *AT = SemaRef.Context.getAsArrayType(T: CurrentObjectType); |
| 3317 | if (!AT) { |
| 3318 | if (!VerifyOnly) |
| 3319 | SemaRef.Diag(Loc: D->getLBracketLoc(), DiagID: diag::err_array_designator_non_array) |
| 3320 | << CurrentObjectType; |
| 3321 | ++Index; |
| 3322 | return true; |
| 3323 | } |
| 3324 | |
| 3325 | Expr *IndexExpr = nullptr; |
| 3326 | llvm::APSInt DesignatedStartIndex, DesignatedEndIndex; |
| 3327 | if (D->isArrayDesignator()) { |
| 3328 | IndexExpr = DIE->getArrayIndex(D: *D); |
| 3329 | DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
| 3330 | DesignatedEndIndex = DesignatedStartIndex; |
| 3331 | } else { |
| 3332 | assert(D->isArrayRangeDesignator() && "Need array-range designator" ); |
| 3333 | |
| 3334 | DesignatedStartIndex = |
| 3335 | DIE->getArrayRangeStart(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
| 3336 | DesignatedEndIndex = |
| 3337 | DIE->getArrayRangeEnd(D: *D)->EvaluateKnownConstInt(Ctx: SemaRef.Context); |
| 3338 | IndexExpr = DIE->getArrayRangeEnd(D: *D); |
| 3339 | |
| 3340 | // Codegen can't handle evaluating array range designators that have side |
| 3341 | // effects, because we replicate the AST value for each initialized element. |
| 3342 | // As such, set the sawArrayRangeDesignator() bit if we initialize multiple |
| 3343 | // elements with something that has a side effect, so codegen can emit an |
| 3344 | // "error unsupported" error instead of miscompiling the app. |
| 3345 | if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&& |
| 3346 | DIE->getInit()->HasSideEffects(Ctx: SemaRef.Context) && !VerifyOnly) |
| 3347 | FullyStructuredList->sawArrayRangeDesignator(); |
| 3348 | } |
| 3349 | |
| 3350 | if (isa<ConstantArrayType>(Val: AT)) { |
| 3351 | llvm::APSInt MaxElements(cast<ConstantArrayType>(Val: AT)->getSize(), false); |
| 3352 | DesignatedStartIndex |
| 3353 | = DesignatedStartIndex.extOrTrunc(width: MaxElements.getBitWidth()); |
| 3354 | DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned()); |
| 3355 | DesignatedEndIndex |
| 3356 | = DesignatedEndIndex.extOrTrunc(width: MaxElements.getBitWidth()); |
| 3357 | DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned()); |
| 3358 | if (DesignatedEndIndex >= MaxElements) { |
| 3359 | if (!VerifyOnly) |
| 3360 | SemaRef.Diag(Loc: IndexExpr->getBeginLoc(), |
| 3361 | DiagID: diag::err_array_designator_too_large) |
| 3362 | << toString(I: DesignatedEndIndex, Radix: 10) << toString(I: MaxElements, Radix: 10) |
| 3363 | << IndexExpr->getSourceRange(); |
| 3364 | ++Index; |
| 3365 | return true; |
| 3366 | } |
| 3367 | } else { |
| 3368 | unsigned DesignatedIndexBitWidth = |
| 3369 | ConstantArrayType::getMaxSizeBits(Context: SemaRef.Context); |
| 3370 | DesignatedStartIndex = |
| 3371 | DesignatedStartIndex.extOrTrunc(width: DesignatedIndexBitWidth); |
| 3372 | DesignatedEndIndex = |
| 3373 | DesignatedEndIndex.extOrTrunc(width: DesignatedIndexBitWidth); |
| 3374 | DesignatedStartIndex.setIsUnsigned(true); |
| 3375 | DesignatedEndIndex.setIsUnsigned(true); |
| 3376 | } |
| 3377 | |
| 3378 | bool IsStringLiteralInitUpdate = |
| 3379 | StructuredList && StructuredList->isStringLiteralInit(); |
| 3380 | if (IsStringLiteralInitUpdate && VerifyOnly) { |
| 3381 | // We're just verifying an update to a string literal init. We don't need |
| 3382 | // to split the string up into individual characters to do that. |
| 3383 | StructuredList = nullptr; |
| 3384 | } else if (IsStringLiteralInitUpdate) { |
| 3385 | // We're modifying a string literal init; we have to decompose the string |
| 3386 | // so we can modify the individual characters. |
| 3387 | ASTContext &Context = SemaRef.Context; |
| 3388 | Expr *SubExpr = StructuredList->getInit(Init: 0)->IgnoreParenImpCasts(); |
| 3389 | |
| 3390 | // Compute the character type |
| 3391 | QualType CharTy = AT->getElementType(); |
| 3392 | |
| 3393 | // Compute the type of the integer literals. |
| 3394 | QualType PromotedCharTy = CharTy; |
| 3395 | if (Context.isPromotableIntegerType(T: CharTy)) |
| 3396 | PromotedCharTy = Context.getPromotedIntegerType(PromotableType: CharTy); |
| 3397 | unsigned PromotedCharTyWidth = Context.getTypeSize(T: PromotedCharTy); |
| 3398 | |
| 3399 | if (StringLiteral *SL = dyn_cast<StringLiteral>(Val: SubExpr)) { |
| 3400 | // Get the length of the string. |
| 3401 | uint64_t StrLen = SL->getLength(); |
| 3402 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT); |
| 3403 | CAT && CAT->getSize().ult(RHS: StrLen)) |
| 3404 | StrLen = CAT->getZExtSize(); |
| 3405 | StructuredList->resizeInits(Context, NumInits: StrLen); |
| 3406 | |
| 3407 | // Build a literal for each character in the string, and put them into |
| 3408 | // the init list. |
| 3409 | for (unsigned i = 0, e = StrLen; i != e; ++i) { |
| 3410 | llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i)); |
| 3411 | Expr *Init = new (Context) IntegerLiteral( |
| 3412 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); |
| 3413 | if (CharTy != PromotedCharTy) |
| 3414 | Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast, |
| 3415 | Operand: Init, BasePath: nullptr, Cat: VK_PRValue, |
| 3416 | FPO: FPOptionsOverride()); |
| 3417 | StructuredList->updateInit(C: Context, Init: i, expr: Init); |
| 3418 | } |
| 3419 | } else { |
| 3420 | ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(Val: SubExpr); |
| 3421 | std::string Str; |
| 3422 | Context.getObjCEncodingForType(T: E->getEncodedType(), S&: Str); |
| 3423 | |
| 3424 | // Get the length of the string. |
| 3425 | uint64_t StrLen = Str.size(); |
| 3426 | if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: AT); |
| 3427 | CAT && CAT->getSize().ult(RHS: StrLen)) |
| 3428 | StrLen = CAT->getZExtSize(); |
| 3429 | StructuredList->resizeInits(Context, NumInits: StrLen); |
| 3430 | |
| 3431 | // Build a literal for each character in the string, and put them into |
| 3432 | // the init list. |
| 3433 | for (unsigned i = 0, e = StrLen; i != e; ++i) { |
| 3434 | llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]); |
| 3435 | Expr *Init = new (Context) IntegerLiteral( |
| 3436 | Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc()); |
| 3437 | if (CharTy != PromotedCharTy) |
| 3438 | Init = ImplicitCastExpr::Create(Context, T: CharTy, Kind: CK_IntegralCast, |
| 3439 | Operand: Init, BasePath: nullptr, Cat: VK_PRValue, |
| 3440 | FPO: FPOptionsOverride()); |
| 3441 | StructuredList->updateInit(C: Context, Init: i, expr: Init); |
| 3442 | } |
| 3443 | } |
| 3444 | } |
| 3445 | |
| 3446 | // Make sure that our non-designated initializer list has space |
| 3447 | // for a subobject corresponding to this array element. |
| 3448 | if (StructuredList && |
| 3449 | DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()) |
| 3450 | StructuredList->resizeInits(Context: SemaRef.Context, |
| 3451 | NumInits: DesignatedEndIndex.getZExtValue() + 1); |
| 3452 | |
| 3453 | // Repeatedly perform subobject initializations in the range |
| 3454 | // [DesignatedStartIndex, DesignatedEndIndex]. |
| 3455 | |
| 3456 | // Move to the next designator |
| 3457 | unsigned ElementIndex = DesignatedStartIndex.getZExtValue(); |
| 3458 | unsigned OldIndex = Index; |
| 3459 | |
| 3460 | InitializedEntity ElementEntity = |
| 3461 | InitializedEntity::InitializeElement(Context&: SemaRef.Context, Index: 0, Parent: Entity); |
| 3462 | |
| 3463 | while (DesignatedStartIndex <= DesignatedEndIndex) { |
| 3464 | // Recurse to check later designated subobjects. |
| 3465 | QualType ElementType = AT->getElementType(); |
| 3466 | Index = OldIndex; |
| 3467 | |
| 3468 | ElementEntity.setElementIndex(ElementIndex); |
| 3469 | if (CheckDesignatedInitializer( |
| 3470 | Entity: ElementEntity, IList, DIE, DesigIdx: DesigIdx + 1, CurrentObjectType&: ElementType, NextField: nullptr, |
| 3471 | NextElementIndex: nullptr, Index, StructuredList, StructuredIndex&: ElementIndex, |
| 3472 | FinishSubobjectInit: FinishSubobjectInit && (DesignatedStartIndex == DesignatedEndIndex), |
| 3473 | TopLevelObject: false)) |
| 3474 | return true; |
| 3475 | |
| 3476 | // Move to the next index in the array that we'll be initializing. |
| 3477 | ++DesignatedStartIndex; |
| 3478 | ElementIndex = DesignatedStartIndex.getZExtValue(); |
| 3479 | } |
| 3480 | |
| 3481 | // If this the first designator, our caller will continue checking |
| 3482 | // the rest of this array subobject. |
| 3483 | if (IsFirstDesignator) { |
| 3484 | if (NextElementIndex) |
| 3485 | *NextElementIndex = std::move(DesignatedStartIndex); |
| 3486 | StructuredIndex = ElementIndex; |
| 3487 | return false; |
| 3488 | } |
| 3489 | |
| 3490 | if (!FinishSubobjectInit) |
| 3491 | return false; |
| 3492 | |
| 3493 | // Check the remaining elements within this array subobject. |
| 3494 | bool prevHadError = hadError; |
| 3495 | CheckArrayType(Entity, IList, DeclType&: CurrentObjectType, elementIndex: DesignatedStartIndex, |
| 3496 | /*SubobjectIsDesignatorContext=*/false, Index, |
| 3497 | StructuredList, StructuredIndex&: ElementIndex); |
| 3498 | return hadError && !prevHadError; |
| 3499 | } |
| 3500 | |
| 3501 | // Get the structured initializer list for a subobject of type |
| 3502 | // @p CurrentObjectType. |
| 3503 | InitListExpr * |
| 3504 | InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index, |
| 3505 | QualType CurrentObjectType, |
| 3506 | InitListExpr *StructuredList, |
| 3507 | unsigned StructuredIndex, |
| 3508 | SourceRange InitRange, |
| 3509 | bool IsFullyOverwritten) { |
| 3510 | if (!StructuredList) |
| 3511 | return nullptr; |
| 3512 | |
| 3513 | Expr *ExistingInit = nullptr; |
| 3514 | if (StructuredIndex < StructuredList->getNumInits()) |
| 3515 | ExistingInit = StructuredList->getInit(Init: StructuredIndex); |
| 3516 | |
| 3517 | if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(Val: ExistingInit)) |
| 3518 | // There might have already been initializers for subobjects of the current |
| 3519 | // object, but a subsequent initializer list will overwrite the entirety |
| 3520 | // of the current object. (See DR 253 and C99 6.7.8p21). e.g., |
| 3521 | // |
| 3522 | // struct P { char x[6]; }; |
| 3523 | // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } }; |
| 3524 | // |
| 3525 | // The first designated initializer is ignored, and l.x is just "f". |
| 3526 | if (!IsFullyOverwritten) |
| 3527 | return Result; |
| 3528 | |
| 3529 | if (ExistingInit) { |
| 3530 | // We are creating an initializer list that initializes the |
| 3531 | // subobjects of the current object, but there was already an |
| 3532 | // initialization that completely initialized the current |
| 3533 | // subobject: |
| 3534 | // |
| 3535 | // struct X { int a, b; }; |
| 3536 | // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 }; |
| 3537 | // |
| 3538 | // Here, xs[0].a == 1 and xs[0].b == 3, since the second, |
| 3539 | // designated initializer overwrites the [0].b initializer |
| 3540 | // from the prior initialization. |
| 3541 | // |
| 3542 | // When the existing initializer is an expression rather than an |
| 3543 | // initializer list, we cannot decompose and update it in this way. |
| 3544 | // For example: |
| 3545 | // |
| 3546 | // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 }; |
| 3547 | // |
| 3548 | // This case is handled by CheckDesignatedInitializer. |
| 3549 | diagnoseInitOverride(OldInit: ExistingInit, NewInitRange: InitRange); |
| 3550 | } |
| 3551 | |
| 3552 | unsigned ExpectedNumInits = 0; |
| 3553 | if (Index < IList->getNumInits()) { |
| 3554 | if (auto *Init = dyn_cast_or_null<InitListExpr>(Val: IList->getInit(Init: Index))) |
| 3555 | ExpectedNumInits = Init->getNumInits(); |
| 3556 | else |
| 3557 | ExpectedNumInits = IList->getNumInits() - Index; |
| 3558 | } |
| 3559 | |
| 3560 | InitListExpr *Result = createInitListExpr( |
| 3561 | CurrentObjectType, InitRange, ExpectedNumInits, /*IsExplicit=*/false); |
| 3562 | |
| 3563 | // Link this new initializer list into the structured initializer |
| 3564 | // lists. |
| 3565 | StructuredList->updateInit(C: SemaRef.Context, Init: StructuredIndex, expr: Result); |
| 3566 | return Result; |
| 3567 | } |
| 3568 | |
| 3569 | InitListExpr *InitListChecker::createInitListExpr(QualType CurrentObjectType, |
| 3570 | SourceRange InitRange, |
| 3571 | unsigned ExpectedNumInits, |
| 3572 | bool IsExplicit) { |
| 3573 | InitListExpr *Result = |
| 3574 | new (SemaRef.Context) InitListExpr(SemaRef.Context, InitRange.getBegin(), |
| 3575 | {}, InitRange.getEnd(), IsExplicit); |
| 3576 | |
| 3577 | QualType ResultType = CurrentObjectType; |
| 3578 | if (!ResultType->isArrayType()) |
| 3579 | ResultType = ResultType.getNonLValueExprType(Context: SemaRef.Context); |
| 3580 | Result->setType(ResultType); |
| 3581 | |
| 3582 | // Pre-allocate storage for the structured initializer list. |
| 3583 | unsigned NumElements = 0; |
| 3584 | |
| 3585 | if (const ArrayType *AType |
| 3586 | = SemaRef.Context.getAsArrayType(T: CurrentObjectType)) { |
| 3587 | if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(Val: AType)) { |
| 3588 | NumElements = CAType->getZExtSize(); |
| 3589 | // Simple heuristic so that we don't allocate a very large |
| 3590 | // initializer with many empty entries at the end. |
| 3591 | if (NumElements > ExpectedNumInits) |
| 3592 | NumElements = 0; |
| 3593 | } |
| 3594 | } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) { |
| 3595 | NumElements = VType->getNumElements(); |
| 3596 | } else if (CurrentObjectType->isRecordType()) { |
| 3597 | NumElements = numStructUnionElements(DeclType: CurrentObjectType); |
| 3598 | } else if (CurrentObjectType->isDependentType()) { |
| 3599 | NumElements = 1; |
| 3600 | } |
| 3601 | |
| 3602 | Result->reserveInits(C: SemaRef.Context, NumInits: NumElements); |
| 3603 | |
| 3604 | return Result; |
| 3605 | } |
| 3606 | |
| 3607 | /// Update the initializer at index @p StructuredIndex within the |
| 3608 | /// structured initializer list to the value @p expr. |
| 3609 | void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList, |
| 3610 | unsigned &StructuredIndex, |
| 3611 | Expr *expr) { |
| 3612 | // No structured initializer list to update |
| 3613 | if (!StructuredList) |
| 3614 | return; |
| 3615 | |
| 3616 | if (Expr *PrevInit = StructuredList->updateInit(C: SemaRef.Context, |
| 3617 | Init: StructuredIndex, expr)) { |
| 3618 | // This initializer overwrites a previous initializer. |
| 3619 | // No need to diagnose when `expr` is nullptr because a more relevant |
| 3620 | // diagnostic has already been issued and this diagnostic is potentially |
| 3621 | // noise. |
| 3622 | if (expr) |
| 3623 | diagnoseInitOverride(OldInit: PrevInit, NewInitRange: expr->getSourceRange()); |
| 3624 | } |
| 3625 | |
| 3626 | ++StructuredIndex; |
| 3627 | } |
| 3628 | |
| 3629 | bool Sema::CanPerformAggregateInitializationForOverloadResolution( |
| 3630 | const InitializedEntity &Entity, InitListExpr *From) { |
| 3631 | QualType Type = Entity.getType(); |
| 3632 | InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true, |
| 3633 | /*TreatUnavailableAsInvalid=*/false, |
| 3634 | /*InOverloadResolution=*/true); |
| 3635 | return !Check.HadError(); |
| 3636 | } |
| 3637 | |
| 3638 | /// Check that the given Index expression is a valid array designator |
| 3639 | /// value. This is essentially just a wrapper around |
| 3640 | /// VerifyIntegerConstantExpression that also checks for negative values |
| 3641 | /// and produces a reasonable diagnostic if there is a |
| 3642 | /// failure. Returns the index expression, possibly with an implicit cast |
| 3643 | /// added, on success. If everything went okay, Value will receive the |
| 3644 | /// value of the constant expression. |
| 3645 | static ExprResult |
| 3646 | CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) { |
| 3647 | SourceLocation Loc = Index->getBeginLoc(); |
| 3648 | |
| 3649 | // Make sure this is an integer constant expression. |
| 3650 | ExprResult Result = |
| 3651 | S.VerifyIntegerConstantExpression(E: Index, Result: &Value, CanFold: AllowFoldKind::Allow); |
| 3652 | if (Result.isInvalid()) |
| 3653 | return Result; |
| 3654 | |
| 3655 | if (Value.isSigned() && Value.isNegative()) |
| 3656 | return S.Diag(Loc, DiagID: diag::err_array_designator_negative) |
| 3657 | << toString(I: Value, Radix: 10) << Index->getSourceRange(); |
| 3658 | |
| 3659 | Value.setIsUnsigned(true); |
| 3660 | return Result; |
| 3661 | } |
| 3662 | |
| 3663 | ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig, |
| 3664 | SourceLocation EqualOrColonLoc, |
| 3665 | bool GNUSyntax, |
| 3666 | ExprResult Init) { |
| 3667 | typedef DesignatedInitExpr::Designator ASTDesignator; |
| 3668 | |
| 3669 | bool Invalid = false; |
| 3670 | SmallVector<ASTDesignator, 32> Designators; |
| 3671 | SmallVector<Expr *, 32> InitExpressions; |
| 3672 | |
| 3673 | // Build designators and check array designator expressions. |
| 3674 | for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); ++Idx) { |
| 3675 | const Designator &D = Desig.getDesignator(Idx); |
| 3676 | |
| 3677 | if (D.isFieldDesignator()) { |
| 3678 | Designators.push_back(Elt: ASTDesignator::CreateFieldDesignator( |
| 3679 | FieldName: D.getFieldDecl(), DotLoc: D.getDotLoc(), FieldLoc: D.getFieldLoc())); |
| 3680 | } else if (D.isArrayDesignator()) { |
| 3681 | Expr *Index = D.getArrayIndex(); |
| 3682 | llvm::APSInt IndexValue; |
| 3683 | if (!Index->isTypeDependent() && !Index->isValueDependent()) |
| 3684 | Index = CheckArrayDesignatorExpr(S&: *this, Index, Value&: IndexValue).get(); |
| 3685 | if (!Index) |
| 3686 | Invalid = true; |
| 3687 | else { |
| 3688 | Designators.push_back(Elt: ASTDesignator::CreateArrayDesignator( |
| 3689 | Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), RBracketLoc: D.getRBracketLoc())); |
| 3690 | InitExpressions.push_back(Elt: Index); |
| 3691 | } |
| 3692 | } else if (D.isArrayRangeDesignator()) { |
| 3693 | Expr *StartIndex = D.getArrayRangeStart(); |
| 3694 | Expr *EndIndex = D.getArrayRangeEnd(); |
| 3695 | llvm::APSInt StartValue; |
| 3696 | llvm::APSInt EndValue; |
| 3697 | bool StartDependent = StartIndex->isTypeDependent() || |
| 3698 | StartIndex->isValueDependent(); |
| 3699 | bool EndDependent = EndIndex->isTypeDependent() || |
| 3700 | EndIndex->isValueDependent(); |
| 3701 | if (!StartDependent) |
| 3702 | StartIndex = |
| 3703 | CheckArrayDesignatorExpr(S&: *this, Index: StartIndex, Value&: StartValue).get(); |
| 3704 | if (!EndDependent) |
| 3705 | EndIndex = CheckArrayDesignatorExpr(S&: *this, Index: EndIndex, Value&: EndValue).get(); |
| 3706 | |
| 3707 | if (!StartIndex || !EndIndex) |
| 3708 | Invalid = true; |
| 3709 | else { |
| 3710 | // Make sure we're comparing values with the same bit width. |
| 3711 | if (StartDependent || EndDependent) { |
| 3712 | // Nothing to compute. |
| 3713 | } else if (StartValue.getBitWidth() > EndValue.getBitWidth()) |
| 3714 | EndValue = EndValue.extend(width: StartValue.getBitWidth()); |
| 3715 | else if (StartValue.getBitWidth() < EndValue.getBitWidth()) |
| 3716 | StartValue = StartValue.extend(width: EndValue.getBitWidth()); |
| 3717 | |
| 3718 | if (!StartDependent && !EndDependent && EndValue < StartValue) { |
| 3719 | Diag(Loc: D.getEllipsisLoc(), DiagID: diag::err_array_designator_empty_range) |
| 3720 | << toString(I: StartValue, Radix: 10) << toString(I: EndValue, Radix: 10) |
| 3721 | << StartIndex->getSourceRange() << EndIndex->getSourceRange(); |
| 3722 | Invalid = true; |
| 3723 | } else { |
| 3724 | Designators.push_back(Elt: ASTDesignator::CreateArrayRangeDesignator( |
| 3725 | Index: InitExpressions.size(), LBracketLoc: D.getLBracketLoc(), EllipsisLoc: D.getEllipsisLoc(), |
| 3726 | RBracketLoc: D.getRBracketLoc())); |
| 3727 | InitExpressions.push_back(Elt: StartIndex); |
| 3728 | InitExpressions.push_back(Elt: EndIndex); |
| 3729 | } |
| 3730 | } |
| 3731 | } |
| 3732 | } |
| 3733 | |
| 3734 | if (Invalid || Init.isInvalid()) |
| 3735 | return ExprError(); |
| 3736 | |
| 3737 | return DesignatedInitExpr::Create(C: Context, Designators, IndexExprs: InitExpressions, |
| 3738 | EqualOrColonLoc, GNUSyntax, |
| 3739 | Init: Init.getAs<Expr>()); |
| 3740 | } |
| 3741 | |
| 3742 | //===----------------------------------------------------------------------===// |
| 3743 | // Initialization entity |
| 3744 | //===----------------------------------------------------------------------===// |
| 3745 | |
| 3746 | InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index, |
| 3747 | const InitializedEntity &Parent) |
| 3748 | : Parent(&Parent), Index(Index) |
| 3749 | { |
| 3750 | if (const ArrayType *AT = Context.getAsArrayType(T: Parent.getType())) { |
| 3751 | Kind = EK_ArrayElement; |
| 3752 | Type = AT->getElementType(); |
| 3753 | } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) { |
| 3754 | Kind = EK_VectorElement; |
| 3755 | Type = VT->getElementType(); |
| 3756 | } else if (const MatrixType *MT = Parent.getType()->getAs<MatrixType>()) { |
| 3757 | Kind = EK_MatrixElement; |
| 3758 | Type = MT->getElementType(); |
| 3759 | } else { |
| 3760 | const ComplexType *CT = Parent.getType()->getAs<ComplexType>(); |
| 3761 | assert(CT && "Unexpected type" ); |
| 3762 | Kind = EK_ComplexElement; |
| 3763 | Type = CT->getElementType(); |
| 3764 | } |
| 3765 | } |
| 3766 | |
| 3767 | InitializedEntity |
| 3768 | InitializedEntity::InitializeBase(ASTContext &Context, |
| 3769 | const CXXBaseSpecifier *Base, |
| 3770 | bool IsInheritedVirtualBase, |
| 3771 | const InitializedEntity *Parent) { |
| 3772 | InitializedEntity Result; |
| 3773 | Result.Kind = EK_Base; |
| 3774 | Result.Parent = Parent; |
| 3775 | Result.Base = {Base, IsInheritedVirtualBase}; |
| 3776 | Result.Type = Base->getType(); |
| 3777 | return Result; |
| 3778 | } |
| 3779 | |
| 3780 | DeclarationName InitializedEntity::getName() const { |
| 3781 | switch (getKind()) { |
| 3782 | case EK_Parameter: |
| 3783 | case EK_Parameter_CF_Audited: { |
| 3784 | ParmVarDecl *D = Parameter.getPointer(); |
| 3785 | return (D ? D->getDeclName() : DeclarationName()); |
| 3786 | } |
| 3787 | |
| 3788 | case EK_Variable: |
| 3789 | case EK_Member: |
| 3790 | case EK_ParenAggInitMember: |
| 3791 | case EK_Binding: |
| 3792 | case EK_TemplateParameter: |
| 3793 | return Variable.VariableOrMember->getDeclName(); |
| 3794 | |
| 3795 | case EK_LambdaCapture: |
| 3796 | return DeclarationName(Capture.VarID); |
| 3797 | |
| 3798 | case EK_Result: |
| 3799 | case EK_StmtExprResult: |
| 3800 | case EK_Exception: |
| 3801 | case EK_New: |
| 3802 | case EK_Temporary: |
| 3803 | case EK_Base: |
| 3804 | case EK_Delegating: |
| 3805 | case EK_ArrayElement: |
| 3806 | case EK_VectorElement: |
| 3807 | case EK_MatrixElement: |
| 3808 | case EK_ComplexElement: |
| 3809 | case EK_BlockElement: |
| 3810 | case EK_LambdaToBlockConversionBlockElement: |
| 3811 | case EK_CompoundLiteralInit: |
| 3812 | case EK_RelatedResult: |
| 3813 | return DeclarationName(); |
| 3814 | } |
| 3815 | |
| 3816 | llvm_unreachable("Invalid EntityKind!" ); |
| 3817 | } |
| 3818 | |
| 3819 | ValueDecl *InitializedEntity::getDecl() const { |
| 3820 | switch (getKind()) { |
| 3821 | case EK_Variable: |
| 3822 | case EK_Member: |
| 3823 | case EK_ParenAggInitMember: |
| 3824 | case EK_Binding: |
| 3825 | case EK_TemplateParameter: |
| 3826 | return cast<ValueDecl>(Val: Variable.VariableOrMember); |
| 3827 | |
| 3828 | case EK_Parameter: |
| 3829 | case EK_Parameter_CF_Audited: |
| 3830 | return Parameter.getPointer(); |
| 3831 | |
| 3832 | case EK_Result: |
| 3833 | case EK_StmtExprResult: |
| 3834 | case EK_Exception: |
| 3835 | case EK_New: |
| 3836 | case EK_Temporary: |
| 3837 | case EK_Base: |
| 3838 | case EK_Delegating: |
| 3839 | case EK_ArrayElement: |
| 3840 | case EK_VectorElement: |
| 3841 | case EK_MatrixElement: |
| 3842 | case EK_ComplexElement: |
| 3843 | case EK_BlockElement: |
| 3844 | case EK_LambdaToBlockConversionBlockElement: |
| 3845 | case EK_LambdaCapture: |
| 3846 | case EK_CompoundLiteralInit: |
| 3847 | case EK_RelatedResult: |
| 3848 | return nullptr; |
| 3849 | } |
| 3850 | |
| 3851 | llvm_unreachable("Invalid EntityKind!" ); |
| 3852 | } |
| 3853 | |
| 3854 | bool InitializedEntity::allowsNRVO() const { |
| 3855 | switch (getKind()) { |
| 3856 | case EK_Result: |
| 3857 | case EK_Exception: |
| 3858 | return LocAndNRVO.NRVO == NRVOKind::Allowed; |
| 3859 | |
| 3860 | case EK_StmtExprResult: |
| 3861 | case EK_Variable: |
| 3862 | case EK_Parameter: |
| 3863 | case EK_Parameter_CF_Audited: |
| 3864 | case EK_TemplateParameter: |
| 3865 | case EK_Member: |
| 3866 | case EK_ParenAggInitMember: |
| 3867 | case EK_Binding: |
| 3868 | case EK_New: |
| 3869 | case EK_Temporary: |
| 3870 | case EK_CompoundLiteralInit: |
| 3871 | case EK_Base: |
| 3872 | case EK_Delegating: |
| 3873 | case EK_ArrayElement: |
| 3874 | case EK_VectorElement: |
| 3875 | case EK_MatrixElement: |
| 3876 | case EK_ComplexElement: |
| 3877 | case EK_BlockElement: |
| 3878 | case EK_LambdaToBlockConversionBlockElement: |
| 3879 | case EK_LambdaCapture: |
| 3880 | case EK_RelatedResult: |
| 3881 | break; |
| 3882 | } |
| 3883 | |
| 3884 | return false; |
| 3885 | } |
| 3886 | |
| 3887 | unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const { |
| 3888 | assert(getParent() != this); |
| 3889 | unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0; |
| 3890 | for (unsigned I = 0; I != Depth; ++I) |
| 3891 | OS << "`-" ; |
| 3892 | |
| 3893 | switch (getKind()) { |
| 3894 | case EK_Variable: OS << "Variable" ; break; |
| 3895 | case EK_Parameter: OS << "Parameter" ; break; |
| 3896 | case EK_Parameter_CF_Audited: OS << "CF audited function Parameter" ; |
| 3897 | break; |
| 3898 | case EK_TemplateParameter: OS << "TemplateParameter" ; break; |
| 3899 | case EK_Result: OS << "Result" ; break; |
| 3900 | case EK_StmtExprResult: OS << "StmtExprResult" ; break; |
| 3901 | case EK_Exception: OS << "Exception" ; break; |
| 3902 | case EK_Member: |
| 3903 | case EK_ParenAggInitMember: |
| 3904 | OS << "Member" ; |
| 3905 | break; |
| 3906 | case EK_Binding: OS << "Binding" ; break; |
| 3907 | case EK_New: OS << "New" ; break; |
| 3908 | case EK_Temporary: OS << "Temporary" ; break; |
| 3909 | case EK_CompoundLiteralInit: OS << "CompoundLiteral" ;break; |
| 3910 | case EK_RelatedResult: OS << "RelatedResult" ; break; |
| 3911 | case EK_Base: OS << "Base" ; break; |
| 3912 | case EK_Delegating: OS << "Delegating" ; break; |
| 3913 | case EK_ArrayElement: OS << "ArrayElement " << Index; break; |
| 3914 | case EK_VectorElement: OS << "VectorElement " << Index; break; |
| 3915 | case EK_MatrixElement: |
| 3916 | OS << "MatrixElement " << Index; |
| 3917 | break; |
| 3918 | case EK_ComplexElement: OS << "ComplexElement " << Index; break; |
| 3919 | case EK_BlockElement: OS << "Block" ; break; |
| 3920 | case EK_LambdaToBlockConversionBlockElement: |
| 3921 | OS << "Block (lambda)" ; |
| 3922 | break; |
| 3923 | case EK_LambdaCapture: |
| 3924 | OS << "LambdaCapture " ; |
| 3925 | OS << DeclarationName(Capture.VarID); |
| 3926 | break; |
| 3927 | } |
| 3928 | |
| 3929 | if (auto *D = getDecl()) { |
| 3930 | OS << " " ; |
| 3931 | D->printQualifiedName(OS); |
| 3932 | } |
| 3933 | |
| 3934 | OS << " '" << getType() << "'\n" ; |
| 3935 | |
| 3936 | return Depth + 1; |
| 3937 | } |
| 3938 | |
| 3939 | LLVM_DUMP_METHOD void InitializedEntity::dump() const { |
| 3940 | dumpImpl(OS&: llvm::errs()); |
| 3941 | } |
| 3942 | |
| 3943 | //===----------------------------------------------------------------------===// |
| 3944 | // Initialization sequence |
| 3945 | //===----------------------------------------------------------------------===// |
| 3946 | |
| 3947 | void InitializationSequence::Step::Destroy() { |
| 3948 | switch (Kind) { |
| 3949 | case SK_ResolveAddressOfOverloadedFunction: |
| 3950 | case SK_CastDerivedToBasePRValue: |
| 3951 | case SK_CastDerivedToBaseXValue: |
| 3952 | case SK_CastDerivedToBaseLValue: |
| 3953 | case SK_BindReference: |
| 3954 | case SK_BindReferenceToTemporary: |
| 3955 | case SK_FinalCopy: |
| 3956 | case SK_ExtraneousCopyToTemporary: |
| 3957 | case SK_UserConversion: |
| 3958 | case SK_QualificationConversionPRValue: |
| 3959 | case SK_QualificationConversionXValue: |
| 3960 | case SK_QualificationConversionLValue: |
| 3961 | case SK_FunctionReferenceConversion: |
| 3962 | case SK_AtomicConversion: |
| 3963 | case SK_ListInitialization: |
| 3964 | case SK_UnwrapInitList: |
| 3965 | case SK_RewrapInitList: |
| 3966 | case SK_ConstructorInitialization: |
| 3967 | case SK_ConstructorInitializationFromList: |
| 3968 | case SK_ZeroInitialization: |
| 3969 | case SK_CAssignment: |
| 3970 | case SK_StringInit: |
| 3971 | case SK_ObjCObjectConversion: |
| 3972 | case SK_ArrayLoopIndex: |
| 3973 | case SK_ArrayLoopInit: |
| 3974 | case SK_ArrayInit: |
| 3975 | case SK_GNUArrayInit: |
| 3976 | case SK_ParenthesizedArrayInit: |
| 3977 | case SK_PassByIndirectCopyRestore: |
| 3978 | case SK_PassByIndirectRestore: |
| 3979 | case SK_ProduceObjCObject: |
| 3980 | case SK_StdInitializerList: |
| 3981 | case SK_StdInitializerListConstructorCall: |
| 3982 | case SK_OCLSamplerInit: |
| 3983 | case SK_OCLZeroOpaqueType: |
| 3984 | case SK_ParenthesizedListInit: |
| 3985 | case SK_HLSLBufferConversion: |
| 3986 | break; |
| 3987 | |
| 3988 | case SK_ConversionSequence: |
| 3989 | case SK_ConversionSequenceNoNarrowing: |
| 3990 | delete ICS; |
| 3991 | } |
| 3992 | } |
| 3993 | |
| 3994 | bool InitializationSequence::isDirectReferenceBinding() const { |
| 3995 | // There can be some lvalue adjustments after the SK_BindReference step. |
| 3996 | for (const Step &S : llvm::reverse(C: Steps)) { |
| 3997 | if (S.Kind == SK_BindReference) |
| 3998 | return true; |
| 3999 | if (S.Kind == SK_BindReferenceToTemporary) |
| 4000 | return false; |
| 4001 | } |
| 4002 | return false; |
| 4003 | } |
| 4004 | |
| 4005 | bool InitializationSequence::isAmbiguous() const { |
| 4006 | if (!Failed()) |
| 4007 | return false; |
| 4008 | |
| 4009 | switch (getFailureKind()) { |
| 4010 | case FK_TooManyInitsForReference: |
| 4011 | case FK_ParenthesizedListInitForReference: |
| 4012 | case FK_ArrayNeedsInitList: |
| 4013 | case FK_ArrayNeedsInitListOrStringLiteral: |
| 4014 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
| 4015 | case FK_NarrowStringIntoWideCharArray: |
| 4016 | case FK_WideStringIntoCharArray: |
| 4017 | case FK_IncompatWideStringIntoWideChar: |
| 4018 | case FK_PlainStringIntoUTF8Char: |
| 4019 | case FK_UTF8StringIntoPlainChar: |
| 4020 | case FK_AddressOfOverloadFailed: // FIXME: Could do better |
| 4021 | case FK_NonConstLValueReferenceBindingToTemporary: |
| 4022 | case FK_NonConstLValueReferenceBindingToBitfield: |
| 4023 | case FK_NonConstLValueReferenceBindingToVectorElement: |
| 4024 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
| 4025 | case FK_NonConstLValueReferenceBindingToUnrelated: |
| 4026 | case FK_RValueReferenceBindingToLValue: |
| 4027 | case FK_ReferenceAddrspaceMismatchTemporary: |
| 4028 | case FK_ReferenceInitDropsQualifiers: |
| 4029 | case FK_ReferenceInitFailed: |
| 4030 | case FK_ConversionFailed: |
| 4031 | case FK_ConversionFromPropertyFailed: |
| 4032 | case FK_TooManyInitsForScalar: |
| 4033 | case FK_ParenthesizedListInitForScalar: |
| 4034 | case FK_ReferenceBindingToInitList: |
| 4035 | case FK_InitListBadDestinationType: |
| 4036 | case FK_DefaultInitOfConst: |
| 4037 | case FK_Incomplete: |
| 4038 | case FK_ArrayTypeMismatch: |
| 4039 | case FK_NonConstantArrayInit: |
| 4040 | case FK_ListInitializationFailed: |
| 4041 | case FK_VariableLengthArrayHasInitializer: |
| 4042 | case FK_PlaceholderType: |
| 4043 | case FK_ExplicitConstructor: |
| 4044 | case FK_AddressOfUnaddressableFunction: |
| 4045 | case FK_ParenthesizedListInitFailed: |
| 4046 | case FK_DesignatedInitForNonAggregate: |
| 4047 | case FK_HLSLInitListFlatteningFailed: |
| 4048 | return false; |
| 4049 | |
| 4050 | case FK_ReferenceInitOverloadFailed: |
| 4051 | case FK_UserConversionOverloadFailed: |
| 4052 | case FK_ConstructorOverloadFailed: |
| 4053 | case FK_ListConstructorOverloadFailed: |
| 4054 | return FailedOverloadResult == OR_Ambiguous; |
| 4055 | } |
| 4056 | |
| 4057 | llvm_unreachable("Invalid EntityKind!" ); |
| 4058 | } |
| 4059 | |
| 4060 | bool InitializationSequence::isConstructorInitialization() const { |
| 4061 | return !Steps.empty() && Steps.back().Kind == SK_ConstructorInitialization; |
| 4062 | } |
| 4063 | |
| 4064 | void |
| 4065 | InitializationSequence |
| 4066 | ::AddAddressOverloadResolutionStep(FunctionDecl *Function, |
| 4067 | DeclAccessPair Found, |
| 4068 | bool HadMultipleCandidates) { |
| 4069 | Step S; |
| 4070 | S.Kind = SK_ResolveAddressOfOverloadedFunction; |
| 4071 | S.Type = Function->getType(); |
| 4072 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
| 4073 | S.Function.Function = Function; |
| 4074 | S.Function.FoundDecl = Found; |
| 4075 | Steps.push_back(Elt: S); |
| 4076 | } |
| 4077 | |
| 4078 | void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType, |
| 4079 | ExprValueKind VK) { |
| 4080 | Step S; |
| 4081 | switch (VK) { |
| 4082 | case VK_PRValue: |
| 4083 | S.Kind = SK_CastDerivedToBasePRValue; |
| 4084 | break; |
| 4085 | case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break; |
| 4086 | case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break; |
| 4087 | } |
| 4088 | S.Type = BaseType; |
| 4089 | Steps.push_back(Elt: S); |
| 4090 | } |
| 4091 | |
| 4092 | void InitializationSequence::AddReferenceBindingStep(QualType T, |
| 4093 | bool BindingTemporary) { |
| 4094 | Step S; |
| 4095 | S.Kind = BindingTemporary? SK_BindReferenceToTemporary : SK_BindReference; |
| 4096 | S.Type = T; |
| 4097 | Steps.push_back(Elt: S); |
| 4098 | } |
| 4099 | |
| 4100 | void InitializationSequence::AddFinalCopy(QualType T) { |
| 4101 | Step S; |
| 4102 | S.Kind = SK_FinalCopy; |
| 4103 | S.Type = T; |
| 4104 | Steps.push_back(Elt: S); |
| 4105 | } |
| 4106 | |
| 4107 | void InitializationSequence::(QualType T) { |
| 4108 | Step S; |
| 4109 | S.Kind = SK_ExtraneousCopyToTemporary; |
| 4110 | S.Type = T; |
| 4111 | Steps.push_back(Elt: S); |
| 4112 | } |
| 4113 | |
| 4114 | void |
| 4115 | InitializationSequence::AddUserConversionStep(FunctionDecl *Function, |
| 4116 | DeclAccessPair FoundDecl, |
| 4117 | QualType T, |
| 4118 | bool HadMultipleCandidates) { |
| 4119 | Step S; |
| 4120 | S.Kind = SK_UserConversion; |
| 4121 | S.Type = T; |
| 4122 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
| 4123 | S.Function.Function = Function; |
| 4124 | S.Function.FoundDecl = FoundDecl; |
| 4125 | Steps.push_back(Elt: S); |
| 4126 | } |
| 4127 | |
| 4128 | void InitializationSequence::AddQualificationConversionStep(QualType Ty, |
| 4129 | ExprValueKind VK) { |
| 4130 | Step S; |
| 4131 | S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning |
| 4132 | switch (VK) { |
| 4133 | case VK_PRValue: |
| 4134 | S.Kind = SK_QualificationConversionPRValue; |
| 4135 | break; |
| 4136 | case VK_XValue: |
| 4137 | S.Kind = SK_QualificationConversionXValue; |
| 4138 | break; |
| 4139 | case VK_LValue: |
| 4140 | S.Kind = SK_QualificationConversionLValue; |
| 4141 | break; |
| 4142 | } |
| 4143 | S.Type = Ty; |
| 4144 | Steps.push_back(Elt: S); |
| 4145 | } |
| 4146 | |
| 4147 | void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) { |
| 4148 | Step S; |
| 4149 | S.Kind = SK_FunctionReferenceConversion; |
| 4150 | S.Type = Ty; |
| 4151 | Steps.push_back(Elt: S); |
| 4152 | } |
| 4153 | |
| 4154 | void InitializationSequence::AddAtomicConversionStep(QualType Ty) { |
| 4155 | Step S; |
| 4156 | S.Kind = SK_AtomicConversion; |
| 4157 | S.Type = Ty; |
| 4158 | Steps.push_back(Elt: S); |
| 4159 | } |
| 4160 | |
| 4161 | void InitializationSequence::AddConversionSequenceStep( |
| 4162 | const ImplicitConversionSequence &ICS, QualType T, |
| 4163 | bool TopLevelOfInitList) { |
| 4164 | Step S; |
| 4165 | S.Kind = TopLevelOfInitList ? SK_ConversionSequenceNoNarrowing |
| 4166 | : SK_ConversionSequence; |
| 4167 | S.Type = T; |
| 4168 | S.ICS = new ImplicitConversionSequence(ICS); |
| 4169 | Steps.push_back(Elt: S); |
| 4170 | } |
| 4171 | |
| 4172 | void InitializationSequence::AddListInitializationStep(QualType T) { |
| 4173 | Step S; |
| 4174 | S.Kind = SK_ListInitialization; |
| 4175 | S.Type = T; |
| 4176 | Steps.push_back(Elt: S); |
| 4177 | } |
| 4178 | |
| 4179 | void InitializationSequence::AddConstructorInitializationStep( |
| 4180 | DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T, |
| 4181 | bool HadMultipleCandidates, bool FromInitList, bool AsInitList) { |
| 4182 | Step S; |
| 4183 | S.Kind = FromInitList ? AsInitList ? SK_StdInitializerListConstructorCall |
| 4184 | : SK_ConstructorInitializationFromList |
| 4185 | : SK_ConstructorInitialization; |
| 4186 | S.Type = T; |
| 4187 | S.Function.HadMultipleCandidates = HadMultipleCandidates; |
| 4188 | S.Function.Function = Constructor; |
| 4189 | S.Function.FoundDecl = FoundDecl; |
| 4190 | Steps.push_back(Elt: S); |
| 4191 | } |
| 4192 | |
| 4193 | void InitializationSequence::AddZeroInitializationStep(QualType T) { |
| 4194 | Step S; |
| 4195 | S.Kind = SK_ZeroInitialization; |
| 4196 | S.Type = T; |
| 4197 | Steps.push_back(Elt: S); |
| 4198 | } |
| 4199 | |
| 4200 | void InitializationSequence::AddCAssignmentStep(QualType T) { |
| 4201 | Step S; |
| 4202 | S.Kind = SK_CAssignment; |
| 4203 | S.Type = T; |
| 4204 | Steps.push_back(Elt: S); |
| 4205 | } |
| 4206 | |
| 4207 | void InitializationSequence::AddStringInitStep(QualType T) { |
| 4208 | Step S; |
| 4209 | S.Kind = SK_StringInit; |
| 4210 | S.Type = T; |
| 4211 | Steps.push_back(Elt: S); |
| 4212 | } |
| 4213 | |
| 4214 | void InitializationSequence::AddObjCObjectConversionStep(QualType T) { |
| 4215 | Step S; |
| 4216 | S.Kind = SK_ObjCObjectConversion; |
| 4217 | S.Type = T; |
| 4218 | Steps.push_back(Elt: S); |
| 4219 | } |
| 4220 | |
| 4221 | void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) { |
| 4222 | Step S; |
| 4223 | S.Kind = IsGNUExtension ? SK_GNUArrayInit : SK_ArrayInit; |
| 4224 | S.Type = T; |
| 4225 | Steps.push_back(Elt: S); |
| 4226 | } |
| 4227 | |
| 4228 | void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) { |
| 4229 | Step S; |
| 4230 | S.Kind = SK_ArrayLoopIndex; |
| 4231 | S.Type = EltT; |
| 4232 | Steps.insert(I: Steps.begin(), Elt: S); |
| 4233 | |
| 4234 | S.Kind = SK_ArrayLoopInit; |
| 4235 | S.Type = T; |
| 4236 | Steps.push_back(Elt: S); |
| 4237 | } |
| 4238 | |
| 4239 | void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) { |
| 4240 | Step S; |
| 4241 | S.Kind = SK_ParenthesizedArrayInit; |
| 4242 | S.Type = T; |
| 4243 | Steps.push_back(Elt: S); |
| 4244 | } |
| 4245 | |
| 4246 | void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type, |
| 4247 | bool shouldCopy) { |
| 4248 | Step s; |
| 4249 | s.Kind = (shouldCopy ? SK_PassByIndirectCopyRestore |
| 4250 | : SK_PassByIndirectRestore); |
| 4251 | s.Type = type; |
| 4252 | Steps.push_back(Elt: s); |
| 4253 | } |
| 4254 | |
| 4255 | void InitializationSequence::AddProduceObjCObjectStep(QualType T) { |
| 4256 | Step S; |
| 4257 | S.Kind = SK_ProduceObjCObject; |
| 4258 | S.Type = T; |
| 4259 | Steps.push_back(Elt: S); |
| 4260 | } |
| 4261 | |
| 4262 | void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) { |
| 4263 | Step S; |
| 4264 | S.Kind = SK_StdInitializerList; |
| 4265 | S.Type = T; |
| 4266 | Steps.push_back(Elt: S); |
| 4267 | } |
| 4268 | |
| 4269 | void InitializationSequence::AddOCLSamplerInitStep(QualType T) { |
| 4270 | Step S; |
| 4271 | S.Kind = SK_OCLSamplerInit; |
| 4272 | S.Type = T; |
| 4273 | Steps.push_back(Elt: S); |
| 4274 | } |
| 4275 | |
| 4276 | void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) { |
| 4277 | Step S; |
| 4278 | S.Kind = SK_OCLZeroOpaqueType; |
| 4279 | S.Type = T; |
| 4280 | Steps.push_back(Elt: S); |
| 4281 | } |
| 4282 | |
| 4283 | void InitializationSequence::AddParenthesizedListInitStep(QualType T) { |
| 4284 | Step S; |
| 4285 | S.Kind = SK_ParenthesizedListInit; |
| 4286 | S.Type = T; |
| 4287 | Steps.push_back(Elt: S); |
| 4288 | } |
| 4289 | |
| 4290 | void InitializationSequence::AddUnwrapInitListInitStep( |
| 4291 | InitListExpr *Syntactic) { |
| 4292 | assert(Syntactic->getNumInits() == 1 && |
| 4293 | "Can only unwrap trivial init lists." ); |
| 4294 | Step S; |
| 4295 | S.Kind = SK_UnwrapInitList; |
| 4296 | S.Type = Syntactic->getInit(Init: 0)->getType(); |
| 4297 | Steps.insert(I: Steps.begin(), Elt: S); |
| 4298 | } |
| 4299 | |
| 4300 | void InitializationSequence::RewrapReferenceInitList(QualType T, |
| 4301 | InitListExpr *Syntactic) { |
| 4302 | assert(Syntactic->getNumInits() == 1 && |
| 4303 | "Can only rewrap trivial init lists." ); |
| 4304 | Step S; |
| 4305 | S.Kind = SK_UnwrapInitList; |
| 4306 | S.Type = Syntactic->getInit(Init: 0)->getType(); |
| 4307 | Steps.insert(I: Steps.begin(), Elt: S); |
| 4308 | |
| 4309 | S.Kind = SK_RewrapInitList; |
| 4310 | S.Type = T; |
| 4311 | S.WrappingSyntacticList = Syntactic; |
| 4312 | Steps.push_back(Elt: S); |
| 4313 | } |
| 4314 | |
| 4315 | void InitializationSequence::AddHLSLBufferConversionStep(QualType T) { |
| 4316 | Step S; |
| 4317 | S.Kind = SK_HLSLBufferConversion; |
| 4318 | S.Type = T; |
| 4319 | Steps.push_back(Elt: S); |
| 4320 | } |
| 4321 | |
| 4322 | void InitializationSequence::SetOverloadFailure(FailureKind Failure, |
| 4323 | OverloadingResult Result) { |
| 4324 | setSequenceKind(FailedSequence); |
| 4325 | this->Failure = Failure; |
| 4326 | this->FailedOverloadResult = Result; |
| 4327 | } |
| 4328 | |
| 4329 | //===----------------------------------------------------------------------===// |
| 4330 | // Attempt initialization |
| 4331 | //===----------------------------------------------------------------------===// |
| 4332 | |
| 4333 | /// Tries to add a zero initializer. Returns true if that worked. |
| 4334 | static bool |
| 4335 | maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence, |
| 4336 | const InitializedEntity &Entity) { |
| 4337 | if (Entity.getKind() != InitializedEntity::EK_Variable) |
| 4338 | return false; |
| 4339 | |
| 4340 | VarDecl *VD = cast<VarDecl>(Val: Entity.getDecl()); |
| 4341 | if (VD->getInit() || VD->getEndLoc().isMacroID()) |
| 4342 | return false; |
| 4343 | |
| 4344 | QualType VariableTy = VD->getType().getCanonicalType(); |
| 4345 | SourceLocation Loc = S.getLocForEndOfToken(Loc: VD->getEndLoc()); |
| 4346 | std::string Init = S.getFixItZeroInitializerForType(T: VariableTy, Loc); |
| 4347 | if (!Init.empty()) { |
| 4348 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
| 4349 | Sequence.SetZeroInitializationFixit(Fixit: Init, L: Loc); |
| 4350 | return true; |
| 4351 | } |
| 4352 | return false; |
| 4353 | } |
| 4354 | |
| 4355 | static void MaybeProduceObjCObject(Sema &S, |
| 4356 | InitializationSequence &Sequence, |
| 4357 | const InitializedEntity &Entity) { |
| 4358 | if (!S.getLangOpts().ObjCAutoRefCount) return; |
| 4359 | |
| 4360 | /// When initializing a parameter, produce the value if it's marked |
| 4361 | /// __attribute__((ns_consumed)). |
| 4362 | if (Entity.isParameterKind()) { |
| 4363 | if (!Entity.isParameterConsumed()) |
| 4364 | return; |
| 4365 | |
| 4366 | assert(Entity.getType()->isObjCRetainableType() && |
| 4367 | "consuming an object of unretainable type?" ); |
| 4368 | Sequence.AddProduceObjCObjectStep(T: Entity.getType()); |
| 4369 | |
| 4370 | /// When initializing a return value, if the return type is a |
| 4371 | /// retainable type, then returns need to immediately retain the |
| 4372 | /// object. If an autorelease is required, it will be done at the |
| 4373 | /// last instant. |
| 4374 | } else if (Entity.getKind() == InitializedEntity::EK_Result || |
| 4375 | Entity.getKind() == InitializedEntity::EK_StmtExprResult) { |
| 4376 | if (!Entity.getType()->isObjCRetainableType()) |
| 4377 | return; |
| 4378 | |
| 4379 | Sequence.AddProduceObjCObjectStep(T: Entity.getType()); |
| 4380 | } |
| 4381 | } |
| 4382 | |
| 4383 | /// Initialize an array from another array |
| 4384 | static void TryArrayCopy(Sema &S, const InitializationKind &Kind, |
| 4385 | const InitializedEntity &Entity, Expr *Initializer, |
| 4386 | QualType DestType, InitializationSequence &Sequence, |
| 4387 | bool TreatUnavailableAsInvalid) { |
| 4388 | // If source is a prvalue, use it directly. |
| 4389 | if (Initializer->isPRValue()) { |
| 4390 | Sequence.AddArrayInitStep(T: DestType, /*IsGNUExtension*/ false); |
| 4391 | return; |
| 4392 | } |
| 4393 | |
| 4394 | // Emit element-at-a-time copy loop. |
| 4395 | InitializedEntity Element = |
| 4396 | InitializedEntity::InitializeElement(Context&: S.Context, Index: 0, Parent: Entity); |
| 4397 | QualType InitEltT = |
| 4398 | S.Context.getAsArrayType(T: Initializer->getType())->getElementType(); |
| 4399 | |
| 4400 | // FIXME: Here's a functional memory leak cuz we don't have a temporary |
| 4401 | // allocator at the moment |
| 4402 | OpaqueValueExpr *OVE = new (S.Context) OpaqueValueExpr( |
| 4403 | Initializer->getExprLoc(), InitEltT, Initializer->getValueKind(), |
| 4404 | Initializer->getObjectKind()); |
| 4405 | Expr *OVEAsExpr = OVE; |
| 4406 | Sequence.InitializeFrom(S, Entity: Element, Kind, Args: OVEAsExpr, |
| 4407 | /*TopLevelOfInitList*/ false, |
| 4408 | TreatUnavailableAsInvalid); |
| 4409 | if (Sequence) |
| 4410 | Sequence.AddArrayInitLoopStep(T: Entity.getType(), EltT: InitEltT); |
| 4411 | } |
| 4412 | |
| 4413 | static void TryListInitialization(Sema &S, |
| 4414 | const InitializedEntity &Entity, |
| 4415 | const InitializationKind &Kind, |
| 4416 | InitListExpr *InitList, |
| 4417 | InitializationSequence &Sequence, |
| 4418 | bool TreatUnavailableAsInvalid); |
| 4419 | |
| 4420 | /// When initializing from init list via constructor, handle |
| 4421 | /// initialization of an object of type std::initializer_list<T>. |
| 4422 | /// |
| 4423 | /// \return true if we have handled initialization of an object of type |
| 4424 | /// std::initializer_list<T>, false otherwise. |
| 4425 | static bool TryInitializerListConstruction(Sema &S, |
| 4426 | InitListExpr *List, |
| 4427 | QualType DestType, |
| 4428 | InitializationSequence &Sequence, |
| 4429 | bool TreatUnavailableAsInvalid) { |
| 4430 | QualType E; |
| 4431 | if (!S.isStdInitializerList(Ty: DestType, Element: &E)) |
| 4432 | return false; |
| 4433 | |
| 4434 | if (!S.isCompleteType(Loc: List->getExprLoc(), T: E)) { |
| 4435 | Sequence.setIncompleteTypeFailure(E); |
| 4436 | return true; |
| 4437 | } |
| 4438 | |
| 4439 | // Try initializing a temporary array from the init list. |
| 4440 | QualType ArrayType = S.Context.getConstantArrayType( |
| 4441 | EltTy: E.withConst(), |
| 4442 | ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()), |
| 4443 | List->getNumInitsWithEmbedExpanded()), |
| 4444 | SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 4445 | InitializedEntity HiddenArray = |
| 4446 | InitializedEntity::InitializeTemporary(Type: ArrayType); |
| 4447 | InitializationKind Kind = InitializationKind::CreateDirectList( |
| 4448 | InitLoc: List->getExprLoc(), LBraceLoc: List->getBeginLoc(), RBraceLoc: List->getEndLoc()); |
| 4449 | TryListInitialization(S, Entity: HiddenArray, Kind, InitList: List, Sequence, |
| 4450 | TreatUnavailableAsInvalid); |
| 4451 | if (Sequence) |
| 4452 | Sequence.AddStdInitializerListConstructionStep(T: DestType); |
| 4453 | return true; |
| 4454 | } |
| 4455 | |
| 4456 | /// Determine if the constructor has the signature of a copy or move |
| 4457 | /// constructor for the type T of the class in which it was found. That is, |
| 4458 | /// determine if its first parameter is of type T or reference to (possibly |
| 4459 | /// cv-qualified) T. |
| 4460 | static bool hasCopyOrMoveCtorParam(ASTContext &Ctx, |
| 4461 | const ConstructorInfo &Info) { |
| 4462 | if (Info.Constructor->getNumParams() == 0) |
| 4463 | return false; |
| 4464 | |
| 4465 | QualType ParmT = |
| 4466 | Info.Constructor->getParamDecl(i: 0)->getType().getNonReferenceType(); |
| 4467 | CanQualType ClassT = Ctx.getCanonicalTagType( |
| 4468 | TD: cast<CXXRecordDecl>(Val: Info.FoundDecl->getDeclContext())); |
| 4469 | |
| 4470 | return Ctx.hasSameUnqualifiedType(T1: ParmT, T2: ClassT); |
| 4471 | } |
| 4472 | |
| 4473 | static OverloadingResult ResolveConstructorOverload( |
| 4474 | Sema &S, SourceLocation DeclLoc, MultiExprArg Args, |
| 4475 | OverloadCandidateSet &CandidateSet, QualType DestType, |
| 4476 | DeclContext::lookup_result Ctors, OverloadCandidateSet::iterator &Best, |
| 4477 | bool CopyInitializing, bool AllowExplicit, bool OnlyListConstructors, |
| 4478 | bool IsListInit, bool RequireActualConstructor, |
| 4479 | bool SecondStepOfCopyInit = false) { |
| 4480 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByConstructor); |
| 4481 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); |
| 4482 | |
| 4483 | for (NamedDecl *D : Ctors) { |
| 4484 | auto Info = getConstructorInfo(ND: D); |
| 4485 | if (!Info.Constructor || Info.Constructor->isInvalidDecl()) |
| 4486 | continue; |
| 4487 | |
| 4488 | if (OnlyListConstructors && !S.isInitListConstructor(Ctor: Info.Constructor)) |
| 4489 | continue; |
| 4490 | |
| 4491 | // C++11 [over.best.ics]p4: |
| 4492 | // ... and the constructor or user-defined conversion function is a |
| 4493 | // candidate by |
| 4494 | // - 13.3.1.3, when the argument is the temporary in the second step |
| 4495 | // of a class copy-initialization, or |
| 4496 | // - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here] |
| 4497 | // - the second phase of 13.3.1.7 when the initializer list has exactly |
| 4498 | // one element that is itself an initializer list, and the target is |
| 4499 | // the first parameter of a constructor of class X, and the conversion |
| 4500 | // is to X or reference to (possibly cv-qualified X), |
| 4501 | // user-defined conversion sequences are not considered. |
| 4502 | bool SuppressUserConversions = |
| 4503 | SecondStepOfCopyInit || |
| 4504 | (IsListInit && Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) && |
| 4505 | hasCopyOrMoveCtorParam(Ctx&: S.Context, Info)); |
| 4506 | |
| 4507 | if (Info.ConstructorTmpl) |
| 4508 | S.AddTemplateOverloadCandidate( |
| 4509 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
| 4510 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args, CandidateSet, SuppressUserConversions, |
| 4511 | /*PartialOverloading=*/false, AllowExplicit); |
| 4512 | else { |
| 4513 | // C++ [over.match.copy]p1: |
| 4514 | // - When initializing a temporary to be bound to the first parameter |
| 4515 | // of a constructor [for type T] that takes a reference to possibly |
| 4516 | // cv-qualified T as its first argument, called with a single |
| 4517 | // argument in the context of direct-initialization, explicit |
| 4518 | // conversion functions are also considered. |
| 4519 | // FIXME: What if a constructor template instantiates to such a signature? |
| 4520 | bool AllowExplicitConv = AllowExplicit && !CopyInitializing && |
| 4521 | Args.size() == 1 && |
| 4522 | hasCopyOrMoveCtorParam(Ctx&: S.Context, Info); |
| 4523 | S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args, |
| 4524 | CandidateSet, SuppressUserConversions, |
| 4525 | /*PartialOverloading=*/false, AllowExplicit, |
| 4526 | AllowExplicitConversion: AllowExplicitConv); |
| 4527 | } |
| 4528 | } |
| 4529 | |
| 4530 | // FIXME: Work around a bug in C++17 guaranteed copy elision. |
| 4531 | // |
| 4532 | // When initializing an object of class type T by constructor |
| 4533 | // ([over.match.ctor]) or by list-initialization ([over.match.list]) |
| 4534 | // from a single expression of class type U, conversion functions of |
| 4535 | // U that convert to the non-reference type cv T are candidates. |
| 4536 | // Explicit conversion functions are only candidates during |
| 4537 | // direct-initialization. |
| 4538 | // |
| 4539 | // Note: SecondStepOfCopyInit is only ever true in this case when |
| 4540 | // evaluating whether to produce a C++98 compatibility warning. |
| 4541 | if (S.getLangOpts().CPlusPlus17 && Args.size() == 1 && |
| 4542 | !RequireActualConstructor && !SecondStepOfCopyInit) { |
| 4543 | Expr *Initializer = Args[0]; |
| 4544 | auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl(); |
| 4545 | if (SourceRD && S.isCompleteType(Loc: DeclLoc, T: Initializer->getType())) { |
| 4546 | const auto &Conversions = SourceRD->getVisibleConversionFunctions(); |
| 4547 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
| 4548 | NamedDecl *D = *I; |
| 4549 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext()); |
| 4550 | D = D->getUnderlyingDecl(); |
| 4551 | |
| 4552 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
| 4553 | CXXConversionDecl *Conv; |
| 4554 | if (ConvTemplate) |
| 4555 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
| 4556 | else |
| 4557 | Conv = cast<CXXConversionDecl>(Val: D); |
| 4558 | |
| 4559 | if (ConvTemplate) |
| 4560 | S.AddTemplateConversionCandidate( |
| 4561 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
| 4562 | CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit, |
| 4563 | /*AllowResultConversion*/ false); |
| 4564 | else |
| 4565 | S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, |
| 4566 | ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, |
| 4567 | AllowExplicit, |
| 4568 | /*AllowResultConversion*/ false); |
| 4569 | } |
| 4570 | } |
| 4571 | } |
| 4572 | |
| 4573 | // Perform overload resolution and return the result. |
| 4574 | return CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best); |
| 4575 | } |
| 4576 | |
| 4577 | /// Attempt initialization by constructor (C++ [dcl.init]), which |
| 4578 | /// enumerates the constructors of the initialized entity and performs overload |
| 4579 | /// resolution to select the best. |
| 4580 | /// \param DestType The destination class type. |
| 4581 | /// \param DestArrayType The destination type, which is either DestType or |
| 4582 | /// a (possibly multidimensional) array of DestType. |
| 4583 | /// \param IsListInit Is this list-initialization? |
| 4584 | /// \param IsInitListCopy Is this non-list-initialization resulting from a |
| 4585 | /// list-initialization from {x} where x is the same |
| 4586 | /// aggregate type as the entity? |
| 4587 | static void TryConstructorInitialization(Sema &S, |
| 4588 | const InitializedEntity &Entity, |
| 4589 | const InitializationKind &Kind, |
| 4590 | MultiExprArg Args, QualType DestType, |
| 4591 | QualType DestArrayType, |
| 4592 | InitializationSequence &Sequence, |
| 4593 | bool IsListInit = false, |
| 4594 | bool IsInitListCopy = false) { |
| 4595 | assert(((!IsListInit && !IsInitListCopy) || |
| 4596 | (Args.size() == 1 && isa<InitListExpr>(Args[0]))) && |
| 4597 | "IsListInit/IsInitListCopy must come with a single initializer list " |
| 4598 | "argument." ); |
| 4599 | InitListExpr *ILE = |
| 4600 | (IsListInit || IsInitListCopy) ? cast<InitListExpr>(Val: Args[0]) : nullptr; |
| 4601 | MultiExprArg UnwrappedArgs = |
| 4602 | ILE ? MultiExprArg(ILE->getInits(), ILE->getNumInits()) : Args; |
| 4603 | |
| 4604 | // The type we're constructing needs to be complete. |
| 4605 | if (!S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) { |
| 4606 | Sequence.setIncompleteTypeFailure(DestType); |
| 4607 | return; |
| 4608 | } |
| 4609 | |
| 4610 | bool RequireActualConstructor = |
| 4611 | !(Entity.getKind() != InitializedEntity::EK_Base && |
| 4612 | Entity.getKind() != InitializedEntity::EK_Delegating && |
| 4613 | Entity.getKind() != |
| 4614 | InitializedEntity::EK_LambdaToBlockConversionBlockElement); |
| 4615 | |
| 4616 | bool CopyElisionPossible = false; |
| 4617 | auto ElideConstructor = [&] { |
| 4618 | // Convert qualifications if necessary. |
| 4619 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
| 4620 | if (ILE) |
| 4621 | Sequence.RewrapReferenceInitList(T: DestType, Syntactic: ILE); |
| 4622 | }; |
| 4623 | |
| 4624 | // C++17 [dcl.init]p17: |
| 4625 | // - If the initializer expression is a prvalue and the cv-unqualified |
| 4626 | // version of the source type is the same class as the class of the |
| 4627 | // destination, the initializer expression is used to initialize the |
| 4628 | // destination object. |
| 4629 | // Per DR (no number yet), this does not apply when initializing a base |
| 4630 | // class or delegating to another constructor from a mem-initializer. |
| 4631 | // ObjC++: Lambda captured by the block in the lambda to block conversion |
| 4632 | // should avoid copy elision. |
| 4633 | if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor && |
| 4634 | UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() && |
| 4635 | S.Context.hasSameUnqualifiedType(T1: UnwrappedArgs[0]->getType(), T2: DestType)) { |
| 4636 | if (ILE && !DestType->isAggregateType()) { |
| 4637 | // CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision |
| 4638 | // Make this an elision if this won't call an initializer-list |
| 4639 | // constructor. (Always on an aggregate type or check constructors first.) |
| 4640 | |
| 4641 | // This effectively makes our resolution as follows. The parts in angle |
| 4642 | // brackets are additions. |
| 4643 | // C++17 [over.match.list]p(1.2): |
| 4644 | // - If no viable initializer-list constructor is found <and the |
| 4645 | // initializer list does not consist of exactly a single element with |
| 4646 | // the same cv-unqualified class type as T>, [...] |
| 4647 | // C++17 [dcl.init.list]p(3.6): |
| 4648 | // - Otherwise, if T is a class type, constructors are considered. The |
| 4649 | // applicable constructors are enumerated and the best one is chosen |
| 4650 | // through overload resolution. <If no constructor is found and the |
| 4651 | // initializer list consists of exactly a single element with the same |
| 4652 | // cv-unqualified class type as T, the object is initialized from that |
| 4653 | // element (by copy-initialization for copy-list-initialization, or by |
| 4654 | // direct-initialization for direct-list-initialization). Otherwise, > |
| 4655 | // if a narrowing conversion [...] |
| 4656 | assert(!IsInitListCopy && |
| 4657 | "IsInitListCopy only possible with aggregate types" ); |
| 4658 | CopyElisionPossible = true; |
| 4659 | } else { |
| 4660 | ElideConstructor(); |
| 4661 | return; |
| 4662 | } |
| 4663 | } |
| 4664 | |
| 4665 | auto *DestRecordDecl = DestType->castAsCXXRecordDecl(); |
| 4666 | // Build the candidate set directly in the initialization sequence |
| 4667 | // structure, so that it will persist if we fail. |
| 4668 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
| 4669 | |
| 4670 | // Determine whether we are allowed to call explicit constructors or |
| 4671 | // explicit conversion operators. |
| 4672 | bool AllowExplicit = Kind.AllowExplicit() || IsListInit; |
| 4673 | bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy; |
| 4674 | |
| 4675 | // - Otherwise, if T is a class type, constructors are considered. The |
| 4676 | // applicable constructors are enumerated, and the best one is chosen |
| 4677 | // through overload resolution. |
| 4678 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class: DestRecordDecl); |
| 4679 | |
| 4680 | OverloadingResult Result = OR_No_Viable_Function; |
| 4681 | OverloadCandidateSet::iterator Best; |
| 4682 | bool AsInitializerList = false; |
| 4683 | |
| 4684 | // C++11 [over.match.list]p1, per DR1467: |
| 4685 | // When objects of non-aggregate type T are list-initialized, such that |
| 4686 | // 8.5.4 [dcl.init.list] specifies that overload resolution is performed |
| 4687 | // according to the rules in this section, overload resolution selects |
| 4688 | // the constructor in two phases: |
| 4689 | // |
| 4690 | // - Initially, the candidate functions are the initializer-list |
| 4691 | // constructors of the class T and the argument list consists of the |
| 4692 | // initializer list as a single argument. |
| 4693 | if (IsListInit) { |
| 4694 | AsInitializerList = true; |
| 4695 | |
| 4696 | // If the initializer list has no elements and T has a default constructor, |
| 4697 | // the first phase is omitted. |
| 4698 | if (!(UnwrappedArgs.empty() && S.LookupDefaultConstructor(Class: DestRecordDecl))) |
| 4699 | Result = ResolveConstructorOverload( |
| 4700 | S, DeclLoc: Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best, |
| 4701 | CopyInitializing: CopyInitialization, AllowExplicit, |
| 4702 | /*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor); |
| 4703 | |
| 4704 | if (CopyElisionPossible && Result == OR_No_Viable_Function) { |
| 4705 | // No initializer list candidate |
| 4706 | ElideConstructor(); |
| 4707 | return; |
| 4708 | } |
| 4709 | } |
| 4710 | |
| 4711 | // if the initialization is direct-initialization, or if it is |
| 4712 | // copy-initialization where the cv-unqualified version of the source type is |
| 4713 | // the same as or is derived from the class of the destination type, |
| 4714 | // constructors are considered. |
| 4715 | if ((Kind.getKind() == InitializationKind::IK_Direct || |
| 4716 | Kind.getKind() == InitializationKind::IK_Copy) && |
| 4717 | Args.size() == 1 && |
| 4718 | S.getASTContext().hasSameUnqualifiedType( |
| 4719 | T1: Args[0]->getType().getNonReferenceType(), |
| 4720 | T2: DestType.getNonReferenceType())) |
| 4721 | RequireActualConstructor = true; |
| 4722 | |
| 4723 | // C++11 [over.match.list]p1: |
| 4724 | // - If no viable initializer-list constructor is found, overload resolution |
| 4725 | // is performed again, where the candidate functions are all the |
| 4726 | // constructors of the class T and the argument list consists of the |
| 4727 | // elements of the initializer list. |
| 4728 | if (Result == OR_No_Viable_Function) { |
| 4729 | AsInitializerList = false; |
| 4730 | Result = ResolveConstructorOverload( |
| 4731 | S, DeclLoc: Kind.getLocation(), Args: UnwrappedArgs, CandidateSet, DestType, Ctors, |
| 4732 | Best, CopyInitializing: CopyInitialization, AllowExplicit, |
| 4733 | /*OnlyListConstructors=*/false, IsListInit, RequireActualConstructor); |
| 4734 | } |
| 4735 | if (Result) { |
| 4736 | Sequence.SetOverloadFailure( |
| 4737 | Failure: IsListInit ? InitializationSequence::FK_ListConstructorOverloadFailed |
| 4738 | : InitializationSequence::FK_ConstructorOverloadFailed, |
| 4739 | Result); |
| 4740 | |
| 4741 | if (Result != OR_Deleted) |
| 4742 | return; |
| 4743 | } |
| 4744 | |
| 4745 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
| 4746 | |
| 4747 | // In C++17, ResolveConstructorOverload can select a conversion function |
| 4748 | // instead of a constructor. |
| 4749 | if (auto *CD = dyn_cast<CXXConversionDecl>(Val: Best->Function)) { |
| 4750 | // Add the user-defined conversion step that calls the conversion function. |
| 4751 | QualType ConvType = CD->getConversionType(); |
| 4752 | assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) && |
| 4753 | "should not have selected this conversion function" ); |
| 4754 | Sequence.AddUserConversionStep(Function: CD, FoundDecl: Best->FoundDecl, T: ConvType, |
| 4755 | HadMultipleCandidates); |
| 4756 | if (!S.Context.hasSameType(T1: ConvType, T2: DestType)) |
| 4757 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
| 4758 | if (IsListInit) |
| 4759 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: ILE); |
| 4760 | return; |
| 4761 | } |
| 4762 | |
| 4763 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
| 4764 | if (Result != OR_Deleted) { |
| 4765 | if (!IsListInit && |
| 4766 | (Kind.getKind() == InitializationKind::IK_Default || |
| 4767 | Kind.getKind() == InitializationKind::IK_Direct) && |
| 4768 | !(CtorDecl->isCopyOrMoveConstructor() && CtorDecl->isImplicit()) && |
| 4769 | DestRecordDecl->isAggregate() && |
| 4770 | DestRecordDecl->hasUninitializedExplicitInitFields() && |
| 4771 | !S.isUnevaluatedContext()) { |
| 4772 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init) |
| 4773 | << /* Var-in-Record */ 1 << DestRecordDecl; |
| 4774 | emitUninitializedExplicitInitFields(S, R: DestRecordDecl); |
| 4775 | } |
| 4776 | |
| 4777 | // C++11 [dcl.init]p6: |
| 4778 | // If a program calls for the default initialization of an object |
| 4779 | // of a const-qualified type T, T shall be a class type with a |
| 4780 | // user-provided default constructor. |
| 4781 | // C++ core issue 253 proposal: |
| 4782 | // If the implicit default constructor initializes all subobjects, no |
| 4783 | // initializer should be required. |
| 4784 | // The 253 proposal is for example needed to process libstdc++ headers |
| 4785 | // in 5.x. |
| 4786 | if (Kind.getKind() == InitializationKind::IK_Default && |
| 4787 | Entity.getType().isConstQualified()) { |
| 4788 | if (!CtorDecl->getParent()->allowConstDefaultInit()) { |
| 4789 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) |
| 4790 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); |
| 4791 | return; |
| 4792 | } |
| 4793 | } |
| 4794 | |
| 4795 | // C++11 [over.match.list]p1: |
| 4796 | // In copy-list-initialization, if an explicit constructor is chosen, the |
| 4797 | // initializer is ill-formed. |
| 4798 | if (IsListInit && !Kind.AllowExplicit() && CtorDecl->isExplicit()) { |
| 4799 | Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor); |
| 4800 | return; |
| 4801 | } |
| 4802 | } |
| 4803 | |
| 4804 | // [class.copy.elision]p3: |
| 4805 | // In some copy-initialization contexts, a two-stage overload resolution |
| 4806 | // is performed. |
| 4807 | // If the first overload resolution selects a deleted function, we also |
| 4808 | // need the initialization sequence to decide whether to perform the second |
| 4809 | // overload resolution. |
| 4810 | // For deleted functions in other contexts, there is no need to get the |
| 4811 | // initialization sequence. |
| 4812 | if (Result == OR_Deleted && Kind.getKind() != InitializationKind::IK_Copy) |
| 4813 | return; |
| 4814 | |
| 4815 | // Add the constructor initialization step. Any cv-qualification conversion is |
| 4816 | // subsumed by the initialization. |
| 4817 | Sequence.AddConstructorInitializationStep( |
| 4818 | FoundDecl: Best->FoundDecl, Constructor: CtorDecl, T: DestArrayType, HadMultipleCandidates, |
| 4819 | FromInitList: IsListInit | IsInitListCopy, AsInitList: AsInitializerList); |
| 4820 | } |
| 4821 | |
| 4822 | static void TryOrBuildParenListInitialization( |
| 4823 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
| 4824 | ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly, |
| 4825 | ExprResult *Result = nullptr); |
| 4826 | |
| 4827 | /// Attempt to initialize an object of a class type either by |
| 4828 | /// direct-initialization, or by copy-initialization from an |
| 4829 | /// expression of the same or derived class type. This corresponds |
| 4830 | /// to the first two sub-bullets of C++2c [dcl.init.general] p16.6. |
| 4831 | /// |
| 4832 | /// \param IsAggrListInit Is this non-list-initialization being done as |
| 4833 | /// part of a list-initialization of an aggregate |
| 4834 | /// from a single expression of the same or |
| 4835 | /// derived class type (C++2c [dcl.init.list] p3.2)? |
| 4836 | static void TryConstructorOrParenListInitialization( |
| 4837 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
| 4838 | MultiExprArg Args, QualType DestType, InitializationSequence &Sequence, |
| 4839 | bool IsAggrListInit) { |
| 4840 | // C++2c [dcl.init.general] p16.6: |
| 4841 | // * Otherwise, if the destination type is a class type: |
| 4842 | // * If the initializer expression is a prvalue and |
| 4843 | // the cv-unqualified version of the source type is the same |
| 4844 | // as the destination type, the initializer expression is used |
| 4845 | // to initialize the destination object. |
| 4846 | // * Otherwise, if the initialization is direct-initialization, |
| 4847 | // or if it is copy-initialization where the cv-unqualified |
| 4848 | // version of the source type is the same as or is derived from |
| 4849 | // the class of the destination type, constructors are considered. |
| 4850 | // The applicable constructors are enumerated, and the best one |
| 4851 | // is chosen through overload resolution. Then: |
| 4852 | // * If overload resolution is successful, the selected |
| 4853 | // constructor is called to initialize the object, with |
| 4854 | // the initializer expression or expression-list as its |
| 4855 | // argument(s). |
| 4856 | TryConstructorInitialization(S, Entity, Kind, Args, DestType, DestArrayType: DestType, |
| 4857 | Sequence, /*IsListInit=*/false, IsInitListCopy: IsAggrListInit); |
| 4858 | |
| 4859 | // * Otherwise, if no constructor is viable, the destination type |
| 4860 | // is an aggregate class, and the initializer is a parenthesized |
| 4861 | // expression-list, the object is initialized as follows. [...] |
| 4862 | // Parenthesized initialization of aggregates is a C++20 feature. |
| 4863 | if (S.getLangOpts().CPlusPlus20 && |
| 4864 | Kind.getKind() == InitializationKind::IK_Direct && Sequence.Failed() && |
| 4865 | Sequence.getFailureKind() == |
| 4866 | InitializationSequence::FK_ConstructorOverloadFailed && |
| 4867 | Sequence.getFailedOverloadResult() == OR_No_Viable_Function && |
| 4868 | (IsAggrListInit || DestType->isAggregateType())) |
| 4869 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence, |
| 4870 | /*VerifyOnly=*/true); |
| 4871 | |
| 4872 | // * Otherwise, the initialization is ill-formed. |
| 4873 | } |
| 4874 | |
| 4875 | static bool |
| 4876 | ResolveOverloadedFunctionForReferenceBinding(Sema &S, |
| 4877 | Expr *Initializer, |
| 4878 | QualType &SourceType, |
| 4879 | QualType &UnqualifiedSourceType, |
| 4880 | QualType UnqualifiedTargetType, |
| 4881 | InitializationSequence &Sequence) { |
| 4882 | if (S.Context.getCanonicalType(T: UnqualifiedSourceType) == |
| 4883 | S.Context.OverloadTy) { |
| 4884 | DeclAccessPair Found; |
| 4885 | bool HadMultipleCandidates = false; |
| 4886 | if (FunctionDecl *Fn |
| 4887 | = S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, |
| 4888 | TargetType: UnqualifiedTargetType, |
| 4889 | Complain: false, Found, |
| 4890 | pHadMultipleCandidates: &HadMultipleCandidates)) { |
| 4891 | Sequence.AddAddressOverloadResolutionStep(Function: Fn, Found, |
| 4892 | HadMultipleCandidates); |
| 4893 | SourceType = Fn->getType(); |
| 4894 | UnqualifiedSourceType = SourceType.getUnqualifiedType(); |
| 4895 | } else if (!UnqualifiedTargetType->isRecordType()) { |
| 4896 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
| 4897 | return true; |
| 4898 | } |
| 4899 | } |
| 4900 | return false; |
| 4901 | } |
| 4902 | |
| 4903 | static void TryReferenceInitializationCore(Sema &S, |
| 4904 | const InitializedEntity &Entity, |
| 4905 | const InitializationKind &Kind, |
| 4906 | Expr *Initializer, |
| 4907 | QualType cv1T1, QualType T1, |
| 4908 | Qualifiers T1Quals, |
| 4909 | QualType cv2T2, QualType T2, |
| 4910 | Qualifiers T2Quals, |
| 4911 | InitializationSequence &Sequence, |
| 4912 | bool TopLevelOfInitList); |
| 4913 | |
| 4914 | static void TryValueInitialization(Sema &S, |
| 4915 | const InitializedEntity &Entity, |
| 4916 | const InitializationKind &Kind, |
| 4917 | InitializationSequence &Sequence, |
| 4918 | InitListExpr *InitList = nullptr); |
| 4919 | |
| 4920 | /// Attempt list initialization of a reference. |
| 4921 | static void TryReferenceListInitialization(Sema &S, |
| 4922 | const InitializedEntity &Entity, |
| 4923 | const InitializationKind &Kind, |
| 4924 | InitListExpr *InitList, |
| 4925 | InitializationSequence &Sequence, |
| 4926 | bool TreatUnavailableAsInvalid) { |
| 4927 | // First, catch C++03 where this isn't possible. |
| 4928 | if (!S.getLangOpts().CPlusPlus11) { |
| 4929 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); |
| 4930 | return; |
| 4931 | } |
| 4932 | // Can't reference initialize a compound literal. |
| 4933 | if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) { |
| 4934 | Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList); |
| 4935 | return; |
| 4936 | } |
| 4937 | |
| 4938 | QualType DestType = Entity.getType(); |
| 4939 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
| 4940 | Qualifiers T1Quals; |
| 4941 | QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals); |
| 4942 | |
| 4943 | // Reference initialization via an initializer list works thus: |
| 4944 | // If the initializer list consists of a single element that is |
| 4945 | // reference-related to the referenced type, bind directly to that element |
| 4946 | // (possibly creating temporaries). |
| 4947 | // Otherwise, initialize a temporary with the initializer list and |
| 4948 | // bind to that. |
| 4949 | if (InitList->getNumInits() == 1) { |
| 4950 | Expr *Initializer = InitList->getInit(Init: 0); |
| 4951 | QualType cv2T2 = S.getCompletedType(E: Initializer); |
| 4952 | Qualifiers T2Quals; |
| 4953 | QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals); |
| 4954 | |
| 4955 | // If this fails, creating a temporary wouldn't work either. |
| 4956 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2, |
| 4957 | UnqualifiedTargetType: T1, Sequence)) |
| 4958 | return; |
| 4959 | |
| 4960 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
| 4961 | Sema::ReferenceCompareResult RefRelationship |
| 4962 | = S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2); |
| 4963 | if (RefRelationship >= Sema::Ref_Related) { |
| 4964 | // Try to bind the reference here. |
| 4965 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, |
| 4966 | T1Quals, cv2T2, T2, T2Quals, Sequence, |
| 4967 | /*TopLevelOfInitList=*/true); |
| 4968 | if (Sequence) |
| 4969 | Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList); |
| 4970 | return; |
| 4971 | } |
| 4972 | |
| 4973 | // Update the initializer if we've resolved an overloaded function. |
| 4974 | if (!Sequence.steps().empty()) |
| 4975 | Sequence.RewrapReferenceInitList(T: cv1T1, Syntactic: InitList); |
| 4976 | } |
| 4977 | // Perform address space compatibility check. |
| 4978 | QualType cv1T1IgnoreAS = cv1T1; |
| 4979 | if (T1Quals.hasAddressSpace()) { |
| 4980 | Qualifiers T2Quals; |
| 4981 | (void)S.Context.getUnqualifiedArrayType(T: InitList->getType(), Quals&: T2Quals); |
| 4982 | if (!T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext())) { |
| 4983 | Sequence.SetFailed( |
| 4984 | InitializationSequence::FK_ReferenceInitDropsQualifiers); |
| 4985 | return; |
| 4986 | } |
| 4987 | // Ignore address space of reference type at this point and perform address |
| 4988 | // space conversion after the reference binding step. |
| 4989 | cv1T1IgnoreAS = |
| 4990 | S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace()); |
| 4991 | } |
| 4992 | // Not reference-related. Create a temporary and bind to that. |
| 4993 | InitializedEntity TempEntity = |
| 4994 | InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS); |
| 4995 | |
| 4996 | TryListInitialization(S, Entity: TempEntity, Kind, InitList, Sequence, |
| 4997 | TreatUnavailableAsInvalid); |
| 4998 | if (Sequence) { |
| 4999 | if (DestType->isRValueReferenceType() || |
| 5000 | (T1Quals.hasConst() && !T1Quals.hasVolatile())) { |
| 5001 | Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, |
| 5002 | /*BindingTemporary=*/true); |
| 5003 | if (S.getLangOpts().CPlusPlus20 && |
| 5004 | isa<IncompleteArrayType>(Val: T1->getUnqualifiedDesugaredType()) && |
| 5005 | DestType->isRValueReferenceType()) { |
| 5006 | // C++20 [dcl.init.list]p3.10: |
| 5007 | // List-initialization of an object or reference of type T is defined as |
| 5008 | // follows: |
| 5009 | // ..., unless T is “reference to array of unknown bound of U”, in which |
| 5010 | // case the type of the prvalue is the type of x in the declaration U |
| 5011 | // x[] H, where H is the initializer list. |
| 5012 | |
| 5013 | // The call to AddReferenceBindingStep above converts the rvalue to an |
| 5014 | // xvalue. Convert that xvalue to the incomplete array type. |
| 5015 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: clang::VK_XValue); |
| 5016 | } |
| 5017 | if (T1Quals.hasAddressSpace()) |
| 5018 | Sequence.AddQualificationConversionStep( |
| 5019 | Ty: cv1T1, VK: DestType->isRValueReferenceType() ? VK_XValue : VK_LValue); |
| 5020 | } else |
| 5021 | Sequence.SetFailed( |
| 5022 | InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary); |
| 5023 | } |
| 5024 | } |
| 5025 | |
| 5026 | /// Attempt list initialization (C++0x [dcl.init.list]) |
| 5027 | static void TryListInitialization(Sema &S, |
| 5028 | const InitializedEntity &Entity, |
| 5029 | const InitializationKind &Kind, |
| 5030 | InitListExpr *InitList, |
| 5031 | InitializationSequence &Sequence, |
| 5032 | bool TreatUnavailableAsInvalid) { |
| 5033 | QualType DestType = Entity.getType(); |
| 5034 | |
| 5035 | if (S.getLangOpts().HLSL && !S.HLSL().transformInitList(Entity, Init: InitList)) { |
| 5036 | Sequence.SetFailed(InitializationSequence::FK_HLSLInitListFlatteningFailed); |
| 5037 | return; |
| 5038 | } |
| 5039 | |
| 5040 | // C++ doesn't allow scalar initialization with more than one argument. |
| 5041 | // But C99 complex numbers are scalars and it makes sense there. |
| 5042 | if (S.getLangOpts().CPlusPlus && DestType->isScalarType() && |
| 5043 | !DestType->isAnyComplexType() && InitList->getNumInits() > 1) { |
| 5044 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar); |
| 5045 | return; |
| 5046 | } |
| 5047 | if (DestType->isReferenceType()) { |
| 5048 | TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence, |
| 5049 | TreatUnavailableAsInvalid); |
| 5050 | return; |
| 5051 | } |
| 5052 | |
| 5053 | if (DestType->isRecordType() && |
| 5054 | !S.isCompleteType(Loc: InitList->getBeginLoc(), T: DestType)) { |
| 5055 | Sequence.setIncompleteTypeFailure(DestType); |
| 5056 | return; |
| 5057 | } |
| 5058 | |
| 5059 | // C++20 [dcl.init.list]p3: |
| 5060 | // - If the braced-init-list contains a designated-initializer-list, T shall |
| 5061 | // be an aggregate class. [...] Aggregate initialization is performed. |
| 5062 | // |
| 5063 | // We allow arrays here too in order to support array designators. |
| 5064 | // |
| 5065 | // FIXME: This check should precede the handling of reference initialization. |
| 5066 | // We follow other compilers in allowing things like 'Aggr &&a = {.x = 1};' |
| 5067 | // as a tentative DR resolution. |
| 5068 | bool IsDesignatedInit = InitList->hasDesignatedInit(); |
| 5069 | if (!DestType->isAggregateType() && IsDesignatedInit) { |
| 5070 | Sequence.SetFailed( |
| 5071 | InitializationSequence::FK_DesignatedInitForNonAggregate); |
| 5072 | return; |
| 5073 | } |
| 5074 | |
| 5075 | // C++11 [dcl.init.list]p3, per DR1467 and DR2137: |
| 5076 | // - If T is an aggregate class and the initializer list has a single element |
| 5077 | // of type cv U, where U is T or a class derived from T, the object is |
| 5078 | // initialized from that element (by copy-initialization for |
| 5079 | // copy-list-initialization, or by direct-initialization for |
| 5080 | // direct-list-initialization). |
| 5081 | // - Otherwise, if T is a character array and the initializer list has a |
| 5082 | // single element that is an appropriately-typed string literal |
| 5083 | // (8.5.2 [dcl.init.string]), initialization is performed as described |
| 5084 | // in that section. |
| 5085 | // - Otherwise, if T is an aggregate, [...] (continue below). |
| 5086 | if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 && |
| 5087 | !IsDesignatedInit) { |
| 5088 | if (DestType->isRecordType() && DestType->isAggregateType()) { |
| 5089 | QualType InitType = InitList->getInit(Init: 0)->getType(); |
| 5090 | if (S.Context.hasSameUnqualifiedType(T1: InitType, T2: DestType) || |
| 5091 | S.IsDerivedFrom(Loc: InitList->getBeginLoc(), Derived: InitType, Base: DestType)) { |
| 5092 | InitializationKind SubKind = |
| 5093 | Kind.getKind() == InitializationKind::IK_DirectList |
| 5094 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
| 5095 | LParenLoc: InitList->getLBraceLoc(), |
| 5096 | RParenLoc: InitList->getRBraceLoc()) |
| 5097 | : Kind; |
| 5098 | Expr *InitListAsExpr = InitList; |
| 5099 | TryConstructorOrParenListInitialization( |
| 5100 | S, Entity, Kind: SubKind, Args: InitListAsExpr, DestType, Sequence, |
| 5101 | /*IsAggrListInit=*/true); |
| 5102 | return; |
| 5103 | } |
| 5104 | } |
| 5105 | if (const ArrayType *DestAT = S.Context.getAsArrayType(T: DestType)) { |
| 5106 | Expr *SubInit[1] = {InitList->getInit(Init: 0)}; |
| 5107 | |
| 5108 | // C++17 [dcl.struct.bind]p1: |
| 5109 | // ... If the assignment-expression in the initializer has array type A |
| 5110 | // and no ref-qualifier is present, e has type cv A and each element is |
| 5111 | // copy-initialized or direct-initialized from the corresponding element |
| 5112 | // of the assignment-expression as specified by the form of the |
| 5113 | // initializer. ... |
| 5114 | // |
| 5115 | // This is a special case not following list-initialization. |
| 5116 | if (isa<ConstantArrayType>(Val: DestAT) && |
| 5117 | Entity.getKind() == InitializedEntity::EK_Variable && |
| 5118 | isa<DecompositionDecl>(Val: Entity.getDecl())) { |
| 5119 | assert( |
| 5120 | S.Context.hasSameUnqualifiedType(SubInit[0]->getType(), DestType) && |
| 5121 | "Deduced to other type?" ); |
| 5122 | assert(Kind.getKind() == clang::InitializationKind::IK_DirectList && |
| 5123 | "List-initialize structured bindings but not " |
| 5124 | "direct-list-initialization?" ); |
| 5125 | TryArrayCopy(S, |
| 5126 | Kind: InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
| 5127 | LParenLoc: InitList->getLBraceLoc(), |
| 5128 | RParenLoc: InitList->getRBraceLoc()), |
| 5129 | Entity, Initializer: SubInit[0], DestType, Sequence, |
| 5130 | TreatUnavailableAsInvalid); |
| 5131 | if (Sequence) |
| 5132 | Sequence.AddUnwrapInitListInitStep(Syntactic: InitList); |
| 5133 | return; |
| 5134 | } |
| 5135 | |
| 5136 | if (!isa<VariableArrayType>(Val: DestAT) && |
| 5137 | IsStringInit(Init: SubInit[0], AT: DestAT, Context&: S.Context) == SIF_None) { |
| 5138 | InitializationKind SubKind = |
| 5139 | Kind.getKind() == InitializationKind::IK_DirectList |
| 5140 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
| 5141 | LParenLoc: InitList->getLBraceLoc(), |
| 5142 | RParenLoc: InitList->getRBraceLoc()) |
| 5143 | : Kind; |
| 5144 | Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit, |
| 5145 | /*TopLevelOfInitList*/ true, |
| 5146 | TreatUnavailableAsInvalid); |
| 5147 | |
| 5148 | // TryStringLiteralInitialization() (in InitializeFrom()) will fail if |
| 5149 | // the element is not an appropriately-typed string literal, in which |
| 5150 | // case we should proceed as in C++11 (below). |
| 5151 | if (Sequence) { |
| 5152 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
| 5153 | return; |
| 5154 | } |
| 5155 | } |
| 5156 | } |
| 5157 | } |
| 5158 | |
| 5159 | // C++11 [dcl.init.list]p3: |
| 5160 | // - If T is an aggregate, aggregate initialization is performed. |
| 5161 | if ((DestType->isRecordType() && !DestType->isAggregateType()) || |
| 5162 | (S.getLangOpts().CPlusPlus11 && |
| 5163 | S.isStdInitializerList(Ty: DestType, Element: nullptr) && !IsDesignatedInit)) { |
| 5164 | if (S.getLangOpts().CPlusPlus11) { |
| 5165 | // - Otherwise, if the initializer list has no elements and T is a |
| 5166 | // class type with a default constructor, the object is |
| 5167 | // value-initialized. |
| 5168 | if (InitList->getNumInits() == 0) { |
| 5169 | CXXRecordDecl *RD = DestType->castAsCXXRecordDecl(); |
| 5170 | if (S.LookupDefaultConstructor(Class: RD)) { |
| 5171 | TryValueInitialization(S, Entity, Kind, Sequence, InitList); |
| 5172 | return; |
| 5173 | } |
| 5174 | } |
| 5175 | |
| 5176 | // - Otherwise, if T is a specialization of std::initializer_list<E>, |
| 5177 | // an initializer_list object constructed [...] |
| 5178 | if (TryInitializerListConstruction(S, List: InitList, DestType, Sequence, |
| 5179 | TreatUnavailableAsInvalid)) |
| 5180 | return; |
| 5181 | |
| 5182 | // - Otherwise, if T is a class type, constructors are considered. |
| 5183 | Expr *InitListAsExpr = InitList; |
| 5184 | TryConstructorInitialization(S, Entity, Kind, Args: InitListAsExpr, DestType, |
| 5185 | DestArrayType: DestType, Sequence, /*InitListSyntax*/IsListInit: true); |
| 5186 | } else |
| 5187 | Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType); |
| 5188 | return; |
| 5189 | } |
| 5190 | |
| 5191 | if (S.getLangOpts().CPlusPlus && !DestType->isAggregateType() && |
| 5192 | InitList->getNumInits() == 1) { |
| 5193 | Expr *E = InitList->getInit(Init: 0); |
| 5194 | |
| 5195 | // - Otherwise, if T is an enumeration with a fixed underlying type, |
| 5196 | // the initializer-list has a single element v, and the initialization |
| 5197 | // is direct-list-initialization, the object is initialized with the |
| 5198 | // value T(v); if a narrowing conversion is required to convert v to |
| 5199 | // the underlying type of T, the program is ill-formed. |
| 5200 | if (S.getLangOpts().CPlusPlus17 && |
| 5201 | Kind.getKind() == InitializationKind::IK_DirectList && |
| 5202 | DestType->isEnumeralType() && DestType->castAsEnumDecl()->isFixed() && |
| 5203 | !S.Context.hasSameUnqualifiedType(T1: E->getType(), T2: DestType) && |
| 5204 | (E->getType()->isIntegralOrUnscopedEnumerationType() || |
| 5205 | E->getType()->isFloatingType())) { |
| 5206 | // There are two ways that T(v) can work when T is an enumeration type. |
| 5207 | // If there is either an implicit conversion sequence from v to T or |
| 5208 | // a conversion function that can convert from v to T, then we use that. |
| 5209 | // Otherwise, if v is of integral, unscoped enumeration, or floating-point |
| 5210 | // type, it is converted to the enumeration type via its underlying type. |
| 5211 | // There is no overlap possible between these two cases (except when the |
| 5212 | // source value is already of the destination type), and the first |
| 5213 | // case is handled by the general case for single-element lists below. |
| 5214 | ImplicitConversionSequence ICS; |
| 5215 | ICS.setStandard(); |
| 5216 | ICS.Standard.setAsIdentityConversion(); |
| 5217 | if (!E->isPRValue()) |
| 5218 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; |
| 5219 | // If E is of a floating-point type, then the conversion is ill-formed |
| 5220 | // due to narrowing, but go through the motions in order to produce the |
| 5221 | // right diagnostic. |
| 5222 | ICS.Standard.Second = E->getType()->isFloatingType() |
| 5223 | ? ICK_Floating_Integral |
| 5224 | : ICK_Integral_Conversion; |
| 5225 | ICS.Standard.setFromType(E->getType()); |
| 5226 | ICS.Standard.setToType(Idx: 0, T: E->getType()); |
| 5227 | ICS.Standard.setToType(Idx: 1, T: DestType); |
| 5228 | ICS.Standard.setToType(Idx: 2, T: DestType); |
| 5229 | Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2), |
| 5230 | /*TopLevelOfInitList*/true); |
| 5231 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
| 5232 | return; |
| 5233 | } |
| 5234 | |
| 5235 | // - Otherwise, if the initializer list has a single element of type E |
| 5236 | // [...references are handled above...], the object or reference is |
| 5237 | // initialized from that element (by copy-initialization for |
| 5238 | // copy-list-initialization, or by direct-initialization for |
| 5239 | // direct-list-initialization); if a narrowing conversion is required |
| 5240 | // to convert the element to T, the program is ill-formed. |
| 5241 | // |
| 5242 | // Per core-24034, this is direct-initialization if we were performing |
| 5243 | // direct-list-initialization and copy-initialization otherwise. |
| 5244 | // We can't use InitListChecker for this, because it always performs |
| 5245 | // copy-initialization. This only matters if we might use an 'explicit' |
| 5246 | // conversion operator, or for the special case conversion of nullptr_t to |
| 5247 | // bool, so we only need to handle those cases. |
| 5248 | // |
| 5249 | // FIXME: Why not do this in all cases? |
| 5250 | Expr *Init = InitList->getInit(Init: 0); |
| 5251 | if (Init->getType()->isRecordType() || |
| 5252 | (Init->getType()->isNullPtrType() && DestType->isBooleanType())) { |
| 5253 | InitializationKind SubKind = |
| 5254 | Kind.getKind() == InitializationKind::IK_DirectList |
| 5255 | ? InitializationKind::CreateDirect(InitLoc: Kind.getLocation(), |
| 5256 | LParenLoc: InitList->getLBraceLoc(), |
| 5257 | RParenLoc: InitList->getRBraceLoc()) |
| 5258 | : Kind; |
| 5259 | Expr *SubInit[1] = { Init }; |
| 5260 | Sequence.InitializeFrom(S, Entity, Kind: SubKind, Args: SubInit, |
| 5261 | /*TopLevelOfInitList*/true, |
| 5262 | TreatUnavailableAsInvalid); |
| 5263 | if (Sequence) |
| 5264 | Sequence.RewrapReferenceInitList(T: Entity.getType(), Syntactic: InitList); |
| 5265 | return; |
| 5266 | } |
| 5267 | } |
| 5268 | |
| 5269 | InitListChecker CheckInitList(S, Entity, InitList, |
| 5270 | DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid); |
| 5271 | if (CheckInitList.HadError()) { |
| 5272 | Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed); |
| 5273 | return; |
| 5274 | } |
| 5275 | |
| 5276 | // Add the list initialization step with the built init list. |
| 5277 | Sequence.AddListInitializationStep(T: DestType); |
| 5278 | } |
| 5279 | |
| 5280 | /// Try a reference initialization that involves calling a conversion |
| 5281 | /// function. |
| 5282 | static OverloadingResult TryRefInitWithConversionFunction( |
| 5283 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
| 5284 | Expr *Initializer, bool AllowRValues, bool IsLValueRef, |
| 5285 | InitializationSequence &Sequence) { |
| 5286 | QualType DestType = Entity.getType(); |
| 5287 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
| 5288 | QualType T1 = cv1T1.getUnqualifiedType(); |
| 5289 | QualType cv2T2 = Initializer->getType(); |
| 5290 | QualType T2 = cv2T2.getUnqualifiedType(); |
| 5291 | |
| 5292 | assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) && |
| 5293 | "Must have incompatible references when binding via conversion" ); |
| 5294 | |
| 5295 | // Build the candidate set directly in the initialization sequence |
| 5296 | // structure, so that it will persist if we fail. |
| 5297 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
| 5298 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
| 5299 | |
| 5300 | // Determine whether we are allowed to call explicit conversion operators. |
| 5301 | // Note that none of [over.match.copy], [over.match.conv], nor |
| 5302 | // [over.match.ref] permit an explicit constructor to be chosen when |
| 5303 | // initializing a reference, not even for direct-initialization. |
| 5304 | bool AllowExplicitCtors = false; |
| 5305 | bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding(); |
| 5306 | |
| 5307 | if (AllowRValues && T1->isRecordType() && |
| 5308 | S.isCompleteType(Loc: Kind.getLocation(), T: T1)) { |
| 5309 | auto *T1RecordDecl = T1->castAsCXXRecordDecl(); |
| 5310 | if (T1RecordDecl->isInvalidDecl()) |
| 5311 | return OR_No_Viable_Function; |
| 5312 | // The type we're converting to is a class type. Enumerate its constructors |
| 5313 | // to see if there is a suitable conversion. |
| 5314 | for (NamedDecl *D : S.LookupConstructors(Class: T1RecordDecl)) { |
| 5315 | auto Info = getConstructorInfo(ND: D); |
| 5316 | if (!Info.Constructor) |
| 5317 | continue; |
| 5318 | |
| 5319 | if (!Info.Constructor->isInvalidDecl() && |
| 5320 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { |
| 5321 | if (Info.ConstructorTmpl) |
| 5322 | S.AddTemplateOverloadCandidate( |
| 5323 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
| 5324 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet, |
| 5325 | /*SuppressUserConversions=*/true, |
| 5326 | /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors); |
| 5327 | else |
| 5328 | S.AddOverloadCandidate( |
| 5329 | Function: Info.Constructor, FoundDecl: Info.FoundDecl, Args: Initializer, CandidateSet, |
| 5330 | /*SuppressUserConversions=*/true, |
| 5331 | /*PartialOverloading*/ false, AllowExplicit: AllowExplicitCtors); |
| 5332 | } |
| 5333 | } |
| 5334 | } |
| 5335 | |
| 5336 | if (T2->isRecordType() && S.isCompleteType(Loc: Kind.getLocation(), T: T2)) { |
| 5337 | const auto *T2RecordDecl = T2->castAsCXXRecordDecl(); |
| 5338 | if (T2RecordDecl->isInvalidDecl()) |
| 5339 | return OR_No_Viable_Function; |
| 5340 | // The type we're converting from is a class type, enumerate its conversion |
| 5341 | // functions. |
| 5342 | const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); |
| 5343 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
| 5344 | NamedDecl *D = *I; |
| 5345 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext()); |
| 5346 | if (isa<UsingShadowDecl>(Val: D)) |
| 5347 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
| 5348 | |
| 5349 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
| 5350 | CXXConversionDecl *Conv; |
| 5351 | if (ConvTemplate) |
| 5352 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
| 5353 | else |
| 5354 | Conv = cast<CXXConversionDecl>(Val: D); |
| 5355 | |
| 5356 | // If the conversion function doesn't return a reference type, |
| 5357 | // it can't be considered for this conversion unless we're allowed to |
| 5358 | // consider rvalues. |
| 5359 | // FIXME: Do we need to make sure that we only consider conversion |
| 5360 | // candidates with reference-compatible results? That might be needed to |
| 5361 | // break recursion. |
| 5362 | if ((AllowRValues || |
| 5363 | Conv->getConversionType()->isLValueReferenceType())) { |
| 5364 | if (ConvTemplate) |
| 5365 | S.AddTemplateConversionCandidate( |
| 5366 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
| 5367 | CandidateSet, |
| 5368 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs); |
| 5369 | else |
| 5370 | S.AddConversionCandidate( |
| 5371 | Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, CandidateSet, |
| 5372 | /*AllowObjCConversionOnExplicit=*/false, AllowExplicit: AllowExplicitConvs); |
| 5373 | } |
| 5374 | } |
| 5375 | } |
| 5376 | |
| 5377 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
| 5378 | |
| 5379 | // Perform overload resolution. If it fails, return the failed result. |
| 5380 | OverloadCandidateSet::iterator Best; |
| 5381 | if (OverloadingResult Result |
| 5382 | = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) |
| 5383 | return Result; |
| 5384 | |
| 5385 | FunctionDecl *Function = Best->Function; |
| 5386 | // This is the overload that will be used for this initialization step if we |
| 5387 | // use this initialization. Mark it as referenced. |
| 5388 | Function->setReferenced(); |
| 5389 | |
| 5390 | // Compute the returned type and value kind of the conversion. |
| 5391 | QualType cv3T3; |
| 5392 | if (isa<CXXConversionDecl>(Val: Function)) |
| 5393 | cv3T3 = Function->getReturnType(); |
| 5394 | else |
| 5395 | cv3T3 = T1; |
| 5396 | |
| 5397 | ExprValueKind VK = VK_PRValue; |
| 5398 | if (cv3T3->isLValueReferenceType()) |
| 5399 | VK = VK_LValue; |
| 5400 | else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>()) |
| 5401 | VK = RRef->getPointeeType()->isFunctionType() ? VK_LValue : VK_XValue; |
| 5402 | cv3T3 = cv3T3.getNonLValueExprType(Context: S.Context); |
| 5403 | |
| 5404 | // Add the user-defined conversion step. |
| 5405 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
| 5406 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: cv3T3, |
| 5407 | HadMultipleCandidates); |
| 5408 | |
| 5409 | // Determine whether we'll need to perform derived-to-base adjustments or |
| 5410 | // other conversions. |
| 5411 | Sema::ReferenceConversions RefConv; |
| 5412 | Sema::ReferenceCompareResult NewRefRelationship = |
| 5413 | S.CompareReferenceRelationship(Loc: DeclLoc, T1, T2: cv3T3, Conv: &RefConv); |
| 5414 | |
| 5415 | // Add the final conversion sequence, if necessary. |
| 5416 | if (NewRefRelationship == Sema::Ref_Incompatible) { |
| 5417 | assert(Best->HasFinalConversion && !isa<CXXConstructorDecl>(Function) && |
| 5418 | "should not have conversion after constructor" ); |
| 5419 | |
| 5420 | ImplicitConversionSequence ICS; |
| 5421 | ICS.setStandard(); |
| 5422 | ICS.Standard = Best->FinalConversion; |
| 5423 | Sequence.AddConversionSequenceStep(ICS, T: ICS.Standard.getToType(Idx: 2)); |
| 5424 | |
| 5425 | // Every implicit conversion results in a prvalue, except for a glvalue |
| 5426 | // derived-to-base conversion, which we handle below. |
| 5427 | cv3T3 = ICS.Standard.getToType(Idx: 2); |
| 5428 | VK = VK_PRValue; |
| 5429 | } |
| 5430 | |
| 5431 | // If the converted initializer is a prvalue, its type T4 is adjusted to |
| 5432 | // type "cv1 T4" and the temporary materialization conversion is applied. |
| 5433 | // |
| 5434 | // We adjust the cv-qualifications to match the reference regardless of |
| 5435 | // whether we have a prvalue so that the AST records the change. In this |
| 5436 | // case, T4 is "cv3 T3". |
| 5437 | QualType cv1T4 = S.Context.getQualifiedType(T: cv3T3, Qs: cv1T1.getQualifiers()); |
| 5438 | if (cv1T4.getQualifiers() != cv3T3.getQualifiers()) |
| 5439 | Sequence.AddQualificationConversionStep(Ty: cv1T4, VK); |
| 5440 | Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: VK == VK_PRValue); |
| 5441 | VK = IsLValueRef ? VK_LValue : VK_XValue; |
| 5442 | |
| 5443 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
| 5444 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK); |
| 5445 | else if (RefConv & Sema::ReferenceConversions::ObjC) |
| 5446 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
| 5447 | else if (RefConv & Sema::ReferenceConversions::Function) |
| 5448 | Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1); |
| 5449 | else if (RefConv & Sema::ReferenceConversions::Qualification) { |
| 5450 | if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1)) |
| 5451 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK); |
| 5452 | } |
| 5453 | |
| 5454 | return OR_Success; |
| 5455 | } |
| 5456 | |
| 5457 | static void CheckCXX98CompatAccessibleCopy(Sema &S, |
| 5458 | const InitializedEntity &Entity, |
| 5459 | Expr *CurInitExpr); |
| 5460 | |
| 5461 | /// Attempt reference initialization (C++0x [dcl.init.ref]) |
| 5462 | static void TryReferenceInitialization(Sema &S, const InitializedEntity &Entity, |
| 5463 | const InitializationKind &Kind, |
| 5464 | Expr *Initializer, |
| 5465 | InitializationSequence &Sequence, |
| 5466 | bool TopLevelOfInitList) { |
| 5467 | QualType DestType = Entity.getType(); |
| 5468 | QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType(); |
| 5469 | Qualifiers T1Quals; |
| 5470 | QualType T1 = S.Context.getUnqualifiedArrayType(T: cv1T1, Quals&: T1Quals); |
| 5471 | QualType cv2T2 = S.getCompletedType(E: Initializer); |
| 5472 | Qualifiers T2Quals; |
| 5473 | QualType T2 = S.Context.getUnqualifiedArrayType(T: cv2T2, Quals&: T2Quals); |
| 5474 | |
| 5475 | // If the initializer is the address of an overloaded function, try |
| 5476 | // to resolve the overloaded function. If all goes well, T2 is the |
| 5477 | // type of the resulting function. |
| 5478 | if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, SourceType&: cv2T2, UnqualifiedSourceType&: T2, |
| 5479 | UnqualifiedTargetType: T1, Sequence)) |
| 5480 | return; |
| 5481 | |
| 5482 | // Delegate everything else to a subfunction. |
| 5483 | TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1, |
| 5484 | T1Quals, cv2T2, T2, T2Quals, Sequence, |
| 5485 | TopLevelOfInitList); |
| 5486 | } |
| 5487 | |
| 5488 | /// Determine whether an expression is a non-referenceable glvalue (one to |
| 5489 | /// which a reference can never bind). Attempting to bind a reference to |
| 5490 | /// such a glvalue will always create a temporary. |
| 5491 | static bool isNonReferenceableGLValue(Expr *E) { |
| 5492 | return E->refersToBitField() || E->refersToVectorElement() || |
| 5493 | E->refersToMatrixElement(); |
| 5494 | } |
| 5495 | |
| 5496 | /// Reference initialization without resolving overloaded functions. |
| 5497 | /// |
| 5498 | /// We also can get here in C if we call a builtin which is declared as |
| 5499 | /// a function with a parameter of reference type (such as __builtin_va_end()). |
| 5500 | static void TryReferenceInitializationCore(Sema &S, |
| 5501 | const InitializedEntity &Entity, |
| 5502 | const InitializationKind &Kind, |
| 5503 | Expr *Initializer, |
| 5504 | QualType cv1T1, QualType T1, |
| 5505 | Qualifiers T1Quals, |
| 5506 | QualType cv2T2, QualType T2, |
| 5507 | Qualifiers T2Quals, |
| 5508 | InitializationSequence &Sequence, |
| 5509 | bool TopLevelOfInitList) { |
| 5510 | QualType DestType = Entity.getType(); |
| 5511 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
| 5512 | |
| 5513 | // Compute some basic properties of the types and the initializer. |
| 5514 | bool isLValueRef = DestType->isLValueReferenceType(); |
| 5515 | bool isRValueRef = !isLValueRef; |
| 5516 | Expr::Classification InitCategory = Initializer->Classify(Ctx&: S.Context); |
| 5517 | |
| 5518 | Sema::ReferenceConversions RefConv; |
| 5519 | Sema::ReferenceCompareResult RefRelationship = |
| 5520 | S.CompareReferenceRelationship(Loc: DeclLoc, T1: cv1T1, T2: cv2T2, Conv: &RefConv); |
| 5521 | |
| 5522 | // C++0x [dcl.init.ref]p5: |
| 5523 | // A reference to type "cv1 T1" is initialized by an expression of type |
| 5524 | // "cv2 T2" as follows: |
| 5525 | // |
| 5526 | // - If the reference is an lvalue reference and the initializer |
| 5527 | // expression |
| 5528 | // Note the analogous bullet points for rvalue refs to functions. Because |
| 5529 | // there are no function rvalues in C++, rvalue refs to functions are treated |
| 5530 | // like lvalue refs. |
| 5531 | OverloadingResult ConvOvlResult = OR_Success; |
| 5532 | bool T1Function = T1->isFunctionType(); |
| 5533 | if (isLValueRef || T1Function) { |
| 5534 | if (InitCategory.isLValue() && !isNonReferenceableGLValue(E: Initializer) && |
| 5535 | (RefRelationship == Sema::Ref_Compatible || |
| 5536 | (Kind.isCStyleOrFunctionalCast() && |
| 5537 | RefRelationship == Sema::Ref_Related))) { |
| 5538 | // - is an lvalue (but is not a bit-field), and "cv1 T1" is |
| 5539 | // reference-compatible with "cv2 T2," or |
| 5540 | if (RefConv & (Sema::ReferenceConversions::DerivedToBase | |
| 5541 | Sema::ReferenceConversions::ObjC)) { |
| 5542 | // If we're converting the pointee, add any qualifiers first; |
| 5543 | // these qualifiers must all be top-level, so just convert to "cv1 T2". |
| 5544 | if (RefConv & (Sema::ReferenceConversions::Qualification)) |
| 5545 | Sequence.AddQualificationConversionStep( |
| 5546 | Ty: S.Context.getQualifiedType(T: T2, Qs: T1Quals), |
| 5547 | VK: Initializer->getValueKind()); |
| 5548 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
| 5549 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: VK_LValue); |
| 5550 | else |
| 5551 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
| 5552 | } else if (RefConv & Sema::ReferenceConversions::Qualification) { |
| 5553 | // Perform a (possibly multi-level) qualification conversion. |
| 5554 | Sequence.AddQualificationConversionStep(Ty: cv1T1, |
| 5555 | VK: Initializer->getValueKind()); |
| 5556 | } else if (RefConv & Sema::ReferenceConversions::Function) { |
| 5557 | Sequence.AddFunctionReferenceConversionStep(Ty: cv1T1); |
| 5558 | } |
| 5559 | |
| 5560 | // We only create a temporary here when binding a reference to a |
| 5561 | // bit-field or vector element. Those cases are't supposed to be |
| 5562 | // handled by this bullet, but the outcome is the same either way. |
| 5563 | Sequence.AddReferenceBindingStep(T: cv1T1, BindingTemporary: false); |
| 5564 | return; |
| 5565 | } |
| 5566 | |
| 5567 | // - has a class type (i.e., T2 is a class type), where T1 is not |
| 5568 | // reference-related to T2, and can be implicitly converted to an |
| 5569 | // lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible |
| 5570 | // with "cv3 T3" (this conversion is selected by enumerating the |
| 5571 | // applicable conversion functions (13.3.1.6) and choosing the best |
| 5572 | // one through overload resolution (13.3)), |
| 5573 | // If we have an rvalue ref to function type here, the rhs must be |
| 5574 | // an rvalue. DR1287 removed the "implicitly" here. |
| 5575 | if (RefRelationship == Sema::Ref_Incompatible && T2->isRecordType() && |
| 5576 | (isLValueRef || InitCategory.isRValue())) { |
| 5577 | if (S.getLangOpts().CPlusPlus) { |
| 5578 | // Try conversion functions only for C++. |
| 5579 | ConvOvlResult = TryRefInitWithConversionFunction( |
| 5580 | S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef, |
| 5581 | /*IsLValueRef*/ isLValueRef, Sequence); |
| 5582 | if (ConvOvlResult == OR_Success) |
| 5583 | return; |
| 5584 | if (ConvOvlResult != OR_No_Viable_Function) |
| 5585 | Sequence.SetOverloadFailure( |
| 5586 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
| 5587 | Result: ConvOvlResult); |
| 5588 | } else { |
| 5589 | ConvOvlResult = OR_No_Viable_Function; |
| 5590 | } |
| 5591 | } |
| 5592 | } |
| 5593 | |
| 5594 | // - Otherwise, the reference shall be an lvalue reference to a |
| 5595 | // non-volatile const type (i.e., cv1 shall be const), or the reference |
| 5596 | // shall be an rvalue reference. |
| 5597 | // For address spaces, we interpret this to mean that an addr space |
| 5598 | // of a reference "cv1 T1" is a superset of addr space of "cv2 T2". |
| 5599 | if (isLValueRef && |
| 5600 | !(T1Quals.hasConst() && !T1Quals.hasVolatile() && |
| 5601 | T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) { |
| 5602 | if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) |
| 5603 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
| 5604 | else if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) |
| 5605 | Sequence.SetOverloadFailure( |
| 5606 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
| 5607 | Result: ConvOvlResult); |
| 5608 | else if (!InitCategory.isLValue()) |
| 5609 | Sequence.SetFailed( |
| 5610 | T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()) |
| 5611 | ? InitializationSequence:: |
| 5612 | FK_NonConstLValueReferenceBindingToTemporary |
| 5613 | : InitializationSequence::FK_ReferenceInitDropsQualifiers); |
| 5614 | else { |
| 5615 | InitializationSequence::FailureKind FK; |
| 5616 | switch (RefRelationship) { |
| 5617 | case Sema::Ref_Compatible: |
| 5618 | if (Initializer->refersToBitField()) |
| 5619 | FK = InitializationSequence:: |
| 5620 | FK_NonConstLValueReferenceBindingToBitfield; |
| 5621 | else if (Initializer->refersToVectorElement()) |
| 5622 | FK = InitializationSequence:: |
| 5623 | FK_NonConstLValueReferenceBindingToVectorElement; |
| 5624 | else if (Initializer->refersToMatrixElement()) |
| 5625 | FK = InitializationSequence:: |
| 5626 | FK_NonConstLValueReferenceBindingToMatrixElement; |
| 5627 | else |
| 5628 | llvm_unreachable("unexpected kind of compatible initializer" ); |
| 5629 | break; |
| 5630 | case Sema::Ref_Related: |
| 5631 | FK = InitializationSequence::FK_ReferenceInitDropsQualifiers; |
| 5632 | break; |
| 5633 | case Sema::Ref_Incompatible: |
| 5634 | FK = InitializationSequence:: |
| 5635 | FK_NonConstLValueReferenceBindingToUnrelated; |
| 5636 | break; |
| 5637 | } |
| 5638 | Sequence.SetFailed(FK); |
| 5639 | } |
| 5640 | return; |
| 5641 | } |
| 5642 | |
| 5643 | // - If the initializer expression |
| 5644 | // - is an |
| 5645 | // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or |
| 5646 | // [1z] rvalue (but not a bit-field) or |
| 5647 | // function lvalue and "cv1 T1" is reference-compatible with "cv2 T2" |
| 5648 | // |
| 5649 | // Note: functions are handled above and below rather than here... |
| 5650 | if (!T1Function && |
| 5651 | (RefRelationship == Sema::Ref_Compatible || |
| 5652 | (Kind.isCStyleOrFunctionalCast() && |
| 5653 | RefRelationship == Sema::Ref_Related)) && |
| 5654 | ((InitCategory.isXValue() && !isNonReferenceableGLValue(E: Initializer)) || |
| 5655 | (InitCategory.isPRValue() && |
| 5656 | (S.getLangOpts().CPlusPlus17 || T2->isRecordType() || |
| 5657 | T2->isArrayType())))) { |
| 5658 | ExprValueKind ValueKind = InitCategory.isXValue() ? VK_XValue : VK_PRValue; |
| 5659 | if (InitCategory.isPRValue() && T2->isRecordType()) { |
| 5660 | // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the |
| 5661 | // compiler the freedom to perform a copy here or bind to the |
| 5662 | // object, while C++0x requires that we bind directly to the |
| 5663 | // object. Hence, we always bind to the object without making an |
| 5664 | // extra copy. However, in C++03 requires that we check for the |
| 5665 | // presence of a suitable copy constructor: |
| 5666 | // |
| 5667 | // The constructor that would be used to make the copy shall |
| 5668 | // be callable whether or not the copy is actually done. |
| 5669 | if (!S.getLangOpts().CPlusPlus11 && !S.getLangOpts().MicrosoftExt) |
| 5670 | Sequence.AddExtraneousCopyToTemporary(T: cv2T2); |
| 5671 | else if (S.getLangOpts().CPlusPlus11) |
| 5672 | CheckCXX98CompatAccessibleCopy(S, Entity, CurInitExpr: Initializer); |
| 5673 | } |
| 5674 | |
| 5675 | // C++1z [dcl.init.ref]/5.2.1.2: |
| 5676 | // If the converted initializer is a prvalue, its type T4 is adjusted |
| 5677 | // to type "cv1 T4" and the temporary materialization conversion is |
| 5678 | // applied. |
| 5679 | // Postpone address space conversions to after the temporary materialization |
| 5680 | // conversion to allow creating temporaries in the alloca address space. |
| 5681 | auto T1QualsIgnoreAS = T1Quals; |
| 5682 | auto T2QualsIgnoreAS = T2Quals; |
| 5683 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { |
| 5684 | T1QualsIgnoreAS.removeAddressSpace(); |
| 5685 | T2QualsIgnoreAS.removeAddressSpace(); |
| 5686 | } |
| 5687 | // Strip the existing ObjC lifetime qualifier from cv2T2 before combining |
| 5688 | // with T1's qualifiers. |
| 5689 | QualType T2ForQualConv = cv2T2; |
| 5690 | if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime()) { |
| 5691 | Qualifiers T2BaseQuals = |
| 5692 | T2ForQualConv.getQualifiers().withoutObjCLifetime(); |
| 5693 | T2ForQualConv = S.Context.getQualifiedType( |
| 5694 | T: T2ForQualConv.getUnqualifiedType(), Qs: T2BaseQuals); |
| 5695 | } |
| 5696 | QualType cv1T4 = S.Context.getQualifiedType(T: T2ForQualConv, Qs: T1QualsIgnoreAS); |
| 5697 | if (T1QualsIgnoreAS != T2QualsIgnoreAS) |
| 5698 | Sequence.AddQualificationConversionStep(Ty: cv1T4, VK: ValueKind); |
| 5699 | Sequence.AddReferenceBindingStep(T: cv1T4, BindingTemporary: ValueKind == VK_PRValue); |
| 5700 | ValueKind = isLValueRef ? VK_LValue : VK_XValue; |
| 5701 | // Add addr space conversion if required. |
| 5702 | if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) { |
| 5703 | auto T4Quals = cv1T4.getQualifiers(); |
| 5704 | T4Quals.addAddressSpace(space: T1Quals.getAddressSpace()); |
| 5705 | QualType cv1T4WithAS = S.Context.getQualifiedType(T: T2, Qs: T4Quals); |
| 5706 | Sequence.AddQualificationConversionStep(Ty: cv1T4WithAS, VK: ValueKind); |
| 5707 | cv1T4 = cv1T4WithAS; |
| 5708 | } |
| 5709 | |
| 5710 | // In any case, the reference is bound to the resulting glvalue (or to |
| 5711 | // an appropriate base class subobject). |
| 5712 | if (RefConv & Sema::ReferenceConversions::DerivedToBase) |
| 5713 | Sequence.AddDerivedToBaseCastStep(BaseType: cv1T1, VK: ValueKind); |
| 5714 | else if (RefConv & Sema::ReferenceConversions::ObjC) |
| 5715 | Sequence.AddObjCObjectConversionStep(T: cv1T1); |
| 5716 | else if (RefConv & Sema::ReferenceConversions::Qualification) { |
| 5717 | if (!S.Context.hasSameType(T1: cv1T4, T2: cv1T1)) |
| 5718 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: ValueKind); |
| 5719 | } |
| 5720 | return; |
| 5721 | } |
| 5722 | |
| 5723 | // - has a class type (i.e., T2 is a class type), where T1 is not |
| 5724 | // reference-related to T2, and can be implicitly converted to an |
| 5725 | // xvalue, class prvalue, or function lvalue of type "cv3 T3", |
| 5726 | // where "cv1 T1" is reference-compatible with "cv3 T3", |
| 5727 | // |
| 5728 | // DR1287 removes the "implicitly" here. |
| 5729 | if (T2->isRecordType()) { |
| 5730 | if (RefRelationship == Sema::Ref_Incompatible) { |
| 5731 | ConvOvlResult = TryRefInitWithConversionFunction( |
| 5732 | S, Entity, Kind, Initializer, /*AllowRValues*/ true, |
| 5733 | /*IsLValueRef*/ isLValueRef, Sequence); |
| 5734 | if (ConvOvlResult) |
| 5735 | Sequence.SetOverloadFailure( |
| 5736 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
| 5737 | Result: ConvOvlResult); |
| 5738 | |
| 5739 | return; |
| 5740 | } |
| 5741 | |
| 5742 | if (RefRelationship == Sema::Ref_Compatible && |
| 5743 | isRValueRef && InitCategory.isLValue()) { |
| 5744 | Sequence.SetFailed( |
| 5745 | InitializationSequence::FK_RValueReferenceBindingToLValue); |
| 5746 | return; |
| 5747 | } |
| 5748 | |
| 5749 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); |
| 5750 | return; |
| 5751 | } |
| 5752 | |
| 5753 | // - Otherwise, a temporary of type "cv1 T1" is created and initialized |
| 5754 | // from the initializer expression using the rules for a non-reference |
| 5755 | // copy-initialization (8.5). The reference is then bound to the |
| 5756 | // temporary. [...] |
| 5757 | |
| 5758 | // Ignore address space of reference type at this point and perform address |
| 5759 | // space conversion after the reference binding step. |
| 5760 | QualType cv1T1IgnoreAS = |
| 5761 | T1Quals.hasAddressSpace() |
| 5762 | ? S.Context.getQualifiedType(T: T1, Qs: T1Quals.withoutAddressSpace()) |
| 5763 | : cv1T1; |
| 5764 | |
| 5765 | InitializedEntity TempEntity = |
| 5766 | InitializedEntity::InitializeTemporary(Type: cv1T1IgnoreAS); |
| 5767 | |
| 5768 | // FIXME: Why do we use an implicit conversion here rather than trying |
| 5769 | // copy-initialization? |
| 5770 | ImplicitConversionSequence ICS |
| 5771 | = S.TryImplicitConversion(From: Initializer, ToType: TempEntity.getType(), |
| 5772 | /*SuppressUserConversions=*/false, |
| 5773 | AllowExplicit: Sema::AllowedExplicit::None, |
| 5774 | /*FIXME:InOverloadResolution=*/InOverloadResolution: false, |
| 5775 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), |
| 5776 | /*AllowObjCWritebackConversion=*/false); |
| 5777 | |
| 5778 | if (ICS.isBad()) { |
| 5779 | // FIXME: Use the conversion function set stored in ICS to turn |
| 5780 | // this into an overloading ambiguity diagnostic. However, we need |
| 5781 | // to keep that set as an OverloadCandidateSet rather than as some |
| 5782 | // other kind of set. |
| 5783 | if (ConvOvlResult && !Sequence.getFailedCandidateSet().empty()) |
| 5784 | Sequence.SetOverloadFailure( |
| 5785 | Failure: InitializationSequence::FK_ReferenceInitOverloadFailed, |
| 5786 | Result: ConvOvlResult); |
| 5787 | else if (S.Context.getCanonicalType(T: T2) == S.Context.OverloadTy) |
| 5788 | Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
| 5789 | else |
| 5790 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitFailed); |
| 5791 | return; |
| 5792 | } else { |
| 5793 | Sequence.AddConversionSequenceStep(ICS, T: TempEntity.getType(), |
| 5794 | TopLevelOfInitList); |
| 5795 | } |
| 5796 | |
| 5797 | // [...] If T1 is reference-related to T2, cv1 must be the |
| 5798 | // same cv-qualification as, or greater cv-qualification |
| 5799 | // than, cv2; otherwise, the program is ill-formed. |
| 5800 | unsigned T1CVRQuals = T1Quals.getCVRQualifiers(); |
| 5801 | unsigned T2CVRQuals = T2Quals.getCVRQualifiers(); |
| 5802 | if (RefRelationship == Sema::Ref_Related && |
| 5803 | ((T1CVRQuals | T2CVRQuals) != T1CVRQuals || |
| 5804 | !T1Quals.isAddressSpaceSupersetOf(other: T2Quals, Ctx: S.getASTContext()))) { |
| 5805 | Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers); |
| 5806 | return; |
| 5807 | } |
| 5808 | |
| 5809 | // [...] If T1 is reference-related to T2 and the reference is an rvalue |
| 5810 | // reference, the initializer expression shall not be an lvalue. |
| 5811 | if (RefRelationship >= Sema::Ref_Related && !isLValueRef && |
| 5812 | InitCategory.isLValue()) { |
| 5813 | Sequence.SetFailed( |
| 5814 | InitializationSequence::FK_RValueReferenceBindingToLValue); |
| 5815 | return; |
| 5816 | } |
| 5817 | |
| 5818 | Sequence.AddReferenceBindingStep(T: cv1T1IgnoreAS, /*BindingTemporary=*/true); |
| 5819 | |
| 5820 | if (T1Quals.hasAddressSpace()) { |
| 5821 | if (!Qualifiers::isAddressSpaceSupersetOf( |
| 5822 | A: T1Quals.getAddressSpace(), B: LangAS::Default, Ctx: S.getASTContext())) { |
| 5823 | Sequence.SetFailed( |
| 5824 | InitializationSequence::FK_ReferenceAddrspaceMismatchTemporary); |
| 5825 | return; |
| 5826 | } |
| 5827 | Sequence.AddQualificationConversionStep(Ty: cv1T1, VK: isLValueRef ? VK_LValue |
| 5828 | : VK_XValue); |
| 5829 | } |
| 5830 | } |
| 5831 | |
| 5832 | /// Attempt character array initialization from a string literal |
| 5833 | /// (C++ [dcl.init.string], C99 6.7.8). |
| 5834 | static void TryStringLiteralInitialization(Sema &S, |
| 5835 | const InitializedEntity &Entity, |
| 5836 | const InitializationKind &Kind, |
| 5837 | Expr *Initializer, |
| 5838 | InitializationSequence &Sequence) { |
| 5839 | Sequence.AddStringInitStep(T: Entity.getType()); |
| 5840 | } |
| 5841 | |
| 5842 | /// Attempt value initialization (C++ [dcl.init]p7). |
| 5843 | static void TryValueInitialization(Sema &S, |
| 5844 | const InitializedEntity &Entity, |
| 5845 | const InitializationKind &Kind, |
| 5846 | InitializationSequence &Sequence, |
| 5847 | InitListExpr *InitList) { |
| 5848 | assert((!InitList || InitList->getNumInits() == 0) && |
| 5849 | "Shouldn't use value-init for non-empty init lists" ); |
| 5850 | |
| 5851 | // C++98 [dcl.init]p5, C++11 [dcl.init]p7: |
| 5852 | // |
| 5853 | // To value-initialize an object of type T means: |
| 5854 | QualType T = Entity.getType(); |
| 5855 | assert(!T->isVoidType() && "Cannot value-init void" ); |
| 5856 | |
| 5857 | // -- if T is an array type, then each element is value-initialized; |
| 5858 | T = S.Context.getBaseElementType(QT: T); |
| 5859 | |
| 5860 | if (auto *ClassDecl = T->getAsCXXRecordDecl()) { |
| 5861 | bool NeedZeroInitialization = true; |
| 5862 | // C++98: |
| 5863 | // -- if T is a class type (clause 9) with a user-declared constructor |
| 5864 | // (12.1), then the default constructor for T is called (and the |
| 5865 | // initialization is ill-formed if T has no accessible default |
| 5866 | // constructor); |
| 5867 | // C++11: |
| 5868 | // -- if T is a class type (clause 9) with either no default constructor |
| 5869 | // (12.1 [class.ctor]) or a default constructor that is user-provided |
| 5870 | // or deleted, then the object is default-initialized; |
| 5871 | // |
| 5872 | // Note that the C++11 rule is the same as the C++98 rule if there are no |
| 5873 | // defaulted or deleted constructors, so we just use it unconditionally. |
| 5874 | CXXConstructorDecl *CD = S.LookupDefaultConstructor(Class: ClassDecl); |
| 5875 | if (!CD || !CD->getCanonicalDecl()->isDefaulted() || CD->isDeleted()) |
| 5876 | NeedZeroInitialization = false; |
| 5877 | |
| 5878 | // -- if T is a (possibly cv-qualified) non-union class type without a |
| 5879 | // user-provided or deleted default constructor, then the object is |
| 5880 | // zero-initialized and, if T has a non-trivial default constructor, |
| 5881 | // default-initialized; |
| 5882 | // The 'non-union' here was removed by DR1502. The 'non-trivial default |
| 5883 | // constructor' part was removed by DR1507. |
| 5884 | if (NeedZeroInitialization) |
| 5885 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
| 5886 | |
| 5887 | // C++03: |
| 5888 | // -- if T is a non-union class type without a user-declared constructor, |
| 5889 | // then every non-static data member and base class component of T is |
| 5890 | // value-initialized; |
| 5891 | // [...] A program that calls for [...] value-initialization of an |
| 5892 | // entity of reference type is ill-formed. |
| 5893 | // |
| 5894 | // C++11 doesn't need this handling, because value-initialization does not |
| 5895 | // occur recursively there, and the implicit default constructor is |
| 5896 | // defined as deleted in the problematic cases. |
| 5897 | if (!S.getLangOpts().CPlusPlus11 && |
| 5898 | ClassDecl->hasUninitializedReferenceMember()) { |
| 5899 | Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForReference); |
| 5900 | return; |
| 5901 | } |
| 5902 | |
| 5903 | // If this is list-value-initialization, pass the empty init list on when |
| 5904 | // building the constructor call. This affects the semantics of a few |
| 5905 | // things (such as whether an explicit default constructor can be called). |
| 5906 | Expr *InitListAsExpr = InitList; |
| 5907 | MultiExprArg Args(&InitListAsExpr, InitList ? 1 : 0); |
| 5908 | bool InitListSyntax = InitList; |
| 5909 | |
| 5910 | // FIXME: Instead of creating a CXXConstructExpr of array type here, |
| 5911 | // wrap a class-typed CXXConstructExpr in an ArrayInitLoopExpr. |
| 5912 | return TryConstructorInitialization( |
| 5913 | S, Entity, Kind, Args, DestType: T, DestArrayType: Entity.getType(), Sequence, IsListInit: InitListSyntax); |
| 5914 | } |
| 5915 | |
| 5916 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
| 5917 | } |
| 5918 | |
| 5919 | /// Attempt default initialization (C++ [dcl.init]p6). |
| 5920 | static void TryDefaultInitialization(Sema &S, |
| 5921 | const InitializedEntity &Entity, |
| 5922 | const InitializationKind &Kind, |
| 5923 | InitializationSequence &Sequence) { |
| 5924 | assert(Kind.getKind() == InitializationKind::IK_Default); |
| 5925 | |
| 5926 | // C++ [dcl.init]p6: |
| 5927 | // To default-initialize an object of type T means: |
| 5928 | // - if T is an array type, each element is default-initialized; |
| 5929 | QualType DestType = S.Context.getBaseElementType(QT: Entity.getType()); |
| 5930 | |
| 5931 | // - if T is a (possibly cv-qualified) class type (Clause 9), the default |
| 5932 | // constructor for T is called (and the initialization is ill-formed if |
| 5933 | // T has no accessible default constructor); |
| 5934 | if (DestType->isRecordType() && S.getLangOpts().CPlusPlus) { |
| 5935 | TryConstructorInitialization(S, Entity, Kind, Args: {}, DestType, |
| 5936 | DestArrayType: Entity.getType(), Sequence); |
| 5937 | return; |
| 5938 | } |
| 5939 | |
| 5940 | // - otherwise, no initialization is performed. |
| 5941 | |
| 5942 | // If a program calls for the default initialization of an object of |
| 5943 | // a const-qualified type T, T shall be a class type with a user-provided |
| 5944 | // default constructor. |
| 5945 | if (DestType.isConstQualified() && S.getLangOpts().CPlusPlus) { |
| 5946 | if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity)) |
| 5947 | Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst); |
| 5948 | return; |
| 5949 | } |
| 5950 | |
| 5951 | // If the destination type has a lifetime property, zero-initialize it. |
| 5952 | if (DestType.getQualifiers().hasObjCLifetime()) { |
| 5953 | Sequence.AddZeroInitializationStep(T: Entity.getType()); |
| 5954 | return; |
| 5955 | } |
| 5956 | } |
| 5957 | |
| 5958 | static void TryOrBuildParenListInitialization( |
| 5959 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
| 5960 | ArrayRef<Expr *> Args, InitializationSequence &Sequence, bool VerifyOnly, |
| 5961 | ExprResult *Result) { |
| 5962 | unsigned EntityIndexToProcess = 0; |
| 5963 | SmallVector<Expr *, 4> InitExprs; |
| 5964 | QualType ResultType; |
| 5965 | Expr *ArrayFiller = nullptr; |
| 5966 | FieldDecl *InitializedFieldInUnion = nullptr; |
| 5967 | |
| 5968 | auto HandleInitializedEntity = [&](const InitializedEntity &SubEntity, |
| 5969 | const InitializationKind &SubKind, |
| 5970 | Expr *Arg, Expr **InitExpr = nullptr) { |
| 5971 | InitializationSequence IS = InitializationSequence( |
| 5972 | S, SubEntity, SubKind, |
| 5973 | Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>()); |
| 5974 | |
| 5975 | if (IS.Failed()) { |
| 5976 | if (!VerifyOnly) { |
| 5977 | IS.Diagnose(S, Entity: SubEntity, Kind: SubKind, |
| 5978 | Args: Arg ? ArrayRef(Arg) : ArrayRef<Expr *>()); |
| 5979 | } else { |
| 5980 | Sequence.SetFailed( |
| 5981 | InitializationSequence::FK_ParenthesizedListInitFailed); |
| 5982 | } |
| 5983 | |
| 5984 | return false; |
| 5985 | } |
| 5986 | if (!VerifyOnly) { |
| 5987 | ExprResult ER; |
| 5988 | ER = IS.Perform(S, Entity: SubEntity, Kind: SubKind, |
| 5989 | Args: Arg ? MultiExprArg(Arg) : MutableArrayRef<Expr *>()); |
| 5990 | |
| 5991 | if (ER.isInvalid()) |
| 5992 | return false; |
| 5993 | |
| 5994 | if (InitExpr) |
| 5995 | *InitExpr = ER.get(); |
| 5996 | else |
| 5997 | InitExprs.push_back(Elt: ER.get()); |
| 5998 | } |
| 5999 | return true; |
| 6000 | }; |
| 6001 | |
| 6002 | if (const ArrayType *AT = |
| 6003 | S.getASTContext().getAsArrayType(T: Entity.getType())) { |
| 6004 | uint64_t ArrayLength; |
| 6005 | // C++ [dcl.init]p16.5 |
| 6006 | // if the destination type is an array, the object is initialized as |
| 6007 | // follows. Let x1, . . . , xk be the elements of the expression-list. If |
| 6008 | // the destination type is an array of unknown bound, it is defined as |
| 6009 | // having k elements. |
| 6010 | if (const ConstantArrayType *CAT = |
| 6011 | S.getASTContext().getAsConstantArrayType(T: Entity.getType())) { |
| 6012 | ArrayLength = CAT->getZExtSize(); |
| 6013 | ResultType = Entity.getType(); |
| 6014 | } else if (const VariableArrayType *VAT = |
| 6015 | S.getASTContext().getAsVariableArrayType(T: Entity.getType())) { |
| 6016 | // Braced-initialization of variable array types is not allowed, even if |
| 6017 | // the size is greater than or equal to the number of args, so we don't |
| 6018 | // allow them to be initialized via parenthesized aggregate initialization |
| 6019 | // either. |
| 6020 | const Expr *SE = VAT->getSizeExpr(); |
| 6021 | S.Diag(Loc: SE->getBeginLoc(), DiagID: diag::err_variable_object_no_init) |
| 6022 | << SE->getSourceRange(); |
| 6023 | return; |
| 6024 | } else { |
| 6025 | assert(Entity.getType()->isIncompleteArrayType()); |
| 6026 | ArrayLength = Args.size(); |
| 6027 | } |
| 6028 | EntityIndexToProcess = ArrayLength; |
| 6029 | |
| 6030 | // ...the ith array element is copy-initialized with xi for each |
| 6031 | // 1 <= i <= k |
| 6032 | for (Expr *E : Args) { |
| 6033 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( |
| 6034 | Context&: S.getASTContext(), Index: EntityIndexToProcess, Parent: Entity); |
| 6035 | InitializationKind SubKind = InitializationKind::CreateForInit( |
| 6036 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
| 6037 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
| 6038 | return; |
| 6039 | } |
| 6040 | // ...and value-initialized for each k < i <= n; |
| 6041 | if (ArrayLength > Args.size() || Entity.isVariableLengthArrayNew()) { |
| 6042 | InitializedEntity SubEntity = InitializedEntity::InitializeElement( |
| 6043 | Context&: S.getASTContext(), Index: Args.size(), Parent: Entity); |
| 6044 | InitializationKind SubKind = InitializationKind::CreateValue( |
| 6045 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true); |
| 6046 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr, &ArrayFiller)) |
| 6047 | return; |
| 6048 | } |
| 6049 | |
| 6050 | if (ResultType.isNull()) { |
| 6051 | ResultType = S.Context.getConstantArrayType( |
| 6052 | EltTy: AT->getElementType(), ArySize: llvm::APInt(/*numBits=*/32, ArrayLength), |
| 6053 | /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 6054 | } |
| 6055 | } else if (auto *RD = Entity.getType()->getAsCXXRecordDecl()) { |
| 6056 | bool IsUnion = RD->isUnion(); |
| 6057 | if (RD->isInvalidDecl()) { |
| 6058 | // Exit early to avoid confusion when processing members. |
| 6059 | // We do the same for braced list initialization in |
| 6060 | // `CheckStructUnionTypes`. |
| 6061 | Sequence.SetFailed( |
| 6062 | clang::InitializationSequence::FK_ParenthesizedListInitFailed); |
| 6063 | return; |
| 6064 | } |
| 6065 | |
| 6066 | if (!IsUnion) { |
| 6067 | for (const CXXBaseSpecifier &Base : RD->bases()) { |
| 6068 | InitializedEntity SubEntity = InitializedEntity::InitializeBase( |
| 6069 | Context&: S.getASTContext(), Base: &Base, IsInheritedVirtualBase: false, Parent: &Entity); |
| 6070 | if (EntityIndexToProcess < Args.size()) { |
| 6071 | // C++ [dcl.init]p16.6.2.2. |
| 6072 | // ...the object is initialized is follows. Let e1, ..., en be the |
| 6073 | // elements of the aggregate([dcl.init.aggr]). Let x1, ..., xk be |
| 6074 | // the elements of the expression-list...The element ei is |
| 6075 | // copy-initialized with xi for 1 <= i <= k. |
| 6076 | Expr *E = Args[EntityIndexToProcess]; |
| 6077 | InitializationKind SubKind = InitializationKind::CreateForInit( |
| 6078 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
| 6079 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
| 6080 | return; |
| 6081 | } else { |
| 6082 | // We've processed all of the args, but there are still base classes |
| 6083 | // that have to be initialized. |
| 6084 | // C++ [dcl.init]p17.6.2.2 |
| 6085 | // The remaining elements...otherwise are value initialzed |
| 6086 | InitializationKind SubKind = InitializationKind::CreateValue( |
| 6087 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), |
| 6088 | /*IsImplicit=*/isImplicit: true); |
| 6089 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) |
| 6090 | return; |
| 6091 | } |
| 6092 | EntityIndexToProcess++; |
| 6093 | } |
| 6094 | } |
| 6095 | |
| 6096 | for (FieldDecl *FD : RD->fields()) { |
| 6097 | // Unnamed bitfields should not be initialized at all, either with an arg |
| 6098 | // or by default. |
| 6099 | if (FD->isUnnamedBitField()) |
| 6100 | continue; |
| 6101 | |
| 6102 | InitializedEntity SubEntity = |
| 6103 | InitializedEntity::InitializeMemberFromParenAggInit(Member: FD); |
| 6104 | |
| 6105 | if (EntityIndexToProcess < Args.size()) { |
| 6106 | // ...The element ei is copy-initialized with xi for 1 <= i <= k. |
| 6107 | Expr *E = Args[EntityIndexToProcess]; |
| 6108 | |
| 6109 | // Incomplete array types indicate flexible array members. Do not allow |
| 6110 | // paren list initializations of structs with these members, as GCC |
| 6111 | // doesn't either. |
| 6112 | if (FD->getType()->isIncompleteArrayType()) { |
| 6113 | if (!VerifyOnly) { |
| 6114 | S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_flexible_array_init) |
| 6115 | << SourceRange(E->getBeginLoc(), E->getEndLoc()); |
| 6116 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_flexible_array_member) << FD; |
| 6117 | } |
| 6118 | Sequence.SetFailed( |
| 6119 | InitializationSequence::FK_ParenthesizedListInitFailed); |
| 6120 | return; |
| 6121 | } |
| 6122 | |
| 6123 | InitializationKind SubKind = InitializationKind::CreateForInit( |
| 6124 | Loc: E->getExprLoc(), /*isDirectInit=*/DirectInit: false, Init: E); |
| 6125 | if (!HandleInitializedEntity(SubEntity, SubKind, E)) |
| 6126 | return; |
| 6127 | |
| 6128 | // Unions should have only one initializer expression, so we bail out |
| 6129 | // after processing the first field. If there are more initializers then |
| 6130 | // it will be caught when we later check whether EntityIndexToProcess is |
| 6131 | // less than Args.size(); |
| 6132 | if (IsUnion) { |
| 6133 | InitializedFieldInUnion = FD; |
| 6134 | EntityIndexToProcess = 1; |
| 6135 | break; |
| 6136 | } |
| 6137 | } else { |
| 6138 | // We've processed all of the args, but there are still members that |
| 6139 | // have to be initialized. |
| 6140 | if (!VerifyOnly && FD->hasAttr<ExplicitInitAttr>() && |
| 6141 | !S.isUnevaluatedContext()) { |
| 6142 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::warn_field_requires_explicit_init) |
| 6143 | << /* Var-in-Record */ 0 << FD; |
| 6144 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD; |
| 6145 | } |
| 6146 | |
| 6147 | if (FD->hasInClassInitializer()) { |
| 6148 | if (!VerifyOnly) { |
| 6149 | // C++ [dcl.init]p16.6.2.2 |
| 6150 | // The remaining elements are initialized with their default |
| 6151 | // member initializers, if any |
| 6152 | ExprResult DIE = S.BuildCXXDefaultInitExpr( |
| 6153 | Loc: Kind.getParenOrBraceRange().getEnd(), Field: FD); |
| 6154 | if (DIE.isInvalid()) |
| 6155 | return; |
| 6156 | S.checkInitializerLifetime(Entity: SubEntity, Init: DIE.get()); |
| 6157 | InitExprs.push_back(Elt: DIE.get()); |
| 6158 | } |
| 6159 | } else { |
| 6160 | // C++ [dcl.init]p17.6.2.2 |
| 6161 | // The remaining elements...otherwise are value initialzed |
| 6162 | if (FD->getType()->isReferenceType()) { |
| 6163 | Sequence.SetFailed( |
| 6164 | InitializationSequence::FK_ParenthesizedListInitFailed); |
| 6165 | if (!VerifyOnly) { |
| 6166 | SourceRange SR = Kind.getParenOrBraceRange(); |
| 6167 | S.Diag(Loc: SR.getEnd(), DiagID: diag::err_init_reference_member_uninitialized) |
| 6168 | << FD->getType() << SR; |
| 6169 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_uninit_reference_member); |
| 6170 | } |
| 6171 | return; |
| 6172 | } |
| 6173 | InitializationKind SubKind = InitializationKind::CreateValue( |
| 6174 | InitLoc: Kind.getLocation(), LParenLoc: Kind.getLocation(), RParenLoc: Kind.getLocation(), isImplicit: true); |
| 6175 | if (!HandleInitializedEntity(SubEntity, SubKind, nullptr)) |
| 6176 | return; |
| 6177 | } |
| 6178 | } |
| 6179 | EntityIndexToProcess++; |
| 6180 | } |
| 6181 | ResultType = Entity.getType(); |
| 6182 | } |
| 6183 | |
| 6184 | // Not all of the args have been processed, so there must've been more args |
| 6185 | // than were required to initialize the element. |
| 6186 | if (EntityIndexToProcess < Args.size()) { |
| 6187 | Sequence.SetFailed(InitializationSequence::FK_ParenthesizedListInitFailed); |
| 6188 | if (!VerifyOnly) { |
| 6189 | QualType T = Entity.getType(); |
| 6190 | int InitKind = T->isArrayType() ? 0 : T->isUnionType() ? 4 : 5; |
| 6191 | SourceRange ExcessInitSR(Args[EntityIndexToProcess]->getBeginLoc(), |
| 6192 | Args.back()->getEndLoc()); |
| 6193 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers) |
| 6194 | << InitKind << ExcessInitSR; |
| 6195 | } |
| 6196 | return; |
| 6197 | } |
| 6198 | |
| 6199 | if (VerifyOnly) { |
| 6200 | Sequence.setSequenceKind(InitializationSequence::NormalSequence); |
| 6201 | Sequence.AddParenthesizedListInitStep(T: Entity.getType()); |
| 6202 | } else if (Result) { |
| 6203 | SourceRange SR = Kind.getParenOrBraceRange(); |
| 6204 | auto *CPLIE = CXXParenListInitExpr::Create( |
| 6205 | C&: S.getASTContext(), Args: InitExprs, T: ResultType, NumUserSpecifiedExprs: Args.size(), |
| 6206 | InitLoc: Kind.getLocation(), LParenLoc: SR.getBegin(), RParenLoc: SR.getEnd()); |
| 6207 | if (ArrayFiller) |
| 6208 | CPLIE->setArrayFiller(ArrayFiller); |
| 6209 | if (InitializedFieldInUnion) |
| 6210 | CPLIE->setInitializedFieldInUnion(InitializedFieldInUnion); |
| 6211 | *Result = CPLIE; |
| 6212 | S.Diag(Loc: Kind.getLocation(), |
| 6213 | DiagID: diag::warn_cxx17_compat_aggregate_init_paren_list) |
| 6214 | << Kind.getLocation() << SR << ResultType; |
| 6215 | } |
| 6216 | } |
| 6217 | |
| 6218 | /// Attempt a user-defined conversion between two types (C++ [dcl.init]), |
| 6219 | /// which enumerates all conversion functions and performs overload resolution |
| 6220 | /// to select the best. |
| 6221 | static void TryUserDefinedConversion(Sema &S, |
| 6222 | QualType DestType, |
| 6223 | const InitializationKind &Kind, |
| 6224 | Expr *Initializer, |
| 6225 | InitializationSequence &Sequence, |
| 6226 | bool TopLevelOfInitList) { |
| 6227 | assert(!DestType->isReferenceType() && "References are handled elsewhere" ); |
| 6228 | QualType SourceType = Initializer->getType(); |
| 6229 | assert((DestType->isRecordType() || SourceType->isRecordType()) && |
| 6230 | "Must have a class type to perform a user-defined conversion" ); |
| 6231 | |
| 6232 | // Build the candidate set directly in the initialization sequence |
| 6233 | // structure, so that it will persist if we fail. |
| 6234 | OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet(); |
| 6235 | CandidateSet.clear(CSK: OverloadCandidateSet::CSK_InitByUserDefinedConversion); |
| 6236 | CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace()); |
| 6237 | |
| 6238 | // Determine whether we are allowed to call explicit constructors or |
| 6239 | // explicit conversion operators. |
| 6240 | bool AllowExplicit = Kind.AllowExplicit(); |
| 6241 | |
| 6242 | if (DestType->isRecordType()) { |
| 6243 | // The type we're converting to is a class type. Enumerate its constructors |
| 6244 | // to see if there is a suitable conversion. |
| 6245 | // Try to complete the type we're converting to. |
| 6246 | if (S.isCompleteType(Loc: Kind.getLocation(), T: DestType)) { |
| 6247 | auto *DestRecordDecl = DestType->castAsCXXRecordDecl(); |
| 6248 | for (NamedDecl *D : S.LookupConstructors(Class: DestRecordDecl)) { |
| 6249 | auto Info = getConstructorInfo(ND: D); |
| 6250 | if (!Info.Constructor) |
| 6251 | continue; |
| 6252 | |
| 6253 | if (!Info.Constructor->isInvalidDecl() && |
| 6254 | Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) { |
| 6255 | if (Info.ConstructorTmpl) |
| 6256 | S.AddTemplateOverloadCandidate( |
| 6257 | FunctionTemplate: Info.ConstructorTmpl, FoundDecl: Info.FoundDecl, |
| 6258 | /*ExplicitArgs*/ ExplicitTemplateArgs: nullptr, Args: Initializer, CandidateSet, |
| 6259 | /*SuppressUserConversions=*/true, |
| 6260 | /*PartialOverloading*/ false, AllowExplicit); |
| 6261 | else |
| 6262 | S.AddOverloadCandidate(Function: Info.Constructor, FoundDecl: Info.FoundDecl, |
| 6263 | Args: Initializer, CandidateSet, |
| 6264 | /*SuppressUserConversions=*/true, |
| 6265 | /*PartialOverloading*/ false, AllowExplicit); |
| 6266 | } |
| 6267 | } |
| 6268 | } |
| 6269 | } |
| 6270 | |
| 6271 | SourceLocation DeclLoc = Initializer->getBeginLoc(); |
| 6272 | |
| 6273 | if (SourceType->isRecordType()) { |
| 6274 | // The type we're converting from is a class type, enumerate its conversion |
| 6275 | // functions. |
| 6276 | |
| 6277 | // We can only enumerate the conversion functions for a complete type; if |
| 6278 | // the type isn't complete, simply skip this step. |
| 6279 | if (S.isCompleteType(Loc: DeclLoc, T: SourceType)) { |
| 6280 | auto *SourceRecordDecl = SourceType->castAsCXXRecordDecl(); |
| 6281 | const auto &Conversions = |
| 6282 | SourceRecordDecl->getVisibleConversionFunctions(); |
| 6283 | for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { |
| 6284 | NamedDecl *D = *I; |
| 6285 | CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Val: D->getDeclContext()); |
| 6286 | if (isa<UsingShadowDecl>(Val: D)) |
| 6287 | D = cast<UsingShadowDecl>(Val: D)->getTargetDecl(); |
| 6288 | |
| 6289 | FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(Val: D); |
| 6290 | CXXConversionDecl *Conv; |
| 6291 | if (ConvTemplate) |
| 6292 | Conv = cast<CXXConversionDecl>(Val: ConvTemplate->getTemplatedDecl()); |
| 6293 | else |
| 6294 | Conv = cast<CXXConversionDecl>(Val: D); |
| 6295 | |
| 6296 | if (ConvTemplate) |
| 6297 | S.AddTemplateConversionCandidate( |
| 6298 | FunctionTemplate: ConvTemplate, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, ToType: DestType, |
| 6299 | CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, AllowExplicit); |
| 6300 | else |
| 6301 | S.AddConversionCandidate(Conversion: Conv, FoundDecl: I.getPair(), ActingContext: ActingDC, From: Initializer, |
| 6302 | ToType: DestType, CandidateSet, AllowObjCConversionOnExplicit: AllowExplicit, |
| 6303 | AllowExplicit); |
| 6304 | } |
| 6305 | } |
| 6306 | } |
| 6307 | |
| 6308 | // Perform overload resolution. If it fails, return the failed result. |
| 6309 | OverloadCandidateSet::iterator Best; |
| 6310 | if (OverloadingResult Result |
| 6311 | = CandidateSet.BestViableFunction(S, Loc: DeclLoc, Best)) { |
| 6312 | Sequence.SetOverloadFailure( |
| 6313 | Failure: InitializationSequence::FK_UserConversionOverloadFailed, Result); |
| 6314 | |
| 6315 | // [class.copy.elision]p3: |
| 6316 | // In some copy-initialization contexts, a two-stage overload resolution |
| 6317 | // is performed. |
| 6318 | // If the first overload resolution selects a deleted function, we also |
| 6319 | // need the initialization sequence to decide whether to perform the second |
| 6320 | // overload resolution. |
| 6321 | if (!(Result == OR_Deleted && |
| 6322 | Kind.getKind() == InitializationKind::IK_Copy)) |
| 6323 | return; |
| 6324 | } |
| 6325 | |
| 6326 | FunctionDecl *Function = Best->Function; |
| 6327 | Function->setReferenced(); |
| 6328 | bool HadMultipleCandidates = (CandidateSet.size() > 1); |
| 6329 | |
| 6330 | if (isa<CXXConstructorDecl>(Val: Function)) { |
| 6331 | // Add the user-defined conversion step. Any cv-qualification conversion is |
| 6332 | // subsumed by the initialization. Per DR5, the created temporary is of the |
| 6333 | // cv-unqualified type of the destination. |
| 6334 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, |
| 6335 | T: DestType.getUnqualifiedType(), |
| 6336 | HadMultipleCandidates); |
| 6337 | |
| 6338 | // C++14 and before: |
| 6339 | // - if the function is a constructor, the call initializes a temporary |
| 6340 | // of the cv-unqualified version of the destination type. The [...] |
| 6341 | // temporary [...] is then used to direct-initialize, according to the |
| 6342 | // rules above, the object that is the destination of the |
| 6343 | // copy-initialization. |
| 6344 | // Note that this just performs a simple object copy from the temporary. |
| 6345 | // |
| 6346 | // C++17: |
| 6347 | // - if the function is a constructor, the call is a prvalue of the |
| 6348 | // cv-unqualified version of the destination type whose return object |
| 6349 | // is initialized by the constructor. The call is used to |
| 6350 | // direct-initialize, according to the rules above, the object that |
| 6351 | // is the destination of the copy-initialization. |
| 6352 | // Therefore we need to do nothing further. |
| 6353 | // |
| 6354 | // FIXME: Mark this copy as extraneous. |
| 6355 | if (!S.getLangOpts().CPlusPlus17) |
| 6356 | Sequence.AddFinalCopy(T: DestType); |
| 6357 | else if (DestType.hasQualifiers()) |
| 6358 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
| 6359 | return; |
| 6360 | } |
| 6361 | |
| 6362 | // Add the user-defined conversion step that calls the conversion function. |
| 6363 | QualType ConvType = Function->getCallResultType(); |
| 6364 | Sequence.AddUserConversionStep(Function, FoundDecl: Best->FoundDecl, T: ConvType, |
| 6365 | HadMultipleCandidates); |
| 6366 | |
| 6367 | if (ConvType->isRecordType()) { |
| 6368 | if (S.getLangOpts().HLSL && |
| 6369 | ConvType.getAddressSpace() == LangAS::hlsl_constant && |
| 6370 | S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType)) { |
| 6371 | Sequence.AddHLSLBufferConversionStep(T: ConvType); |
| 6372 | return; |
| 6373 | } |
| 6374 | |
| 6375 | // The call is used to direct-initialize [...] the object that is the |
| 6376 | // destination of the copy-initialization. |
| 6377 | // |
| 6378 | // In C++17, this does not call a constructor if we enter /17.6.1: |
| 6379 | // - If the initializer expression is a prvalue and the cv-unqualified |
| 6380 | // version of the source type is the same as the class of the |
| 6381 | // destination [... do not make an extra copy] |
| 6382 | // |
| 6383 | // FIXME: Mark this copy as extraneous. |
| 6384 | if (!S.getLangOpts().CPlusPlus17 || |
| 6385 | Function->getReturnType()->isReferenceType() || |
| 6386 | !S.Context.hasSameUnqualifiedType(T1: ConvType, T2: DestType)) |
| 6387 | Sequence.AddFinalCopy(T: DestType); |
| 6388 | else if (!S.Context.hasSameType(T1: ConvType, T2: DestType)) |
| 6389 | Sequence.AddQualificationConversionStep(Ty: DestType, VK: VK_PRValue); |
| 6390 | return; |
| 6391 | } |
| 6392 | |
| 6393 | // If the conversion following the call to the conversion function |
| 6394 | // is interesting, add it as a separate step. |
| 6395 | assert(Best->HasFinalConversion); |
| 6396 | if (Best->FinalConversion.First || Best->FinalConversion.Second || |
| 6397 | Best->FinalConversion.Third) { |
| 6398 | ImplicitConversionSequence ICS; |
| 6399 | ICS.setStandard(); |
| 6400 | ICS.Standard = Best->FinalConversion; |
| 6401 | Sequence.AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList); |
| 6402 | } |
| 6403 | } |
| 6404 | |
| 6405 | /// The non-zero enum values here are indexes into diagnostic alternatives. |
| 6406 | enum InvalidICRKind { IIK_okay, IIK_nonlocal, IIK_nonscalar }; |
| 6407 | |
| 6408 | /// Determines whether this expression is an acceptable ICR source. |
| 6409 | static InvalidICRKind isInvalidICRSource(ASTContext &C, Expr *e, |
| 6410 | bool isAddressOf, bool &isWeakAccess) { |
| 6411 | // Skip parens. |
| 6412 | e = e->IgnoreParens(); |
| 6413 | |
| 6414 | // Skip address-of nodes. |
| 6415 | if (UnaryOperator *op = dyn_cast<UnaryOperator>(Val: e)) { |
| 6416 | if (op->getOpcode() == UO_AddrOf) |
| 6417 | return isInvalidICRSource(C, e: op->getSubExpr(), /*addressof*/ isAddressOf: true, |
| 6418 | isWeakAccess); |
| 6419 | |
| 6420 | // Skip certain casts. |
| 6421 | } else if (CastExpr *ce = dyn_cast<CastExpr>(Val: e)) { |
| 6422 | switch (ce->getCastKind()) { |
| 6423 | case CK_Dependent: |
| 6424 | case CK_BitCast: |
| 6425 | case CK_LValueBitCast: |
| 6426 | case CK_NoOp: |
| 6427 | return isInvalidICRSource(C, e: ce->getSubExpr(), isAddressOf, isWeakAccess); |
| 6428 | |
| 6429 | case CK_ArrayToPointerDecay: |
| 6430 | return IIK_nonscalar; |
| 6431 | |
| 6432 | case CK_NullToPointer: |
| 6433 | return IIK_okay; |
| 6434 | |
| 6435 | default: |
| 6436 | break; |
| 6437 | } |
| 6438 | |
| 6439 | // If we have a declaration reference, it had better be a local variable. |
| 6440 | } else if (isa<DeclRefExpr>(Val: e)) { |
| 6441 | // set isWeakAccess to true, to mean that there will be an implicit |
| 6442 | // load which requires a cleanup. |
| 6443 | if (e->getType().getObjCLifetime() == Qualifiers::OCL_Weak) |
| 6444 | isWeakAccess = true; |
| 6445 | |
| 6446 | if (!isAddressOf) return IIK_nonlocal; |
| 6447 | |
| 6448 | VarDecl *var = dyn_cast<VarDecl>(Val: cast<DeclRefExpr>(Val: e)->getDecl()); |
| 6449 | if (!var) return IIK_nonlocal; |
| 6450 | |
| 6451 | return (var->hasLocalStorage() ? IIK_okay : IIK_nonlocal); |
| 6452 | |
| 6453 | // If we have a conditional operator, check both sides. |
| 6454 | } else if (ConditionalOperator *cond = dyn_cast<ConditionalOperator>(Val: e)) { |
| 6455 | if (InvalidICRKind iik = isInvalidICRSource(C, e: cond->getLHS(), isAddressOf, |
| 6456 | isWeakAccess)) |
| 6457 | return iik; |
| 6458 | |
| 6459 | return isInvalidICRSource(C, e: cond->getRHS(), isAddressOf, isWeakAccess); |
| 6460 | |
| 6461 | // These are never scalar. |
| 6462 | } else if (isa<ArraySubscriptExpr>(Val: e)) { |
| 6463 | return IIK_nonscalar; |
| 6464 | |
| 6465 | // Otherwise, it needs to be a null pointer constant. |
| 6466 | } else { |
| 6467 | return (e->isNullPointerConstant(Ctx&: C, NPC: Expr::NPC_ValueDependentIsNull) |
| 6468 | ? IIK_okay : IIK_nonlocal); |
| 6469 | } |
| 6470 | |
| 6471 | return IIK_nonlocal; |
| 6472 | } |
| 6473 | |
| 6474 | /// Check whether the given expression is a valid operand for an |
| 6475 | /// indirect copy/restore. |
| 6476 | static void checkIndirectCopyRestoreSource(Sema &S, Expr *src) { |
| 6477 | assert(src->isPRValue()); |
| 6478 | bool isWeakAccess = false; |
| 6479 | InvalidICRKind iik = isInvalidICRSource(C&: S.Context, e: src, isAddressOf: false, isWeakAccess); |
| 6480 | // If isWeakAccess to true, there will be an implicit |
| 6481 | // load which requires a cleanup. |
| 6482 | if (S.getLangOpts().ObjCAutoRefCount && isWeakAccess) |
| 6483 | S.Cleanup.setExprNeedsCleanups(true); |
| 6484 | |
| 6485 | if (iik == IIK_okay) return; |
| 6486 | |
| 6487 | S.Diag(Loc: src->getExprLoc(), DiagID: diag::err_arc_nonlocal_writeback) |
| 6488 | << ((unsigned) iik - 1) // shift index into diagnostic explanations |
| 6489 | << src->getSourceRange(); |
| 6490 | } |
| 6491 | |
| 6492 | /// Determine whether we have compatible array types for the |
| 6493 | /// purposes of GNU by-copy array initialization. |
| 6494 | static bool hasCompatibleArrayTypes(ASTContext &Context, const ArrayType *Dest, |
| 6495 | const ArrayType *Source) { |
| 6496 | // If the source and destination array types are equivalent, we're |
| 6497 | // done. |
| 6498 | if (Context.hasSameType(T1: QualType(Dest, 0), T2: QualType(Source, 0))) |
| 6499 | return true; |
| 6500 | |
| 6501 | // Make sure that the element types are the same. |
| 6502 | if (!Context.hasSameType(T1: Dest->getElementType(), T2: Source->getElementType())) |
| 6503 | return false; |
| 6504 | |
| 6505 | // The only mismatch we allow is when the destination is an |
| 6506 | // incomplete array type and the source is a constant array type. |
| 6507 | return Source->isConstantArrayType() && Dest->isIncompleteArrayType(); |
| 6508 | } |
| 6509 | |
| 6510 | static bool tryObjCWritebackConversion(Sema &S, |
| 6511 | InitializationSequence &Sequence, |
| 6512 | const InitializedEntity &Entity, |
| 6513 | Expr *Initializer) { |
| 6514 | bool ArrayDecay = false; |
| 6515 | QualType ArgType = Initializer->getType(); |
| 6516 | QualType ArgPointee; |
| 6517 | if (const ArrayType *ArgArrayType = S.Context.getAsArrayType(T: ArgType)) { |
| 6518 | ArrayDecay = true; |
| 6519 | ArgPointee = ArgArrayType->getElementType(); |
| 6520 | ArgType = S.Context.getPointerType(T: ArgPointee); |
| 6521 | } |
| 6522 | |
| 6523 | // Handle write-back conversion. |
| 6524 | QualType ConvertedArgType; |
| 6525 | if (!S.ObjC().isObjCWritebackConversion(FromType: ArgType, ToType: Entity.getType(), |
| 6526 | ConvertedType&: ConvertedArgType)) |
| 6527 | return false; |
| 6528 | |
| 6529 | // We should copy unless we're passing to an argument explicitly |
| 6530 | // marked 'out'. |
| 6531 | bool ShouldCopy = true; |
| 6532 | if (ParmVarDecl *param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl())) |
| 6533 | ShouldCopy = (param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); |
| 6534 | |
| 6535 | // Do we need an lvalue conversion? |
| 6536 | if (ArrayDecay || Initializer->isGLValue()) { |
| 6537 | ImplicitConversionSequence ICS; |
| 6538 | ICS.setStandard(); |
| 6539 | ICS.Standard.setAsIdentityConversion(); |
| 6540 | |
| 6541 | QualType ResultType; |
| 6542 | if (ArrayDecay) { |
| 6543 | ICS.Standard.First = ICK_Array_To_Pointer; |
| 6544 | ResultType = S.Context.getPointerType(T: ArgPointee); |
| 6545 | } else { |
| 6546 | ICS.Standard.First = ICK_Lvalue_To_Rvalue; |
| 6547 | ResultType = Initializer->getType().getNonLValueExprType(Context: S.Context); |
| 6548 | } |
| 6549 | |
| 6550 | Sequence.AddConversionSequenceStep(ICS, T: ResultType); |
| 6551 | } |
| 6552 | |
| 6553 | Sequence.AddPassByIndirectCopyRestoreStep(type: Entity.getType(), shouldCopy: ShouldCopy); |
| 6554 | return true; |
| 6555 | } |
| 6556 | |
| 6557 | static bool TryOCLSamplerInitialization(Sema &S, |
| 6558 | InitializationSequence &Sequence, |
| 6559 | QualType DestType, |
| 6560 | Expr *Initializer) { |
| 6561 | if (!S.getLangOpts().OpenCL || !DestType->isSamplerT() || |
| 6562 | (!Initializer->isIntegerConstantExpr(Ctx: S.Context) && |
| 6563 | !Initializer->getType()->isSamplerT())) |
| 6564 | return false; |
| 6565 | |
| 6566 | Sequence.AddOCLSamplerInitStep(T: DestType); |
| 6567 | return true; |
| 6568 | } |
| 6569 | |
| 6570 | static bool IsZeroInitializer(const Expr *Init, ASTContext &Ctx) { |
| 6571 | std::optional<llvm::APSInt> Value = Init->getIntegerConstantExpr(Ctx); |
| 6572 | return Value && Value->isZero(); |
| 6573 | } |
| 6574 | |
| 6575 | static bool TryOCLZeroOpaqueTypeInitialization(Sema &S, |
| 6576 | InitializationSequence &Sequence, |
| 6577 | QualType DestType, |
| 6578 | Expr *Initializer) { |
| 6579 | if (!S.getLangOpts().OpenCL) |
| 6580 | return false; |
| 6581 | |
| 6582 | // |
| 6583 | // OpenCL 1.2 spec, s6.12.10 |
| 6584 | // |
| 6585 | // The event argument can also be used to associate the |
| 6586 | // async_work_group_copy with a previous async copy allowing |
| 6587 | // an event to be shared by multiple async copies; otherwise |
| 6588 | // event should be zero. |
| 6589 | // |
| 6590 | if (DestType->isEventT() || DestType->isQueueT()) { |
| 6591 | if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext())) |
| 6592 | return false; |
| 6593 | |
| 6594 | Sequence.AddOCLZeroOpaqueTypeStep(T: DestType); |
| 6595 | return true; |
| 6596 | } |
| 6597 | |
| 6598 | // We should allow zero initialization for all types defined in the |
| 6599 | // cl_intel_device_side_avc_motion_estimation extension, except |
| 6600 | // intel_sub_group_avc_mce_payload_t and intel_sub_group_avc_mce_result_t. |
| 6601 | if (S.getOpenCLOptions().isAvailableOption( |
| 6602 | Ext: "cl_intel_device_side_avc_motion_estimation" , LO: S.getLangOpts()) && |
| 6603 | DestType->isOCLIntelSubgroupAVCType()) { |
| 6604 | if (DestType->isOCLIntelSubgroupAVCMcePayloadType() || |
| 6605 | DestType->isOCLIntelSubgroupAVCMceResultType()) |
| 6606 | return false; |
| 6607 | if (!IsZeroInitializer(Init: Initializer, Ctx&: S.getASTContext())) |
| 6608 | return false; |
| 6609 | |
| 6610 | Sequence.AddOCLZeroOpaqueTypeStep(T: DestType); |
| 6611 | return true; |
| 6612 | } |
| 6613 | |
| 6614 | return false; |
| 6615 | } |
| 6616 | |
| 6617 | InitializationSequence::InitializationSequence( |
| 6618 | Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, |
| 6619 | MultiExprArg Args, bool TopLevelOfInitList, bool TreatUnavailableAsInvalid) |
| 6620 | : FailedOverloadResult(OR_Success), |
| 6621 | FailedCandidateSet(Kind.getLocation(), OverloadCandidateSet::CSK_Normal) { |
| 6622 | InitializeFrom(S, Entity, Kind, Args, TopLevelOfInitList, |
| 6623 | TreatUnavailableAsInvalid); |
| 6624 | } |
| 6625 | |
| 6626 | /// Tries to get a FunctionDecl out of `E`. If it succeeds and we can take the |
| 6627 | /// address of that function, this returns true. Otherwise, it returns false. |
| 6628 | static bool isExprAnUnaddressableFunction(Sema &S, const Expr *E) { |
| 6629 | auto *DRE = dyn_cast<DeclRefExpr>(Val: E); |
| 6630 | if (!DRE || !isa<FunctionDecl>(Val: DRE->getDecl())) |
| 6631 | return false; |
| 6632 | |
| 6633 | return !S.checkAddressOfFunctionIsAvailable( |
| 6634 | Function: cast<FunctionDecl>(Val: DRE->getDecl())); |
| 6635 | } |
| 6636 | |
| 6637 | /// Determine whether we can perform an elementwise array copy for this kind |
| 6638 | /// of entity. |
| 6639 | static bool canPerformArrayCopy(const InitializedEntity &Entity) { |
| 6640 | switch (Entity.getKind()) { |
| 6641 | case InitializedEntity::EK_LambdaCapture: |
| 6642 | // C++ [expr.prim.lambda]p24: |
| 6643 | // For array members, the array elements are direct-initialized in |
| 6644 | // increasing subscript order. |
| 6645 | return true; |
| 6646 | |
| 6647 | case InitializedEntity::EK_Variable: |
| 6648 | // C++ [dcl.decomp]p1: |
| 6649 | // [...] each element is copy-initialized or direct-initialized from the |
| 6650 | // corresponding element of the assignment-expression [...] |
| 6651 | return isa<DecompositionDecl>(Val: Entity.getDecl()); |
| 6652 | |
| 6653 | case InitializedEntity::EK_Member: |
| 6654 | // C++ [class.copy.ctor]p14: |
| 6655 | // - if the member is an array, each element is direct-initialized with |
| 6656 | // the corresponding subobject of x |
| 6657 | return Entity.isImplicitMemberInitializer(); |
| 6658 | |
| 6659 | case InitializedEntity::EK_ArrayElement: |
| 6660 | // All the above cases are intended to apply recursively, even though none |
| 6661 | // of them actually say that. |
| 6662 | if (auto *E = Entity.getParent()) |
| 6663 | return canPerformArrayCopy(Entity: *E); |
| 6664 | break; |
| 6665 | |
| 6666 | default: |
| 6667 | break; |
| 6668 | } |
| 6669 | |
| 6670 | return false; |
| 6671 | } |
| 6672 | |
| 6673 | static const FieldDecl *getConstField(const RecordDecl *RD) { |
| 6674 | assert(!isa<CXXRecordDecl>(RD) && "Only expect to call this in C mode" ); |
| 6675 | for (const FieldDecl *FD : RD->fields()) { |
| 6676 | // If the field is a flexible array member, we don't want to consider it |
| 6677 | // as a const field because there's no way to initialize the FAM anyway. |
| 6678 | const ASTContext &Ctx = FD->getASTContext(); |
| 6679 | if (Decl::isFlexibleArrayMemberLike( |
| 6680 | Context: Ctx, D: FD, Ty: FD->getType(), |
| 6681 | StrictFlexArraysLevel: Ctx.getLangOpts().getStrictFlexArraysLevel(), |
| 6682 | /*IgnoreTemplateOrMacroSubstitution=*/true)) |
| 6683 | continue; |
| 6684 | |
| 6685 | QualType QT = FD->getType(); |
| 6686 | if (QT.isConstQualified()) |
| 6687 | return FD; |
| 6688 | if (const auto *RD = QT->getAsRecordDecl()) { |
| 6689 | if (const FieldDecl *FD = getConstField(RD)) |
| 6690 | return FD; |
| 6691 | } |
| 6692 | } |
| 6693 | return nullptr; |
| 6694 | } |
| 6695 | |
| 6696 | void InitializationSequence::InitializeFrom(Sema &S, |
| 6697 | const InitializedEntity &Entity, |
| 6698 | const InitializationKind &Kind, |
| 6699 | MultiExprArg Args, |
| 6700 | bool TopLevelOfInitList, |
| 6701 | bool TreatUnavailableAsInvalid) { |
| 6702 | ASTContext &Context = S.Context; |
| 6703 | |
| 6704 | // Eliminate non-overload placeholder types in the arguments. We |
| 6705 | // need to do this before checking whether types are dependent |
| 6706 | // because lowering a pseudo-object expression might well give us |
| 6707 | // something of dependent type. |
| 6708 | for (unsigned I = 0, E = Args.size(); I != E; ++I) |
| 6709 | if (Args[I]->getType()->isNonOverloadPlaceholderType()) { |
| 6710 | // FIXME: should we be doing this here? |
| 6711 | ExprResult result = S.CheckPlaceholderExpr(E: Args[I]); |
| 6712 | if (result.isInvalid()) { |
| 6713 | SetFailed(FK_PlaceholderType); |
| 6714 | return; |
| 6715 | } |
| 6716 | Args[I] = result.get(); |
| 6717 | } |
| 6718 | |
| 6719 | // C++0x [dcl.init]p16: |
| 6720 | // The semantics of initializers are as follows. The destination type is |
| 6721 | // the type of the object or reference being initialized and the source |
| 6722 | // type is the type of the initializer expression. The source type is not |
| 6723 | // defined when the initializer is a braced-init-list or when it is a |
| 6724 | // parenthesized list of expressions. |
| 6725 | QualType DestType = Entity.getType(); |
| 6726 | |
| 6727 | if (DestType->isDependentType() || |
| 6728 | Expr::hasAnyTypeDependentArguments(Exprs: Args)) { |
| 6729 | SequenceKind = DependentSequence; |
| 6730 | return; |
| 6731 | } |
| 6732 | |
| 6733 | // Almost everything is a normal sequence. |
| 6734 | setSequenceKind(NormalSequence); |
| 6735 | |
| 6736 | QualType SourceType; |
| 6737 | Expr *Initializer = nullptr; |
| 6738 | if (Args.size() == 1) { |
| 6739 | Initializer = Args[0]; |
| 6740 | if (S.getLangOpts().ObjC) { |
| 6741 | if (S.ObjC().CheckObjCBridgeRelatedConversions( |
| 6742 | Loc: Initializer->getBeginLoc(), DestType, SrcType: Initializer->getType(), |
| 6743 | SrcExpr&: Initializer) || |
| 6744 | S.ObjC().CheckConversionToObjCLiteral(DstType: DestType, SrcExpr&: Initializer)) |
| 6745 | Args[0] = Initializer; |
| 6746 | } |
| 6747 | if (!isa<InitListExpr>(Val: Initializer)) |
| 6748 | SourceType = Initializer->getType(); |
| 6749 | } |
| 6750 | |
| 6751 | // - If the initializer is a (non-parenthesized) braced-init-list, the |
| 6752 | // object is list-initialized (8.5.4). |
| 6753 | if (Kind.getKind() != InitializationKind::IK_Direct) { |
| 6754 | if (InitListExpr *InitList = dyn_cast_or_null<InitListExpr>(Val: Initializer)) { |
| 6755 | TryListInitialization(S, Entity, Kind, InitList, Sequence&: *this, |
| 6756 | TreatUnavailableAsInvalid); |
| 6757 | return; |
| 6758 | } |
| 6759 | } |
| 6760 | |
| 6761 | if (!S.getLangOpts().CPlusPlus && |
| 6762 | Kind.getKind() == InitializationKind::IK_Default) { |
| 6763 | if (RecordDecl *Rec = DestType->getAsRecordDecl()) { |
| 6764 | VarDecl *Var = dyn_cast_or_null<VarDecl>(Val: Entity.getDecl()); |
| 6765 | if (Rec->hasUninitializedExplicitInitFields()) { |
| 6766 | if (Var && !Initializer && !S.isUnevaluatedContext()) { |
| 6767 | S.Diag(Loc: Var->getLocation(), DiagID: diag::warn_field_requires_explicit_init) |
| 6768 | << /* Var-in-Record */ 1 << Rec; |
| 6769 | emitUninitializedExplicitInitFields(S, R: Rec); |
| 6770 | } |
| 6771 | } |
| 6772 | // If the record has any members which are const (recursively checked), |
| 6773 | // then we want to diagnose those as being uninitialized if there is no |
| 6774 | // initializer present. However, we only do this for structure types, not |
| 6775 | // union types, because an unitialized field in a union is generally |
| 6776 | // reasonable, especially in C where unions can be used for type punning. |
| 6777 | if (Var && !Initializer && !Rec->isUnion() && !Rec->isInvalidDecl()) { |
| 6778 | if (const FieldDecl *FD = getConstField(RD: Rec)) { |
| 6779 | unsigned DiagID = diag::warn_default_init_const_field_unsafe; |
| 6780 | if (Var->getStorageDuration() == SD_Static || |
| 6781 | Var->getStorageDuration() == SD_Thread) |
| 6782 | DiagID = diag::warn_default_init_const_field; |
| 6783 | |
| 6784 | bool EmitCppCompat = !S.Diags.isIgnored( |
| 6785 | DiagID: diag::warn_cxx_compat_hack_fake_diagnostic_do_not_emit, |
| 6786 | Loc: Var->getLocation()); |
| 6787 | |
| 6788 | S.Diag(Loc: Var->getLocation(), DiagID) << Var->getType() << EmitCppCompat; |
| 6789 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_default_init_const_member) << FD; |
| 6790 | } |
| 6791 | } |
| 6792 | } |
| 6793 | } |
| 6794 | |
| 6795 | // - If the destination type is a reference type, see 8.5.3. |
| 6796 | if (DestType->isReferenceType()) { |
| 6797 | // C++0x [dcl.init.ref]p1: |
| 6798 | // A variable declared to be a T& or T&&, that is, "reference to type T" |
| 6799 | // (8.3.2), shall be initialized by an object, or function, of type T or |
| 6800 | // by an object that can be converted into a T. |
| 6801 | // (Therefore, multiple arguments are not permitted.) |
| 6802 | if (Args.size() != 1) |
| 6803 | SetFailed(FK_TooManyInitsForReference); |
| 6804 | // C++17 [dcl.init.ref]p5: |
| 6805 | // A reference [...] is initialized by an expression [...] as follows: |
| 6806 | // If the initializer is not an expression, presumably we should reject, |
| 6807 | // but the standard fails to actually say so. |
| 6808 | else if (isa<InitListExpr>(Val: Args[0])) |
| 6809 | SetFailed(FK_ParenthesizedListInitForReference); |
| 6810 | else |
| 6811 | TryReferenceInitialization(S, Entity, Kind, Initializer: Args[0], Sequence&: *this, |
| 6812 | TopLevelOfInitList); |
| 6813 | return; |
| 6814 | } |
| 6815 | |
| 6816 | // - If the initializer is (), the object is value-initialized. |
| 6817 | if (Kind.getKind() == InitializationKind::IK_Value || |
| 6818 | (Kind.getKind() == InitializationKind::IK_Direct && Args.empty())) { |
| 6819 | TryValueInitialization(S, Entity, Kind, Sequence&: *this); |
| 6820 | return; |
| 6821 | } |
| 6822 | |
| 6823 | // Handle default initialization. |
| 6824 | if (Kind.getKind() == InitializationKind::IK_Default) { |
| 6825 | TryDefaultInitialization(S, Entity, Kind, Sequence&: *this); |
| 6826 | return; |
| 6827 | } |
| 6828 | |
| 6829 | // - If the destination type is an array of characters, an array of |
| 6830 | // char16_t, an array of char32_t, or an array of wchar_t, and the |
| 6831 | // initializer is a string literal, see 8.5.2. |
| 6832 | // - Otherwise, if the destination type is an array, the program is |
| 6833 | // ill-formed. |
| 6834 | // - Except in HLSL, where non-decaying array parameters behave like |
| 6835 | // non-array types for initialization. |
| 6836 | if (DestType->isArrayType() && !DestType->isArrayParameterType()) { |
| 6837 | const ArrayType *DestAT = Context.getAsArrayType(T: DestType); |
| 6838 | if (Initializer && isa<VariableArrayType>(Val: DestAT)) { |
| 6839 | SetFailed(FK_VariableLengthArrayHasInitializer); |
| 6840 | return; |
| 6841 | } |
| 6842 | |
| 6843 | if (Initializer) { |
| 6844 | switch (IsStringInit(Init: Initializer, AT: DestAT, Context)) { |
| 6845 | case SIF_None: |
| 6846 | TryStringLiteralInitialization(S, Entity, Kind, Initializer, Sequence&: *this); |
| 6847 | return; |
| 6848 | case SIF_NarrowStringIntoWideChar: |
| 6849 | SetFailed(FK_NarrowStringIntoWideCharArray); |
| 6850 | return; |
| 6851 | case SIF_WideStringIntoChar: |
| 6852 | SetFailed(FK_WideStringIntoCharArray); |
| 6853 | return; |
| 6854 | case SIF_IncompatWideStringIntoWideChar: |
| 6855 | SetFailed(FK_IncompatWideStringIntoWideChar); |
| 6856 | return; |
| 6857 | case SIF_PlainStringIntoUTF8Char: |
| 6858 | SetFailed(FK_PlainStringIntoUTF8Char); |
| 6859 | return; |
| 6860 | case SIF_UTF8StringIntoPlainChar: |
| 6861 | SetFailed(FK_UTF8StringIntoPlainChar); |
| 6862 | return; |
| 6863 | case SIF_Other: |
| 6864 | break; |
| 6865 | } |
| 6866 | } |
| 6867 | |
| 6868 | if (S.getLangOpts().HLSL && Initializer && isa<ConstantArrayType>(Val: DestAT)) { |
| 6869 | QualType SrcType = Entity.getType(); |
| 6870 | if (SrcType->isArrayParameterType()) |
| 6871 | SrcType = |
| 6872 | cast<ArrayParameterType>(Val&: SrcType)->getConstantArrayType(Ctx: Context); |
| 6873 | if (S.Context.hasSameUnqualifiedType(T1: DestType, T2: SrcType)) { |
| 6874 | TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this, |
| 6875 | TreatUnavailableAsInvalid); |
| 6876 | return; |
| 6877 | } |
| 6878 | } |
| 6879 | |
| 6880 | // Some kinds of initialization permit an array to be initialized from |
| 6881 | // another array of the same type, and perform elementwise initialization. |
| 6882 | if (Initializer && isa<ConstantArrayType>(Val: DestAT) && |
| 6883 | S.Context.hasSameUnqualifiedType(T1: Initializer->getType(), |
| 6884 | T2: Entity.getType()) && |
| 6885 | canPerformArrayCopy(Entity)) { |
| 6886 | TryArrayCopy(S, Kind, Entity, Initializer, DestType, Sequence&: *this, |
| 6887 | TreatUnavailableAsInvalid); |
| 6888 | return; |
| 6889 | } |
| 6890 | |
| 6891 | // Note: as an GNU C extension, we allow initialization of an |
| 6892 | // array from a compound literal that creates an array of the same |
| 6893 | // type, so long as the initializer has no side effects. |
| 6894 | if (!S.getLangOpts().CPlusPlus && Initializer && |
| 6895 | isa<CompoundLiteralExpr>(Val: Initializer->IgnoreParens()) && |
| 6896 | Initializer->getType()->isArrayType()) { |
| 6897 | const ArrayType *SourceAT |
| 6898 | = Context.getAsArrayType(T: Initializer->getType()); |
| 6899 | if (!hasCompatibleArrayTypes(Context&: S.Context, Dest: DestAT, Source: SourceAT)) |
| 6900 | SetFailed(FK_ArrayTypeMismatch); |
| 6901 | else if (Initializer->HasSideEffects(Ctx: S.Context)) |
| 6902 | SetFailed(FK_NonConstantArrayInit); |
| 6903 | else { |
| 6904 | AddArrayInitStep(T: DestType, /*IsGNUExtension*/true); |
| 6905 | } |
| 6906 | } |
| 6907 | // Note: as a GNU C++ extension, we allow list-initialization of a |
| 6908 | // class member of array type from a parenthesized initializer list. |
| 6909 | else if (S.getLangOpts().CPlusPlus && |
| 6910 | Entity.getKind() == InitializedEntity::EK_Member && |
| 6911 | isa_and_nonnull<InitListExpr>(Val: Initializer)) { |
| 6912 | TryListInitialization(S, Entity, Kind, InitList: cast<InitListExpr>(Val: Initializer), |
| 6913 | Sequence&: *this, TreatUnavailableAsInvalid); |
| 6914 | AddParenthesizedArrayInitStep(T: DestType); |
| 6915 | } else if (S.getLangOpts().CPlusPlus20 && !TopLevelOfInitList && |
| 6916 | Kind.getKind() == InitializationKind::IK_Direct) |
| 6917 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
| 6918 | /*VerifyOnly=*/true); |
| 6919 | else if (DestAT->getElementType()->isCharType()) |
| 6920 | SetFailed(FK_ArrayNeedsInitListOrStringLiteral); |
| 6921 | else if (IsWideCharCompatible(T: DestAT->getElementType(), Context)) |
| 6922 | SetFailed(FK_ArrayNeedsInitListOrWideStringLiteral); |
| 6923 | else |
| 6924 | SetFailed(FK_ArrayNeedsInitList); |
| 6925 | |
| 6926 | return; |
| 6927 | } |
| 6928 | |
| 6929 | // Determine whether we should consider writeback conversions for |
| 6930 | // Objective-C ARC. |
| 6931 | bool allowObjCWritebackConversion = S.getLangOpts().ObjCAutoRefCount && |
| 6932 | Entity.isParameterKind(); |
| 6933 | |
| 6934 | if (TryOCLSamplerInitialization(S, Sequence&: *this, DestType, Initializer)) |
| 6935 | return; |
| 6936 | |
| 6937 | // We're at the end of the line for C: it's either a write-back conversion |
| 6938 | // or it's a C assignment. There's no need to check anything else. |
| 6939 | if (!S.getLangOpts().CPlusPlus) { |
| 6940 | assert(Initializer && "Initializer must be non-null" ); |
| 6941 | // If allowed, check whether this is an Objective-C writeback conversion. |
| 6942 | if (allowObjCWritebackConversion && |
| 6943 | tryObjCWritebackConversion(S, Sequence&: *this, Entity, Initializer)) { |
| 6944 | return; |
| 6945 | } |
| 6946 | |
| 6947 | if (TryOCLZeroOpaqueTypeInitialization(S, Sequence&: *this, DestType, Initializer)) |
| 6948 | return; |
| 6949 | |
| 6950 | // Handle initialization in C |
| 6951 | AddCAssignmentStep(T: DestType); |
| 6952 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
| 6953 | return; |
| 6954 | } |
| 6955 | |
| 6956 | assert(S.getLangOpts().CPlusPlus); |
| 6957 | |
| 6958 | // - If the destination type is a (possibly cv-qualified) class type: |
| 6959 | // (except for HLSL, where user-defined record types do not have |
| 6960 | // constructors or conversion functions) |
| 6961 | if (DestType->isRecordType() && |
| 6962 | (!S.getLangOpts().HLSL || |
| 6963 | DestType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) { |
| 6964 | // - If the initialization is direct-initialization, or if it is |
| 6965 | // copy-initialization where the cv-unqualified version of the |
| 6966 | // source type is the same class as, or a derived class of, the |
| 6967 | // class of the destination, constructors are considered. [...] |
| 6968 | if (Kind.getKind() == InitializationKind::IK_Direct || |
| 6969 | (Kind.getKind() == InitializationKind::IK_Copy && |
| 6970 | (Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType) || |
| 6971 | (Initializer && S.IsDerivedFrom(Loc: Initializer->getBeginLoc(), |
| 6972 | Derived: SourceType, Base: DestType))))) { |
| 6973 | TryConstructorOrParenListInitialization(S, Entity, Kind, Args, DestType, |
| 6974 | Sequence&: *this, /*IsAggrListInit=*/false); |
| 6975 | } else { |
| 6976 | // - Otherwise (i.e., for the remaining copy-initialization cases), |
| 6977 | // user-defined conversion sequences that can convert from the |
| 6978 | // source type to the destination type or (when a conversion |
| 6979 | // function is used) to a derived class thereof are enumerated as |
| 6980 | // described in 13.3.1.4, and the best one is chosen through |
| 6981 | // overload resolution (13.3). |
| 6982 | assert(Initializer && "Initializer must be non-null" ); |
| 6983 | TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this, |
| 6984 | TopLevelOfInitList); |
| 6985 | } |
| 6986 | return; |
| 6987 | } |
| 6988 | |
| 6989 | assert(Args.size() >= 1 && "Zero-argument case handled above" ); |
| 6990 | |
| 6991 | // For HLSL ext vector types we allow list initialization behavior for C++ |
| 6992 | // functional cast expressions which look like constructor syntax. This is |
| 6993 | // accomplished by converting initialization arguments to InitListExpr. |
| 6994 | auto ShouldTryListInitialization = [&]() -> bool { |
| 6995 | // Only try list initialization for HLSL. |
| 6996 | if (!S.getLangOpts().HLSL) |
| 6997 | return false; |
| 6998 | |
| 6999 | bool DestIsVec = DestType->isExtVectorType(); |
| 7000 | bool DestIsMat = DestType->isConstantMatrixType(); |
| 7001 | |
| 7002 | // If the destination type is neither a vector nor a matrix, then don't try |
| 7003 | // list initialization. |
| 7004 | if (!DestIsVec && !DestIsMat) |
| 7005 | return false; |
| 7006 | |
| 7007 | // If there is only a single source argument, then only try list |
| 7008 | // initialization if initializing a matrix with a vector or vice versa. |
| 7009 | if (Args.size() == 1) { |
| 7010 | assert(!SourceType.isNull() && |
| 7011 | "Source QualType should not be null when arg size is exactly 1" ); |
| 7012 | bool SourceIsVec = SourceType->isExtVectorType(); |
| 7013 | bool SourceIsMat = SourceType->isConstantMatrixType(); |
| 7014 | |
| 7015 | if (DestIsMat && !SourceIsVec) |
| 7016 | return false; |
| 7017 | if (DestIsVec && !SourceIsMat) |
| 7018 | return false; |
| 7019 | } |
| 7020 | |
| 7021 | // Try list initialization if the source type is null or if the |
| 7022 | // destination and source types differ. |
| 7023 | return SourceType.isNull() || |
| 7024 | !Context.hasSameUnqualifiedType(T1: SourceType, T2: DestType); |
| 7025 | }; |
| 7026 | if (ShouldTryListInitialization()) { |
| 7027 | InitListExpr *ILE = new (Context) |
| 7028 | InitListExpr(S.getASTContext(), Args.front()->getBeginLoc(), Args, |
| 7029 | Args.back()->getEndLoc(), /*isExplicit=*/false); |
| 7030 | ILE->setType(DestType); |
| 7031 | Args[0] = ILE; |
| 7032 | TryListInitialization(S, Entity, Kind, InitList: ILE, Sequence&: *this, |
| 7033 | TreatUnavailableAsInvalid); |
| 7034 | return; |
| 7035 | } |
| 7036 | |
| 7037 | // The remaining cases all need a source type. |
| 7038 | if (Args.size() > 1) { |
| 7039 | SetFailed(FK_TooManyInitsForScalar); |
| 7040 | return; |
| 7041 | } else if (isa<InitListExpr>(Val: Args[0])) { |
| 7042 | SetFailed(FK_ParenthesizedListInitForScalar); |
| 7043 | return; |
| 7044 | } |
| 7045 | |
| 7046 | // - Otherwise, if the source type is a (possibly cv-qualified) class |
| 7047 | // type, conversion functions are considered. |
| 7048 | // (except for HLSL, where user-defined record types do not have |
| 7049 | // constructors or conversion functions). |
| 7050 | if (!SourceType.isNull() && SourceType->isRecordType() && |
| 7051 | (!S.getLangOpts().HLSL || |
| 7052 | SourceType->getAsCXXRecordDecl()->isHLSLBuiltinRecord())) { |
| 7053 | assert(Initializer && "Initializer must be non-null" ); |
| 7054 | // For a conversion to _Atomic(T) from either T or a class type derived |
| 7055 | // from T, initialize the T object then convert to _Atomic type. |
| 7056 | bool NeedAtomicConversion = false; |
| 7057 | if (const AtomicType *Atomic = DestType->getAs<AtomicType>()) { |
| 7058 | if (Context.hasSameUnqualifiedType(T1: SourceType, T2: Atomic->getValueType()) || |
| 7059 | S.IsDerivedFrom(Loc: Initializer->getBeginLoc(), Derived: SourceType, |
| 7060 | Base: Atomic->getValueType())) { |
| 7061 | DestType = Atomic->getValueType(); |
| 7062 | NeedAtomicConversion = true; |
| 7063 | } |
| 7064 | } |
| 7065 | |
| 7066 | TryUserDefinedConversion(S, DestType, Kind, Initializer, Sequence&: *this, |
| 7067 | TopLevelOfInitList); |
| 7068 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
| 7069 | if (!Failed() && NeedAtomicConversion) |
| 7070 | AddAtomicConversionStep(Ty: Entity.getType()); |
| 7071 | return; |
| 7072 | } |
| 7073 | |
| 7074 | // - Otherwise, if the initialization is direct-initialization, the source |
| 7075 | // type is std::nullptr_t, and the destination type is bool, the initial |
| 7076 | // value of the object being initialized is false. |
| 7077 | if (!SourceType.isNull() && SourceType->isNullPtrType() && |
| 7078 | DestType->isBooleanType() && |
| 7079 | Kind.getKind() == InitializationKind::IK_Direct) { |
| 7080 | AddConversionSequenceStep( |
| 7081 | ICS: ImplicitConversionSequence::getNullptrToBool(SourceType, DestType, |
| 7082 | NeedLValToRVal: Initializer->isGLValue()), |
| 7083 | T: DestType); |
| 7084 | return; |
| 7085 | } |
| 7086 | |
| 7087 | // - Otherwise, the initial value of the object being initialized is the |
| 7088 | // (possibly converted) value of the initializer expression. Standard |
| 7089 | // conversions (Clause 4) will be used, if necessary, to convert the |
| 7090 | // initializer expression to the cv-unqualified version of the |
| 7091 | // destination type; no user-defined conversions are considered. |
| 7092 | |
| 7093 | ImplicitConversionSequence ICS |
| 7094 | = S.TryImplicitConversion(From: Initializer, ToType: DestType, |
| 7095 | /*SuppressUserConversions*/true, |
| 7096 | AllowExplicit: Sema::AllowedExplicit::None, |
| 7097 | /*InOverloadResolution*/ false, |
| 7098 | /*CStyle=*/Kind.isCStyleOrFunctionalCast(), |
| 7099 | AllowObjCWritebackConversion: allowObjCWritebackConversion); |
| 7100 | |
| 7101 | if (ICS.isStandard() && |
| 7102 | ICS.Standard.Second == ICK_Writeback_Conversion) { |
| 7103 | // Objective-C ARC writeback conversion. |
| 7104 | |
| 7105 | // We should copy unless we're passing to an argument explicitly |
| 7106 | // marked 'out'. |
| 7107 | bool ShouldCopy = true; |
| 7108 | if (ParmVarDecl *Param = cast_or_null<ParmVarDecl>(Val: Entity.getDecl())) |
| 7109 | ShouldCopy = (Param->getObjCDeclQualifier() != ParmVarDecl::OBJC_TQ_Out); |
| 7110 | |
| 7111 | // If there was an lvalue adjustment, add it as a separate conversion. |
| 7112 | if (ICS.Standard.First == ICK_Array_To_Pointer || |
| 7113 | ICS.Standard.First == ICK_Lvalue_To_Rvalue) { |
| 7114 | ImplicitConversionSequence LvalueICS; |
| 7115 | LvalueICS.setStandard(); |
| 7116 | LvalueICS.Standard.setAsIdentityConversion(); |
| 7117 | LvalueICS.Standard.setAllToTypes(ICS.Standard.getToType(Idx: 0)); |
| 7118 | LvalueICS.Standard.First = ICS.Standard.First; |
| 7119 | AddConversionSequenceStep(ICS: LvalueICS, T: ICS.Standard.getToType(Idx: 0)); |
| 7120 | } |
| 7121 | |
| 7122 | AddPassByIndirectCopyRestoreStep(type: DestType, shouldCopy: ShouldCopy); |
| 7123 | } else if (ICS.isBad()) { |
| 7124 | if (DeclAccessPair Found; |
| 7125 | Initializer->getType() == Context.OverloadTy && |
| 7126 | !S.ResolveAddressOfOverloadedFunction(AddressOfExpr: Initializer, TargetType: DestType, |
| 7127 | /*Complain=*/false, Found)) |
| 7128 | SetFailed(InitializationSequence::FK_AddressOfOverloadFailed); |
| 7129 | else if (Initializer->getType()->isFunctionType() && |
| 7130 | isExprAnUnaddressableFunction(S, E: Initializer)) |
| 7131 | SetFailed(InitializationSequence::FK_AddressOfUnaddressableFunction); |
| 7132 | else |
| 7133 | SetFailed(InitializationSequence::FK_ConversionFailed); |
| 7134 | } else { |
| 7135 | AddConversionSequenceStep(ICS, T: DestType, TopLevelOfInitList); |
| 7136 | |
| 7137 | MaybeProduceObjCObject(S, Sequence&: *this, Entity); |
| 7138 | } |
| 7139 | } |
| 7140 | |
| 7141 | InitializationSequence::~InitializationSequence() { |
| 7142 | for (auto &S : Steps) |
| 7143 | S.Destroy(); |
| 7144 | } |
| 7145 | |
| 7146 | //===----------------------------------------------------------------------===// |
| 7147 | // Perform initialization |
| 7148 | //===----------------------------------------------------------------------===// |
| 7149 | static AssignmentAction getAssignmentAction(const InitializedEntity &Entity, |
| 7150 | bool Diagnose = false) { |
| 7151 | switch(Entity.getKind()) { |
| 7152 | case InitializedEntity::EK_Variable: |
| 7153 | case InitializedEntity::EK_New: |
| 7154 | case InitializedEntity::EK_Exception: |
| 7155 | case InitializedEntity::EK_Base: |
| 7156 | case InitializedEntity::EK_Delegating: |
| 7157 | return AssignmentAction::Initializing; |
| 7158 | |
| 7159 | case InitializedEntity::EK_Parameter: |
| 7160 | if (Entity.getDecl() && |
| 7161 | isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext())) |
| 7162 | return AssignmentAction::Sending; |
| 7163 | |
| 7164 | return AssignmentAction::Passing; |
| 7165 | |
| 7166 | case InitializedEntity::EK_Parameter_CF_Audited: |
| 7167 | if (Entity.getDecl() && |
| 7168 | isa<ObjCMethodDecl>(Val: Entity.getDecl()->getDeclContext())) |
| 7169 | return AssignmentAction::Sending; |
| 7170 | |
| 7171 | return !Diagnose ? AssignmentAction::Passing |
| 7172 | : AssignmentAction::Passing_CFAudited; |
| 7173 | |
| 7174 | case InitializedEntity::EK_Result: |
| 7175 | case InitializedEntity::EK_StmtExprResult: // FIXME: Not quite right. |
| 7176 | return AssignmentAction::Returning; |
| 7177 | |
| 7178 | case InitializedEntity::EK_Temporary: |
| 7179 | case InitializedEntity::EK_RelatedResult: |
| 7180 | // FIXME: Can we tell apart casting vs. converting? |
| 7181 | return AssignmentAction::Casting; |
| 7182 | |
| 7183 | case InitializedEntity::EK_TemplateParameter: |
| 7184 | // This is really initialization, but refer to it as conversion for |
| 7185 | // consistency with CheckConvertedConstantExpression. |
| 7186 | return AssignmentAction::Converting; |
| 7187 | |
| 7188 | case InitializedEntity::EK_Member: |
| 7189 | case InitializedEntity::EK_ParenAggInitMember: |
| 7190 | case InitializedEntity::EK_Binding: |
| 7191 | case InitializedEntity::EK_ArrayElement: |
| 7192 | case InitializedEntity::EK_VectorElement: |
| 7193 | case InitializedEntity::EK_MatrixElement: |
| 7194 | case InitializedEntity::EK_ComplexElement: |
| 7195 | case InitializedEntity::EK_BlockElement: |
| 7196 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
| 7197 | case InitializedEntity::EK_LambdaCapture: |
| 7198 | case InitializedEntity::EK_CompoundLiteralInit: |
| 7199 | return AssignmentAction::Initializing; |
| 7200 | } |
| 7201 | |
| 7202 | llvm_unreachable("Invalid EntityKind!" ); |
| 7203 | } |
| 7204 | |
| 7205 | /// Whether we should bind a created object as a temporary when |
| 7206 | /// initializing the given entity. |
| 7207 | static bool shouldBindAsTemporary(const InitializedEntity &Entity) { |
| 7208 | switch (Entity.getKind()) { |
| 7209 | case InitializedEntity::EK_ArrayElement: |
| 7210 | case InitializedEntity::EK_Member: |
| 7211 | case InitializedEntity::EK_ParenAggInitMember: |
| 7212 | case InitializedEntity::EK_Result: |
| 7213 | case InitializedEntity::EK_StmtExprResult: |
| 7214 | case InitializedEntity::EK_New: |
| 7215 | case InitializedEntity::EK_Variable: |
| 7216 | case InitializedEntity::EK_Base: |
| 7217 | case InitializedEntity::EK_Delegating: |
| 7218 | case InitializedEntity::EK_VectorElement: |
| 7219 | case InitializedEntity::EK_MatrixElement: |
| 7220 | case InitializedEntity::EK_ComplexElement: |
| 7221 | case InitializedEntity::EK_Exception: |
| 7222 | case InitializedEntity::EK_BlockElement: |
| 7223 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
| 7224 | case InitializedEntity::EK_LambdaCapture: |
| 7225 | case InitializedEntity::EK_CompoundLiteralInit: |
| 7226 | case InitializedEntity::EK_TemplateParameter: |
| 7227 | return false; |
| 7228 | |
| 7229 | case InitializedEntity::EK_Parameter: |
| 7230 | case InitializedEntity::EK_Parameter_CF_Audited: |
| 7231 | case InitializedEntity::EK_Temporary: |
| 7232 | case InitializedEntity::EK_RelatedResult: |
| 7233 | case InitializedEntity::EK_Binding: |
| 7234 | return true; |
| 7235 | } |
| 7236 | |
| 7237 | llvm_unreachable("missed an InitializedEntity kind?" ); |
| 7238 | } |
| 7239 | |
| 7240 | /// Whether the given entity, when initialized with an object |
| 7241 | /// created for that initialization, requires destruction. |
| 7242 | static bool shouldDestroyEntity(const InitializedEntity &Entity) { |
| 7243 | switch (Entity.getKind()) { |
| 7244 | case InitializedEntity::EK_Result: |
| 7245 | case InitializedEntity::EK_StmtExprResult: |
| 7246 | case InitializedEntity::EK_New: |
| 7247 | case InitializedEntity::EK_Base: |
| 7248 | case InitializedEntity::EK_Delegating: |
| 7249 | case InitializedEntity::EK_VectorElement: |
| 7250 | case InitializedEntity::EK_MatrixElement: |
| 7251 | case InitializedEntity::EK_ComplexElement: |
| 7252 | case InitializedEntity::EK_BlockElement: |
| 7253 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
| 7254 | case InitializedEntity::EK_LambdaCapture: |
| 7255 | return false; |
| 7256 | |
| 7257 | case InitializedEntity::EK_Member: |
| 7258 | case InitializedEntity::EK_ParenAggInitMember: |
| 7259 | case InitializedEntity::EK_Binding: |
| 7260 | case InitializedEntity::EK_Variable: |
| 7261 | case InitializedEntity::EK_Parameter: |
| 7262 | case InitializedEntity::EK_Parameter_CF_Audited: |
| 7263 | case InitializedEntity::EK_TemplateParameter: |
| 7264 | case InitializedEntity::EK_Temporary: |
| 7265 | case InitializedEntity::EK_ArrayElement: |
| 7266 | case InitializedEntity::EK_Exception: |
| 7267 | case InitializedEntity::EK_CompoundLiteralInit: |
| 7268 | case InitializedEntity::EK_RelatedResult: |
| 7269 | return true; |
| 7270 | } |
| 7271 | |
| 7272 | llvm_unreachable("missed an InitializedEntity kind?" ); |
| 7273 | } |
| 7274 | |
| 7275 | /// Get the location at which initialization diagnostics should appear. |
| 7276 | static SourceLocation getInitializationLoc(const InitializedEntity &Entity, |
| 7277 | Expr *Initializer) { |
| 7278 | switch (Entity.getKind()) { |
| 7279 | case InitializedEntity::EK_Result: |
| 7280 | case InitializedEntity::EK_StmtExprResult: |
| 7281 | return Entity.getReturnLoc(); |
| 7282 | |
| 7283 | case InitializedEntity::EK_Exception: |
| 7284 | return Entity.getThrowLoc(); |
| 7285 | |
| 7286 | case InitializedEntity::EK_Variable: |
| 7287 | case InitializedEntity::EK_Binding: |
| 7288 | return Entity.getDecl()->getLocation(); |
| 7289 | |
| 7290 | case InitializedEntity::EK_LambdaCapture: |
| 7291 | return Entity.getCaptureLoc(); |
| 7292 | |
| 7293 | case InitializedEntity::EK_ArrayElement: |
| 7294 | case InitializedEntity::EK_Member: |
| 7295 | case InitializedEntity::EK_ParenAggInitMember: |
| 7296 | case InitializedEntity::EK_Parameter: |
| 7297 | case InitializedEntity::EK_Parameter_CF_Audited: |
| 7298 | case InitializedEntity::EK_TemplateParameter: |
| 7299 | case InitializedEntity::EK_Temporary: |
| 7300 | case InitializedEntity::EK_New: |
| 7301 | case InitializedEntity::EK_Base: |
| 7302 | case InitializedEntity::EK_Delegating: |
| 7303 | case InitializedEntity::EK_VectorElement: |
| 7304 | case InitializedEntity::EK_MatrixElement: |
| 7305 | case InitializedEntity::EK_ComplexElement: |
| 7306 | case InitializedEntity::EK_BlockElement: |
| 7307 | case InitializedEntity::EK_LambdaToBlockConversionBlockElement: |
| 7308 | case InitializedEntity::EK_CompoundLiteralInit: |
| 7309 | case InitializedEntity::EK_RelatedResult: |
| 7310 | return Initializer->getBeginLoc(); |
| 7311 | } |
| 7312 | llvm_unreachable("missed an InitializedEntity kind?" ); |
| 7313 | } |
| 7314 | |
| 7315 | /// Make a (potentially elidable) temporary copy of the object |
| 7316 | /// provided by the given initializer by calling the appropriate copy |
| 7317 | /// constructor. |
| 7318 | /// |
| 7319 | /// \param S The Sema object used for type-checking. |
| 7320 | /// |
| 7321 | /// \param T The type of the temporary object, which must either be |
| 7322 | /// the type of the initializer expression or a superclass thereof. |
| 7323 | /// |
| 7324 | /// \param Entity The entity being initialized. |
| 7325 | /// |
| 7326 | /// \param CurInit The initializer expression. |
| 7327 | /// |
| 7328 | /// \param IsExtraneousCopy Whether this is an "extraneous" copy that |
| 7329 | /// is permitted in C++03 (but not C++0x) when binding a reference to |
| 7330 | /// an rvalue. |
| 7331 | /// |
| 7332 | /// \returns An expression that copies the initializer expression into |
| 7333 | /// a temporary object, or an error expression if a copy could not be |
| 7334 | /// created. |
| 7335 | static ExprResult CopyObject(Sema &S, |
| 7336 | QualType T, |
| 7337 | const InitializedEntity &Entity, |
| 7338 | ExprResult CurInit, |
| 7339 | bool ) { |
| 7340 | if (CurInit.isInvalid()) |
| 7341 | return CurInit; |
| 7342 | // Determine which class type we're copying to. |
| 7343 | Expr *CurInitExpr = (Expr *)CurInit.get(); |
| 7344 | auto *Class = T->getAsCXXRecordDecl(); |
| 7345 | if (!Class) |
| 7346 | return CurInit; |
| 7347 | |
| 7348 | SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInit.get()); |
| 7349 | |
| 7350 | // Make sure that the type we are copying is complete. |
| 7351 | if (S.RequireCompleteType(Loc, T, DiagID: diag::err_temp_copy_incomplete)) |
| 7352 | return CurInit; |
| 7353 | |
| 7354 | // Perform overload resolution using the class's constructors. Per |
| 7355 | // C++11 [dcl.init]p16, second bullet for class types, this initialization |
| 7356 | // is direct-initialization. |
| 7357 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
| 7358 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class); |
| 7359 | |
| 7360 | OverloadCandidateSet::iterator Best; |
| 7361 | switch (ResolveConstructorOverload( |
| 7362 | S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: T, Ctors, Best, |
| 7363 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, |
| 7364 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, |
| 7365 | /*RequireActualConstructor=*/false, |
| 7366 | /*SecondStepOfCopyInit=*/true)) { |
| 7367 | case OR_Success: |
| 7368 | break; |
| 7369 | |
| 7370 | case OR_No_Viable_Function: |
| 7371 | CandidateSet.NoteCandidates( |
| 7372 | PA: PartialDiagnosticAt( |
| 7373 | Loc, S.PDiag(DiagID: IsExtraneousCopy && !S.isSFINAEContext() |
| 7374 | ? diag::ext_rvalue_to_reference_temp_copy_no_viable |
| 7375 | : diag::err_temp_copy_no_viable) |
| 7376 | << (int)Entity.getKind() << CurInitExpr->getType() |
| 7377 | << CurInitExpr->getSourceRange()), |
| 7378 | S, OCD: OCD_AllCandidates, Args: CurInitExpr); |
| 7379 | if (!IsExtraneousCopy || S.isSFINAEContext()) |
| 7380 | return ExprError(); |
| 7381 | return CurInit; |
| 7382 | |
| 7383 | case OR_Ambiguous: |
| 7384 | CandidateSet.NoteCandidates( |
| 7385 | PA: PartialDiagnosticAt(Loc, S.PDiag(DiagID: diag::err_temp_copy_ambiguous) |
| 7386 | << (int)Entity.getKind() |
| 7387 | << CurInitExpr->getType() |
| 7388 | << CurInitExpr->getSourceRange()), |
| 7389 | S, OCD: OCD_AmbiguousCandidates, Args: CurInitExpr); |
| 7390 | return ExprError(); |
| 7391 | |
| 7392 | case OR_Deleted: |
| 7393 | S.Diag(Loc, DiagID: diag::err_temp_copy_deleted) |
| 7394 | << (int)Entity.getKind() << CurInitExpr->getType() |
| 7395 | << CurInitExpr->getSourceRange(); |
| 7396 | S.NoteDeletedFunction(FD: Best->Function); |
| 7397 | return ExprError(); |
| 7398 | } |
| 7399 | |
| 7400 | bool HadMultipleCandidates = CandidateSet.size() > 1; |
| 7401 | |
| 7402 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: Best->Function); |
| 7403 | SmallVector<Expr*, 8> ConstructorArgs; |
| 7404 | CurInit.get(); // Ownership transferred into MultiExprArg, below. |
| 7405 | |
| 7406 | S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Best->FoundDecl, Entity, |
| 7407 | IsCopyBindingRefToTemp: IsExtraneousCopy); |
| 7408 | |
| 7409 | if (IsExtraneousCopy) { |
| 7410 | // If this is a totally extraneous copy for C++03 reference |
| 7411 | // binding purposes, just return the original initialization |
| 7412 | // expression. We don't generate an (elided) copy operation here |
| 7413 | // because doing so would require us to pass down a flag to avoid |
| 7414 | // infinite recursion, where each step adds another extraneous, |
| 7415 | // elidable copy. |
| 7416 | |
| 7417 | // Instantiate the default arguments of any extra parameters in |
| 7418 | // the selected copy constructor, as if we were going to create a |
| 7419 | // proper call to the copy constructor. |
| 7420 | for (unsigned I = 1, N = Constructor->getNumParams(); I != N; ++I) { |
| 7421 | ParmVarDecl *Parm = Constructor->getParamDecl(i: I); |
| 7422 | if (S.RequireCompleteType(Loc, T: Parm->getType(), |
| 7423 | DiagID: diag::err_call_incomplete_argument)) |
| 7424 | break; |
| 7425 | |
| 7426 | // Build the default argument expression; we don't actually care |
| 7427 | // if this succeeds or not, because this routine will complain |
| 7428 | // if there was a problem. |
| 7429 | S.BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Constructor, Param: Parm); |
| 7430 | } |
| 7431 | |
| 7432 | return CurInitExpr; |
| 7433 | } |
| 7434 | |
| 7435 | // Determine the arguments required to actually perform the |
| 7436 | // constructor call (we might have derived-to-base conversions, or |
| 7437 | // the copy constructor may have default arguments). |
| 7438 | if (S.CompleteConstructorCall(Constructor, DeclInitType: T, ArgsPtr: CurInitExpr, Loc, |
| 7439 | ConvertedArgs&: ConstructorArgs)) |
| 7440 | return ExprError(); |
| 7441 | |
| 7442 | // C++0x [class.copy]p32: |
| 7443 | // When certain criteria are met, an implementation is allowed to |
| 7444 | // omit the copy/move construction of a class object, even if the |
| 7445 | // copy/move constructor and/or destructor for the object have |
| 7446 | // side effects. [...] |
| 7447 | // - when a temporary class object that has not been bound to a |
| 7448 | // reference (12.2) would be copied/moved to a class object |
| 7449 | // with the same cv-unqualified type, the copy/move operation |
| 7450 | // can be omitted by constructing the temporary object |
| 7451 | // directly into the target of the omitted copy/move |
| 7452 | // |
| 7453 | // Note that the other three bullets are handled elsewhere. Copy |
| 7454 | // elision for return statements and throw expressions are handled as part |
| 7455 | // of constructor initialization, while copy elision for exception handlers |
| 7456 | // is handled by the run-time. |
| 7457 | // |
| 7458 | // FIXME: If the function parameter is not the same type as the temporary, we |
| 7459 | // should still be able to elide the copy, but we don't have a way to |
| 7460 | // represent in the AST how much should be elided in this case. |
| 7461 | bool Elidable = |
| 7462 | CurInitExpr->isTemporaryObject(Ctx&: S.Context, TempTy: Class) && |
| 7463 | S.Context.hasSameUnqualifiedType( |
| 7464 | T1: Best->Function->getParamDecl(i: 0)->getType().getNonReferenceType(), |
| 7465 | T2: CurInitExpr->getType()); |
| 7466 | |
| 7467 | // Actually perform the constructor call. |
| 7468 | CurInit = S.BuildCXXConstructExpr( |
| 7469 | ConstructLoc: Loc, DeclInitType: T, FoundDecl: Best->FoundDecl, Constructor, Elidable, Exprs: ConstructorArgs, |
| 7470 | HadMultipleCandidates, |
| 7471 | /*ListInit*/ IsListInitialization: false, |
| 7472 | /*StdInitListInit*/ IsStdInitListInitialization: false, |
| 7473 | /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
| 7474 | |
| 7475 | // If we're supposed to bind temporaries, do so. |
| 7476 | if (!CurInit.isInvalid() && shouldBindAsTemporary(Entity)) |
| 7477 | CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>()); |
| 7478 | return CurInit; |
| 7479 | } |
| 7480 | |
| 7481 | /// Check whether elidable copy construction for binding a reference to |
| 7482 | /// a temporary would have succeeded if we were building in C++98 mode, for |
| 7483 | /// -Wc++98-compat. |
| 7484 | static void CheckCXX98CompatAccessibleCopy(Sema &S, |
| 7485 | const InitializedEntity &Entity, |
| 7486 | Expr *CurInitExpr) { |
| 7487 | assert(S.getLangOpts().CPlusPlus11); |
| 7488 | |
| 7489 | auto *Record = CurInitExpr->getType()->getAsCXXRecordDecl(); |
| 7490 | if (!Record) |
| 7491 | return; |
| 7492 | |
| 7493 | SourceLocation Loc = getInitializationLoc(Entity, Initializer: CurInitExpr); |
| 7494 | if (S.Diags.isIgnored(DiagID: diag::warn_cxx98_compat_temp_copy, Loc)) |
| 7495 | return; |
| 7496 | |
| 7497 | // Find constructors which would have been considered. |
| 7498 | OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); |
| 7499 | DeclContext::lookup_result Ctors = S.LookupConstructors(Class: Record); |
| 7500 | |
| 7501 | // Perform overload resolution. |
| 7502 | OverloadCandidateSet::iterator Best; |
| 7503 | OverloadingResult OR = ResolveConstructorOverload( |
| 7504 | S, DeclLoc: Loc, Args: CurInitExpr, CandidateSet, DestType: CurInitExpr->getType(), Ctors, Best, |
| 7505 | /*CopyInitializing=*/false, /*AllowExplicit=*/true, |
| 7506 | /*OnlyListConstructors=*/false, /*IsListInit=*/false, |
| 7507 | /*RequireActualConstructor=*/false, |
| 7508 | /*SecondStepOfCopyInit=*/true); |
| 7509 | |
| 7510 | PartialDiagnostic Diag = S.PDiag(DiagID: diag::warn_cxx98_compat_temp_copy) |
| 7511 | << OR << (int)Entity.getKind() << CurInitExpr->getType() |
| 7512 | << CurInitExpr->getSourceRange(); |
| 7513 | |
| 7514 | switch (OR) { |
| 7515 | case OR_Success: |
| 7516 | S.CheckConstructorAccess(Loc, D: cast<CXXConstructorDecl>(Val: Best->Function), |
| 7517 | FoundDecl: Best->FoundDecl, Entity, PDiag: Diag); |
| 7518 | // FIXME: Check default arguments as far as that's possible. |
| 7519 | break; |
| 7520 | |
| 7521 | case OR_No_Viable_Function: |
| 7522 | CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, |
| 7523 | OCD: OCD_AllCandidates, Args: CurInitExpr); |
| 7524 | break; |
| 7525 | |
| 7526 | case OR_Ambiguous: |
| 7527 | CandidateSet.NoteCandidates(PA: PartialDiagnosticAt(Loc, Diag), S, |
| 7528 | OCD: OCD_AmbiguousCandidates, Args: CurInitExpr); |
| 7529 | break; |
| 7530 | |
| 7531 | case OR_Deleted: |
| 7532 | S.Diag(Loc, PD: Diag); |
| 7533 | S.NoteDeletedFunction(FD: Best->Function); |
| 7534 | break; |
| 7535 | } |
| 7536 | } |
| 7537 | |
| 7538 | void InitializationSequence::PrintInitLocationNote(Sema &S, |
| 7539 | const InitializedEntity &Entity) { |
| 7540 | if (Entity.isParamOrTemplateParamKind() && Entity.getDecl()) { |
| 7541 | if (Entity.getDecl()->getLocation().isInvalid()) |
| 7542 | return; |
| 7543 | |
| 7544 | if (Entity.getDecl()->getDeclName()) |
| 7545 | S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_named_here) |
| 7546 | << Entity.getDecl()->getDeclName(); |
| 7547 | else |
| 7548 | S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_parameter_here); |
| 7549 | } |
| 7550 | else if (Entity.getKind() == InitializedEntity::EK_RelatedResult && |
| 7551 | Entity.getMethodDecl()) |
| 7552 | S.Diag(Loc: Entity.getMethodDecl()->getLocation(), |
| 7553 | DiagID: diag::note_method_return_type_change) |
| 7554 | << Entity.getMethodDecl()->getDeclName(); |
| 7555 | } |
| 7556 | |
| 7557 | /// Returns true if the parameters describe a constructor initialization of |
| 7558 | /// an explicit temporary object, e.g. "Point(x, y)". |
| 7559 | static bool isExplicitTemporary(const InitializedEntity &Entity, |
| 7560 | const InitializationKind &Kind, |
| 7561 | unsigned NumArgs) { |
| 7562 | switch (Entity.getKind()) { |
| 7563 | case InitializedEntity::EK_Temporary: |
| 7564 | case InitializedEntity::EK_CompoundLiteralInit: |
| 7565 | case InitializedEntity::EK_RelatedResult: |
| 7566 | break; |
| 7567 | default: |
| 7568 | return false; |
| 7569 | } |
| 7570 | |
| 7571 | switch (Kind.getKind()) { |
| 7572 | case InitializationKind::IK_DirectList: |
| 7573 | return true; |
| 7574 | // FIXME: Hack to work around cast weirdness. |
| 7575 | case InitializationKind::IK_Direct: |
| 7576 | case InitializationKind::IK_Value: |
| 7577 | return NumArgs != 1; |
| 7578 | default: |
| 7579 | return false; |
| 7580 | } |
| 7581 | } |
| 7582 | |
| 7583 | static ExprResult |
| 7584 | PerformConstructorInitialization(Sema &S, |
| 7585 | const InitializedEntity &Entity, |
| 7586 | const InitializationKind &Kind, |
| 7587 | MultiExprArg Args, |
| 7588 | const InitializationSequence::Step& Step, |
| 7589 | bool &ConstructorInitRequiresZeroInit, |
| 7590 | bool IsListInitialization, |
| 7591 | bool IsStdInitListInitialization, |
| 7592 | SourceLocation LBraceLoc, |
| 7593 | SourceLocation RBraceLoc) { |
| 7594 | unsigned NumArgs = Args.size(); |
| 7595 | CXXConstructorDecl *Constructor |
| 7596 | = cast<CXXConstructorDecl>(Val: Step.Function.Function); |
| 7597 | bool HadMultipleCandidates = Step.Function.HadMultipleCandidates; |
| 7598 | |
| 7599 | // Build a call to the selected constructor. |
| 7600 | SmallVector<Expr*, 8> ConstructorArgs; |
| 7601 | SourceLocation Loc = (Kind.isCopyInit() && Kind.getEqualLoc().isValid()) |
| 7602 | ? Kind.getEqualLoc() |
| 7603 | : Kind.getLocation(); |
| 7604 | |
| 7605 | if (Kind.getKind() == InitializationKind::IK_Default) { |
| 7606 | // Force even a trivial, implicit default constructor to be |
| 7607 | // semantically checked. We do this explicitly because we don't build |
| 7608 | // the definition for completely trivial constructors. |
| 7609 | assert(Constructor->getParent() && "No parent class for constructor." ); |
| 7610 | if (Constructor->isDefaulted() && Constructor->isDefaultConstructor() && |
| 7611 | Constructor->isTrivial() && !Constructor->isUsed(CheckUsedAttr: false)) { |
| 7612 | S.runWithSufficientStackSpace(Loc, Fn: [&] { |
| 7613 | S.DefineImplicitDefaultConstructor(CurrentLocation: Loc, Constructor); |
| 7614 | }); |
| 7615 | } |
| 7616 | } |
| 7617 | |
| 7618 | ExprResult CurInit((Expr *)nullptr); |
| 7619 | |
| 7620 | // C++ [over.match.copy]p1: |
| 7621 | // - When initializing a temporary to be bound to the first parameter |
| 7622 | // of a constructor that takes a reference to possibly cv-qualified |
| 7623 | // T as its first argument, called with a single argument in the |
| 7624 | // context of direct-initialization, explicit conversion functions |
| 7625 | // are also considered. |
| 7626 | bool AllowExplicitConv = |
| 7627 | Kind.AllowExplicit() && !Kind.isCopyInit() && Args.size() == 1 && |
| 7628 | hasCopyOrMoveCtorParam(Ctx&: S.Context, |
| 7629 | Info: getConstructorInfo(ND: Step.Function.FoundDecl)); |
| 7630 | |
| 7631 | // A smart pointer constructed from a nullable pointer is nullable. |
| 7632 | if (NumArgs == 1 && !Kind.isExplicitCast()) |
| 7633 | S.diagnoseNullableToNonnullConversion( |
| 7634 | DstType: Entity.getType(), SrcType: Args.front()->getType(), Loc: Kind.getLocation()); |
| 7635 | |
| 7636 | // Determine the arguments required to actually perform the constructor |
| 7637 | // call. |
| 7638 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Step.Type, ArgsPtr: Args, Loc, |
| 7639 | ConvertedArgs&: ConstructorArgs, AllowExplicit: AllowExplicitConv, |
| 7640 | IsListInitialization)) |
| 7641 | return ExprError(); |
| 7642 | |
| 7643 | if (isExplicitTemporary(Entity, Kind, NumArgs)) { |
| 7644 | // An explicitly-constructed temporary, e.g., X(1, 2). |
| 7645 | if (S.DiagnoseUseOfDecl(D: Step.Function.FoundDecl, Locs: Loc)) |
| 7646 | return ExprError(); |
| 7647 | |
| 7648 | if (Kind.getKind() == InitializationKind::IK_Value && |
| 7649 | Constructor->isImplicit()) { |
| 7650 | auto *RD = Step.Type.getCanonicalType()->getAsCXXRecordDecl(); |
| 7651 | if (RD && RD->isAggregate() && RD->hasUninitializedExplicitInitFields()) { |
| 7652 | unsigned I = 0; |
| 7653 | for (const FieldDecl *FD : RD->fields()) { |
| 7654 | if (I >= ConstructorArgs.size() && FD->hasAttr<ExplicitInitAttr>() && |
| 7655 | !S.isUnevaluatedContext()) { |
| 7656 | S.Diag(Loc, DiagID: diag::warn_field_requires_explicit_init) |
| 7657 | << /* Var-in-Record */ 0 << FD; |
| 7658 | S.Diag(Loc: FD->getLocation(), DiagID: diag::note_entity_declared_at) << FD; |
| 7659 | } |
| 7660 | ++I; |
| 7661 | } |
| 7662 | } |
| 7663 | } |
| 7664 | |
| 7665 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); |
| 7666 | if (!TSInfo) |
| 7667 | TSInfo = S.Context.getTrivialTypeSourceInfo(T: Entity.getType(), Loc); |
| 7668 | SourceRange ParenOrBraceRange = |
| 7669 | (Kind.getKind() == InitializationKind::IK_DirectList) |
| 7670 | ? SourceRange(LBraceLoc, RBraceLoc) |
| 7671 | : Kind.getParenOrBraceRange(); |
| 7672 | |
| 7673 | CXXConstructorDecl *CalleeDecl = Constructor; |
| 7674 | if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>( |
| 7675 | Val: Step.Function.FoundDecl.getDecl())) { |
| 7676 | CalleeDecl = S.findInheritingConstructor(Loc, BaseCtor: Constructor, DerivedShadow: Shadow); |
| 7677 | } |
| 7678 | S.MarkFunctionReferenced(Loc, Func: CalleeDecl); |
| 7679 | |
| 7680 | CurInit = S.CheckForImmediateInvocation( |
| 7681 | E: CXXTemporaryObjectExpr::Create( |
| 7682 | Ctx: S.Context, Cons: CalleeDecl, |
| 7683 | Ty: Entity.getType().getNonLValueExprType(Context: S.Context), TSI: TSInfo, |
| 7684 | Args: ConstructorArgs, ParenOrBraceRange, HadMultipleCandidates, |
| 7685 | ListInitialization: IsListInitialization, StdInitListInitialization: IsStdInitListInitialization, |
| 7686 | ZeroInitialization: ConstructorInitRequiresZeroInit), |
| 7687 | Decl: CalleeDecl); |
| 7688 | } else { |
| 7689 | CXXConstructionKind ConstructKind = CXXConstructionKind::Complete; |
| 7690 | |
| 7691 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
| 7692 | ConstructKind = Entity.getBaseSpecifier()->isVirtual() |
| 7693 | ? CXXConstructionKind::VirtualBase |
| 7694 | : CXXConstructionKind::NonVirtualBase; |
| 7695 | } else if (Entity.getKind() == InitializedEntity::EK_Delegating) { |
| 7696 | ConstructKind = CXXConstructionKind::Delegating; |
| 7697 | } |
| 7698 | |
| 7699 | // Only get the parenthesis or brace range if it is a list initialization or |
| 7700 | // direct construction. |
| 7701 | SourceRange ParenOrBraceRange; |
| 7702 | if (IsListInitialization) |
| 7703 | ParenOrBraceRange = SourceRange(LBraceLoc, RBraceLoc); |
| 7704 | else if (Kind.getKind() == InitializationKind::IK_Direct) |
| 7705 | ParenOrBraceRange = Kind.getParenOrBraceRange(); |
| 7706 | |
| 7707 | // If the entity allows NRVO, mark the construction as elidable |
| 7708 | // unconditionally. |
| 7709 | if (Entity.allowsNRVO()) |
| 7710 | CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type, |
| 7711 | FoundDecl: Step.Function.FoundDecl, |
| 7712 | Constructor, /*Elidable=*/true, |
| 7713 | Exprs: ConstructorArgs, |
| 7714 | HadMultipleCandidates, |
| 7715 | IsListInitialization, |
| 7716 | IsStdInitListInitialization, |
| 7717 | RequiresZeroInit: ConstructorInitRequiresZeroInit, |
| 7718 | ConstructKind, |
| 7719 | ParenRange: ParenOrBraceRange); |
| 7720 | else |
| 7721 | CurInit = S.BuildCXXConstructExpr(ConstructLoc: Loc, DeclInitType: Step.Type, |
| 7722 | FoundDecl: Step.Function.FoundDecl, |
| 7723 | Constructor, |
| 7724 | Exprs: ConstructorArgs, |
| 7725 | HadMultipleCandidates, |
| 7726 | IsListInitialization, |
| 7727 | IsStdInitListInitialization, |
| 7728 | RequiresZeroInit: ConstructorInitRequiresZeroInit, |
| 7729 | ConstructKind, |
| 7730 | ParenRange: ParenOrBraceRange); |
| 7731 | } |
| 7732 | if (CurInit.isInvalid()) |
| 7733 | return ExprError(); |
| 7734 | |
| 7735 | // Only check access if all of that succeeded. |
| 7736 | S.CheckConstructorAccess(Loc, D: Constructor, FoundDecl: Step.Function.FoundDecl, Entity); |
| 7737 | if (S.DiagnoseUseOfOverloadedDecl(D: Constructor, Loc)) |
| 7738 | return ExprError(); |
| 7739 | |
| 7740 | if (const ArrayType *AT = S.Context.getAsArrayType(T: Entity.getType())) |
| 7741 | if (checkDestructorReference(ElementType: S.Context.getBaseElementType(VAT: AT), Loc, SemaRef&: S)) |
| 7742 | return ExprError(); |
| 7743 | |
| 7744 | if (shouldBindAsTemporary(Entity)) |
| 7745 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
| 7746 | |
| 7747 | return CurInit; |
| 7748 | } |
| 7749 | |
| 7750 | void Sema::checkInitializerLifetime(const InitializedEntity &Entity, |
| 7751 | Expr *Init) { |
| 7752 | return sema::checkInitLifetime(SemaRef&: *this, Entity, Init); |
| 7753 | } |
| 7754 | |
| 7755 | static void DiagnoseNarrowingInInitList(Sema &S, |
| 7756 | const ImplicitConversionSequence &ICS, |
| 7757 | QualType PreNarrowingType, |
| 7758 | QualType EntityType, |
| 7759 | const Expr *PostInit); |
| 7760 | |
| 7761 | static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, |
| 7762 | QualType ToType, Expr *Init); |
| 7763 | |
| 7764 | /// Provide warnings when std::move is used on construction. |
| 7765 | static void CheckMoveOnConstruction(Sema &S, const Expr *InitExpr, |
| 7766 | bool IsReturnStmt) { |
| 7767 | if (!InitExpr) |
| 7768 | return; |
| 7769 | |
| 7770 | if (S.inTemplateInstantiation()) |
| 7771 | return; |
| 7772 | |
| 7773 | QualType DestType = InitExpr->getType(); |
| 7774 | if (!DestType->isRecordType()) |
| 7775 | return; |
| 7776 | |
| 7777 | unsigned DiagID = 0; |
| 7778 | if (IsReturnStmt) { |
| 7779 | const CXXConstructExpr *CCE = |
| 7780 | dyn_cast<CXXConstructExpr>(Val: InitExpr->IgnoreParens()); |
| 7781 | if (!CCE || CCE->getNumArgs() != 1) |
| 7782 | return; |
| 7783 | |
| 7784 | if (!CCE->getConstructor()->isCopyOrMoveConstructor()) |
| 7785 | return; |
| 7786 | |
| 7787 | InitExpr = CCE->getArg(Arg: 0)->IgnoreImpCasts(); |
| 7788 | } |
| 7789 | |
| 7790 | // Find the std::move call and get the argument. |
| 7791 | const CallExpr *CE = dyn_cast<CallExpr>(Val: InitExpr->IgnoreParens()); |
| 7792 | if (!CE || !CE->isCallToStdMove()) |
| 7793 | return; |
| 7794 | |
| 7795 | const Expr *Arg = CE->getArg(Arg: 0)->IgnoreImplicit(); |
| 7796 | |
| 7797 | if (IsReturnStmt) { |
| 7798 | const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Arg->IgnoreParenImpCasts()); |
| 7799 | if (!DRE || DRE->refersToEnclosingVariableOrCapture()) |
| 7800 | return; |
| 7801 | |
| 7802 | const VarDecl *VD = dyn_cast<VarDecl>(Val: DRE->getDecl()); |
| 7803 | if (!VD || !VD->hasLocalStorage()) |
| 7804 | return; |
| 7805 | |
| 7806 | // __block variables are not moved implicitly. |
| 7807 | if (VD->hasAttr<BlocksAttr>()) |
| 7808 | return; |
| 7809 | |
| 7810 | QualType SourceType = VD->getType(); |
| 7811 | if (!SourceType->isRecordType()) |
| 7812 | return; |
| 7813 | |
| 7814 | if (!S.Context.hasSameUnqualifiedType(T1: DestType, T2: SourceType)) { |
| 7815 | return; |
| 7816 | } |
| 7817 | |
| 7818 | // If we're returning a function parameter, copy elision |
| 7819 | // is not possible. |
| 7820 | if (isa<ParmVarDecl>(Val: VD)) |
| 7821 | DiagID = diag::warn_redundant_move_on_return; |
| 7822 | else |
| 7823 | DiagID = diag::warn_pessimizing_move_on_return; |
| 7824 | } else { |
| 7825 | DiagID = diag::warn_pessimizing_move_on_initialization; |
| 7826 | const Expr *ArgStripped = Arg->IgnoreImplicit()->IgnoreParens(); |
| 7827 | if (!ArgStripped->isPRValue() || !ArgStripped->getType()->isRecordType()) |
| 7828 | return; |
| 7829 | } |
| 7830 | |
| 7831 | S.Diag(Loc: CE->getBeginLoc(), DiagID); |
| 7832 | |
| 7833 | // Get all the locations for a fix-it. Don't emit the fix-it if any location |
| 7834 | // is within a macro. |
| 7835 | SourceLocation CallBegin = CE->getCallee()->getBeginLoc(); |
| 7836 | if (CallBegin.isMacroID()) |
| 7837 | return; |
| 7838 | SourceLocation RParen = CE->getRParenLoc(); |
| 7839 | if (RParen.isMacroID()) |
| 7840 | return; |
| 7841 | SourceLocation LParen; |
| 7842 | SourceLocation ArgLoc = Arg->getBeginLoc(); |
| 7843 | |
| 7844 | // Special testing for the argument location. Since the fix-it needs the |
| 7845 | // location right before the argument, the argument location can be in a |
| 7846 | // macro only if it is at the beginning of the macro. |
| 7847 | while (ArgLoc.isMacroID() && |
| 7848 | S.getSourceManager().isAtStartOfImmediateMacroExpansion(Loc: ArgLoc)) { |
| 7849 | ArgLoc = S.getSourceManager().getImmediateExpansionRange(Loc: ArgLoc).getBegin(); |
| 7850 | } |
| 7851 | |
| 7852 | if (LParen.isMacroID()) |
| 7853 | return; |
| 7854 | |
| 7855 | LParen = ArgLoc.getLocWithOffset(Offset: -1); |
| 7856 | |
| 7857 | S.Diag(Loc: CE->getBeginLoc(), DiagID: diag::note_remove_move) |
| 7858 | << FixItHint::CreateRemoval(RemoveRange: SourceRange(CallBegin, LParen)) |
| 7859 | << FixItHint::CreateRemoval(RemoveRange: SourceRange(RParen, RParen)); |
| 7860 | } |
| 7861 | |
| 7862 | static void CheckForNullPointerDereference(Sema &S, const Expr *E) { |
| 7863 | // Check to see if we are dereferencing a null pointer. If so, this is |
| 7864 | // undefined behavior, so warn about it. This only handles the pattern |
| 7865 | // "*null", which is a very syntactic check. |
| 7866 | if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: E->IgnoreParenCasts())) |
| 7867 | if (UO->getOpcode() == UO_Deref && |
| 7868 | UO->getSubExpr()->IgnoreParenCasts()-> |
| 7869 | isNullPointerConstant(Ctx&: S.Context, NPC: Expr::NPC_ValueDependentIsNotNull)) { |
| 7870 | S.DiagRuntimeBehavior(Loc: UO->getOperatorLoc(), Statement: UO, |
| 7871 | PD: S.PDiag(DiagID: diag::warn_binding_null_to_reference) |
| 7872 | << UO->getSubExpr()->getSourceRange()); |
| 7873 | } |
| 7874 | } |
| 7875 | |
| 7876 | MaterializeTemporaryExpr * |
| 7877 | Sema::CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, |
| 7878 | bool BoundToLvalueReference) { |
| 7879 | auto MTE = new (Context) |
| 7880 | MaterializeTemporaryExpr(T, Temporary, BoundToLvalueReference); |
| 7881 | |
| 7882 | // Order an ExprWithCleanups for lifetime marks. |
| 7883 | // |
| 7884 | // TODO: It'll be good to have a single place to check the access of the |
| 7885 | // destructor and generate ExprWithCleanups for various uses. Currently these |
| 7886 | // are done in both CreateMaterializeTemporaryExpr and MaybeBindToTemporary, |
| 7887 | // but there may be a chance to merge them. |
| 7888 | Cleanup.setExprNeedsCleanups(false); |
| 7889 | if (isInLifetimeExtendingContext()) |
| 7890 | currentEvaluationContext().ForRangeLifetimeExtendTemps.push_back(Elt: MTE); |
| 7891 | return MTE; |
| 7892 | } |
| 7893 | |
| 7894 | ExprResult Sema::TemporaryMaterializationConversion(Expr *E) { |
| 7895 | // In C++98, we don't want to implicitly create an xvalue. C11 added the |
| 7896 | // same rule, but C99 is broken without this behavior and so we treat the |
| 7897 | // change as applying to all C language modes. |
| 7898 | // FIXME: This means that AST consumers need to deal with "prvalues" that |
| 7899 | // denote materialized temporaries. Maybe we should add another ValueKind |
| 7900 | // for "xvalue pretending to be a prvalue" for C++98 support. |
| 7901 | if (!E->isPRValue() || |
| 7902 | (!getLangOpts().CPlusPlus11 && getLangOpts().CPlusPlus)) |
| 7903 | return E; |
| 7904 | |
| 7905 | // C++1z [conv.rval]/1: T shall be a complete type. |
| 7906 | // FIXME: Does this ever matter (can we form a prvalue of incomplete type)? |
| 7907 | // If so, we should check for a non-abstract class type here too. |
| 7908 | QualType T = E->getType(); |
| 7909 | if (RequireCompleteType(Loc: E->getExprLoc(), T, DiagID: diag::err_incomplete_type)) |
| 7910 | return ExprError(); |
| 7911 | |
| 7912 | return CreateMaterializeTemporaryExpr(T: E->getType(), Temporary: E, BoundToLvalueReference: false); |
| 7913 | } |
| 7914 | |
| 7915 | ExprResult Sema::PerformQualificationConversion(Expr *E, QualType Ty, |
| 7916 | ExprValueKind VK, |
| 7917 | CheckedConversionKind CCK) { |
| 7918 | |
| 7919 | CastKind CK = CK_NoOp; |
| 7920 | |
| 7921 | if (VK == VK_PRValue) { |
| 7922 | auto PointeeTy = Ty->getPointeeType(); |
| 7923 | auto ExprPointeeTy = E->getType()->getPointeeType(); |
| 7924 | if (!PointeeTy.isNull() && |
| 7925 | PointeeTy.getAddressSpace() != ExprPointeeTy.getAddressSpace()) |
| 7926 | CK = CK_AddressSpaceConversion; |
| 7927 | } else if (Ty.getAddressSpace() != E->getType().getAddressSpace()) { |
| 7928 | CK = CK_AddressSpaceConversion; |
| 7929 | } |
| 7930 | |
| 7931 | return ImpCastExprToType(E, Type: Ty, CK, VK, /*BasePath=*/nullptr, CCK); |
| 7932 | } |
| 7933 | |
| 7934 | ExprResult InitializationSequence::Perform(Sema &S, |
| 7935 | const InitializedEntity &Entity, |
| 7936 | const InitializationKind &Kind, |
| 7937 | MultiExprArg Args, |
| 7938 | QualType *ResultType) { |
| 7939 | if (Failed()) { |
| 7940 | Diagnose(S, Entity, Kind, Args); |
| 7941 | return ExprError(); |
| 7942 | } |
| 7943 | if (!ZeroInitializationFixit.empty()) { |
| 7944 | const Decl *D = Entity.getDecl(); |
| 7945 | const auto *VD = dyn_cast_or_null<VarDecl>(Val: D); |
| 7946 | QualType DestType = Entity.getType(); |
| 7947 | |
| 7948 | // The initialization would have succeeded with this fixit. Since the fixit |
| 7949 | // is on the error, we need to build a valid AST in this case, so this isn't |
| 7950 | // handled in the Failed() branch above. |
| 7951 | if (!DestType->isRecordType() && VD && VD->isConstexpr()) { |
| 7952 | // Use a more useful diagnostic for constexpr variables. |
| 7953 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init) |
| 7954 | << VD |
| 7955 | << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc, |
| 7956 | Code: ZeroInitializationFixit); |
| 7957 | } else { |
| 7958 | unsigned DiagID = diag::err_default_init_const; |
| 7959 | if (S.getLangOpts().MSVCCompat && D && D->hasAttr<SelectAnyAttr>()) |
| 7960 | DiagID = diag::ext_default_init_const; |
| 7961 | |
| 7962 | S.Diag(Loc: Kind.getLocation(), DiagID) |
| 7963 | << DestType << DestType->isRecordType() |
| 7964 | << FixItHint::CreateInsertion(InsertionLoc: ZeroInitializationFixitLoc, |
| 7965 | Code: ZeroInitializationFixit); |
| 7966 | } |
| 7967 | } |
| 7968 | |
| 7969 | if (getKind() == DependentSequence) { |
| 7970 | // If the declaration is a non-dependent, incomplete array type |
| 7971 | // that has an initializer, then its type will be completed once |
| 7972 | // the initializer is instantiated. |
| 7973 | if (ResultType && !Entity.getType()->isDependentType() && |
| 7974 | Args.size() == 1) { |
| 7975 | QualType DeclType = Entity.getType(); |
| 7976 | if (const IncompleteArrayType *ArrayT |
| 7977 | = S.Context.getAsIncompleteArrayType(T: DeclType)) { |
| 7978 | // FIXME: We don't currently have the ability to accurately |
| 7979 | // compute the length of an initializer list without |
| 7980 | // performing full type-checking of the initializer list |
| 7981 | // (since we have to determine where braces are implicitly |
| 7982 | // introduced and such). So, we fall back to making the array |
| 7983 | // type a dependently-sized array type with no specified |
| 7984 | // bound. |
| 7985 | if (isa<InitListExpr>(Val: (Expr *)Args[0])) |
| 7986 | *ResultType = S.Context.getDependentSizedArrayType( |
| 7987 | EltTy: ArrayT->getElementType(), |
| 7988 | /*NumElts=*/nullptr, ASM: ArrayT->getSizeModifier(), |
| 7989 | IndexTypeQuals: ArrayT->getIndexTypeCVRQualifiers()); |
| 7990 | } |
| 7991 | } |
| 7992 | if (Kind.getKind() == InitializationKind::IK_Direct && |
| 7993 | !Kind.isExplicitCast()) { |
| 7994 | // Rebuild the ParenListExpr. |
| 7995 | SourceRange ParenRange = Kind.getParenOrBraceRange(); |
| 7996 | return S.ActOnParenListExpr(L: ParenRange.getBegin(), R: ParenRange.getEnd(), |
| 7997 | Val: Args); |
| 7998 | } |
| 7999 | assert(Kind.getKind() == InitializationKind::IK_Copy || |
| 8000 | Kind.isExplicitCast() || |
| 8001 | Kind.getKind() == InitializationKind::IK_DirectList); |
| 8002 | return ExprResult(Args[0]); |
| 8003 | } |
| 8004 | |
| 8005 | // No steps means no initialization. |
| 8006 | if (Steps.empty()) |
| 8007 | return ExprResult((Expr *)nullptr); |
| 8008 | |
| 8009 | if (S.getLangOpts().CPlusPlus11 && Entity.getType()->isReferenceType() && |
| 8010 | Args.size() == 1 && isa<InitListExpr>(Val: Args[0]) && |
| 8011 | !Entity.isParamOrTemplateParamKind()) { |
| 8012 | // Produce a C++98 compatibility warning if we are initializing a reference |
| 8013 | // from an initializer list. For parameters, we produce a better warning |
| 8014 | // elsewhere. |
| 8015 | Expr *Init = Args[0]; |
| 8016 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::warn_cxx98_compat_reference_list_init) |
| 8017 | << Init->getSourceRange(); |
| 8018 | } |
| 8019 | |
| 8020 | if (S.getLangOpts().MicrosoftExt && Args.size() == 1 && |
| 8021 | isa<PredefinedExpr>(Val: Args[0]) && Entity.getType()->isArrayType()) { |
| 8022 | // Produce a Microsoft compatibility warning when initializing from a |
| 8023 | // predefined expression since MSVC treats predefined expressions as string |
| 8024 | // literals. |
| 8025 | Expr *Init = Args[0]; |
| 8026 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::ext_init_from_predefined) << Init; |
| 8027 | } |
| 8028 | |
| 8029 | // OpenCL v2.0 s6.13.11.1. atomic variables can be initialized in global scope |
| 8030 | QualType ETy = Entity.getType(); |
| 8031 | bool HasGlobalAS = ETy.hasAddressSpace() && |
| 8032 | ETy.getAddressSpace() == LangAS::opencl_global; |
| 8033 | |
| 8034 | if (S.getLangOpts().OpenCLVersion >= 200 && |
| 8035 | ETy->isAtomicType() && !HasGlobalAS && |
| 8036 | Entity.getKind() == InitializedEntity::EK_Variable && Args.size() > 0) { |
| 8037 | S.Diag(Loc: Args[0]->getBeginLoc(), DiagID: diag::err_opencl_atomic_init) |
| 8038 | << 1 |
| 8039 | << SourceRange(Entity.getDecl()->getBeginLoc(), Args[0]->getEndLoc()); |
| 8040 | return ExprError(); |
| 8041 | } |
| 8042 | |
| 8043 | QualType DestType = Entity.getType().getNonReferenceType(); |
| 8044 | // FIXME: Ugly hack around the fact that Entity.getType() is not |
| 8045 | // the same as Entity.getDecl()->getType() in cases involving type merging, |
| 8046 | // and we want latter when it makes sense. |
| 8047 | if (ResultType) |
| 8048 | *ResultType = Entity.getDecl() ? Entity.getDecl()->getType() : |
| 8049 | Entity.getType(); |
| 8050 | |
| 8051 | ExprResult CurInit((Expr *)nullptr); |
| 8052 | SmallVector<Expr*, 4> ArrayLoopCommonExprs; |
| 8053 | |
| 8054 | // HLSL allows vector/matrix initialization to function like list |
| 8055 | // initialization, but use the syntax of a C++-like constructor. |
| 8056 | bool IsHLSLVectorOrMatrixInit = |
| 8057 | S.getLangOpts().HLSL && |
| 8058 | (DestType->isExtVectorType() || DestType->isConstantMatrixType()) && |
| 8059 | isa<InitListExpr>(Val: Args[0]); |
| 8060 | (void)IsHLSLVectorOrMatrixInit; |
| 8061 | |
| 8062 | // For initialization steps that start with a single initializer, |
| 8063 | // grab the only argument out the Args and place it into the "current" |
| 8064 | // initializer. |
| 8065 | switch (Steps.front().Kind) { |
| 8066 | case SK_ResolveAddressOfOverloadedFunction: |
| 8067 | case SK_CastDerivedToBasePRValue: |
| 8068 | case SK_CastDerivedToBaseXValue: |
| 8069 | case SK_CastDerivedToBaseLValue: |
| 8070 | case SK_BindReference: |
| 8071 | case SK_BindReferenceToTemporary: |
| 8072 | case SK_FinalCopy: |
| 8073 | case SK_ExtraneousCopyToTemporary: |
| 8074 | case SK_UserConversion: |
| 8075 | case SK_QualificationConversionLValue: |
| 8076 | case SK_QualificationConversionXValue: |
| 8077 | case SK_QualificationConversionPRValue: |
| 8078 | case SK_FunctionReferenceConversion: |
| 8079 | case SK_AtomicConversion: |
| 8080 | case SK_ConversionSequence: |
| 8081 | case SK_ConversionSequenceNoNarrowing: |
| 8082 | case SK_ListInitialization: |
| 8083 | case SK_UnwrapInitList: |
| 8084 | case SK_RewrapInitList: |
| 8085 | case SK_CAssignment: |
| 8086 | case SK_StringInit: |
| 8087 | case SK_ObjCObjectConversion: |
| 8088 | case SK_ArrayLoopIndex: |
| 8089 | case SK_ArrayLoopInit: |
| 8090 | case SK_ArrayInit: |
| 8091 | case SK_GNUArrayInit: |
| 8092 | case SK_ParenthesizedArrayInit: |
| 8093 | case SK_PassByIndirectCopyRestore: |
| 8094 | case SK_PassByIndirectRestore: |
| 8095 | case SK_ProduceObjCObject: |
| 8096 | case SK_StdInitializerList: |
| 8097 | case SK_OCLSamplerInit: |
| 8098 | case SK_OCLZeroOpaqueType: |
| 8099 | case SK_HLSLBufferConversion: { |
| 8100 | assert(Args.size() == 1 || IsHLSLVectorOrMatrixInit); |
| 8101 | CurInit = Args[0]; |
| 8102 | if (!CurInit.get()) return ExprError(); |
| 8103 | break; |
| 8104 | } |
| 8105 | |
| 8106 | case SK_ConstructorInitialization: |
| 8107 | case SK_ConstructorInitializationFromList: |
| 8108 | case SK_StdInitializerListConstructorCall: |
| 8109 | case SK_ZeroInitialization: |
| 8110 | case SK_ParenthesizedListInit: |
| 8111 | break; |
| 8112 | } |
| 8113 | |
| 8114 | // Promote from an unevaluated context to an unevaluated list context in |
| 8115 | // C++11 list-initialization; we need to instantiate entities usable in |
| 8116 | // constant expressions here in order to perform narrowing checks =( |
| 8117 | EnterExpressionEvaluationContext Evaluated( |
| 8118 | S, EnterExpressionEvaluationContext::InitList, |
| 8119 | isa_and_nonnull<InitListExpr>(Val: CurInit.get())); |
| 8120 | |
| 8121 | // C++ [class.abstract]p2: |
| 8122 | // no objects of an abstract class can be created except as subobjects |
| 8123 | // of a class derived from it |
| 8124 | auto checkAbstractType = [&](QualType T) -> bool { |
| 8125 | if (Entity.getKind() == InitializedEntity::EK_Base || |
| 8126 | Entity.getKind() == InitializedEntity::EK_Delegating) |
| 8127 | return false; |
| 8128 | return S.RequireNonAbstractType(Loc: Kind.getLocation(), T, |
| 8129 | DiagID: diag::err_allocation_of_abstract_type); |
| 8130 | }; |
| 8131 | |
| 8132 | // Walk through the computed steps for the initialization sequence, |
| 8133 | // performing the specified conversions along the way. |
| 8134 | bool ConstructorInitRequiresZeroInit = false; |
| 8135 | for (step_iterator Step = step_begin(), StepEnd = step_end(); |
| 8136 | Step != StepEnd; ++Step) { |
| 8137 | if (CurInit.isInvalid()) |
| 8138 | return ExprError(); |
| 8139 | |
| 8140 | QualType SourceType = CurInit.get() ? CurInit.get()->getType() : QualType(); |
| 8141 | |
| 8142 | switch (Step->Kind) { |
| 8143 | case SK_ResolveAddressOfOverloadedFunction: |
| 8144 | // Overload resolution determined which function invoke; update the |
| 8145 | // initializer to reflect that choice. |
| 8146 | S.CheckAddressOfMemberAccess(OvlExpr: CurInit.get(), FoundDecl: Step->Function.FoundDecl); |
| 8147 | if (S.DiagnoseUseOfDecl(D: Step->Function.FoundDecl, Locs: Kind.getLocation())) |
| 8148 | return ExprError(); |
| 8149 | CurInit = S.FixOverloadedFunctionReference(CurInit, |
| 8150 | FoundDecl: Step->Function.FoundDecl, |
| 8151 | Fn: Step->Function.Function); |
| 8152 | // We might get back another placeholder expression if we resolved to a |
| 8153 | // builtin. |
| 8154 | if (!CurInit.isInvalid()) |
| 8155 | CurInit = S.CheckPlaceholderExpr(E: CurInit.get()); |
| 8156 | break; |
| 8157 | |
| 8158 | case SK_CastDerivedToBasePRValue: |
| 8159 | case SK_CastDerivedToBaseXValue: |
| 8160 | case SK_CastDerivedToBaseLValue: { |
| 8161 | // We have a derived-to-base cast that produces either an rvalue or an |
| 8162 | // lvalue. Perform that cast. |
| 8163 | |
| 8164 | CXXCastPath BasePath; |
| 8165 | |
| 8166 | // Casts to inaccessible base classes are allowed with C-style casts. |
| 8167 | bool IgnoreBaseAccess = Kind.isCStyleOrFunctionalCast(); |
| 8168 | if (S.CheckDerivedToBaseConversion( |
| 8169 | Derived: SourceType, Base: Step->Type, Loc: CurInit.get()->getBeginLoc(), |
| 8170 | Range: CurInit.get()->getSourceRange(), BasePath: &BasePath, IgnoreAccess: IgnoreBaseAccess)) |
| 8171 | return ExprError(); |
| 8172 | |
| 8173 | ExprValueKind VK = |
| 8174 | Step->Kind == SK_CastDerivedToBaseLValue |
| 8175 | ? VK_LValue |
| 8176 | : (Step->Kind == SK_CastDerivedToBaseXValue ? VK_XValue |
| 8177 | : VK_PRValue); |
| 8178 | CurInit = ImplicitCastExpr::Create(Context: S.Context, T: Step->Type, |
| 8179 | Kind: CK_DerivedToBase, Operand: CurInit.get(), |
| 8180 | BasePath: &BasePath, Cat: VK, FPO: FPOptionsOverride()); |
| 8181 | break; |
| 8182 | } |
| 8183 | |
| 8184 | case SK_BindReference: |
| 8185 | // Reference binding does not have any corresponding ASTs. |
| 8186 | |
| 8187 | // Check exception specifications |
| 8188 | if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType)) |
| 8189 | return ExprError(); |
| 8190 | |
| 8191 | // We don't check for e.g. function pointers here, since address |
| 8192 | // availability checks should only occur when the function first decays |
| 8193 | // into a pointer or reference. |
| 8194 | if (CurInit.get()->getType()->isFunctionProtoType()) { |
| 8195 | if (auto *DRE = dyn_cast<DeclRefExpr>(Val: CurInit.get()->IgnoreParens())) { |
| 8196 | if (auto *FD = dyn_cast<FunctionDecl>(Val: DRE->getDecl())) { |
| 8197 | if (!S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
| 8198 | Loc: DRE->getBeginLoc())) |
| 8199 | return ExprError(); |
| 8200 | } |
| 8201 | } |
| 8202 | } |
| 8203 | |
| 8204 | CheckForNullPointerDereference(S, E: CurInit.get()); |
| 8205 | break; |
| 8206 | |
| 8207 | case SK_BindReferenceToTemporary: { |
| 8208 | // Make sure the "temporary" is actually an rvalue. |
| 8209 | assert(CurInit.get()->isPRValue() && "not a temporary" ); |
| 8210 | |
| 8211 | // Check exception specifications |
| 8212 | if (S.CheckExceptionSpecCompatibility(From: CurInit.get(), ToType: DestType)) |
| 8213 | return ExprError(); |
| 8214 | |
| 8215 | QualType MTETy = Step->Type; |
| 8216 | |
| 8217 | // When this is an incomplete array type (such as when this is |
| 8218 | // initializing an array of unknown bounds from an init list), use THAT |
| 8219 | // type instead so that we propagate the array bounds. |
| 8220 | if (MTETy->isIncompleteArrayType() && |
| 8221 | !CurInit.get()->getType()->isIncompleteArrayType() && |
| 8222 | S.Context.hasSameType( |
| 8223 | T1: MTETy->getPointeeOrArrayElementType(), |
| 8224 | T2: CurInit.get()->getType()->getPointeeOrArrayElementType())) |
| 8225 | MTETy = CurInit.get()->getType(); |
| 8226 | |
| 8227 | // Materialize the temporary into memory. |
| 8228 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( |
| 8229 | T: MTETy, Temporary: CurInit.get(), BoundToLvalueReference: Entity.getType()->isLValueReferenceType()); |
| 8230 | CurInit = MTE; |
| 8231 | |
| 8232 | // If we're extending this temporary to automatic storage duration -- we |
| 8233 | // need to register its cleanup during the full-expression's cleanups. |
| 8234 | if (MTE->getStorageDuration() == SD_Automatic && |
| 8235 | MTE->getType().isDestructedType()) |
| 8236 | S.Cleanup.setExprNeedsCleanups(true); |
| 8237 | break; |
| 8238 | } |
| 8239 | |
| 8240 | case SK_FinalCopy: |
| 8241 | if (checkAbstractType(Step->Type)) |
| 8242 | return ExprError(); |
| 8243 | |
| 8244 | // If the overall initialization is initializing a temporary, we already |
| 8245 | // bound our argument if it was necessary to do so. If not (if we're |
| 8246 | // ultimately initializing a non-temporary), our argument needs to be |
| 8247 | // bound since it's initializing a function parameter. |
| 8248 | // FIXME: This is a mess. Rationalize temporary destruction. |
| 8249 | if (!shouldBindAsTemporary(Entity)) |
| 8250 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
| 8251 | CurInit = CopyObject(S, T: Step->Type, Entity, CurInit, |
| 8252 | /*IsExtraneousCopy=*/false); |
| 8253 | break; |
| 8254 | |
| 8255 | case SK_ExtraneousCopyToTemporary: |
| 8256 | CurInit = CopyObject(S, T: Step->Type, Entity, CurInit, |
| 8257 | /*IsExtraneousCopy=*/true); |
| 8258 | break; |
| 8259 | |
| 8260 | case SK_UserConversion: { |
| 8261 | // We have a user-defined conversion that invokes either a constructor |
| 8262 | // or a conversion function. |
| 8263 | CastKind CastKind; |
| 8264 | FunctionDecl *Fn = Step->Function.Function; |
| 8265 | DeclAccessPair FoundFn = Step->Function.FoundDecl; |
| 8266 | bool HadMultipleCandidates = Step->Function.HadMultipleCandidates; |
| 8267 | bool CreatedObject = false; |
| 8268 | if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Fn)) { |
| 8269 | // Build a call to the selected constructor. |
| 8270 | SmallVector<Expr*, 8> ConstructorArgs; |
| 8271 | SourceLocation Loc = CurInit.get()->getBeginLoc(); |
| 8272 | |
| 8273 | // Determine the arguments required to actually perform the constructor |
| 8274 | // call. |
| 8275 | Expr *Arg = CurInit.get(); |
| 8276 | if (S.CompleteConstructorCall(Constructor, DeclInitType: Step->Type, |
| 8277 | ArgsPtr: MultiExprArg(&Arg, 1), Loc, |
| 8278 | ConvertedArgs&: ConstructorArgs)) |
| 8279 | return ExprError(); |
| 8280 | |
| 8281 | // Build an expression that constructs a temporary. |
| 8282 | CurInit = S.BuildCXXConstructExpr( |
| 8283 | ConstructLoc: Loc, DeclInitType: Step->Type, FoundDecl: FoundFn, Constructor, Exprs: ConstructorArgs, |
| 8284 | HadMultipleCandidates, |
| 8285 | /*ListInit*/ IsListInitialization: false, |
| 8286 | /*StdInitListInit*/ IsStdInitListInitialization: false, |
| 8287 | /*ZeroInit*/ RequiresZeroInit: false, ConstructKind: CXXConstructionKind::Complete, ParenRange: SourceRange()); |
| 8288 | if (CurInit.isInvalid()) |
| 8289 | return ExprError(); |
| 8290 | |
| 8291 | S.CheckConstructorAccess(Loc: Kind.getLocation(), D: Constructor, FoundDecl: FoundFn, |
| 8292 | Entity); |
| 8293 | if (S.DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: Kind.getLocation())) |
| 8294 | return ExprError(); |
| 8295 | |
| 8296 | CastKind = CK_ConstructorConversion; |
| 8297 | CreatedObject = true; |
| 8298 | } else { |
| 8299 | // Build a call to the conversion function. |
| 8300 | CXXConversionDecl *Conversion = cast<CXXConversionDecl>(Val: Fn); |
| 8301 | S.CheckMemberOperatorAccess(Loc: Kind.getLocation(), ObjectExpr: CurInit.get(), ArgExpr: nullptr, |
| 8302 | FoundDecl: FoundFn); |
| 8303 | if (S.DiagnoseUseOfOverloadedDecl(D: Conversion, Loc: Kind.getLocation())) |
| 8304 | return ExprError(); |
| 8305 | |
| 8306 | CurInit = S.BuildCXXMemberCallExpr(Exp: CurInit.get(), FoundDecl: FoundFn, Method: Conversion, |
| 8307 | HadMultipleCandidates); |
| 8308 | if (CurInit.isInvalid()) |
| 8309 | return ExprError(); |
| 8310 | |
| 8311 | CastKind = CK_UserDefinedConversion; |
| 8312 | CreatedObject = Conversion->getReturnType()->isRecordType(); |
| 8313 | } |
| 8314 | |
| 8315 | if (CreatedObject && checkAbstractType(CurInit.get()->getType())) |
| 8316 | return ExprError(); |
| 8317 | |
| 8318 | CurInit = ImplicitCastExpr::Create( |
| 8319 | Context: S.Context, T: CurInit.get()->getType(), Kind: CastKind, Operand: CurInit.get(), BasePath: nullptr, |
| 8320 | Cat: CurInit.get()->getValueKind(), FPO: S.CurFPFeatureOverrides()); |
| 8321 | |
| 8322 | if (shouldBindAsTemporary(Entity)) |
| 8323 | // The overall entity is temporary, so this expression should be |
| 8324 | // destroyed at the end of its full-expression. |
| 8325 | CurInit = S.MaybeBindToTemporary(E: CurInit.getAs<Expr>()); |
| 8326 | else if (CreatedObject && shouldDestroyEntity(Entity)) { |
| 8327 | // The object outlasts the full-expression, but we need to prepare for |
| 8328 | // a destructor being run on it. |
| 8329 | // FIXME: It makes no sense to do this here. This should happen |
| 8330 | // regardless of how we initialized the entity. |
| 8331 | QualType T = CurInit.get()->getType(); |
| 8332 | if (auto *Record = T->castAsCXXRecordDecl()) { |
| 8333 | CXXDestructorDecl *Destructor = S.LookupDestructor(Class: Record); |
| 8334 | S.CheckDestructorAccess(Loc: CurInit.get()->getBeginLoc(), Dtor: Destructor, |
| 8335 | PDiag: S.PDiag(DiagID: diag::err_access_dtor_temp) << T); |
| 8336 | S.MarkFunctionReferenced(Loc: CurInit.get()->getBeginLoc(), Func: Destructor); |
| 8337 | if (S.DiagnoseUseOfDecl(D: Destructor, Locs: CurInit.get()->getBeginLoc())) |
| 8338 | return ExprError(); |
| 8339 | } |
| 8340 | } |
| 8341 | break; |
| 8342 | } |
| 8343 | |
| 8344 | case SK_QualificationConversionLValue: |
| 8345 | case SK_QualificationConversionXValue: |
| 8346 | case SK_QualificationConversionPRValue: { |
| 8347 | // Perform a qualification conversion; these can never go wrong. |
| 8348 | ExprValueKind VK = |
| 8349 | Step->Kind == SK_QualificationConversionLValue |
| 8350 | ? VK_LValue |
| 8351 | : (Step->Kind == SK_QualificationConversionXValue ? VK_XValue |
| 8352 | : VK_PRValue); |
| 8353 | CurInit = S.PerformQualificationConversion(E: CurInit.get(), Ty: Step->Type, VK); |
| 8354 | break; |
| 8355 | } |
| 8356 | |
| 8357 | case SK_FunctionReferenceConversion: |
| 8358 | assert(CurInit.get()->isLValue() && |
| 8359 | "function reference should be lvalue" ); |
| 8360 | CurInit = |
| 8361 | S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, CK: CK_NoOp, VK: VK_LValue); |
| 8362 | break; |
| 8363 | |
| 8364 | case SK_AtomicConversion: { |
| 8365 | assert(CurInit.get()->isPRValue() && "cannot convert glvalue to atomic" ); |
| 8366 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
| 8367 | CK: CK_NonAtomicToAtomic, VK: VK_PRValue); |
| 8368 | break; |
| 8369 | } |
| 8370 | |
| 8371 | case SK_ConversionSequence: |
| 8372 | case SK_ConversionSequenceNoNarrowing: { |
| 8373 | if (const auto *FromPtrType = |
| 8374 | CurInit.get()->getType()->getAs<PointerType>()) { |
| 8375 | if (const auto *ToPtrType = Step->Type->getAs<PointerType>()) { |
| 8376 | if (FromPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref) && |
| 8377 | !ToPtrType->getPointeeType()->hasAttr(AK: attr::NoDeref)) { |
| 8378 | // Do not check static casts here because they are checked earlier |
| 8379 | // in Sema::ActOnCXXNamedCast() |
| 8380 | if (!Kind.isStaticCast()) { |
| 8381 | S.Diag(Loc: CurInit.get()->getExprLoc(), |
| 8382 | DiagID: diag::warn_noderef_to_dereferenceable_pointer) |
| 8383 | << CurInit.get()->getSourceRange(); |
| 8384 | } |
| 8385 | } |
| 8386 | } |
| 8387 | } |
| 8388 | Expr *Init = CurInit.get(); |
| 8389 | CheckedConversionKind CCK = |
| 8390 | Kind.isCStyleCast() ? CheckedConversionKind::CStyleCast |
| 8391 | : Kind.isFunctionalCast() ? CheckedConversionKind::FunctionalCast |
| 8392 | : Kind.isExplicitCast() ? CheckedConversionKind::OtherCast |
| 8393 | : CheckedConversionKind::Implicit; |
| 8394 | ExprResult CurInitExprRes = S.PerformImplicitConversion( |
| 8395 | From: Init, ToType: Step->Type, ICS: *Step->ICS, Action: getAssignmentAction(Entity), CCK); |
| 8396 | if (CurInitExprRes.isInvalid()) |
| 8397 | return ExprError(); |
| 8398 | |
| 8399 | S.DiscardMisalignedMemberAddress(T: Step->Type.getTypePtr(), E: Init); |
| 8400 | |
| 8401 | CurInit = CurInitExprRes; |
| 8402 | |
| 8403 | if (Step->Kind == SK_ConversionSequenceNoNarrowing && |
| 8404 | S.getLangOpts().CPlusPlus) |
| 8405 | DiagnoseNarrowingInInitList(S, ICS: *Step->ICS, PreNarrowingType: SourceType, EntityType: Entity.getType(), |
| 8406 | PostInit: CurInit.get()); |
| 8407 | |
| 8408 | break; |
| 8409 | } |
| 8410 | |
| 8411 | case SK_ListInitialization: { |
| 8412 | if (checkAbstractType(Step->Type)) |
| 8413 | return ExprError(); |
| 8414 | |
| 8415 | InitListExpr *InitList = cast<InitListExpr>(Val: CurInit.get()); |
| 8416 | // If we're not initializing the top-level entity, we need to create an |
| 8417 | // InitializeTemporary entity for our target type. |
| 8418 | QualType Ty = Step->Type; |
| 8419 | bool IsTemporary = !S.Context.hasSameType(T1: Entity.getType(), T2: Ty); |
| 8420 | InitializedEntity InitEntity = |
| 8421 | IsTemporary ? InitializedEntity::InitializeTemporary(Type: Ty) : Entity; |
| 8422 | InitListChecker PerformInitList(S, InitEntity, |
| 8423 | InitList, Ty, /*VerifyOnly=*/false, |
| 8424 | /*TreatUnavailableAsInvalid=*/false); |
| 8425 | if (PerformInitList.HadError()) |
| 8426 | return ExprError(); |
| 8427 | |
| 8428 | // Hack: We must update *ResultType if available in order to set the |
| 8429 | // bounds of arrays, e.g. in 'int ar[] = {1, 2, 3};'. |
| 8430 | // Worst case: 'const int (&arref)[] = {1, 2, 3};'. |
| 8431 | if (ResultType && |
| 8432 | ResultType->getNonReferenceType()->isIncompleteArrayType()) { |
| 8433 | if ((*ResultType)->isRValueReferenceType()) |
| 8434 | Ty = S.Context.getRValueReferenceType(T: Ty); |
| 8435 | else if ((*ResultType)->isLValueReferenceType()) |
| 8436 | Ty = S.Context.getLValueReferenceType(T: Ty, |
| 8437 | SpelledAsLValue: (*ResultType)->castAs<LValueReferenceType>()->isSpelledAsLValue()); |
| 8438 | *ResultType = Ty; |
| 8439 | } |
| 8440 | |
| 8441 | InitListExpr *StructuredInitList = |
| 8442 | PerformInitList.getFullyStructuredList(); |
| 8443 | CurInit = shouldBindAsTemporary(Entity: InitEntity) |
| 8444 | ? S.MaybeBindToTemporary(E: StructuredInitList) |
| 8445 | : StructuredInitList; |
| 8446 | break; |
| 8447 | } |
| 8448 | |
| 8449 | case SK_ConstructorInitializationFromList: { |
| 8450 | if (checkAbstractType(Step->Type)) |
| 8451 | return ExprError(); |
| 8452 | |
| 8453 | // When an initializer list is passed for a parameter of type "reference |
| 8454 | // to object", we don't get an EK_Temporary entity, but instead an |
| 8455 | // EK_Parameter entity with reference type. |
| 8456 | // FIXME: This is a hack. What we really should do is create a user |
| 8457 | // conversion step for this case, but this makes it considerably more |
| 8458 | // complicated. For now, this will do. |
| 8459 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( |
| 8460 | Type: Entity.getType().getNonReferenceType()); |
| 8461 | bool UseTemporary = Entity.getType()->isReferenceType(); |
| 8462 | assert(Args.size() == 1 && "expected a single argument for list init" ); |
| 8463 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
| 8464 | S.Diag(Loc: InitList->getExprLoc(), DiagID: diag::warn_cxx98_compat_ctor_list_init) |
| 8465 | << InitList->getSourceRange(); |
| 8466 | MultiExprArg Arg(InitList->getInits(), InitList->getNumInits()); |
| 8467 | CurInit = PerformConstructorInitialization(S, Entity: UseTemporary ? TempEntity : |
| 8468 | Entity, |
| 8469 | Kind, Args: Arg, Step: *Step, |
| 8470 | ConstructorInitRequiresZeroInit, |
| 8471 | /*IsListInitialization*/true, |
| 8472 | /*IsStdInitListInit*/IsStdInitListInitialization: false, |
| 8473 | LBraceLoc: InitList->getLBraceLoc(), |
| 8474 | RBraceLoc: InitList->getRBraceLoc()); |
| 8475 | break; |
| 8476 | } |
| 8477 | |
| 8478 | case SK_UnwrapInitList: |
| 8479 | CurInit = cast<InitListExpr>(Val: CurInit.get())->getInit(Init: 0); |
| 8480 | break; |
| 8481 | |
| 8482 | case SK_RewrapInitList: { |
| 8483 | Expr *E = CurInit.get(); |
| 8484 | InitListExpr *Syntactic = Step->WrappingSyntacticList; |
| 8485 | InitListExpr *ILE = new (S.Context) |
| 8486 | InitListExpr(S.Context, Syntactic->getLBraceLoc(), E, |
| 8487 | Syntactic->getRBraceLoc(), Syntactic->isExplicit()); |
| 8488 | ILE->setSyntacticForm(Syntactic); |
| 8489 | ILE->setType(E->getType()); |
| 8490 | ILE->setValueKind(E->getValueKind()); |
| 8491 | CurInit = ILE; |
| 8492 | break; |
| 8493 | } |
| 8494 | |
| 8495 | case SK_ConstructorInitialization: |
| 8496 | case SK_StdInitializerListConstructorCall: { |
| 8497 | if (checkAbstractType(Step->Type)) |
| 8498 | return ExprError(); |
| 8499 | |
| 8500 | // When an initializer list is passed for a parameter of type "reference |
| 8501 | // to object", we don't get an EK_Temporary entity, but instead an |
| 8502 | // EK_Parameter entity with reference type. |
| 8503 | // FIXME: This is a hack. What we really should do is create a user |
| 8504 | // conversion step for this case, but this makes it considerably more |
| 8505 | // complicated. For now, this will do. |
| 8506 | InitializedEntity TempEntity = InitializedEntity::InitializeTemporary( |
| 8507 | Type: Entity.getType().getNonReferenceType()); |
| 8508 | bool UseTemporary = Entity.getType()->isReferenceType(); |
| 8509 | bool IsStdInitListInit = |
| 8510 | Step->Kind == SK_StdInitializerListConstructorCall; |
| 8511 | Expr *Source = CurInit.get(); |
| 8512 | SourceRange Range = Kind.hasParenOrBraceRange() |
| 8513 | ? Kind.getParenOrBraceRange() |
| 8514 | : SourceRange(); |
| 8515 | CurInit = PerformConstructorInitialization( |
| 8516 | S, Entity: UseTemporary ? TempEntity : Entity, Kind, |
| 8517 | Args: Source ? MultiExprArg(Source) : Args, Step: *Step, |
| 8518 | ConstructorInitRequiresZeroInit, |
| 8519 | /*IsListInitialization*/ IsStdInitListInit, |
| 8520 | /*IsStdInitListInitialization*/ IsStdInitListInit, |
| 8521 | /*LBraceLoc*/ Range.getBegin(), |
| 8522 | /*RBraceLoc*/ Range.getEnd()); |
| 8523 | break; |
| 8524 | } |
| 8525 | |
| 8526 | case SK_ZeroInitialization: { |
| 8527 | step_iterator NextStep = Step; |
| 8528 | ++NextStep; |
| 8529 | if (NextStep != StepEnd && |
| 8530 | (NextStep->Kind == SK_ConstructorInitialization || |
| 8531 | NextStep->Kind == SK_ConstructorInitializationFromList)) { |
| 8532 | // The need for zero-initialization is recorded directly into |
| 8533 | // the call to the object's constructor within the next step. |
| 8534 | ConstructorInitRequiresZeroInit = true; |
| 8535 | } else if (Kind.getKind() == InitializationKind::IK_Value && |
| 8536 | S.getLangOpts().CPlusPlus && |
| 8537 | !Kind.isImplicitValueInit()) { |
| 8538 | TypeSourceInfo *TSInfo = Entity.getTypeSourceInfo(); |
| 8539 | if (!TSInfo) |
| 8540 | TSInfo = S.Context.getTrivialTypeSourceInfo(T: Step->Type, |
| 8541 | Loc: Kind.getRange().getBegin()); |
| 8542 | |
| 8543 | CurInit = new (S.Context) CXXScalarValueInitExpr( |
| 8544 | Entity.getType().getNonLValueExprType(Context: S.Context), TSInfo, |
| 8545 | Kind.getRange().getEnd()); |
| 8546 | } else { |
| 8547 | CurInit = new (S.Context) ImplicitValueInitExpr(Step->Type); |
| 8548 | // Note the return value isn't used to return a ExprError() when |
| 8549 | // initialization fails . For struct initialization allows all field |
| 8550 | // assignments to be checked rather than bailing on the first error. |
| 8551 | S.BoundsSafetyCheckInitialization(Entity, Kind, |
| 8552 | Action: AssignmentAction::Initializing, |
| 8553 | LHSType: Step->Type, RHSExpr: CurInit.get()); |
| 8554 | } |
| 8555 | break; |
| 8556 | } |
| 8557 | |
| 8558 | case SK_CAssignment: { |
| 8559 | QualType SourceType = CurInit.get()->getType(); |
| 8560 | Expr *Init = CurInit.get(); |
| 8561 | |
| 8562 | // Save off the initial CurInit in case we need to emit a diagnostic |
| 8563 | ExprResult InitialCurInit = Init; |
| 8564 | ExprResult Result = Init; |
| 8565 | AssignConvertType ConvTy = S.CheckSingleAssignmentConstraints( |
| 8566 | LHSType: Step->Type, RHS&: Result, Diagnose: true, |
| 8567 | DiagnoseCFAudited: Entity.getKind() == InitializedEntity::EK_Parameter_CF_Audited); |
| 8568 | if (Result.isInvalid()) |
| 8569 | return ExprError(); |
| 8570 | CurInit = Result; |
| 8571 | |
| 8572 | // If this is a call, allow conversion to a transparent union. |
| 8573 | ExprResult CurInitExprRes = CurInit; |
| 8574 | if (!S.IsAssignConvertCompatible(ConvTy) && Entity.isParameterKind() && |
| 8575 | S.CheckTransparentUnionArgumentConstraints( |
| 8576 | ArgType: Step->Type, RHS&: CurInitExprRes) == AssignConvertType::Compatible) |
| 8577 | ConvTy = AssignConvertType::Compatible; |
| 8578 | if (CurInitExprRes.isInvalid()) |
| 8579 | return ExprError(); |
| 8580 | CurInit = CurInitExprRes; |
| 8581 | |
| 8582 | if (S.getLangOpts().C23 && initializingConstexprVariable(Entity)) { |
| 8583 | CheckC23ConstexprInitConversion(S, FromType: SourceType, ToType: Entity.getType(), |
| 8584 | Init: CurInit.get()); |
| 8585 | |
| 8586 | // C23 6.7.1p6: If an object or subobject declared with storage-class |
| 8587 | // specifier constexpr has pointer, integer, or arithmetic type, any |
| 8588 | // explicit initializer value for it shall be null, an integer |
| 8589 | // constant expression, or an arithmetic constant expression, |
| 8590 | // respectively. |
| 8591 | Expr::EvalResult ER; |
| 8592 | if (Entity.getType()->getAs<PointerType>() && |
| 8593 | CurInit.get()->EvaluateAsRValue(Result&: ER, Ctx: S.Context) && |
| 8594 | (ER.Val.isLValue() && !ER.Val.isNullPointer())) { |
| 8595 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_c23_constexpr_pointer_not_null); |
| 8596 | return ExprError(); |
| 8597 | } |
| 8598 | } |
| 8599 | |
| 8600 | // Note the return value isn't used to return a ExprError() when |
| 8601 | // initialization fails. For struct initialization this allows all field |
| 8602 | // assignments to be checked rather than bailing on the first error. |
| 8603 | S.BoundsSafetyCheckInitialization(Entity, Kind, |
| 8604 | Action: getAssignmentAction(Entity, Diagnose: true), |
| 8605 | LHSType: Step->Type, RHSExpr: InitialCurInit.get()); |
| 8606 | |
| 8607 | bool Complained; |
| 8608 | if (S.DiagnoseAssignmentResult(ConvTy, Loc: Kind.getLocation(), |
| 8609 | DstType: Step->Type, SrcType: SourceType, |
| 8610 | SrcExpr: InitialCurInit.get(), |
| 8611 | Action: getAssignmentAction(Entity, Diagnose: true), |
| 8612 | Complained: &Complained)) { |
| 8613 | PrintInitLocationNote(S, Entity); |
| 8614 | return ExprError(); |
| 8615 | } else if (Complained) |
| 8616 | PrintInitLocationNote(S, Entity); |
| 8617 | break; |
| 8618 | } |
| 8619 | |
| 8620 | case SK_StringInit: { |
| 8621 | QualType Ty = Step->Type; |
| 8622 | bool UpdateType = ResultType && Entity.getType()->isIncompleteArrayType(); |
| 8623 | CheckStringInit(Str: CurInit.get(), DeclT&: UpdateType ? *ResultType : Ty, |
| 8624 | AT: S.Context.getAsArrayType(T: Ty), S, Entity, |
| 8625 | CheckC23ConstexprInit: S.getLangOpts().C23 && |
| 8626 | initializingConstexprVariable(Entity)); |
| 8627 | break; |
| 8628 | } |
| 8629 | |
| 8630 | case SK_ObjCObjectConversion: |
| 8631 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
| 8632 | CK: CK_ObjCObjectLValueCast, |
| 8633 | VK: CurInit.get()->getValueKind()); |
| 8634 | break; |
| 8635 | |
| 8636 | case SK_ArrayLoopIndex: { |
| 8637 | Expr *Cur = CurInit.get(); |
| 8638 | Expr *BaseExpr = new (S.Context) |
| 8639 | OpaqueValueExpr(Cur->getExprLoc(), Cur->getType(), |
| 8640 | Cur->getValueKind(), Cur->getObjectKind(), Cur); |
| 8641 | Expr *IndexExpr = |
| 8642 | new (S.Context) ArrayInitIndexExpr(S.Context.getSizeType()); |
| 8643 | CurInit = S.CreateBuiltinArraySubscriptExpr( |
| 8644 | Base: BaseExpr, LLoc: Kind.getLocation(), Idx: IndexExpr, RLoc: Kind.getLocation()); |
| 8645 | ArrayLoopCommonExprs.push_back(Elt: BaseExpr); |
| 8646 | break; |
| 8647 | } |
| 8648 | |
| 8649 | case SK_ArrayLoopInit: { |
| 8650 | assert(!ArrayLoopCommonExprs.empty() && |
| 8651 | "mismatched SK_ArrayLoopIndex and SK_ArrayLoopInit" ); |
| 8652 | Expr *Common = ArrayLoopCommonExprs.pop_back_val(); |
| 8653 | CurInit = new (S.Context) ArrayInitLoopExpr(Step->Type, Common, |
| 8654 | CurInit.get()); |
| 8655 | break; |
| 8656 | } |
| 8657 | |
| 8658 | case SK_GNUArrayInit: |
| 8659 | // Okay: we checked everything before creating this step. Note that |
| 8660 | // this is a GNU extension. |
| 8661 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_copy) |
| 8662 | << Step->Type << CurInit.get()->getType() |
| 8663 | << CurInit.get()->getSourceRange(); |
| 8664 | updateGNUCompoundLiteralRValue(E: CurInit.get()); |
| 8665 | [[fallthrough]]; |
| 8666 | case SK_ArrayInit: |
| 8667 | // If the destination type is an incomplete array type, update the |
| 8668 | // type accordingly. |
| 8669 | if (ResultType) { |
| 8670 | if (const IncompleteArrayType *IncompleteDest |
| 8671 | = S.Context.getAsIncompleteArrayType(T: Step->Type)) { |
| 8672 | if (const ConstantArrayType *ConstantSource |
| 8673 | = S.Context.getAsConstantArrayType(T: CurInit.get()->getType())) { |
| 8674 | *ResultType = S.Context.getConstantArrayType( |
| 8675 | EltTy: IncompleteDest->getElementType(), ArySize: ConstantSource->getSize(), |
| 8676 | SizeExpr: ConstantSource->getSizeExpr(), ASM: ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 8677 | } |
| 8678 | } |
| 8679 | } |
| 8680 | break; |
| 8681 | |
| 8682 | case SK_ParenthesizedArrayInit: |
| 8683 | // Okay: we checked everything before creating this step. Note that |
| 8684 | // this is a GNU extension. |
| 8685 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::ext_array_init_parens) |
| 8686 | << CurInit.get()->getSourceRange(); |
| 8687 | break; |
| 8688 | |
| 8689 | case SK_PassByIndirectCopyRestore: |
| 8690 | case SK_PassByIndirectRestore: |
| 8691 | checkIndirectCopyRestoreSource(S, src: CurInit.get()); |
| 8692 | CurInit = new (S.Context) ObjCIndirectCopyRestoreExpr( |
| 8693 | CurInit.get(), Step->Type, |
| 8694 | Step->Kind == SK_PassByIndirectCopyRestore); |
| 8695 | break; |
| 8696 | |
| 8697 | case SK_ProduceObjCObject: |
| 8698 | CurInit = ImplicitCastExpr::Create( |
| 8699 | Context: S.Context, T: Step->Type, Kind: CK_ARCProduceObject, Operand: CurInit.get(), BasePath: nullptr, |
| 8700 | Cat: VK_PRValue, FPO: FPOptionsOverride()); |
| 8701 | break; |
| 8702 | |
| 8703 | case SK_StdInitializerList: { |
| 8704 | S.Diag(Loc: CurInit.get()->getExprLoc(), |
| 8705 | DiagID: diag::warn_cxx98_compat_initializer_list_init) |
| 8706 | << CurInit.get()->getSourceRange(); |
| 8707 | |
| 8708 | // Materialize the temporary into memory. |
| 8709 | MaterializeTemporaryExpr *MTE = S.CreateMaterializeTemporaryExpr( |
| 8710 | T: CurInit.get()->getType(), Temporary: CurInit.get(), |
| 8711 | /*BoundToLvalueReference=*/false); |
| 8712 | |
| 8713 | // Wrap it in a construction of a std::initializer_list<T>. |
| 8714 | CurInit = new (S.Context) CXXStdInitializerListExpr(Step->Type, MTE); |
| 8715 | |
| 8716 | if (!Step->Type->isDependentType()) { |
| 8717 | QualType ElementType; |
| 8718 | [[maybe_unused]] bool IsStdInitializerList = |
| 8719 | S.isStdInitializerList(Ty: Step->Type, Element: &ElementType); |
| 8720 | assert(IsStdInitializerList && |
| 8721 | "StdInitializerList step to non-std::initializer_list" ); |
| 8722 | const auto *Record = Step->Type->castAsCXXRecordDecl(); |
| 8723 | assert(Record->isCompleteDefinition() && |
| 8724 | "std::initializer_list should have already be " |
| 8725 | "complete/instantiated by this point" ); |
| 8726 | |
| 8727 | auto InvalidType = [&] { |
| 8728 | S.Diag(Loc: Record->getLocation(), |
| 8729 | DiagID: diag::err_std_initializer_list_malformed) |
| 8730 | << Step->Type.getUnqualifiedType(); |
| 8731 | return ExprError(); |
| 8732 | }; |
| 8733 | |
| 8734 | if (Record->isUnion() || Record->getNumBases() != 0 || |
| 8735 | Record->isPolymorphic()) |
| 8736 | return InvalidType(); |
| 8737 | |
| 8738 | RecordDecl::field_iterator Field = Record->field_begin(); |
| 8739 | if (Field == Record->field_end()) |
| 8740 | return InvalidType(); |
| 8741 | |
| 8742 | // Start pointer |
| 8743 | if (!Field->getType()->isPointerType() || |
| 8744 | !S.Context.hasSameType(T1: Field->getType()->getPointeeType(), |
| 8745 | T2: ElementType.withConst())) |
| 8746 | return InvalidType(); |
| 8747 | |
| 8748 | if (++Field == Record->field_end()) |
| 8749 | return InvalidType(); |
| 8750 | |
| 8751 | // Size or end pointer |
| 8752 | if (const auto *PT = Field->getType()->getAs<PointerType>()) { |
| 8753 | if (!S.Context.hasSameType(T1: PT->getPointeeType(), |
| 8754 | T2: ElementType.withConst())) |
| 8755 | return InvalidType(); |
| 8756 | } else { |
| 8757 | if (Field->isBitField() || |
| 8758 | !S.Context.hasSameType(T1: Field->getType(), T2: S.Context.getSizeType())) |
| 8759 | return InvalidType(); |
| 8760 | } |
| 8761 | |
| 8762 | if (++Field != Record->field_end()) |
| 8763 | return InvalidType(); |
| 8764 | } |
| 8765 | |
| 8766 | // Bind the result, in case the library has given initializer_list a |
| 8767 | // non-trivial destructor. |
| 8768 | if (shouldBindAsTemporary(Entity)) |
| 8769 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
| 8770 | break; |
| 8771 | } |
| 8772 | |
| 8773 | case SK_OCLSamplerInit: { |
| 8774 | // Sampler initialization have 5 cases: |
| 8775 | // 1. function argument passing |
| 8776 | // 1a. argument is a file-scope variable |
| 8777 | // 1b. argument is a function-scope variable |
| 8778 | // 1c. argument is one of caller function's parameters |
| 8779 | // 2. variable initialization |
| 8780 | // 2a. initializing a file-scope variable |
| 8781 | // 2b. initializing a function-scope variable |
| 8782 | // |
| 8783 | // For file-scope variables, since they cannot be initialized by function |
| 8784 | // call of __translate_sampler_initializer in LLVM IR, their references |
| 8785 | // need to be replaced by a cast from their literal initializers to |
| 8786 | // sampler type. Since sampler variables can only be used in function |
| 8787 | // calls as arguments, we only need to replace them when handling the |
| 8788 | // argument passing. |
| 8789 | assert(Step->Type->isSamplerT() && |
| 8790 | "Sampler initialization on non-sampler type." ); |
| 8791 | Expr *Init = CurInit.get()->IgnoreParens(); |
| 8792 | QualType SourceType = Init->getType(); |
| 8793 | // Case 1 |
| 8794 | if (Entity.isParameterKind()) { |
| 8795 | if (!SourceType->isSamplerT() && !SourceType->isIntegerType()) { |
| 8796 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_argument_required) |
| 8797 | << SourceType; |
| 8798 | break; |
| 8799 | } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: Init)) { |
| 8800 | auto Var = cast<VarDecl>(Val: DRE->getDecl()); |
| 8801 | // Case 1b and 1c |
| 8802 | // No cast from integer to sampler is needed. |
| 8803 | if (!Var->hasGlobalStorage()) { |
| 8804 | CurInit = ImplicitCastExpr::Create( |
| 8805 | Context: S.Context, T: Step->Type, Kind: CK_LValueToRValue, Operand: Init, |
| 8806 | /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
| 8807 | break; |
| 8808 | } |
| 8809 | // Case 1a |
| 8810 | // For function call with a file-scope sampler variable as argument, |
| 8811 | // get the integer literal. |
| 8812 | // Do not diagnose if the file-scope variable does not have initializer |
| 8813 | // since this has already been diagnosed when parsing the variable |
| 8814 | // declaration. |
| 8815 | if (!Var->getInit() || !isa<ImplicitCastExpr>(Val: Var->getInit())) |
| 8816 | break; |
| 8817 | Init = cast<ImplicitCastExpr>(Val: const_cast<Expr*>( |
| 8818 | Var->getInit()))->getSubExpr(); |
| 8819 | SourceType = Init->getType(); |
| 8820 | } |
| 8821 | } else { |
| 8822 | // Case 2 |
| 8823 | // Check initializer is 32 bit integer constant. |
| 8824 | // If the initializer is taken from global variable, do not diagnose since |
| 8825 | // this has already been done when parsing the variable declaration. |
| 8826 | if (!Init->isConstantInitializer(Ctx&: S.Context)) |
| 8827 | break; |
| 8828 | |
| 8829 | if (!SourceType->isIntegerType() || |
| 8830 | 32 != S.Context.getIntWidth(T: SourceType)) { |
| 8831 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_sampler_initializer_not_integer) |
| 8832 | << SourceType; |
| 8833 | break; |
| 8834 | } |
| 8835 | |
| 8836 | Expr::EvalResult EVResult; |
| 8837 | Init->EvaluateAsInt(Result&: EVResult, Ctx: S.Context); |
| 8838 | llvm::APSInt Result = EVResult.Val.getInt(); |
| 8839 | const uint64_t SamplerValue = Result.getLimitedValue(); |
| 8840 | // 32-bit value of sampler's initializer is interpreted as |
| 8841 | // bit-field with the following structure: |
| 8842 | // |unspecified|Filter|Addressing Mode| Normalized Coords| |
| 8843 | // |31 6|5 4|3 1| 0| |
| 8844 | // This structure corresponds to enum values of sampler properties |
| 8845 | // defined in SPIR spec v1.2 and also opencl-c.h |
| 8846 | unsigned AddressingMode = (0x0E & SamplerValue) >> 1; |
| 8847 | unsigned FilterMode = (0x30 & SamplerValue) >> 4; |
| 8848 | if (FilterMode != 1 && FilterMode != 2 && |
| 8849 | !S.getOpenCLOptions().isAvailableOption( |
| 8850 | Ext: "cl_intel_device_side_avc_motion_estimation" , LO: S.getLangOpts())) |
| 8851 | S.Diag(Loc: Kind.getLocation(), |
| 8852 | DiagID: diag::warn_sampler_initializer_invalid_bits) |
| 8853 | << "Filter Mode" ; |
| 8854 | if (AddressingMode > 4) |
| 8855 | S.Diag(Loc: Kind.getLocation(), |
| 8856 | DiagID: diag::warn_sampler_initializer_invalid_bits) |
| 8857 | << "Addressing Mode" ; |
| 8858 | } |
| 8859 | |
| 8860 | // Cases 1a, 2a and 2b |
| 8861 | // Insert cast from integer to sampler. |
| 8862 | CurInit = S.ImpCastExprToType(E: Init, Type: S.Context.OCLSamplerTy, |
| 8863 | CK: CK_IntToOCLSampler); |
| 8864 | break; |
| 8865 | } |
| 8866 | case SK_OCLZeroOpaqueType: { |
| 8867 | assert((Step->Type->isEventT() || Step->Type->isQueueT() || |
| 8868 | Step->Type->isOCLIntelSubgroupAVCType()) && |
| 8869 | "Wrong type for initialization of OpenCL opaque type." ); |
| 8870 | |
| 8871 | CurInit = S.ImpCastExprToType(E: CurInit.get(), Type: Step->Type, |
| 8872 | CK: CK_ZeroToOCLOpaqueType, |
| 8873 | VK: CurInit.get()->getValueKind()); |
| 8874 | break; |
| 8875 | } |
| 8876 | case SK_ParenthesizedListInit: { |
| 8877 | CurInit = nullptr; |
| 8878 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
| 8879 | /*VerifyOnly=*/false, Result: &CurInit); |
| 8880 | if (CurInit.get() && ResultType) |
| 8881 | *ResultType = CurInit.get()->getType(); |
| 8882 | if (shouldBindAsTemporary(Entity)) |
| 8883 | CurInit = S.MaybeBindToTemporary(E: CurInit.get()); |
| 8884 | break; |
| 8885 | } |
| 8886 | case SK_HLSLBufferConversion: { |
| 8887 | CurInit = ImplicitCastExpr::Create( |
| 8888 | Context: S.Context, T: Step->Type.getLocalUnqualifiedType(), Kind: CK_LValueToRValue, |
| 8889 | Operand: CurInit.get(), |
| 8890 | /*BasePath=*/nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride()); |
| 8891 | break; |
| 8892 | } |
| 8893 | } |
| 8894 | } |
| 8895 | |
| 8896 | Expr *Init = CurInit.get(); |
| 8897 | if (!Init) |
| 8898 | return ExprError(); |
| 8899 | |
| 8900 | // Check whether the initializer has a shorter lifetime than the initialized |
| 8901 | // entity, and if not, either lifetime-extend or warn as appropriate. |
| 8902 | S.checkInitializerLifetime(Entity, Init); |
| 8903 | |
| 8904 | // Diagnose non-fatal problems with the completed initialization. |
| 8905 | if (InitializedEntity::EntityKind EK = Entity.getKind(); |
| 8906 | (EK == InitializedEntity::EK_Member || |
| 8907 | EK == InitializedEntity::EK_ParenAggInitMember) && |
| 8908 | cast<FieldDecl>(Val: Entity.getDecl())->isBitField()) |
| 8909 | S.CheckBitFieldInitialization(InitLoc: Kind.getLocation(), |
| 8910 | Field: cast<FieldDecl>(Val: Entity.getDecl()), Init); |
| 8911 | |
| 8912 | // Check for std::move on construction. |
| 8913 | CheckMoveOnConstruction(S, InitExpr: Init, |
| 8914 | IsReturnStmt: Entity.getKind() == InitializedEntity::EK_Result); |
| 8915 | |
| 8916 | return Init; |
| 8917 | } |
| 8918 | |
| 8919 | /// Somewhere within T there is an uninitialized reference subobject. |
| 8920 | /// Dig it out and diagnose it. |
| 8921 | static bool DiagnoseUninitializedReference(Sema &S, SourceLocation Loc, |
| 8922 | QualType T) { |
| 8923 | if (T->isReferenceType()) { |
| 8924 | S.Diag(Loc, DiagID: diag::err_reference_without_init) |
| 8925 | << T.getNonReferenceType(); |
| 8926 | return true; |
| 8927 | } |
| 8928 | |
| 8929 | CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); |
| 8930 | if (!RD || !RD->hasUninitializedReferenceMember()) |
| 8931 | return false; |
| 8932 | |
| 8933 | for (const auto *FI : RD->fields()) { |
| 8934 | if (FI->isUnnamedBitField()) |
| 8935 | continue; |
| 8936 | |
| 8937 | if (DiagnoseUninitializedReference(S, Loc: FI->getLocation(), T: FI->getType())) { |
| 8938 | S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD; |
| 8939 | return true; |
| 8940 | } |
| 8941 | } |
| 8942 | |
| 8943 | for (const auto &BI : RD->bases()) { |
| 8944 | if (DiagnoseUninitializedReference(S, Loc: BI.getBeginLoc(), T: BI.getType())) { |
| 8945 | S.Diag(Loc, DiagID: diag::note_value_initialization_here) << RD; |
| 8946 | return true; |
| 8947 | } |
| 8948 | } |
| 8949 | |
| 8950 | return false; |
| 8951 | } |
| 8952 | |
| 8953 | |
| 8954 | //===----------------------------------------------------------------------===// |
| 8955 | // Diagnose initialization failures |
| 8956 | //===----------------------------------------------------------------------===// |
| 8957 | |
| 8958 | /// Emit notes associated with an initialization that failed due to a |
| 8959 | /// "simple" conversion failure. |
| 8960 | static void emitBadConversionNotes(Sema &S, const InitializedEntity &entity, |
| 8961 | Expr *op) { |
| 8962 | QualType destType = entity.getType(); |
| 8963 | if (destType.getNonReferenceType()->isObjCObjectPointerType() && |
| 8964 | op->getType()->isObjCObjectPointerType()) { |
| 8965 | |
| 8966 | // Emit a possible note about the conversion failing because the |
| 8967 | // operand is a message send with a related result type. |
| 8968 | S.ObjC().EmitRelatedResultTypeNote(E: op); |
| 8969 | |
| 8970 | // Emit a possible note about a return failing because we're |
| 8971 | // expecting a related result type. |
| 8972 | if (entity.getKind() == InitializedEntity::EK_Result) |
| 8973 | S.ObjC().EmitRelatedResultTypeNoteForReturn(destType); |
| 8974 | } |
| 8975 | QualType fromType = op->getType(); |
| 8976 | QualType fromPointeeType = fromType.getCanonicalType()->getPointeeType(); |
| 8977 | QualType destPointeeType = destType.getCanonicalType()->getPointeeType(); |
| 8978 | auto *fromDecl = fromType->getPointeeCXXRecordDecl(); |
| 8979 | auto *destDecl = destType->getPointeeCXXRecordDecl(); |
| 8980 | if (fromDecl && destDecl && fromDecl->getDeclKind() == Decl::CXXRecord && |
| 8981 | destDecl->getDeclKind() == Decl::CXXRecord && |
| 8982 | !fromDecl->isInvalidDecl() && !destDecl->isInvalidDecl() && |
| 8983 | !fromDecl->hasDefinition() && |
| 8984 | destPointeeType.getQualifiers().compatiblyIncludes( |
| 8985 | other: fromPointeeType.getQualifiers(), Ctx: S.getASTContext())) |
| 8986 | S.Diag(Loc: fromDecl->getLocation(), DiagID: diag::note_forward_class_conversion) |
| 8987 | << S.getASTContext().getCanonicalTagType(TD: fromDecl) |
| 8988 | << S.getASTContext().getCanonicalTagType(TD: destDecl); |
| 8989 | } |
| 8990 | |
| 8991 | static void diagnoseListInit(Sema &S, const InitializedEntity &Entity, |
| 8992 | InitListExpr *InitList) { |
| 8993 | QualType DestType = Entity.getType(); |
| 8994 | |
| 8995 | QualType E; |
| 8996 | if (S.getLangOpts().CPlusPlus11 && S.isStdInitializerList(Ty: DestType, Element: &E)) { |
| 8997 | QualType ArrayType = S.Context.getConstantArrayType( |
| 8998 | EltTy: E.withConst(), |
| 8999 | ArySize: llvm::APInt(S.Context.getTypeSize(T: S.Context.getSizeType()), |
| 9000 | InitList->getNumInits()), |
| 9001 | SizeExpr: nullptr, ASM: clang::ArraySizeModifier::Normal, IndexTypeQuals: 0); |
| 9002 | InitializedEntity HiddenArray = |
| 9003 | InitializedEntity::InitializeTemporary(Type: ArrayType); |
| 9004 | return diagnoseListInit(S, Entity: HiddenArray, InitList); |
| 9005 | } |
| 9006 | |
| 9007 | if (DestType->isReferenceType()) { |
| 9008 | // A list-initialization failure for a reference means that we tried to |
| 9009 | // create a temporary of the inner type (per [dcl.init.list]p3.6) and the |
| 9010 | // inner initialization failed. |
| 9011 | QualType T = DestType->castAs<ReferenceType>()->getPointeeType(); |
| 9012 | diagnoseListInit(S, Entity: InitializedEntity::InitializeTemporary(Type: T), InitList); |
| 9013 | SourceLocation Loc = InitList->getBeginLoc(); |
| 9014 | if (auto *D = Entity.getDecl()) |
| 9015 | Loc = D->getLocation(); |
| 9016 | S.Diag(Loc, DiagID: diag::note_in_reference_temporary_list_initializer) << T; |
| 9017 | return; |
| 9018 | } |
| 9019 | |
| 9020 | InitListChecker DiagnoseInitList(S, Entity, InitList, DestType, |
| 9021 | /*VerifyOnly=*/false, |
| 9022 | /*TreatUnavailableAsInvalid=*/false); |
| 9023 | assert(DiagnoseInitList.HadError() && |
| 9024 | "Inconsistent init list check result." ); |
| 9025 | } |
| 9026 | |
| 9027 | bool InitializationSequence::Diagnose(Sema &S, |
| 9028 | const InitializedEntity &Entity, |
| 9029 | const InitializationKind &Kind, |
| 9030 | ArrayRef<Expr *> Args) { |
| 9031 | if (!Failed()) |
| 9032 | return false; |
| 9033 | |
| 9034 | QualType DestType = Entity.getType(); |
| 9035 | |
| 9036 | // When we want to diagnose only one element of a braced-init-list, |
| 9037 | // we need to factor it out. |
| 9038 | Expr *OnlyArg; |
| 9039 | if (Args.size() == 1) { |
| 9040 | auto *List = dyn_cast<InitListExpr>(Val: Args[0]); |
| 9041 | if (List && List->getNumInits() == 1) |
| 9042 | OnlyArg = List->getInit(Init: 0); |
| 9043 | else |
| 9044 | OnlyArg = Args[0]; |
| 9045 | |
| 9046 | if (OnlyArg->getType() == S.Context.OverloadTy) { |
| 9047 | DeclAccessPair Found; |
| 9048 | if (FunctionDecl *FD = S.ResolveAddressOfOverloadedFunction( |
| 9049 | AddressOfExpr: OnlyArg, TargetType: DestType.getNonReferenceType(), /*Complain=*/false, |
| 9050 | Found)) { |
| 9051 | if (Expr *Resolved = |
| 9052 | S.FixOverloadedFunctionReference(E: OnlyArg, FoundDecl: Found, Fn: FD).get()) |
| 9053 | OnlyArg = Resolved; |
| 9054 | } |
| 9055 | } |
| 9056 | } |
| 9057 | else |
| 9058 | OnlyArg = nullptr; |
| 9059 | |
| 9060 | switch (Failure) { |
| 9061 | case FK_TooManyInitsForReference: |
| 9062 | // FIXME: Customize for the initialized entity? |
| 9063 | if (Args.empty()) { |
| 9064 | // Dig out the reference subobject which is uninitialized and diagnose it. |
| 9065 | // If this is value-initialization, this could be nested some way within |
| 9066 | // the target type. |
| 9067 | assert(Kind.getKind() == InitializationKind::IK_Value || |
| 9068 | DestType->isReferenceType()); |
| 9069 | bool Diagnosed = |
| 9070 | DiagnoseUninitializedReference(S, Loc: Kind.getLocation(), T: DestType); |
| 9071 | assert(Diagnosed && "couldn't find uninitialized reference to diagnose" ); |
| 9072 | (void)Diagnosed; |
| 9073 | } else // FIXME: diagnostic below could be better! |
| 9074 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_has_multiple_inits) |
| 9075 | << SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); |
| 9076 | break; |
| 9077 | case FK_ParenthesizedListInitForReference: |
| 9078 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens) |
| 9079 | << 1 << Entity.getType() << Args[0]->getSourceRange(); |
| 9080 | break; |
| 9081 | |
| 9082 | case FK_ArrayNeedsInitList: |
| 9083 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 0; |
| 9084 | break; |
| 9085 | case FK_ArrayNeedsInitListOrStringLiteral: |
| 9086 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 1; |
| 9087 | break; |
| 9088 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
| 9089 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_not_init_list) << 2; |
| 9090 | break; |
| 9091 | case FK_NarrowStringIntoWideCharArray: |
| 9092 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_narrow_string_into_wchar); |
| 9093 | break; |
| 9094 | case FK_WideStringIntoCharArray: |
| 9095 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_wide_string_into_char); |
| 9096 | break; |
| 9097 | case FK_IncompatWideStringIntoWideChar: |
| 9098 | S.Diag(Loc: Kind.getLocation(), |
| 9099 | DiagID: diag::err_array_init_incompat_wide_string_into_wchar); |
| 9100 | break; |
| 9101 | case FK_PlainStringIntoUTF8Char: |
| 9102 | S.Diag(Loc: Kind.getLocation(), |
| 9103 | DiagID: diag::err_array_init_plain_string_into_char8_t); |
| 9104 | S.Diag(Loc: Args.front()->getBeginLoc(), |
| 9105 | DiagID: diag::note_array_init_plain_string_into_char8_t) |
| 9106 | << FixItHint::CreateInsertion(InsertionLoc: Args.front()->getBeginLoc(), Code: "u8" ); |
| 9107 | break; |
| 9108 | case FK_UTF8StringIntoPlainChar: |
| 9109 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_array_init_utf8_string_into_char) |
| 9110 | << DestType->isSignedIntegerType() << S.getLangOpts().CPlusPlus20; |
| 9111 | break; |
| 9112 | case FK_ArrayTypeMismatch: |
| 9113 | case FK_NonConstantArrayInit: |
| 9114 | S.Diag(Loc: Kind.getLocation(), |
| 9115 | DiagID: (Failure == FK_ArrayTypeMismatch |
| 9116 | ? diag::err_array_init_different_type |
| 9117 | : diag::err_array_init_non_constant_array)) |
| 9118 | << DestType.getNonReferenceType() |
| 9119 | << OnlyArg->getType() |
| 9120 | << Args[0]->getSourceRange(); |
| 9121 | break; |
| 9122 | |
| 9123 | case FK_VariableLengthArrayHasInitializer: |
| 9124 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_variable_object_no_init) |
| 9125 | << Args[0]->getSourceRange(); |
| 9126 | break; |
| 9127 | |
| 9128 | case FK_AddressOfOverloadFailed: { |
| 9129 | DeclAccessPair Found; |
| 9130 | S.ResolveAddressOfOverloadedFunction(AddressOfExpr: OnlyArg, |
| 9131 | TargetType: DestType.getNonReferenceType(), |
| 9132 | Complain: true, |
| 9133 | Found); |
| 9134 | break; |
| 9135 | } |
| 9136 | |
| 9137 | case FK_AddressOfUnaddressableFunction: { |
| 9138 | auto *FD = cast<FunctionDecl>(Val: cast<DeclRefExpr>(Val: OnlyArg)->getDecl()); |
| 9139 | S.checkAddressOfFunctionIsAvailable(Function: FD, /*Complain=*/true, |
| 9140 | Loc: OnlyArg->getBeginLoc()); |
| 9141 | break; |
| 9142 | } |
| 9143 | |
| 9144 | case FK_ReferenceInitOverloadFailed: |
| 9145 | case FK_UserConversionOverloadFailed: |
| 9146 | switch (FailedOverloadResult) { |
| 9147 | case OR_Ambiguous: |
| 9148 | |
| 9149 | FailedCandidateSet.NoteCandidates( |
| 9150 | PA: PartialDiagnosticAt( |
| 9151 | Kind.getLocation(), |
| 9152 | Failure == FK_UserConversionOverloadFailed |
| 9153 | ? (S.PDiag(DiagID: diag::err_typecheck_ambiguous_condition) |
| 9154 | << OnlyArg->getType() << DestType |
| 9155 | << Args[0]->getSourceRange()) |
| 9156 | : (S.PDiag(DiagID: diag::err_ref_init_ambiguous) |
| 9157 | << DestType << OnlyArg->getType() |
| 9158 | << Args[0]->getSourceRange())), |
| 9159 | S, OCD: OCD_AmbiguousCandidates, Args); |
| 9160 | break; |
| 9161 | |
| 9162 | case OR_No_Viable_Function: { |
| 9163 | auto Cands = FailedCandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args); |
| 9164 | if (!S.RequireCompleteType(Loc: Kind.getLocation(), |
| 9165 | T: DestType.getNonReferenceType(), |
| 9166 | DiagID: diag::err_typecheck_nonviable_condition_incomplete, |
| 9167 | Args: OnlyArg->getType(), Args: Args[0]->getSourceRange())) |
| 9168 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_nonviable_condition) |
| 9169 | << (Entity.getKind() == InitializedEntity::EK_Result) |
| 9170 | << OnlyArg->getType() << Args[0]->getSourceRange() |
| 9171 | << DestType.getNonReferenceType(); |
| 9172 | |
| 9173 | FailedCandidateSet.NoteCandidates(S, Args, Cands); |
| 9174 | break; |
| 9175 | } |
| 9176 | case OR_Deleted: { |
| 9177 | OverloadCandidateSet::iterator Best; |
| 9178 | OverloadingResult Ovl |
| 9179 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
| 9180 | |
| 9181 | StringLiteral *Msg = Best->Function->getDeletedMessage(); |
| 9182 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_typecheck_deleted_function) |
| 9183 | << OnlyArg->getType() << DestType.getNonReferenceType() |
| 9184 | << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef()) |
| 9185 | << Args[0]->getSourceRange(); |
| 9186 | if (Ovl == OR_Deleted) { |
| 9187 | S.NoteDeletedFunction(FD: Best->Function); |
| 9188 | } else { |
| 9189 | llvm_unreachable("Inconsistent overload resolution?" ); |
| 9190 | } |
| 9191 | break; |
| 9192 | } |
| 9193 | |
| 9194 | case OR_Success: |
| 9195 | llvm_unreachable("Conversion did not fail!" ); |
| 9196 | } |
| 9197 | break; |
| 9198 | |
| 9199 | case FK_NonConstLValueReferenceBindingToTemporary: |
| 9200 | if (isa<InitListExpr>(Val: Args[0])) { |
| 9201 | S.Diag(Loc: Kind.getLocation(), |
| 9202 | DiagID: diag::err_lvalue_reference_bind_to_initlist) |
| 9203 | << DestType.getNonReferenceType().isVolatileQualified() |
| 9204 | << DestType.getNonReferenceType() |
| 9205 | << Args[0]->getSourceRange(); |
| 9206 | break; |
| 9207 | } |
| 9208 | [[fallthrough]]; |
| 9209 | |
| 9210 | case FK_NonConstLValueReferenceBindingToUnrelated: |
| 9211 | S.Diag(Loc: Kind.getLocation(), |
| 9212 | DiagID: Failure == FK_NonConstLValueReferenceBindingToTemporary |
| 9213 | ? diag::err_lvalue_reference_bind_to_temporary |
| 9214 | : diag::err_lvalue_reference_bind_to_unrelated) |
| 9215 | << DestType.getNonReferenceType().isVolatileQualified() |
| 9216 | << DestType.getNonReferenceType() |
| 9217 | << OnlyArg->getType() |
| 9218 | << Args[0]->getSourceRange(); |
| 9219 | break; |
| 9220 | |
| 9221 | case FK_NonConstLValueReferenceBindingToBitfield: { |
| 9222 | // We don't necessarily have an unambiguous source bit-field. |
| 9223 | FieldDecl *BitField = Args[0]->getSourceBitField(); |
| 9224 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_bitfield) |
| 9225 | << DestType.isVolatileQualified() |
| 9226 | << (BitField ? BitField->getDeclName() : DeclarationName()) |
| 9227 | << (BitField != nullptr) |
| 9228 | << Args[0]->getSourceRange(); |
| 9229 | if (BitField) |
| 9230 | S.Diag(Loc: BitField->getLocation(), DiagID: diag::note_bitfield_decl); |
| 9231 | break; |
| 9232 | } |
| 9233 | |
| 9234 | case FK_NonConstLValueReferenceBindingToVectorElement: |
| 9235 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_vector_element) |
| 9236 | << DestType.isVolatileQualified() |
| 9237 | << Args[0]->getSourceRange(); |
| 9238 | break; |
| 9239 | |
| 9240 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
| 9241 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_to_matrix_element) |
| 9242 | << DestType.isVolatileQualified() << Args[0]->getSourceRange(); |
| 9243 | break; |
| 9244 | |
| 9245 | case FK_RValueReferenceBindingToLValue: |
| 9246 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_lvalue_to_rvalue_ref) |
| 9247 | << DestType.getNonReferenceType() << OnlyArg->getType() |
| 9248 | << Args[0]->getSourceRange(); |
| 9249 | break; |
| 9250 | |
| 9251 | case FK_ReferenceAddrspaceMismatchTemporary: |
| 9252 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_temporary_addrspace) |
| 9253 | << DestType << Args[0]->getSourceRange(); |
| 9254 | break; |
| 9255 | |
| 9256 | case FK_ReferenceInitDropsQualifiers: { |
| 9257 | QualType SourceType = OnlyArg->getType(); |
| 9258 | QualType NonRefType = DestType.getNonReferenceType(); |
| 9259 | Qualifiers DroppedQualifiers = |
| 9260 | SourceType.getQualifiers() - NonRefType.getQualifiers(); |
| 9261 | |
| 9262 | if (!NonRefType.getQualifiers().isAddressSpaceSupersetOf( |
| 9263 | other: SourceType.getQualifiers(), Ctx: S.getASTContext())) |
| 9264 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals) |
| 9265 | << NonRefType << SourceType << 1 /*addr space*/ |
| 9266 | << Args[0]->getSourceRange(); |
| 9267 | else if (DroppedQualifiers.hasQualifiers()) |
| 9268 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals) |
| 9269 | << NonRefType << SourceType << 0 /*cv quals*/ |
| 9270 | << Qualifiers::fromCVRMask(CVR: DroppedQualifiers.getCVRQualifiers()) |
| 9271 | << DroppedQualifiers.getCVRQualifiers() << Args[0]->getSourceRange(); |
| 9272 | else |
| 9273 | // FIXME: Consider decomposing the type and explaining which qualifiers |
| 9274 | // were dropped where, or on which level a 'const' is missing, etc. |
| 9275 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_drops_quals) |
| 9276 | << NonRefType << SourceType << 2 /*incompatible quals*/ |
| 9277 | << Args[0]->getSourceRange(); |
| 9278 | break; |
| 9279 | } |
| 9280 | |
| 9281 | case FK_ReferenceInitFailed: |
| 9282 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_failed) |
| 9283 | << DestType.getNonReferenceType() |
| 9284 | << DestType.getNonReferenceType()->isIncompleteType() |
| 9285 | << OnlyArg->isLValue() |
| 9286 | << OnlyArg->getType() |
| 9287 | << Args[0]->getSourceRange(); |
| 9288 | emitBadConversionNotes(S, entity: Entity, op: Args[0]); |
| 9289 | break; |
| 9290 | |
| 9291 | case FK_ConversionFailed: { |
| 9292 | QualType FromType = OnlyArg->getType(); |
| 9293 | // __amdgpu_feature_predicate_t can be explicitly cast to the logical op |
| 9294 | // type, although this is almost always an error and we advise against it. |
| 9295 | if (FromType == S.Context.AMDGPUFeaturePredicateTy && |
| 9296 | DestType == S.Context.getLogicalOperationType()) { |
| 9297 | S.Diag(Loc: OnlyArg->getExprLoc(), |
| 9298 | DiagID: diag::err_amdgcn_predicate_type_needs_explicit_bool_cast) |
| 9299 | << OnlyArg << DestType; |
| 9300 | break; |
| 9301 | } |
| 9302 | PartialDiagnostic PDiag = S.PDiag(DiagID: diag::err_init_conversion_failed) |
| 9303 | << (int)Entity.getKind() |
| 9304 | << DestType |
| 9305 | << OnlyArg->isLValue() |
| 9306 | << FromType |
| 9307 | << Args[0]->getSourceRange(); |
| 9308 | S.HandleFunctionTypeMismatch(PDiag, FromType, ToType: DestType); |
| 9309 | S.Diag(Loc: Kind.getLocation(), PD: PDiag); |
| 9310 | emitBadConversionNotes(S, entity: Entity, op: Args[0]); |
| 9311 | break; |
| 9312 | } |
| 9313 | |
| 9314 | case FK_ConversionFromPropertyFailed: |
| 9315 | // No-op. This error has already been reported. |
| 9316 | break; |
| 9317 | |
| 9318 | case FK_TooManyInitsForScalar: { |
| 9319 | SourceRange R; |
| 9320 | |
| 9321 | auto *InitList = dyn_cast<InitListExpr>(Val: Args[0]); |
| 9322 | if (InitList && InitList->getNumInits() >= 1) { |
| 9323 | R = SourceRange(InitList->getInit(Init: 0)->getEndLoc(), InitList->getEndLoc()); |
| 9324 | } else { |
| 9325 | assert(Args.size() > 1 && "Expected multiple initializers!" ); |
| 9326 | R = SourceRange(Args.front()->getEndLoc(), Args.back()->getEndLoc()); |
| 9327 | } |
| 9328 | |
| 9329 | R.setBegin(S.getLocForEndOfToken(Loc: R.getBegin())); |
| 9330 | if (Kind.isCStyleOrFunctionalCast()) |
| 9331 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_builtin_func_cast_more_than_one_arg) |
| 9332 | << R; |
| 9333 | else |
| 9334 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_excess_initializers) |
| 9335 | << /*scalar=*/3 << R; |
| 9336 | break; |
| 9337 | } |
| 9338 | |
| 9339 | case FK_ParenthesizedListInitForScalar: |
| 9340 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_list_init_in_parens) |
| 9341 | << 0 << Entity.getType() << Args[0]->getSourceRange(); |
| 9342 | break; |
| 9343 | |
| 9344 | case FK_ReferenceBindingToInitList: |
| 9345 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_reference_bind_init_list) |
| 9346 | << DestType.getNonReferenceType() << Args[0]->getSourceRange(); |
| 9347 | break; |
| 9348 | |
| 9349 | case FK_InitListBadDestinationType: |
| 9350 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_init_list_bad_dest_type) |
| 9351 | << (DestType->isRecordType()) << DestType << Args[0]->getSourceRange(); |
| 9352 | break; |
| 9353 | |
| 9354 | case FK_ListConstructorOverloadFailed: |
| 9355 | case FK_ConstructorOverloadFailed: { |
| 9356 | SourceRange ArgsRange; |
| 9357 | if (Args.size()) |
| 9358 | ArgsRange = |
| 9359 | SourceRange(Args.front()->getBeginLoc(), Args.back()->getEndLoc()); |
| 9360 | |
| 9361 | if (Failure == FK_ListConstructorOverloadFailed) { |
| 9362 | assert(Args.size() == 1 && |
| 9363 | "List construction from other than 1 argument." ); |
| 9364 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
| 9365 | Args = MultiExprArg(InitList->getInits(), InitList->getNumInits()); |
| 9366 | } |
| 9367 | |
| 9368 | // FIXME: Using "DestType" for the entity we're printing is probably |
| 9369 | // bad. |
| 9370 | switch (FailedOverloadResult) { |
| 9371 | case OR_Ambiguous: |
| 9372 | FailedCandidateSet.NoteCandidates( |
| 9373 | PA: PartialDiagnosticAt(Kind.getLocation(), |
| 9374 | S.PDiag(DiagID: diag::err_ovl_ambiguous_init) |
| 9375 | << DestType << ArgsRange), |
| 9376 | S, OCD: OCD_AmbiguousCandidates, Args); |
| 9377 | break; |
| 9378 | |
| 9379 | case OR_No_Viable_Function: |
| 9380 | if (Kind.getKind() == InitializationKind::IK_Default && |
| 9381 | (Entity.getKind() == InitializedEntity::EK_Base || |
| 9382 | Entity.getKind() == InitializedEntity::EK_Member || |
| 9383 | Entity.getKind() == InitializedEntity::EK_ParenAggInitMember) && |
| 9384 | isa<CXXConstructorDecl>(Val: S.CurContext)) { |
| 9385 | // This is implicit default initialization of a member or |
| 9386 | // base within a constructor. If no viable function was |
| 9387 | // found, notify the user that they need to explicitly |
| 9388 | // initialize this base/member. |
| 9389 | CXXConstructorDecl *Constructor |
| 9390 | = cast<CXXConstructorDecl>(Val: S.CurContext); |
| 9391 | const CXXRecordDecl *InheritedFrom = nullptr; |
| 9392 | if (auto Inherited = Constructor->getInheritedConstructor()) |
| 9393 | InheritedFrom = Inherited.getShadowDecl()->getNominatedBaseClass(); |
| 9394 | if (Entity.getKind() == InitializedEntity::EK_Base) { |
| 9395 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor) |
| 9396 | << (InheritedFrom ? 2 |
| 9397 | : Constructor->isImplicit() ? 1 |
| 9398 | : 0) |
| 9399 | << S.Context.getCanonicalTagType(TD: Constructor->getParent()) |
| 9400 | << /*base=*/0 << Entity.getType() << InheritedFrom; |
| 9401 | |
| 9402 | auto *BaseDecl = |
| 9403 | Entity.getBaseSpecifier()->getType()->castAsRecordDecl(); |
| 9404 | S.Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_previous_decl) |
| 9405 | << S.Context.getCanonicalTagType(TD: BaseDecl); |
| 9406 | } else { |
| 9407 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_missing_default_ctor) |
| 9408 | << (InheritedFrom ? 2 |
| 9409 | : Constructor->isImplicit() ? 1 |
| 9410 | : 0) |
| 9411 | << S.Context.getCanonicalTagType(TD: Constructor->getParent()) |
| 9412 | << /*member=*/1 << Entity.getName() << InheritedFrom; |
| 9413 | S.Diag(Loc: Entity.getDecl()->getLocation(), |
| 9414 | DiagID: diag::note_member_declared_at); |
| 9415 | |
| 9416 | if (const auto *Record = Entity.getType()->getAs<RecordType>()) |
| 9417 | S.Diag(Loc: Record->getDecl()->getLocation(), DiagID: diag::note_previous_decl) |
| 9418 | << S.Context.getCanonicalTagType(TD: Record->getDecl()); |
| 9419 | } |
| 9420 | break; |
| 9421 | } |
| 9422 | |
| 9423 | FailedCandidateSet.NoteCandidates( |
| 9424 | PA: PartialDiagnosticAt( |
| 9425 | Kind.getLocation(), |
| 9426 | S.PDiag(DiagID: diag::err_ovl_no_viable_function_in_init) |
| 9427 | << DestType << ArgsRange), |
| 9428 | S, OCD: OCD_AllCandidates, Args); |
| 9429 | break; |
| 9430 | |
| 9431 | case OR_Deleted: { |
| 9432 | OverloadCandidateSet::iterator Best; |
| 9433 | OverloadingResult Ovl |
| 9434 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
| 9435 | if (Ovl != OR_Deleted) { |
| 9436 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init) |
| 9437 | << DestType << ArgsRange; |
| 9438 | llvm_unreachable("Inconsistent overload resolution?" ); |
| 9439 | break; |
| 9440 | } |
| 9441 | |
| 9442 | // If this is a defaulted or implicitly-declared function, then |
| 9443 | // it was implicitly deleted. Make it clear that the deletion was |
| 9444 | // implicit. |
| 9445 | if (S.isImplicitlyDeleted(FD: Best->Function)) |
| 9446 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_special_init) |
| 9447 | << S.getSpecialMember(MD: cast<CXXMethodDecl>(Val: Best->Function)) |
| 9448 | << DestType << ArgsRange; |
| 9449 | else { |
| 9450 | StringLiteral *Msg = Best->Function->getDeletedMessage(); |
| 9451 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_ovl_deleted_init) |
| 9452 | << DestType << (Msg != nullptr) |
| 9453 | << (Msg ? Msg->getString() : StringRef()) << ArgsRange; |
| 9454 | } |
| 9455 | |
| 9456 | // If it's a default constructed member, but it's not in the |
| 9457 | // constructor's initializer list, explicitly note where the member is |
| 9458 | // declared so the user can see which member is erroneously initialized |
| 9459 | // with a deleted default constructor. |
| 9460 | if (Kind.getKind() == InitializationKind::IK_Default && |
| 9461 | (Entity.getKind() == InitializedEntity::EK_Member || |
| 9462 | Entity.getKind() == InitializedEntity::EK_ParenAggInitMember)) { |
| 9463 | S.Diag(Loc: Entity.getDecl()->getLocation(), |
| 9464 | DiagID: diag::note_default_constructed_field) |
| 9465 | << Entity.getDecl(); |
| 9466 | } |
| 9467 | S.NoteDeletedFunction(FD: Best->Function); |
| 9468 | break; |
| 9469 | } |
| 9470 | |
| 9471 | case OR_Success: |
| 9472 | llvm_unreachable("Conversion did not fail!" ); |
| 9473 | } |
| 9474 | } |
| 9475 | break; |
| 9476 | |
| 9477 | case FK_DefaultInitOfConst: |
| 9478 | if (Entity.getKind() == InitializedEntity::EK_Member && |
| 9479 | isa<CXXConstructorDecl>(Val: S.CurContext)) { |
| 9480 | // This is implicit default-initialization of a const member in |
| 9481 | // a constructor. Complain that it needs to be explicitly |
| 9482 | // initialized. |
| 9483 | CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Val: S.CurContext); |
| 9484 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_uninitialized_member_in_ctor) |
| 9485 | << (Constructor->getInheritedConstructor() ? 2 |
| 9486 | : Constructor->isImplicit() ? 1 |
| 9487 | : 0) |
| 9488 | << S.Context.getCanonicalTagType(TD: Constructor->getParent()) |
| 9489 | << /*const=*/1 << Entity.getName(); |
| 9490 | S.Diag(Loc: Entity.getDecl()->getLocation(), DiagID: diag::note_previous_decl) |
| 9491 | << Entity.getName(); |
| 9492 | } else if (const auto *VD = dyn_cast_if_present<VarDecl>(Val: Entity.getDecl()); |
| 9493 | VD && VD->isConstexpr()) { |
| 9494 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_constexpr_var_requires_const_init) |
| 9495 | << VD; |
| 9496 | } else { |
| 9497 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_default_init_const) |
| 9498 | << DestType << DestType->isRecordType(); |
| 9499 | } |
| 9500 | break; |
| 9501 | |
| 9502 | case FK_Incomplete: |
| 9503 | S.RequireCompleteType(Loc: Kind.getLocation(), T: FailedIncompleteType, |
| 9504 | DiagID: diag::err_init_incomplete_type); |
| 9505 | break; |
| 9506 | |
| 9507 | case FK_ListInitializationFailed: { |
| 9508 | // Run the init list checker again to emit diagnostics. |
| 9509 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
| 9510 | diagnoseListInit(S, Entity, InitList); |
| 9511 | break; |
| 9512 | } |
| 9513 | |
| 9514 | case FK_PlaceholderType: { |
| 9515 | // FIXME: Already diagnosed! |
| 9516 | break; |
| 9517 | } |
| 9518 | |
| 9519 | case InitializationSequence::FK_HLSLInitListFlatteningFailed: { |
| 9520 | // Unlike C/C++ list initialization, there is no fallback if it fails. This |
| 9521 | // allows us to diagnose the failure when it happens in the |
| 9522 | // TryListInitialization call instead of delaying the diagnosis, which is |
| 9523 | // beneficial because the flattening is also expensive. |
| 9524 | break; |
| 9525 | } |
| 9526 | |
| 9527 | case FK_ExplicitConstructor: { |
| 9528 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_selected_explicit_constructor) |
| 9529 | << Args[0]->getSourceRange(); |
| 9530 | OverloadCandidateSet::iterator Best; |
| 9531 | OverloadingResult Ovl |
| 9532 | = FailedCandidateSet.BestViableFunction(S, Loc: Kind.getLocation(), Best); |
| 9533 | (void)Ovl; |
| 9534 | assert(Ovl == OR_Success && "Inconsistent overload resolution" ); |
| 9535 | CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Val: Best->Function); |
| 9536 | S.Diag(Loc: CtorDecl->getLocation(), |
| 9537 | DiagID: diag::note_explicit_ctor_deduction_guide_here) << false; |
| 9538 | break; |
| 9539 | } |
| 9540 | |
| 9541 | case FK_ParenthesizedListInitFailed: |
| 9542 | TryOrBuildParenListInitialization(S, Entity, Kind, Args, Sequence&: *this, |
| 9543 | /*VerifyOnly=*/false); |
| 9544 | break; |
| 9545 | |
| 9546 | case FK_DesignatedInitForNonAggregate: |
| 9547 | InitListExpr *InitList = cast<InitListExpr>(Val: Args[0]); |
| 9548 | S.Diag(Loc: Kind.getLocation(), DiagID: diag::err_designated_init_for_non_aggregate) |
| 9549 | << Entity.getType() << InitList->getSourceRange(); |
| 9550 | break; |
| 9551 | } |
| 9552 | |
| 9553 | PrintInitLocationNote(S, Entity); |
| 9554 | return true; |
| 9555 | } |
| 9556 | |
| 9557 | void InitializationSequence::dump(raw_ostream &OS) const { |
| 9558 | switch (SequenceKind) { |
| 9559 | case FailedSequence: { |
| 9560 | OS << "Failed sequence: " ; |
| 9561 | switch (Failure) { |
| 9562 | case FK_TooManyInitsForReference: |
| 9563 | OS << "too many initializers for reference" ; |
| 9564 | break; |
| 9565 | |
| 9566 | case FK_ParenthesizedListInitForReference: |
| 9567 | OS << "parenthesized list init for reference" ; |
| 9568 | break; |
| 9569 | |
| 9570 | case FK_ArrayNeedsInitList: |
| 9571 | OS << "array requires initializer list" ; |
| 9572 | break; |
| 9573 | |
| 9574 | case FK_AddressOfUnaddressableFunction: |
| 9575 | OS << "address of unaddressable function was taken" ; |
| 9576 | break; |
| 9577 | |
| 9578 | case FK_ArrayNeedsInitListOrStringLiteral: |
| 9579 | OS << "array requires initializer list or string literal" ; |
| 9580 | break; |
| 9581 | |
| 9582 | case FK_ArrayNeedsInitListOrWideStringLiteral: |
| 9583 | OS << "array requires initializer list or wide string literal" ; |
| 9584 | break; |
| 9585 | |
| 9586 | case FK_NarrowStringIntoWideCharArray: |
| 9587 | OS << "narrow string into wide char array" ; |
| 9588 | break; |
| 9589 | |
| 9590 | case FK_WideStringIntoCharArray: |
| 9591 | OS << "wide string into char array" ; |
| 9592 | break; |
| 9593 | |
| 9594 | case FK_IncompatWideStringIntoWideChar: |
| 9595 | OS << "incompatible wide string into wide char array" ; |
| 9596 | break; |
| 9597 | |
| 9598 | case FK_PlainStringIntoUTF8Char: |
| 9599 | OS << "plain string literal into char8_t array" ; |
| 9600 | break; |
| 9601 | |
| 9602 | case FK_UTF8StringIntoPlainChar: |
| 9603 | OS << "u8 string literal into char array" ; |
| 9604 | break; |
| 9605 | |
| 9606 | case FK_ArrayTypeMismatch: |
| 9607 | OS << "array type mismatch" ; |
| 9608 | break; |
| 9609 | |
| 9610 | case FK_NonConstantArrayInit: |
| 9611 | OS << "non-constant array initializer" ; |
| 9612 | break; |
| 9613 | |
| 9614 | case FK_AddressOfOverloadFailed: |
| 9615 | OS << "address of overloaded function failed" ; |
| 9616 | break; |
| 9617 | |
| 9618 | case FK_ReferenceInitOverloadFailed: |
| 9619 | OS << "overload resolution for reference initialization failed" ; |
| 9620 | break; |
| 9621 | |
| 9622 | case FK_NonConstLValueReferenceBindingToTemporary: |
| 9623 | OS << "non-const lvalue reference bound to temporary" ; |
| 9624 | break; |
| 9625 | |
| 9626 | case FK_NonConstLValueReferenceBindingToBitfield: |
| 9627 | OS << "non-const lvalue reference bound to bit-field" ; |
| 9628 | break; |
| 9629 | |
| 9630 | case FK_NonConstLValueReferenceBindingToVectorElement: |
| 9631 | OS << "non-const lvalue reference bound to vector element" ; |
| 9632 | break; |
| 9633 | |
| 9634 | case FK_NonConstLValueReferenceBindingToMatrixElement: |
| 9635 | OS << "non-const lvalue reference bound to matrix element" ; |
| 9636 | break; |
| 9637 | |
| 9638 | case FK_NonConstLValueReferenceBindingToUnrelated: |
| 9639 | OS << "non-const lvalue reference bound to unrelated type" ; |
| 9640 | break; |
| 9641 | |
| 9642 | case FK_RValueReferenceBindingToLValue: |
| 9643 | OS << "rvalue reference bound to an lvalue" ; |
| 9644 | break; |
| 9645 | |
| 9646 | case FK_ReferenceInitDropsQualifiers: |
| 9647 | OS << "reference initialization drops qualifiers" ; |
| 9648 | break; |
| 9649 | |
| 9650 | case FK_ReferenceAddrspaceMismatchTemporary: |
| 9651 | OS << "reference with mismatching address space bound to temporary" ; |
| 9652 | break; |
| 9653 | |
| 9654 | case FK_ReferenceInitFailed: |
| 9655 | OS << "reference initialization failed" ; |
| 9656 | break; |
| 9657 | |
| 9658 | case FK_ConversionFailed: |
| 9659 | OS << "conversion failed" ; |
| 9660 | break; |
| 9661 | |
| 9662 | case FK_ConversionFromPropertyFailed: |
| 9663 | OS << "conversion from property failed" ; |
| 9664 | break; |
| 9665 | |
| 9666 | case FK_TooManyInitsForScalar: |
| 9667 | OS << "too many initializers for scalar" ; |
| 9668 | break; |
| 9669 | |
| 9670 | case FK_ParenthesizedListInitForScalar: |
| 9671 | OS << "parenthesized list init for reference" ; |
| 9672 | break; |
| 9673 | |
| 9674 | case FK_ReferenceBindingToInitList: |
| 9675 | OS << "referencing binding to initializer list" ; |
| 9676 | break; |
| 9677 | |
| 9678 | case FK_InitListBadDestinationType: |
| 9679 | OS << "initializer list for non-aggregate, non-scalar type" ; |
| 9680 | break; |
| 9681 | |
| 9682 | case FK_UserConversionOverloadFailed: |
| 9683 | OS << "overloading failed for user-defined conversion" ; |
| 9684 | break; |
| 9685 | |
| 9686 | case FK_ConstructorOverloadFailed: |
| 9687 | OS << "constructor overloading failed" ; |
| 9688 | break; |
| 9689 | |
| 9690 | case FK_DefaultInitOfConst: |
| 9691 | OS << "default initialization of a const variable" ; |
| 9692 | break; |
| 9693 | |
| 9694 | case FK_Incomplete: |
| 9695 | OS << "initialization of incomplete type" ; |
| 9696 | break; |
| 9697 | |
| 9698 | case FK_ListInitializationFailed: |
| 9699 | OS << "list initialization checker failure" ; |
| 9700 | break; |
| 9701 | |
| 9702 | case FK_VariableLengthArrayHasInitializer: |
| 9703 | OS << "variable length array has an initializer" ; |
| 9704 | break; |
| 9705 | |
| 9706 | case FK_PlaceholderType: |
| 9707 | OS << "initializer expression isn't contextually valid" ; |
| 9708 | break; |
| 9709 | |
| 9710 | case FK_ListConstructorOverloadFailed: |
| 9711 | OS << "list constructor overloading failed" ; |
| 9712 | break; |
| 9713 | |
| 9714 | case FK_ExplicitConstructor: |
| 9715 | OS << "list copy initialization chose explicit constructor" ; |
| 9716 | break; |
| 9717 | |
| 9718 | case FK_ParenthesizedListInitFailed: |
| 9719 | OS << "parenthesized list initialization failed" ; |
| 9720 | break; |
| 9721 | |
| 9722 | case FK_DesignatedInitForNonAggregate: |
| 9723 | OS << "designated initializer for non-aggregate type" ; |
| 9724 | break; |
| 9725 | |
| 9726 | case FK_HLSLInitListFlatteningFailed: |
| 9727 | OS << "HLSL initialization list flattening failed" ; |
| 9728 | break; |
| 9729 | } |
| 9730 | OS << '\n'; |
| 9731 | return; |
| 9732 | } |
| 9733 | |
| 9734 | case DependentSequence: |
| 9735 | OS << "Dependent sequence\n" ; |
| 9736 | return; |
| 9737 | |
| 9738 | case NormalSequence: |
| 9739 | OS << "Normal sequence: " ; |
| 9740 | break; |
| 9741 | } |
| 9742 | |
| 9743 | for (step_iterator S = step_begin(), SEnd = step_end(); S != SEnd; ++S) { |
| 9744 | if (S != step_begin()) { |
| 9745 | OS << " -> " ; |
| 9746 | } |
| 9747 | |
| 9748 | switch (S->Kind) { |
| 9749 | case SK_ResolveAddressOfOverloadedFunction: |
| 9750 | OS << "resolve address of overloaded function" ; |
| 9751 | break; |
| 9752 | |
| 9753 | case SK_CastDerivedToBasePRValue: |
| 9754 | OS << "derived-to-base (prvalue)" ; |
| 9755 | break; |
| 9756 | |
| 9757 | case SK_CastDerivedToBaseXValue: |
| 9758 | OS << "derived-to-base (xvalue)" ; |
| 9759 | break; |
| 9760 | |
| 9761 | case SK_CastDerivedToBaseLValue: |
| 9762 | OS << "derived-to-base (lvalue)" ; |
| 9763 | break; |
| 9764 | |
| 9765 | case SK_BindReference: |
| 9766 | OS << "bind reference to lvalue" ; |
| 9767 | break; |
| 9768 | |
| 9769 | case SK_BindReferenceToTemporary: |
| 9770 | OS << "bind reference to a temporary" ; |
| 9771 | break; |
| 9772 | |
| 9773 | case SK_FinalCopy: |
| 9774 | OS << "final copy in class direct-initialization" ; |
| 9775 | break; |
| 9776 | |
| 9777 | case SK_ExtraneousCopyToTemporary: |
| 9778 | OS << "extraneous C++03 copy to temporary" ; |
| 9779 | break; |
| 9780 | |
| 9781 | case SK_UserConversion: |
| 9782 | OS << "user-defined conversion via " << *S->Function.Function; |
| 9783 | break; |
| 9784 | |
| 9785 | case SK_QualificationConversionPRValue: |
| 9786 | OS << "qualification conversion (prvalue)" ; |
| 9787 | break; |
| 9788 | |
| 9789 | case SK_QualificationConversionXValue: |
| 9790 | OS << "qualification conversion (xvalue)" ; |
| 9791 | break; |
| 9792 | |
| 9793 | case SK_QualificationConversionLValue: |
| 9794 | OS << "qualification conversion (lvalue)" ; |
| 9795 | break; |
| 9796 | |
| 9797 | case SK_FunctionReferenceConversion: |
| 9798 | OS << "function reference conversion" ; |
| 9799 | break; |
| 9800 | |
| 9801 | case SK_AtomicConversion: |
| 9802 | OS << "non-atomic-to-atomic conversion" ; |
| 9803 | break; |
| 9804 | |
| 9805 | case SK_ConversionSequence: |
| 9806 | OS << "implicit conversion sequence (" ; |
| 9807 | S->ICS->dump(); // FIXME: use OS |
| 9808 | OS << ")" ; |
| 9809 | break; |
| 9810 | |
| 9811 | case SK_ConversionSequenceNoNarrowing: |
| 9812 | OS << "implicit conversion sequence with narrowing prohibited (" ; |
| 9813 | S->ICS->dump(); // FIXME: use OS |
| 9814 | OS << ")" ; |
| 9815 | break; |
| 9816 | |
| 9817 | case SK_ListInitialization: |
| 9818 | OS << "list aggregate initialization" ; |
| 9819 | break; |
| 9820 | |
| 9821 | case SK_UnwrapInitList: |
| 9822 | OS << "unwrap reference initializer list" ; |
| 9823 | break; |
| 9824 | |
| 9825 | case SK_RewrapInitList: |
| 9826 | OS << "rewrap reference initializer list" ; |
| 9827 | break; |
| 9828 | |
| 9829 | case SK_ConstructorInitialization: |
| 9830 | OS << "constructor initialization" ; |
| 9831 | break; |
| 9832 | |
| 9833 | case SK_ConstructorInitializationFromList: |
| 9834 | OS << "list initialization via constructor" ; |
| 9835 | break; |
| 9836 | |
| 9837 | case SK_ZeroInitialization: |
| 9838 | OS << "zero initialization" ; |
| 9839 | break; |
| 9840 | |
| 9841 | case SK_CAssignment: |
| 9842 | OS << "C assignment" ; |
| 9843 | break; |
| 9844 | |
| 9845 | case SK_StringInit: |
| 9846 | OS << "string initialization" ; |
| 9847 | break; |
| 9848 | |
| 9849 | case SK_ObjCObjectConversion: |
| 9850 | OS << "Objective-C object conversion" ; |
| 9851 | break; |
| 9852 | |
| 9853 | case SK_ArrayLoopIndex: |
| 9854 | OS << "indexing for array initialization loop" ; |
| 9855 | break; |
| 9856 | |
| 9857 | case SK_ArrayLoopInit: |
| 9858 | OS << "array initialization loop" ; |
| 9859 | break; |
| 9860 | |
| 9861 | case SK_ArrayInit: |
| 9862 | OS << "array initialization" ; |
| 9863 | break; |
| 9864 | |
| 9865 | case SK_GNUArrayInit: |
| 9866 | OS << "array initialization (GNU extension)" ; |
| 9867 | break; |
| 9868 | |
| 9869 | case SK_ParenthesizedArrayInit: |
| 9870 | OS << "parenthesized array initialization" ; |
| 9871 | break; |
| 9872 | |
| 9873 | case SK_PassByIndirectCopyRestore: |
| 9874 | OS << "pass by indirect copy and restore" ; |
| 9875 | break; |
| 9876 | |
| 9877 | case SK_PassByIndirectRestore: |
| 9878 | OS << "pass by indirect restore" ; |
| 9879 | break; |
| 9880 | |
| 9881 | case SK_ProduceObjCObject: |
| 9882 | OS << "Objective-C object retension" ; |
| 9883 | break; |
| 9884 | |
| 9885 | case SK_StdInitializerList: |
| 9886 | OS << "std::initializer_list from initializer list" ; |
| 9887 | break; |
| 9888 | |
| 9889 | case SK_StdInitializerListConstructorCall: |
| 9890 | OS << "list initialization from std::initializer_list" ; |
| 9891 | break; |
| 9892 | |
| 9893 | case SK_OCLSamplerInit: |
| 9894 | OS << "OpenCL sampler_t from integer constant" ; |
| 9895 | break; |
| 9896 | |
| 9897 | case SK_OCLZeroOpaqueType: |
| 9898 | OS << "OpenCL opaque type from zero" ; |
| 9899 | break; |
| 9900 | |
| 9901 | case SK_ParenthesizedListInit: |
| 9902 | OS << "initialization from a parenthesized list of values" ; |
| 9903 | break; |
| 9904 | |
| 9905 | case SK_HLSLBufferConversion: |
| 9906 | OS << "HLSL buffer conversion" ; |
| 9907 | break; |
| 9908 | } |
| 9909 | |
| 9910 | OS << " [" << S->Type << ']'; |
| 9911 | } |
| 9912 | |
| 9913 | OS << '\n'; |
| 9914 | } |
| 9915 | |
| 9916 | void InitializationSequence::dump() const { |
| 9917 | dump(OS&: llvm::errs()); |
| 9918 | } |
| 9919 | |
| 9920 | static void DiagnoseNarrowingInInitList(Sema &S, |
| 9921 | const ImplicitConversionSequence &ICS, |
| 9922 | QualType PreNarrowingType, |
| 9923 | QualType EntityType, |
| 9924 | const Expr *PostInit) { |
| 9925 | const StandardConversionSequence *SCS = nullptr; |
| 9926 | switch (ICS.getKind()) { |
| 9927 | case ImplicitConversionSequence::StandardConversion: |
| 9928 | SCS = &ICS.Standard; |
| 9929 | break; |
| 9930 | case ImplicitConversionSequence::UserDefinedConversion: |
| 9931 | SCS = &ICS.UserDefined.After; |
| 9932 | break; |
| 9933 | case ImplicitConversionSequence::AmbiguousConversion: |
| 9934 | case ImplicitConversionSequence::StaticObjectArgumentConversion: |
| 9935 | case ImplicitConversionSequence::EllipsisConversion: |
| 9936 | case ImplicitConversionSequence::BadConversion: |
| 9937 | return; |
| 9938 | } |
| 9939 | |
| 9940 | auto MakeDiag = [&](bool IsConstRef, unsigned DefaultDiagID, |
| 9941 | unsigned ConstRefDiagID, unsigned WarnDiagID) { |
| 9942 | unsigned DiagID; |
| 9943 | auto &L = S.getLangOpts(); |
| 9944 | if (L.CPlusPlus11 && !L.HLSL && |
| 9945 | (!L.MicrosoftExt || L.isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))) |
| 9946 | DiagID = IsConstRef ? ConstRefDiagID : DefaultDiagID; |
| 9947 | else |
| 9948 | DiagID = WarnDiagID; |
| 9949 | return S.Diag(Loc: PostInit->getBeginLoc(), DiagID) |
| 9950 | << PostInit->getSourceRange(); |
| 9951 | }; |
| 9952 | |
| 9953 | // C++11 [dcl.init.list]p7: Check whether this is a narrowing conversion. |
| 9954 | APValue ConstantValue; |
| 9955 | QualType ConstantType; |
| 9956 | switch (SCS->getNarrowingKind(Context&: S.Context, Converted: PostInit, ConstantValue, |
| 9957 | ConstantType)) { |
| 9958 | case NK_Not_Narrowing: |
| 9959 | case NK_Dependent_Narrowing: |
| 9960 | // No narrowing occurred. |
| 9961 | return; |
| 9962 | |
| 9963 | case NK_Type_Narrowing: { |
| 9964 | // This was a floating-to-integer conversion, which is always considered a |
| 9965 | // narrowing conversion even if the value is a constant and can be |
| 9966 | // represented exactly as an integer. |
| 9967 | QualType T = EntityType.getNonReferenceType(); |
| 9968 | MakeDiag(T != EntityType, diag::ext_init_list_type_narrowing, |
| 9969 | diag::ext_init_list_type_narrowing_const_reference, |
| 9970 | diag::warn_init_list_type_narrowing) |
| 9971 | << PreNarrowingType.getLocalUnqualifiedType() |
| 9972 | << T.getLocalUnqualifiedType(); |
| 9973 | break; |
| 9974 | } |
| 9975 | |
| 9976 | case NK_Constant_Narrowing: { |
| 9977 | // A constant value was narrowed. |
| 9978 | MakeDiag(EntityType.getNonReferenceType() != EntityType, |
| 9979 | diag::ext_init_list_constant_narrowing, |
| 9980 | diag::ext_init_list_constant_narrowing_const_reference, |
| 9981 | diag::warn_init_list_constant_narrowing) |
| 9982 | << ConstantValue.getAsString(Ctx: S.getASTContext(), Ty: ConstantType) |
| 9983 | << EntityType.getNonReferenceType().getLocalUnqualifiedType(); |
| 9984 | break; |
| 9985 | } |
| 9986 | |
| 9987 | case NK_Variable_Narrowing: { |
| 9988 | // A variable's value may have been narrowed. |
| 9989 | MakeDiag(EntityType.getNonReferenceType() != EntityType, |
| 9990 | diag::ext_init_list_variable_narrowing, |
| 9991 | diag::ext_init_list_variable_narrowing_const_reference, |
| 9992 | diag::warn_init_list_variable_narrowing) |
| 9993 | << PreNarrowingType.getLocalUnqualifiedType() |
| 9994 | << EntityType.getNonReferenceType().getLocalUnqualifiedType(); |
| 9995 | break; |
| 9996 | } |
| 9997 | } |
| 9998 | |
| 9999 | SmallString<128> StaticCast; |
| 10000 | llvm::raw_svector_ostream OS(StaticCast); |
| 10001 | OS << "static_cast<" ; |
| 10002 | if (const TypedefType *TT = EntityType->getAs<TypedefType>()) { |
| 10003 | // It's important to use the typedef's name if there is one so that the |
| 10004 | // fixit doesn't break code using types like int64_t. |
| 10005 | // |
| 10006 | // FIXME: This will break if the typedef requires qualification. But |
| 10007 | // getQualifiedNameAsString() includes non-machine-parsable components. |
| 10008 | OS << *TT->getDecl(); |
| 10009 | } else if (const BuiltinType *BT = EntityType->getAs<BuiltinType>()) |
| 10010 | OS << BT->getName(Policy: S.getLangOpts()); |
| 10011 | else { |
| 10012 | // Oops, we didn't find the actual type of the variable. Don't emit a fixit |
| 10013 | // with a broken cast. |
| 10014 | return; |
| 10015 | } |
| 10016 | OS << ">(" ; |
| 10017 | S.Diag(Loc: PostInit->getBeginLoc(), DiagID: diag::note_init_list_narrowing_silence) |
| 10018 | << PostInit->getSourceRange() |
| 10019 | << FixItHint::CreateInsertion(InsertionLoc: PostInit->getBeginLoc(), Code: OS.str()) |
| 10020 | << FixItHint::CreateInsertion( |
| 10021 | InsertionLoc: S.getLocForEndOfToken(Loc: PostInit->getEndLoc()), Code: ")" ); |
| 10022 | } |
| 10023 | |
| 10024 | static void CheckC23ConstexprInitConversion(Sema &S, QualType FromType, |
| 10025 | QualType ToType, Expr *Init) { |
| 10026 | assert(S.getLangOpts().C23); |
| 10027 | ImplicitConversionSequence ICS = S.TryImplicitConversion( |
| 10028 | From: Init->IgnoreParenImpCasts(), ToType, /*SuppressUserConversions*/ false, |
| 10029 | AllowExplicit: Sema::AllowedExplicit::None, |
| 10030 | /*InOverloadResolution*/ false, |
| 10031 | /*CStyle*/ false, |
| 10032 | /*AllowObjCWritebackConversion=*/false); |
| 10033 | |
| 10034 | if (!ICS.isStandard()) |
| 10035 | return; |
| 10036 | |
| 10037 | APValue Value; |
| 10038 | QualType PreNarrowingType; |
| 10039 | // Reuse C++ narrowing check. |
| 10040 | switch (ICS.Standard.getNarrowingKind( |
| 10041 | Context&: S.Context, Converted: Init, ConstantValue&: Value, ConstantType&: PreNarrowingType, |
| 10042 | /*IgnoreFloatToIntegralConversion*/ false)) { |
| 10043 | // The value doesn't fit. |
| 10044 | case NK_Constant_Narrowing: |
| 10045 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_not_representable) |
| 10046 | << Value.getAsString(Ctx: S.Context, Ty: PreNarrowingType) << ToType; |
| 10047 | return; |
| 10048 | |
| 10049 | // Conversion to a narrower type. |
| 10050 | case NK_Type_Narrowing: |
| 10051 | S.Diag(Loc: Init->getBeginLoc(), DiagID: diag::err_c23_constexpr_init_type_mismatch) |
| 10052 | << ToType << FromType; |
| 10053 | return; |
| 10054 | |
| 10055 | // Since we only reuse narrowing check for C23 constexpr variables here, we're |
| 10056 | // not really interested in these cases. |
| 10057 | case NK_Dependent_Narrowing: |
| 10058 | case NK_Variable_Narrowing: |
| 10059 | case NK_Not_Narrowing: |
| 10060 | return; |
| 10061 | } |
| 10062 | llvm_unreachable("unhandled case in switch" ); |
| 10063 | } |
| 10064 | |
| 10065 | static void CheckC23ConstexprInitStringLiteral(const StringLiteral *SE, |
| 10066 | Sema &SemaRef, QualType &TT) { |
| 10067 | assert(SemaRef.getLangOpts().C23); |
| 10068 | // character that string literal contains fits into TT - target type. |
| 10069 | const ArrayType *AT = SemaRef.Context.getAsArrayType(T: TT); |
| 10070 | QualType CharType = AT->getElementType(); |
| 10071 | uint32_t BitWidth = SemaRef.Context.getTypeSize(T: CharType); |
| 10072 | bool isUnsigned = CharType->isUnsignedIntegerType(); |
| 10073 | llvm::APSInt Value(BitWidth, isUnsigned); |
| 10074 | for (unsigned I = 0, N = SE->getLength(); I != N; ++I) { |
| 10075 | int64_t C = SE->getCodeUnitS(I, BitWidth: SemaRef.Context.getCharWidth()); |
| 10076 | Value = C; |
| 10077 | if (Value != C) { |
| 10078 | SemaRef.Diag(Loc: SemaRef.getLocationOfStringLiteralByte(SL: SE, ByteNo: I), |
| 10079 | DiagID: diag::err_c23_constexpr_init_not_representable) |
| 10080 | << C << CharType; |
| 10081 | return; |
| 10082 | } |
| 10083 | } |
| 10084 | } |
| 10085 | |
| 10086 | //===----------------------------------------------------------------------===// |
| 10087 | // Initialization helper functions |
| 10088 | //===----------------------------------------------------------------------===// |
| 10089 | bool |
| 10090 | Sema::CanPerformCopyInitialization(const InitializedEntity &Entity, |
| 10091 | ExprResult Init) { |
| 10092 | if (Init.isInvalid()) |
| 10093 | return false; |
| 10094 | |
| 10095 | Expr *InitE = Init.get(); |
| 10096 | assert(InitE && "No initialization expression" ); |
| 10097 | |
| 10098 | InitializationKind Kind = |
| 10099 | InitializationKind::CreateCopy(InitLoc: InitE->getBeginLoc(), EqualLoc: SourceLocation()); |
| 10100 | InitializationSequence Seq(*this, Entity, Kind, InitE); |
| 10101 | return !Seq.Failed(); |
| 10102 | } |
| 10103 | |
| 10104 | ExprResult |
| 10105 | Sema::PerformCopyInitialization(const InitializedEntity &Entity, |
| 10106 | SourceLocation EqualLoc, |
| 10107 | ExprResult Init, |
| 10108 | bool TopLevelOfInitList, |
| 10109 | bool AllowExplicit) { |
| 10110 | if (Init.isInvalid()) |
| 10111 | return ExprError(); |
| 10112 | |
| 10113 | Expr *InitE = Init.get(); |
| 10114 | assert(InitE && "No initialization expression?" ); |
| 10115 | |
| 10116 | if (EqualLoc.isInvalid()) |
| 10117 | EqualLoc = InitE->getBeginLoc(); |
| 10118 | |
| 10119 | if (Entity.getType().getDesugaredType(Context) == |
| 10120 | Context.AMDGPUFeaturePredicateTy && |
| 10121 | Entity.getDecl()) { |
| 10122 | Diag(Loc: EqualLoc, DiagID: diag::err_amdgcn_predicate_type_is_not_constructible) |
| 10123 | << Entity.getDecl(); |
| 10124 | return ExprError(); |
| 10125 | } |
| 10126 | |
| 10127 | InitializationKind Kind = InitializationKind::CreateCopy( |
| 10128 | InitLoc: InitE->getBeginLoc(), EqualLoc, AllowExplicitConvs: AllowExplicit); |
| 10129 | InitializationSequence Seq(*this, Entity, Kind, InitE, TopLevelOfInitList); |
| 10130 | |
| 10131 | // Prevent infinite recursion when performing parameter copy-initialization. |
| 10132 | const bool ShouldTrackCopy = |
| 10133 | Entity.isParameterKind() && Seq.isConstructorInitialization(); |
| 10134 | if (ShouldTrackCopy) { |
| 10135 | if (llvm::is_contained(Range&: CurrentParameterCopyTypes, Element: Entity.getType())) { |
| 10136 | Seq.SetOverloadFailure( |
| 10137 | Failure: InitializationSequence::FK_ConstructorOverloadFailed, |
| 10138 | Result: OR_No_Viable_Function); |
| 10139 | |
| 10140 | // Try to give a meaningful diagnostic note for the problematic |
| 10141 | // constructor. |
| 10142 | const auto LastStep = Seq.step_end() - 1; |
| 10143 | assert(LastStep->Kind == |
| 10144 | InitializationSequence::SK_ConstructorInitialization); |
| 10145 | const FunctionDecl *Function = LastStep->Function.Function; |
| 10146 | auto Candidate = |
| 10147 | llvm::find_if(Range&: Seq.getFailedCandidateSet(), |
| 10148 | P: [Function](const OverloadCandidate &Candidate) -> bool { |
| 10149 | return Candidate.Viable && |
| 10150 | Candidate.Function == Function && |
| 10151 | Candidate.Conversions.size() > 0; |
| 10152 | }); |
| 10153 | if (Candidate != Seq.getFailedCandidateSet().end() && |
| 10154 | Function->getNumParams() > 0) { |
| 10155 | Candidate->Viable = false; |
| 10156 | Candidate->FailureKind = ovl_fail_bad_conversion; |
| 10157 | Candidate->Conversions[0].setBad(Failure: BadConversionSequence::no_conversion, |
| 10158 | FromExpr: InitE, |
| 10159 | ToType: Function->getParamDecl(i: 0)->getType()); |
| 10160 | } |
| 10161 | } |
| 10162 | CurrentParameterCopyTypes.push_back(Elt: Entity.getType()); |
| 10163 | } |
| 10164 | |
| 10165 | ExprResult Result = Seq.Perform(S&: *this, Entity, Kind, Args: InitE); |
| 10166 | |
| 10167 | if (ShouldTrackCopy) |
| 10168 | CurrentParameterCopyTypes.pop_back(); |
| 10169 | |
| 10170 | return Result; |
| 10171 | } |
| 10172 | |
| 10173 | /// Determine whether RD is, or is derived from, a specialization of CTD. |
| 10174 | static bool isOrIsDerivedFromSpecializationOf(CXXRecordDecl *RD, |
| 10175 | ClassTemplateDecl *CTD) { |
| 10176 | auto NotSpecialization = [&] (const CXXRecordDecl *Candidate) { |
| 10177 | auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Candidate); |
| 10178 | return !CTSD || !declaresSameEntity(D1: CTSD->getSpecializedTemplate(), D2: CTD); |
| 10179 | }; |
| 10180 | return !(NotSpecialization(RD) && RD->forallBases(BaseMatches: NotSpecialization)); |
| 10181 | } |
| 10182 | |
| 10183 | QualType Sema::DeduceTemplateSpecializationFromInitializer( |
| 10184 | TypeSourceInfo *TSInfo, const InitializedEntity &Entity, |
| 10185 | const InitializationKind &Kind, MultiExprArg Inits) { |
| 10186 | auto *DeducedTST = dyn_cast<DeducedTemplateSpecializationType>( |
| 10187 | Val: TSInfo->getType()->getContainedDeducedType()); |
| 10188 | assert(DeducedTST && "not a deduced template specialization type" ); |
| 10189 | |
| 10190 | auto TemplateName = DeducedTST->getTemplateName(); |
| 10191 | if (TemplateName.isDependent()) |
| 10192 | return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType(); |
| 10193 | |
| 10194 | // We can only perform deduction for class templates or alias templates. |
| 10195 | auto *Template = |
| 10196 | dyn_cast_or_null<ClassTemplateDecl>(Val: TemplateName.getAsTemplateDecl()); |
| 10197 | TemplateDecl *LookupTemplateDecl = Template; |
| 10198 | if (!Template) { |
| 10199 | if (auto *AliasTemplate = dyn_cast_or_null<TypeAliasTemplateDecl>( |
| 10200 | Val: TemplateName.getAsTemplateDecl())) { |
| 10201 | DiagCompat(Loc: Kind.getLocation(), CompatDiagId: diag_compat::ctad_for_alias_templates); |
| 10202 | LookupTemplateDecl = AliasTemplate; |
| 10203 | auto UnderlyingType = AliasTemplate->getTemplatedDecl() |
| 10204 | ->getUnderlyingType() |
| 10205 | .getCanonicalType(); |
| 10206 | // C++ [over.match.class.deduct#3]: ..., the defining-type-id of A must be |
| 10207 | // of the form |
| 10208 | // [typename] [nested-name-specifier] [template] simple-template-id |
| 10209 | if (const auto *TST = |
| 10210 | UnderlyingType->getAs<TemplateSpecializationType>()) { |
| 10211 | Template = dyn_cast_or_null<ClassTemplateDecl>( |
| 10212 | Val: TST->getTemplateName().getAsTemplateDecl()); |
| 10213 | } else if (const auto *RT = UnderlyingType->getAs<RecordType>()) { |
| 10214 | // Cases where template arguments in the RHS of the alias are not |
| 10215 | // dependent. e.g. |
| 10216 | // using AliasFoo = Foo<bool>; |
| 10217 | if (const auto *CTSD = |
| 10218 | llvm::dyn_cast<ClassTemplateSpecializationDecl>(Val: RT->getDecl())) |
| 10219 | Template = CTSD->getSpecializedTemplate(); |
| 10220 | } |
| 10221 | } |
| 10222 | } |
| 10223 | if (!Template) { |
| 10224 | Diag(Loc: Kind.getLocation(), |
| 10225 | DiagID: diag::err_deduced_non_class_or_alias_template_specialization_type) |
| 10226 | << (int)getTemplateNameKindForDiagnostics(Name: TemplateName) << TemplateName; |
| 10227 | if (auto *TD = TemplateName.getAsTemplateDecl()) |
| 10228 | NoteTemplateLocation(Decl: *TD); |
| 10229 | return QualType(); |
| 10230 | } |
| 10231 | |
| 10232 | // Can't deduce from dependent arguments. |
| 10233 | if (Expr::hasAnyTypeDependentArguments(Exprs: Inits)) { |
| 10234 | Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(), |
| 10235 | DiagID: diag::warn_cxx14_compat_class_template_argument_deduction) |
| 10236 | << TSInfo->getTypeLoc().getSourceRange() << 0; |
| 10237 | return SubstAutoTypeSourceInfoDependent(TypeWithAuto: TSInfo)->getType(); |
| 10238 | } |
| 10239 | |
| 10240 | // FIXME: Perform "exact type" matching first, per CWG discussion? |
| 10241 | // Or implement this via an implied 'T(T) -> T' deduction guide? |
| 10242 | |
| 10243 | // Look up deduction guides, including those synthesized from constructors. |
| 10244 | // |
| 10245 | // C++1z [over.match.class.deduct]p1: |
| 10246 | // A set of functions and function templates is formed comprising: |
| 10247 | // - For each constructor of the class template designated by the |
| 10248 | // template-name, a function template [...] |
| 10249 | // - For each deduction-guide, a function or function template [...] |
| 10250 | DeclarationNameInfo NameInfo( |
| 10251 | Context.DeclarationNames.getCXXDeductionGuideName(TD: LookupTemplateDecl), |
| 10252 | TSInfo->getTypeLoc().getEndLoc()); |
| 10253 | LookupResult Guides(*this, NameInfo, LookupOrdinaryName); |
| 10254 | LookupQualifiedName(R&: Guides, LookupCtx: LookupTemplateDecl->getDeclContext()); |
| 10255 | |
| 10256 | // FIXME: Do not diagnose inaccessible deduction guides. The standard isn't |
| 10257 | // clear on this, but they're not found by name so access does not apply. |
| 10258 | Guides.suppressDiagnostics(); |
| 10259 | |
| 10260 | // Figure out if this is list-initialization. |
| 10261 | InitListExpr *ListInit = |
| 10262 | (Inits.size() == 1 && Kind.getKind() != InitializationKind::IK_Direct) |
| 10263 | ? dyn_cast<InitListExpr>(Val: Inits[0]) |
| 10264 | : nullptr; |
| 10265 | |
| 10266 | // C++1z [over.match.class.deduct]p1: |
| 10267 | // Initialization and overload resolution are performed as described in |
| 10268 | // [dcl.init] and [over.match.ctor], [over.match.copy], or [over.match.list] |
| 10269 | // (as appropriate for the type of initialization performed) for an object |
| 10270 | // of a hypothetical class type, where the selected functions and function |
| 10271 | // templates are considered to be the constructors of that class type |
| 10272 | // |
| 10273 | // Since we know we're initializing a class type of a type unrelated to that |
| 10274 | // of the initializer, this reduces to something fairly reasonable. |
| 10275 | OverloadCandidateSet Candidates(Kind.getLocation(), |
| 10276 | OverloadCandidateSet::CSK_Normal); |
| 10277 | OverloadCandidateSet::iterator Best; |
| 10278 | |
| 10279 | bool AllowExplicit = !Kind.isCopyInit() || ListInit; |
| 10280 | |
| 10281 | // Return true if the candidate is added successfully, false otherwise. |
| 10282 | auto addDeductionCandidate = [&](FunctionTemplateDecl *TD, |
| 10283 | CXXDeductionGuideDecl *GD, |
| 10284 | DeclAccessPair FoundDecl, |
| 10285 | bool OnlyListConstructors, |
| 10286 | bool AllowAggregateDeductionCandidate) { |
| 10287 | // C++ [over.match.ctor]p1: (non-list copy-initialization from non-class) |
| 10288 | // For copy-initialization, the candidate functions are all the |
| 10289 | // converting constructors (12.3.1) of that class. |
| 10290 | // C++ [over.match.copy]p1: (non-list copy-initialization from class) |
| 10291 | // The converting constructors of T are candidate functions. |
| 10292 | if (!AllowExplicit) { |
| 10293 | // Overload resolution checks whether the deduction guide is declared |
| 10294 | // explicit for us. |
| 10295 | |
| 10296 | // When looking for a converting constructor, deduction guides that |
| 10297 | // could never be called with one argument are not interesting to |
| 10298 | // check or note. |
| 10299 | if (GD->getMinRequiredArguments() > 1 || |
| 10300 | (GD->getNumParams() == 0 && !GD->isVariadic())) |
| 10301 | return; |
| 10302 | } |
| 10303 | |
| 10304 | // C++ [over.match.list]p1.1: (first phase list initialization) |
| 10305 | // Initially, the candidate functions are the initializer-list |
| 10306 | // constructors of the class T |
| 10307 | if (OnlyListConstructors && !isInitListConstructor(Ctor: GD)) |
| 10308 | return; |
| 10309 | |
| 10310 | if (!AllowAggregateDeductionCandidate && |
| 10311 | GD->getDeductionCandidateKind() == DeductionCandidate::Aggregate) |
| 10312 | return; |
| 10313 | |
| 10314 | // C++ [over.match.list]p1.2: (second phase list initialization) |
| 10315 | // the candidate functions are all the constructors of the class T |
| 10316 | // C++ [over.match.ctor]p1: (all other cases) |
| 10317 | // the candidate functions are all the constructors of the class of |
| 10318 | // the object being initialized |
| 10319 | |
| 10320 | // C++ [over.best.ics]p4: |
| 10321 | // When [...] the constructor [...] is a candidate by |
| 10322 | // - [over.match.copy] (in all cases) |
| 10323 | if (TD) { |
| 10324 | |
| 10325 | // As template candidates are not deduced immediately, |
| 10326 | // persist the array in the overload set. |
| 10327 | MutableArrayRef<Expr *> TmpInits = |
| 10328 | Candidates.getPersistentArgsArray(N: Inits.size()); |
| 10329 | |
| 10330 | for (auto [I, E] : llvm::enumerate(First&: Inits)) { |
| 10331 | if (auto *DI = dyn_cast<DesignatedInitExpr>(Val: E)) |
| 10332 | TmpInits[I] = DI->getInit(); |
| 10333 | else |
| 10334 | TmpInits[I] = E; |
| 10335 | } |
| 10336 | |
| 10337 | AddTemplateOverloadCandidate( |
| 10338 | FunctionTemplate: TD, FoundDecl, /*ExplicitArgs=*/ExplicitTemplateArgs: nullptr, Args: TmpInits, CandidateSet&: Candidates, |
| 10339 | /*SuppressUserConversions=*/false, |
| 10340 | /*PartialOverloading=*/false, AllowExplicit, IsADLCandidate: ADLCallKind::NotADL, |
| 10341 | /*PO=*/{}, AggregateCandidateDeduction: AllowAggregateDeductionCandidate); |
| 10342 | } else { |
| 10343 | AddOverloadCandidate(Function: GD, FoundDecl, Args: Inits, CandidateSet&: Candidates, |
| 10344 | /*SuppressUserConversions=*/false, |
| 10345 | /*PartialOverloading=*/false, AllowExplicit); |
| 10346 | } |
| 10347 | }; |
| 10348 | |
| 10349 | bool FoundDeductionGuide = false; |
| 10350 | |
| 10351 | auto TryToResolveOverload = |
| 10352 | [&](bool OnlyListConstructors) -> OverloadingResult { |
| 10353 | Candidates.clear(CSK: OverloadCandidateSet::CSK_Normal); |
| 10354 | bool HasAnyDeductionGuide = false; |
| 10355 | |
| 10356 | auto SynthesizeAggrGuide = [&](InitListExpr *ListInit) { |
| 10357 | auto *Pattern = Template; |
| 10358 | while (Pattern->getInstantiatedFromMemberTemplate()) { |
| 10359 | if (Pattern->isMemberSpecialization()) |
| 10360 | break; |
| 10361 | Pattern = Pattern->getInstantiatedFromMemberTemplate(); |
| 10362 | } |
| 10363 | |
| 10364 | auto *RD = cast<CXXRecordDecl>(Val: Pattern->getTemplatedDecl()); |
| 10365 | if (!(RD->getDefinition() && RD->isAggregate())) |
| 10366 | return; |
| 10367 | QualType Ty = Context.getCanonicalTagType(TD: RD); |
| 10368 | SmallVector<QualType, 8> ElementTypes; |
| 10369 | |
| 10370 | InitListChecker CheckInitList(*this, Entity, ListInit, Ty, ElementTypes); |
| 10371 | if (!CheckInitList.HadError()) { |
| 10372 | // C++ [over.match.class.deduct]p1.8: |
| 10373 | // if e_i is of array type and x_i is a braced-init-list, T_i is an |
| 10374 | // rvalue reference to the declared type of e_i and |
| 10375 | // C++ [over.match.class.deduct]p1.9: |
| 10376 | // if e_i is of array type and x_i is a string-literal, T_i is an |
| 10377 | // lvalue reference to the const-qualified declared type of e_i and |
| 10378 | // C++ [over.match.class.deduct]p1.10: |
| 10379 | // otherwise, T_i is the declared type of e_i |
| 10380 | for (int I = 0, E = ListInit->getNumInits(); |
| 10381 | I < E && !isa<PackExpansionType>(Val: ElementTypes[I]); ++I) |
| 10382 | if (ElementTypes[I]->isArrayType()) { |
| 10383 | if (isa<InitListExpr, DesignatedInitExpr>(Val: ListInit->getInit(Init: I))) |
| 10384 | ElementTypes[I] = Context.getRValueReferenceType(T: ElementTypes[I]); |
| 10385 | else if (isa<StringLiteral>( |
| 10386 | Val: ListInit->getInit(Init: I)->IgnoreParenImpCasts())) |
| 10387 | ElementTypes[I] = |
| 10388 | Context.getLValueReferenceType(T: ElementTypes[I].withConst()); |
| 10389 | } |
| 10390 | |
| 10391 | if (CXXDeductionGuideDecl *GD = |
| 10392 | DeclareAggregateDeductionGuideFromInitList( |
| 10393 | Template: LookupTemplateDecl, ParamTypes: ElementTypes, |
| 10394 | Loc: TSInfo->getTypeLoc().getEndLoc())) { |
| 10395 | auto *TD = GD->getDescribedFunctionTemplate(); |
| 10396 | addDeductionCandidate(TD, GD, DeclAccessPair::make(D: TD, AS: AS_public), |
| 10397 | OnlyListConstructors, |
| 10398 | /*AllowAggregateDeductionCandidate=*/true); |
| 10399 | HasAnyDeductionGuide = true; |
| 10400 | } |
| 10401 | } |
| 10402 | }; |
| 10403 | |
| 10404 | for (auto I = Guides.begin(), E = Guides.end(); I != E; ++I) { |
| 10405 | NamedDecl *D = (*I)->getUnderlyingDecl(); |
| 10406 | if (D->isInvalidDecl()) |
| 10407 | continue; |
| 10408 | |
| 10409 | auto *TD = dyn_cast<FunctionTemplateDecl>(Val: D); |
| 10410 | auto *GD = dyn_cast_if_present<CXXDeductionGuideDecl>( |
| 10411 | Val: TD ? TD->getTemplatedDecl() : dyn_cast<FunctionDecl>(Val: D)); |
| 10412 | if (!GD) |
| 10413 | continue; |
| 10414 | |
| 10415 | if (!GD->isImplicit()) |
| 10416 | HasAnyDeductionGuide = true; |
| 10417 | |
| 10418 | addDeductionCandidate(TD, GD, I.getPair(), OnlyListConstructors, |
| 10419 | /*AllowAggregateDeductionCandidate=*/false); |
| 10420 | } |
| 10421 | |
| 10422 | // C++ [over.match.class.deduct]p1.4: |
| 10423 | // if C is defined and its definition satisfies the conditions for an |
| 10424 | // aggregate class ([dcl.init.aggr]) with the assumption that any |
| 10425 | // dependent base class has no virtual functions and no virtual base |
| 10426 | // classes, and the initializer is a non-empty braced-init-list or |
| 10427 | // parenthesized expression-list, and there are no deduction-guides for |
| 10428 | // C, the set contains an additional function template, called the |
| 10429 | // aggregate deduction candidate, defined as follows. |
| 10430 | if (getLangOpts().CPlusPlus20 && !HasAnyDeductionGuide) { |
| 10431 | if (ListInit && ListInit->getNumInits()) { |
| 10432 | SynthesizeAggrGuide(ListInit); |
| 10433 | } else if (Inits.size()) { // parenthesized expression-list |
| 10434 | // Inits are expressions inside the parentheses. We don't have |
| 10435 | // the parentheses source locations, use the begin/end of Inits as the |
| 10436 | // best heuristic. |
| 10437 | InitListExpr TempListInit(getASTContext(), Inits.front()->getBeginLoc(), |
| 10438 | Inits, Inits.back()->getEndLoc(), |
| 10439 | /*isExplicit=*/false); |
| 10440 | SynthesizeAggrGuide(&TempListInit); |
| 10441 | } |
| 10442 | } |
| 10443 | |
| 10444 | FoundDeductionGuide = FoundDeductionGuide || HasAnyDeductionGuide; |
| 10445 | |
| 10446 | return Candidates.BestViableFunction(S&: *this, Loc: Kind.getLocation(), Best); |
| 10447 | }; |
| 10448 | |
| 10449 | OverloadingResult Result = OR_No_Viable_Function; |
| 10450 | |
| 10451 | // C++11 [over.match.list]p1, per DR1467: for list-initialization, first |
| 10452 | // try initializer-list constructors. |
| 10453 | if (ListInit) { |
| 10454 | bool TryListConstructors = true; |
| 10455 | |
| 10456 | // Try list constructors unless the list is empty and the class has one or |
| 10457 | // more default constructors, in which case those constructors win. |
| 10458 | if (!ListInit->getNumInits()) { |
| 10459 | for (NamedDecl *D : Guides) { |
| 10460 | auto *FD = dyn_cast<FunctionDecl>(Val: D->getUnderlyingDecl()); |
| 10461 | if (FD && FD->getMinRequiredArguments() == 0) { |
| 10462 | TryListConstructors = false; |
| 10463 | break; |
| 10464 | } |
| 10465 | } |
| 10466 | } else if (ListInit->getNumInits() == 1) { |
| 10467 | // C++ [over.match.class.deduct]: |
| 10468 | // As an exception, the first phase in [over.match.list] (considering |
| 10469 | // initializer-list constructors) is omitted if the initializer list |
| 10470 | // consists of a single expression of type cv U, where U is a |
| 10471 | // specialization of C or a class derived from a specialization of C. |
| 10472 | Expr *E = ListInit->getInit(Init: 0); |
| 10473 | auto *RD = E->getType()->getAsCXXRecordDecl(); |
| 10474 | if (!isa<InitListExpr>(Val: E) && RD && |
| 10475 | isCompleteType(Loc: Kind.getLocation(), T: E->getType()) && |
| 10476 | isOrIsDerivedFromSpecializationOf(RD, CTD: Template)) |
| 10477 | TryListConstructors = false; |
| 10478 | } |
| 10479 | |
| 10480 | if (TryListConstructors) |
| 10481 | Result = TryToResolveOverload(/*OnlyListConstructor*/true); |
| 10482 | // Then unwrap the initializer list and try again considering all |
| 10483 | // constructors. |
| 10484 | Inits = MultiExprArg(ListInit->getInits(), ListInit->getNumInits()); |
| 10485 | } |
| 10486 | |
| 10487 | // If list-initialization fails, or if we're doing any other kind of |
| 10488 | // initialization, we (eventually) consider constructors. |
| 10489 | if (Result == OR_No_Viable_Function) |
| 10490 | Result = TryToResolveOverload(/*OnlyListConstructor*/false); |
| 10491 | |
| 10492 | switch (Result) { |
| 10493 | case OR_Ambiguous: |
| 10494 | // FIXME: For list-initialization candidates, it'd usually be better to |
| 10495 | // list why they were not viable when given the initializer list itself as |
| 10496 | // an argument. |
| 10497 | Candidates.NoteCandidates( |
| 10498 | PA: PartialDiagnosticAt( |
| 10499 | Kind.getLocation(), |
| 10500 | PDiag(DiagID: diag::err_deduced_class_template_ctor_ambiguous) |
| 10501 | << TemplateName), |
| 10502 | S&: *this, OCD: OCD_AmbiguousCandidates, Args: Inits); |
| 10503 | return QualType(); |
| 10504 | |
| 10505 | case OR_No_Viable_Function: { |
| 10506 | CXXRecordDecl *Primary = |
| 10507 | cast<ClassTemplateDecl>(Val: Template)->getTemplatedDecl(); |
| 10508 | bool Complete = isCompleteType(Loc: Kind.getLocation(), |
| 10509 | T: Context.getCanonicalTagType(TD: Primary)); |
| 10510 | Candidates.NoteCandidates( |
| 10511 | PA: PartialDiagnosticAt( |
| 10512 | Kind.getLocation(), |
| 10513 | PDiag(DiagID: Complete ? diag::err_deduced_class_template_ctor_no_viable |
| 10514 | : diag::err_deduced_class_template_incomplete) |
| 10515 | << TemplateName << !Guides.empty()), |
| 10516 | S&: *this, OCD: OCD_AllCandidates, Args: Inits); |
| 10517 | return QualType(); |
| 10518 | } |
| 10519 | |
| 10520 | case OR_Deleted: { |
| 10521 | // FIXME: There are no tests for this diagnostic, and it doesn't seem |
| 10522 | // like we ever get here; attempts to trigger this seem to yield a |
| 10523 | // generic c'all to deleted function' diagnostic instead. |
| 10524 | Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_deleted) |
| 10525 | << TemplateName; |
| 10526 | NoteDeletedFunction(FD: Best->Function); |
| 10527 | return QualType(); |
| 10528 | } |
| 10529 | |
| 10530 | case OR_Success: |
| 10531 | // C++ [over.match.list]p1: |
| 10532 | // In copy-list-initialization, if an explicit constructor is chosen, the |
| 10533 | // initialization is ill-formed. |
| 10534 | if (Kind.isCopyInit() && ListInit && |
| 10535 | cast<CXXDeductionGuideDecl>(Val: Best->Function)->isExplicit()) { |
| 10536 | bool IsDeductionGuide = !Best->Function->isImplicit(); |
| 10537 | Diag(Loc: Kind.getLocation(), DiagID: diag::err_deduced_class_template_explicit) |
| 10538 | << TemplateName << IsDeductionGuide; |
| 10539 | Diag(Loc: Best->Function->getLocation(), |
| 10540 | DiagID: diag::note_explicit_ctor_deduction_guide_here) |
| 10541 | << IsDeductionGuide; |
| 10542 | return QualType(); |
| 10543 | } |
| 10544 | |
| 10545 | // Make sure we didn't select an unusable deduction guide, and mark it |
| 10546 | // as referenced. |
| 10547 | DiagnoseUseOfDecl(D: Best->Function, Locs: Kind.getLocation()); |
| 10548 | MarkFunctionReferenced(Loc: Kind.getLocation(), Func: Best->Function); |
| 10549 | break; |
| 10550 | } |
| 10551 | |
| 10552 | // C++ [dcl.type.class.deduct]p1: |
| 10553 | // The placeholder is replaced by the return type of the function selected |
| 10554 | // by overload resolution for class template deduction. |
| 10555 | QualType DeducedType = |
| 10556 | SubstAutoTypeSourceInfo(TypeWithAuto: TSInfo, Replacement: Best->Function->getReturnType()) |
| 10557 | ->getType(); |
| 10558 | Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(), |
| 10559 | DiagID: diag::warn_cxx14_compat_class_template_argument_deduction) |
| 10560 | << TSInfo->getTypeLoc().getSourceRange() << 1 << DeducedType; |
| 10561 | |
| 10562 | // Warn if CTAD was used on a type that does not have any user-defined |
| 10563 | // deduction guides. |
| 10564 | if (!FoundDeductionGuide) { |
| 10565 | Diag(Loc: TSInfo->getTypeLoc().getBeginLoc(), |
| 10566 | DiagID: diag::warn_ctad_maybe_unsupported) |
| 10567 | << TemplateName; |
| 10568 | Diag(Loc: Template->getLocation(), DiagID: diag::note_suppress_ctad_maybe_unsupported); |
| 10569 | } |
| 10570 | |
| 10571 | return DeducedType; |
| 10572 | } |
| 10573 | |