Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaInit.cpp
Line
Count
Source (jump to first uncovered line)
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 "clang/AST/ASTContext.h"
14
#include "clang/AST/DeclObjC.h"
15
#include "clang/AST/ExprCXX.h"
16
#include "clang/AST/ExprObjC.h"
17
#include "clang/AST/ExprOpenMP.h"
18
#include "clang/AST/TypeLoc.h"
19
#include "clang/Basic/CharInfo.h"
20
#include "clang/Basic/SourceManager.h"
21
#include "clang/Basic/TargetInfo.h"
22
#include "clang/Sema/Designator.h"
23
#include "clang/Sema/Initialization.h"
24
#include "clang/Sema/Lookup.h"
25
#include "clang/Sema/SemaInternal.h"
26
#include "llvm/ADT/APInt.h"
27
#include "llvm/ADT/PointerIntPair.h"
28
#include "llvm/ADT/SmallString.h"
29
#include "llvm/Support/ErrorHandling.h"
30
#include "llvm/Support/raw_ostream.h"
31
32
using namespace clang;
33
34
//===----------------------------------------------------------------------===//
35
// Sema Initialization Checking
36
//===----------------------------------------------------------------------===//
37
38
/// Check whether T is compatible with a wide character type (wchar_t,
39
/// char16_t or char32_t).
40
1.07k
static bool IsWideCharCompatible(QualType T, ASTContext &Context) {
41
1.07k
  if (Context.typesAreCompatible(Context.getWideCharType(), T))
42
69
    return true;
43
1.00k
  if (Context.getLangOpts().CPlusPlus || 
Context.getLangOpts().C11163
) {
44
995
    return Context.typesAreCompatible(Context.Char16Ty, T) ||
45
995
           
Context.typesAreCompatible(Context.Char32Ty, T)950
;
46
995
  }
47
12
  return false;
48
1.00k
}
49
50
enum StringInitFailureKind {
51
  SIF_None,
52
  SIF_NarrowStringIntoWideChar,
53
  SIF_WideStringIntoChar,
54
  SIF_IncompatWideStringIntoWideChar,
55
  SIF_UTF8StringIntoPlainChar,
56
  SIF_PlainStringIntoUTF8Char,
57
  SIF_Other
58
};
59
60
/// Check whether the array of type AT can be initialized by the Init
61
/// expression by means of string initialization. Returns SIF_None if so,
62
/// otherwise returns a StringInitFailureKind that describes why the
63
/// initialization would not work.
64
static StringInitFailureKind IsStringInit(Expr *Init, const ArrayType *AT,
65
44.1k
                                          ASTContext &Context) {
66
44.1k
  if (!isa<ConstantArrayType>(AT) && 
!isa<IncompleteArrayType>(AT)11.3k
)
67
20
    return SIF_Other;
68
69
  // See if this is a string literal or @encode.
70
44.0k
  Init = Init->IgnoreParens();
71
72
  // Handle @encode, which is a narrow string.
73
44.0k
  if (isa<ObjCEncodeExpr>(Init) && 
AT->getElementType()->isCharType()105
)
74
102
    return SIF_None;
75
76
  // Otherwise we can only handle string literals.
77
43.9k
  StringLiteral *SL = dyn_cast<StringLiteral>(Init);
78
43.9k
  if (!SL)
79
40.7k
    return SIF_Other;
80
81
3.19k
  const QualType ElemTy =
82
3.19k
      Context.getCanonicalType(AT->getElementType()).getUnqualifiedType();
83
84
3.19k
  switch (SL->getKind()) {
85
32
  case StringLiteral::UTF8:
86
    // char8_t array can be initialized with a UTF-8 string.
87
32
    if (ElemTy->isChar8Type())
88
13
      return SIF_None;
89
32
    
LLVM_FALLTHROUGH19
;19
90
2.91k
  case StringLiteral::Ordinary:
91
    // char array can be initialized with a narrow string.
92
    // Only allow char x[] = "foo";  not char x[] = L"foo";
93
2.91k
    if (ElemTy->isCharType())
94
2.58k
      return (SL->getKind() == StringLiteral::UTF8 &&
95
2.58k
              
Context.getLangOpts().Char88
)
96
2.58k
                 ? 
SIF_UTF8StringIntoPlainChar3
97
2.58k
                 : 
SIF_None2.58k
;
98
330
    if (ElemTy->isChar8Type())
99
2
      return SIF_PlainStringIntoUTF8Char;
100
328
    if (IsWideCharCompatible(ElemTy, Context))
101
82
      return SIF_NarrowStringIntoWideChar;
102
246
    return SIF_Other;
103
  // C99 6.7.8p15 (with correction from DR343), or C11 6.7.9p15:
104
  // "An array with element type compatible with a qualified or unqualified
105
  // version of wchar_t, char16_t, or char32_t may be initialized by a wide
106
  // string literal with the corresponding encoding prefix (L, u, or U,
107
  // respectively), optionally enclosed in braces.
108
69
  case StringLiteral::UTF16:
109
69
    if (Context.typesAreCompatible(Context.Char16Ty, ElemTy))
110
33
      return SIF_None;
111
36
    if (ElemTy->isCharType() || 
ElemTy->isChar8Type()25
)
112
11
      return SIF_WideStringIntoChar;
113
25
    if (IsWideCharCompatible(ElemTy, Context))
114
23
      return SIF_IncompatWideStringIntoWideChar;
115
2
    return SIF_Other;
116
65
  case StringLiteral::UTF32:
117
65
    if (Context.typesAreCompatible(Context.Char32Ty, ElemTy))
118
29
      return SIF_None;
119
36
    if (ElemTy->isCharType() || 
ElemTy->isChar8Type()25
)
120
11
      return SIF_WideStringIntoChar;
121
25
    if (IsWideCharCompatible(ElemTy, Context))
122
23
      return SIF_IncompatWideStringIntoWideChar;
123
2
    return SIF_Other;
124
133
  case StringLiteral::Wide:
125
133
    if (Context.typesAreCompatible(Context.getWideCharType(), ElemTy))
126
89
      return SIF_None;
127
44
    if (ElemTy->isCharType() || 
ElemTy->isChar8Type()31
)
128
13
      return SIF_WideStringIntoChar;
129
31
    if (IsWideCharCompatible(ElemTy, Context))
130
22
      return SIF_IncompatWideStringIntoWideChar;
131
9
    return SIF_Other;
132
3.19k
  }
133
134
0
  llvm_unreachable("missed a StringLiteral kind?");
135
0
}
136
137
static StringInitFailureKind IsStringInit(Expr *init, QualType declType,
138
4.04k
                                          ASTContext &Context) {
139
4.04k
  const ArrayType *arrayType = Context.getAsArrayType(declType);
140
4.04k
  if (!arrayType)
141
2.25k
    return SIF_Other;
142
1.79k
  return IsStringInit(init, arrayType, Context);
143
4.04k
}
144
145
239
bool Sema::IsStringInit(Expr *Init, const ArrayType *AT) {
146
239
  return ::IsStringInit(Init, AT, Context) == SIF_None;
147
239
}
148
149
/// Update the type of a string literal, including any surrounding parentheses,
150
/// to match the type of the object which it is initializing.
151
2.41k
static void updateStringLiteralType(Expr *E, QualType Ty) {
152
2.46k
  while (true) {
153
2.46k
    E->setType(Ty);
154
2.46k
    E->setValueKind(VK_PRValue);
155
2.46k
    if (isa<StringLiteral>(E) || 
isa<ObjCEncodeExpr>(E)143
) {
156
2.41k
      break;
157
2.41k
    } else 
if (ParenExpr *50
PE50
= dyn_cast<ParenExpr>(E)) {
158
44
      E = PE->getSubExpr();
159
44
    } else 
if (UnaryOperator *6
UO6
= dyn_cast<UnaryOperator>(E)) {
160
4
      assert(UO->getOpcode() == UO_Extension);
161
0
      E = UO->getSubExpr();
162
4
    } else 
if (GenericSelectionExpr *2
GSE2
= dyn_cast<GenericSelectionExpr>(E)) {
163
2
      E = GSE->getResultExpr();
164
2
    } else 
if (ChooseExpr *0
CE0
= dyn_cast<ChooseExpr>(E)) {
165
0
      E = CE->getChosenSubExpr();
166
0
    } else {
167
0
      llvm_unreachable("unexpected expr in string literal init");
168
0
    }
169
2.46k
  }
170
2.41k
}
171
172
/// Fix a compound literal initializing an array so it's correctly marked
173
/// as an rvalue.
174
21
static void updateGNUCompoundLiteralRValue(Expr *E) {
175
27
  while (true) {
176
27
    E->setValueKind(VK_PRValue);
177
27
    if (isa<CompoundLiteralExpr>(E)) {
178
21
      break;
179
21
    } else 
if (ParenExpr *6
PE6
= dyn_cast<ParenExpr>(E)) {
180
3
      E = PE->getSubExpr();
181
3
    } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
182
1
      assert(UO->getOpcode() == UO_Extension);
183
0
      E = UO->getSubExpr();
184
2
    } else if (GenericSelectionExpr *GSE = dyn_cast<GenericSelectionExpr>(E)) {
185
1
      E = GSE->getResultExpr();
186
1
    } else if (ChooseExpr *CE = dyn_cast<ChooseExpr>(E)) {
187
1
      E = CE->getChosenSubExpr();
188
1
    } else {
189
0
      llvm_unreachable("unexpected expr in array compound literal init");
190
0
    }
191
27
  }
192
21
}
193
194
static void CheckStringInit(Expr *Str, QualType &DeclT, const ArrayType *AT,
195
2.41k
                            Sema &S) {
196
  // Get the length of the string as parsed.
197
2.41k
  auto *ConstantArrayTy =
198
2.41k
      cast<ConstantArrayType>(Str->getType()->getAsArrayTypeUnsafe());
199
2.41k
  uint64_t StrLength = ConstantArrayTy->getSize().getZExtValue();
200
201
2.41k
  if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
202
    // C99 6.7.8p14. We have an array of character type with unknown size
203
    // being initialized to a string literal.
204
1.95k
    llvm::APInt ConstVal(32, StrLength);
205
    // Return a new array type (C99 6.7.8p22).
206
1.95k
    DeclT = S.Context.getConstantArrayType(IAT->getElementType(),
207
1.95k
                                           ConstVal, nullptr,
208
1.95k
                                           ArrayType::Normal, 0);
209
1.95k
    updateStringLiteralType(Str, DeclT);
210
1.95k
    return;
211
1.95k
  }
212
213
468
  const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
214
215
  // We have an array of character type with known size.  However,
216
  // the size may be smaller or larger than the string we are initializing.
217
  // FIXME: Avoid truncation for 64-bit length strings.
218
468
  if (S.getLangOpts().CPlusPlus) {
219
176
    if (StringLiteral *SL = dyn_cast<StringLiteral>(Str->IgnoreParens())) {
220
      // For Pascal strings it's OK to strip off the terminating null character,
221
      // so the example below is valid:
222
      //
223
      // unsigned char a[2] = "\pa";
224
175
      if (SL->isPascal())
225
5
        StrLength--;
226
175
    }
227
228
    // [dcl.init.string]p2
229
176
    if (StrLength > CAT->getSize().getZExtValue())
230
4
      S.Diag(Str->getBeginLoc(),
231
4
             diag::err_initializer_string_for_char_array_too_long)
232
4
          << Str->getSourceRange();
233
292
  } else {
234
    // C99 6.7.8p14.
235
292
    if (StrLength-1 > CAT->getSize().getZExtValue())
236
27
      S.Diag(Str->getBeginLoc(),
237
27
             diag::ext_initializer_string_for_char_array_too_long)
238
27
          << Str->getSourceRange();
239
292
  }
240
241
  // Set the type to the actual size that we are initializing.  If we have
242
  // something like:
243
  //   char x[1] = "foo";
244
  // then this will set the string literal's type to char[1].
245
468
  updateStringLiteralType(Str, DeclT);
246
468
}
247
248
//===----------------------------------------------------------------------===//
249
// Semantic checking for initializer lists.
250
//===----------------------------------------------------------------------===//
251
252
namespace {
253
254
/// Semantic checking for initializer lists.
255
///
256
/// The InitListChecker class contains a set of routines that each
257
/// handle the initialization of a certain kind of entity, e.g.,
258
/// arrays, vectors, struct/union types, scalars, etc. The
259
/// InitListChecker itself performs a recursive walk of the subobject
260
/// structure of the type to be initialized, while stepping through
261
/// the initializer list one element at a time. The IList and Index
262
/// parameters to each of the Check* routines contain the active
263
/// (syntactic) initializer list and the index into that initializer
264
/// list that represents the current initializer. Each routine is
265
/// responsible for moving that Index forward as it consumes elements.
266
///
267
/// Each Check* routine also has a StructuredList/StructuredIndex
268
/// arguments, which contains the current "structured" (semantic)
269
/// initializer list and the index into that initializer list where we
270
/// are copying initializers as we map them over to the semantic
271
/// list. Once we have completed our recursive walk of the subobject
272
/// structure, we will have constructed a full semantic initializer
273
/// list.
274
///
275
/// C99 designators cause changes in the initializer list traversal,
276
/// because they make the initialization "jump" into a specific
277
/// subobject and then continue the initialization from that
278
/// point. CheckDesignatedInitializer() recursively steps into the
279
/// designated subobject and manages backing out the recursion to
280
/// initialize the subobjects after the one designated.
281
///
282
/// If an initializer list contains any designators, we build a placeholder
283
/// structured list even in 'verify only' mode, so that we can track which
284
/// elements need 'empty' initializtion.
285
class InitListChecker {
286
  Sema &SemaRef;
287
  bool hadError = false;
288
  bool VerifyOnly; // No diagnostics.
289
  bool TreatUnavailableAsInvalid; // Used only in VerifyOnly mode.
290
  bool InOverloadResolution;
291
  InitListExpr *FullyStructuredList = nullptr;
292
  NoInitExpr *DummyExpr = nullptr;
293
294
309k
  NoInitExpr *getDummyInit() {
295
309k
    if (!DummyExpr)
296
55.5k
      DummyExpr = new (SemaRef.Context) NoInitExpr(SemaRef.Context.VoidTy);
297
309k
    return DummyExpr;
298
309k
  }
299
300
  void CheckImplicitInitList(const InitializedEntity &Entity,
301
                             InitListExpr *ParentIList, QualType T,
302
                             unsigned &Index, InitListExpr *StructuredList,
303
                             unsigned &StructuredIndex);
304
  void CheckExplicitInitList(const InitializedEntity &Entity,
305
                             InitListExpr *IList, QualType &T,
306
                             InitListExpr *StructuredList,
307
                             bool TopLevelObject = false);
308
  void CheckListElementTypes(const InitializedEntity &Entity,
309
                             InitListExpr *IList, QualType &DeclType,
310
                             bool SubobjectIsDesignatorContext,
311
                             unsigned &Index,
312
                             InitListExpr *StructuredList,
313
                             unsigned &StructuredIndex,
314
                             bool TopLevelObject = false);
315
  void CheckSubElementType(const InitializedEntity &Entity,
316
                           InitListExpr *IList, QualType ElemType,
317
                           unsigned &Index,
318
                           InitListExpr *StructuredList,
319
                           unsigned &StructuredIndex,
320
                           bool DirectlyDesignated = false);
321
  void CheckComplexType(const InitializedEntity &Entity,
322
                        InitListExpr *IList, QualType DeclType,
323
                        unsigned &Index,
324
                        InitListExpr *StructuredList,
325
                        unsigned &StructuredIndex);
326
  void CheckScalarType(const InitializedEntity &Entity,
327
                       InitListExpr *IList, QualType DeclType,
328
                       unsigned &Index,
329
                       InitListExpr *StructuredList,
330
                       unsigned &StructuredIndex);
331
  void CheckReferenceType(const InitializedEntity &Entity,
332
                          InitListExpr *IList, QualType DeclType,
333
                          unsigned &Index,
334
                          InitListExpr *StructuredList,
335
                          unsigned &StructuredIndex);
336
  void CheckVectorType(const InitializedEntity &Entity,
337
                       InitListExpr *IList, QualType DeclType, unsigned &Index,
338
                       InitListExpr *StructuredList,
339
                       unsigned &StructuredIndex);
340
  void CheckStructUnionTypes(const InitializedEntity &Entity,
341
                             InitListExpr *IList, QualType DeclType,
342
                             CXXRecordDecl::base_class_range Bases,
343
                             RecordDecl::field_iterator Field,
344
                             bool SubobjectIsDesignatorContext, unsigned &Index,
345
                             InitListExpr *StructuredList,
346
                             unsigned &StructuredIndex,
347
                             bool TopLevelObject = false);
348
  void CheckArrayType(const InitializedEntity &Entity,
349
                      InitListExpr *IList, QualType &DeclType,
350
                      llvm::APSInt elementIndex,
351
                      bool SubobjectIsDesignatorContext, unsigned &Index,
352
                      InitListExpr *StructuredList,
353
                      unsigned &StructuredIndex);
354
  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
355
                                  InitListExpr *IList, DesignatedInitExpr *DIE,
356
                                  unsigned DesigIdx,
357
                                  QualType &CurrentObjectType,
358
                                  RecordDecl::field_iterator *NextField,
359
                                  llvm::APSInt *NextElementIndex,
360
                                  unsigned &Index,
361
                                  InitListExpr *StructuredList,
362
                                  unsigned &StructuredIndex,
363
                                  bool FinishSubobjectInit,
364
                                  bool TopLevelObject);
365
  InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
366
                                           QualType CurrentObjectType,
367
                                           InitListExpr *StructuredList,
368
                                           unsigned StructuredIndex,
369
                                           SourceRange InitRange,
370
                                           bool IsFullyOverwritten = false);
371
  void UpdateStructuredListElement(InitListExpr *StructuredList,
372
                                   unsigned &StructuredIndex,
373
                                   Expr *expr);
374
  InitListExpr *createInitListExpr(QualType CurrentObjectType,
375
                                   SourceRange InitRange,
376
                                   unsigned ExpectedNumInits);
377
  int numArrayElements(QualType DeclType);
378
  int numStructUnionElements(QualType DeclType);
379
380
  ExprResult PerformEmptyInit(SourceLocation Loc,
381
                              const InitializedEntity &Entity);
382
383
  /// Diagnose that OldInit (or part thereof) has been overridden by NewInit.
384
  void diagnoseInitOverride(Expr *OldInit, SourceRange NewInitRange,
385
403
                            bool FullyOverwritten = true) {
386
    // Overriding an initializer via a designator is valid with C99 designated
387
    // initializers, but ill-formed with C++20 designated initializers.
388
403
    unsigned DiagID = SemaRef.getLangOpts().CPlusPlus
389
403
                          ? 
diag::ext_initializer_overrides226
390
403
                          : 
diag::warn_initializer_overrides177
;
391
392
403
    if (InOverloadResolution && 
SemaRef.getLangOpts().CPlusPlus12
) {
393
      // In overload resolution, we have to strictly enforce the rules, and so
394
      // don't allow any overriding of prior initializers. This matters for a
395
      // case such as:
396
      //
397
      //   union U { int a, b; };
398
      //   struct S { int a, b; };
399
      //   void f(U), f(S);
400
      //
401
      // Here, f({.a = 1, .b = 2}) is required to call the struct overload. For
402
      // consistency, we disallow all overriding of prior initializers in
403
      // overload resolution, not only overriding of union members.
404
12
      hadError = true;
405
391
    } else if (OldInit->getType().isDestructedType() && 
!FullyOverwritten4
) {
406
      // If we'll be keeping around the old initializer but overwriting part of
407
      // the object it initialized, and that object is not trivially
408
      // destructible, this can leak. Don't allow that, not even as an
409
      // extension.
410
      //
411
      // FIXME: It might be reasonable to allow this in cases where the part of
412
      // the initializer that we're overriding has trivial destruction.
413
4
      DiagID = diag::err_initializer_overrides_destructed;
414
387
    } else if (!OldInit->getSourceRange().isValid()) {
415
      // We need to check on source range validity because the previous
416
      // initializer does not have to be an explicit initializer. e.g.,
417
      //
418
      // struct P { int a, b; };
419
      // struct PP { struct P p } l = { { .a = 2 }, .p.b = 3 };
420
      //
421
      // There is an overwrite taking place because the first braced initializer
422
      // list "{ .a = 2 }" already provides value for .p.b (which is zero).
423
      //
424
      // Such overwrites are harmless, so we don't diagnose them. (Note that in
425
      // C++, this cannot be reached unless we've already seen and diagnosed a
426
      // different conformance issue, such as a mixture of designated and
427
      // non-designated initializers or a multi-level designator.)
428
153
      return;
429
153
    }
430
431
250
    if (!VerifyOnly) {
432
189
      SemaRef.Diag(NewInitRange.getBegin(), DiagID)
433
189
          << NewInitRange << FullyOverwritten << OldInit->getType();
434
189
      SemaRef.Diag(OldInit->getBeginLoc(), diag::note_previous_initializer)
435
189
          << (OldInit->HasSideEffects(SemaRef.Context) && 
FullyOverwritten17
)
436
189
          << OldInit->getSourceRange();
437
189
    }
438
250
  }
439
440
  // Explanation on the "FillWithNoInit" mode:
441
  //
442
  // Assume we have the following definitions (Case#1):
443
  // struct P { char x[6][6]; } xp = { .x[1] = "bar" };
444
  // struct PP { struct P lp; } l = { .lp = xp, .lp.x[1][2] = 'f' };
445
  //
446
  // l.lp.x[1][0..1] should not be filled with implicit initializers because the
447
  // "base" initializer "xp" will provide values for them; l.lp.x[1] will be "baf".
448
  //
449
  // But if we have (Case#2):
450
  // struct PP l = { .lp = xp, .lp.x[1] = { [2] = 'f' } };
451
  //
452
  // l.lp.x[1][0..1] are implicitly initialized and do not use values from the
453
  // "base" initializer; l.lp.x[1] will be "\0\0f\0\0\0".
454
  //
455
  // To distinguish Case#1 from Case#2, and also to avoid leaving many "holes"
456
  // in the InitListExpr, the "holes" in Case#1 are filled not with empty
457
  // initializers but with special "NoInitExpr" place holders, which tells the
458
  // CodeGen not to generate any initializers for these parts.
459
  void FillInEmptyInitForBase(unsigned Init, const CXXBaseSpecifier &Base,
460
                              const InitializedEntity &ParentEntity,
461
                              InitListExpr *ILE, bool &RequiresSecondPass,
462
                              bool FillWithNoInit);
463
  void FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
464
                               const InitializedEntity &ParentEntity,
465
                               InitListExpr *ILE, bool &RequiresSecondPass,
466
                               bool FillWithNoInit = false);
467
  void FillInEmptyInitializations(const InitializedEntity &Entity,
468
                                  InitListExpr *ILE, bool &RequiresSecondPass,
469
                                  InitListExpr *OuterILE, unsigned OuterIndex,
470
                                  bool FillWithNoInit = false);
471
  bool CheckFlexibleArrayInit(const InitializedEntity &Entity,
472
                              Expr *InitExpr, FieldDecl *Field,
473
                              bool TopLevelObject);
474
  void CheckEmptyInitializable(const InitializedEntity &Entity,
475
                               SourceLocation Loc);
476
477
public:
478
  InitListChecker(Sema &S, const InitializedEntity &Entity, InitListExpr *IL,
479
                  QualType &T, bool VerifyOnly, bool TreatUnavailableAsInvalid,
480
                  bool InOverloadResolution = false);
481
200k
  bool HadError() { return hadError; }
482
483
  // Retrieves the fully-structured initializer list used for
484
  // semantic analysis and code generation.
485
96.1k
  InitListExpr *getFullyStructuredList() const { return FullyStructuredList; }
486
};
487
488
} // end anonymous namespace
489
490
ExprResult InitListChecker::PerformEmptyInit(SourceLocation Loc,
491
33.1k
                                             const InitializedEntity &Entity) {
492
33.1k
  InitializationKind Kind = InitializationKind::CreateValue(Loc, Loc, Loc,
493
33.1k
                                                            true);
494
33.1k
  MultiExprArg SubInit;
495
33.1k
  Expr *InitExpr;
496
33.1k
  InitListExpr DummyInitList(SemaRef.Context, Loc, None, Loc);
497
498
  // C++ [dcl.init.aggr]p7:
499
  //   If there are fewer initializer-clauses in the list than there are
500
  //   members in the aggregate, then each member not explicitly initialized
501
  //   ...
502
33.1k
  bool EmptyInitList = SemaRef.getLangOpts().CPlusPlus11 &&
503
33.1k
      
Entity.getType()->getBaseElementTypeUnsafe()->isRecordType()24.0k
;
504
33.1k
  if (EmptyInitList) {
505
    // C++1y / DR1070:
506
    //   shall be initialized [...] from an empty initializer list.
507
    //
508
    // We apply the resolution of this DR to C++11 but not C++98, since C++98
509
    // does not have useful semantics for initialization from an init list.
510
    // We treat this as copy-initialization, because aggregate initialization
511
    // always performs copy-initialization on its elements.
512
    //
513
    // Only do this if we're initializing a class type, to avoid filling in
514
    // the initializer list where possible.
515
2.00k
    InitExpr = VerifyOnly ? 
&DummyInitList1.18k
: new (SemaRef.Context)
516
820
                   InitListExpr(SemaRef.Context, Loc, None, Loc);
517
2.00k
    InitExpr->setType(SemaRef.Context.VoidTy);
518
2.00k
    SubInit = InitExpr;
519
2.00k
    Kind = InitializationKind::CreateCopy(Loc, Loc);
520
31.1k
  } else {
521
    // C++03:
522
    //   shall be value-initialized.
523
31.1k
  }
524
525
33.1k
  InitializationSequence InitSeq(SemaRef, Entity, Kind, SubInit);
526
  // libstdc++4.6 marks the vector default constructor as explicit in
527
  // _GLIBCXX_DEBUG mode, so recover using the C++03 logic in that case.
528
  // stlport does so too. Look for std::__debug for libstdc++, and for
529
  // std:: for stlport.  This is effectively a compiler-side implementation of
530
  // LWG2193.
531
33.1k
  if (!InitSeq && 
EmptyInitList78
&& InitSeq.getFailureKind() ==
532
67
          InitializationSequence::FK_ExplicitConstructor) {
533
5
    OverloadCandidateSet::iterator Best;
534
5
    OverloadingResult O =
535
5
        InitSeq.getFailedCandidateSet()
536
5
            .BestViableFunction(SemaRef, Kind.getLocation(), Best);
537
5
    (void)O;
538
5
    assert(O == OR_Success && "Inconsistent overload resolution");
539
0
    CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
540
5
    CXXRecordDecl *R = CtorDecl->getParent();
541
542
5
    if (CtorDecl->getMinRequiredArguments() == 0 &&
543
5
        CtorDecl->isExplicit() && R->getDeclName() &&
544
5
        SemaRef.SourceMgr.isInSystemHeader(CtorDecl->getLocation())) {
545
5
      bool IsInStd = false;
546
5
      for (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(R->getDeclContext());
547
15
           ND && 
!IsInStd10
;
ND = dyn_cast<NamespaceDecl>(ND->getParent())10
) {
548
10
        if (SemaRef.getStdNamespace()->InEnclosingNamespaceSetOf(ND))
549
5
          IsInStd = true;
550
10
      }
551
552
5
      if (IsInStd && llvm::StringSwitch<bool>(R->getName())
553
5
              .Cases("basic_string", "deque", "forward_list", true)
554
5
              .Cases("list", "map", "multimap", "multiset", true)
555
5
              .Cases("priority_queue", "queue", "set", "stack", true)
556
5
              .Cases("unordered_map", "unordered_set", "vector", true)
557
5
              .Default(false)) {
558
5
        InitSeq.InitializeFrom(
559
5
            SemaRef, Entity,
560
5
            InitializationKind::CreateValue(Loc, Loc, Loc, true),
561
5
            MultiExprArg(), /*TopLevelOfInitList=*/false,
562
5
            TreatUnavailableAsInvalid);
563
        // Emit a warning for this.  System header warnings aren't shown
564
        // by default, but people working on system headers should see it.
565
5
        if (!VerifyOnly) {
566
2
          SemaRef.Diag(CtorDecl->getLocation(),
567
2
                       diag::warn_invalid_initializer_from_system_header);
568
2
          if (Entity.getKind() == InitializedEntity::EK_Member)
569
1
            SemaRef.Diag(Entity.getDecl()->getLocation(),
570
1
                         diag::note_used_in_initialization_here);
571
1
          else if (Entity.getKind() == InitializedEntity::EK_ArrayElement)
572
1
            SemaRef.Diag(Loc, diag::note_used_in_initialization_here);
573
2
        }
574
5
      }
575
5
    }
576
5
  }
577
33.1k
  if (!InitSeq) {
578
73
    if (!VerifyOnly) {
579
31
      InitSeq.Diagnose(SemaRef, Entity, Kind, SubInit);
580
31
      if (Entity.getKind() == InitializedEntity::EK_Member)
581
12
        SemaRef.Diag(Entity.getDecl()->getLocation(),
582
12
                     diag::note_in_omitted_aggregate_initializer)
583
12
          << /*field*/1 << Entity.getDecl();
584
19
      else if (Entity.getKind() == InitializedEntity::EK_ArrayElement) {
585
17
        bool IsTrailingArrayNewMember =
586
17
            Entity.getParent() &&
587
17
            Entity.getParent()->isVariableLengthArrayNew();
588
17
        SemaRef.Diag(Loc, diag::note_in_omitted_aggregate_initializer)
589
17
          << (IsTrailingArrayNewMember ? 
24
: /*array element*/
013
)
590
17
          << Entity.getElementIndex();
591
17
      }
592
31
    }
593
73
    hadError = true;
594
73
    return ExprError();
595
73
  }
596
597
33.0k
  return VerifyOnly ? 
ExprResult()14.6k
598
33.0k
                    : 
InitSeq.Perform(SemaRef, Entity, Kind, SubInit)18.4k
;
599
33.1k
}
600
601
void InitListChecker::CheckEmptyInitializable(const InitializedEntity &Entity,
602
21.4k
                                              SourceLocation Loc) {
603
  // If we're building a fully-structured list, we'll check this at the end
604
  // once we know which elements are actually initialized. Otherwise, we know
605
  // that there are no designators so we can just check now.
606
21.4k
  if (FullyStructuredList)
607
7.90k
    return;
608
13.5k
  PerformEmptyInit(Loc, Entity);
609
13.5k
}
610
611
void InitListChecker::FillInEmptyInitForBase(
612
    unsigned Init, const CXXBaseSpecifier &Base,
613
    const InitializedEntity &ParentEntity, InitListExpr *ILE,
614
355
    bool &RequiresSecondPass, bool FillWithNoInit) {
615
355
  InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
616
355
      SemaRef.Context, &Base, false, &ParentEntity);
617
618
355
  if (Init >= ILE->getNumInits() || !ILE->getInit(Init)) {
619
207
    ExprResult BaseInit = FillWithNoInit
620
207
                              ? 
new (SemaRef.Context) NoInitExpr(Base.getType())0
621
207
                              : PerformEmptyInit(ILE->getEndLoc(), BaseEntity);
622
207
    if (BaseInit.isInvalid()) {
623
2
      hadError = true;
624
2
      return;
625
2
    }
626
627
205
    if (!VerifyOnly) {
628
195
      assert(Init < ILE->getNumInits() && "should have been expanded");
629
0
      ILE->setInit(Init, BaseInit.getAs<Expr>());
630
195
    }
631
205
  } else 
if (InitListExpr *148
InnerILE148
=
632
148
                 dyn_cast<InitListExpr>(ILE->getInit(Init))) {
633
104
    FillInEmptyInitializations(BaseEntity, InnerILE, RequiresSecondPass,
634
104
                               ILE, Init, FillWithNoInit);
635
104
  } else 
if (DesignatedInitUpdateExpr *44
InnerDIUE44
=
636
44
               dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
637
0
    FillInEmptyInitializations(BaseEntity, InnerDIUE->getUpdater(),
638
0
                               RequiresSecondPass, ILE, Init,
639
0
                               /*FillWithNoInit =*/true);
640
0
  }
641
355
}
642
643
void InitListChecker::FillInEmptyInitForField(unsigned Init, FieldDecl *Field,
644
                                        const InitializedEntity &ParentEntity,
645
                                              InitListExpr *ILE,
646
                                              bool &RequiresSecondPass,
647
48.2k
                                              bool FillWithNoInit) {
648
48.2k
  SourceLocation Loc = ILE->getEndLoc();
649
48.2k
  unsigned NumInits = ILE->getNumInits();
650
48.2k
  InitializedEntity MemberEntity
651
48.2k
    = InitializedEntity::InitializeMember(Field, &ParentEntity);
652
653
48.2k
  if (Init >= NumInits || 
!ILE->getInit(Init)47.2k
) {
654
5.86k
    if (const RecordType *RType = ILE->getType()->getAs<RecordType>())
655
5.86k
      if (!RType->getDecl()->isUnion())
656
5.63k
        assert((Init < NumInits || VerifyOnly) &&
657
5.86k
               "This ILE should have been expanded");
658
659
5.86k
    if (FillWithNoInit) {
660
35
      assert(!VerifyOnly && "should not fill with no-init in verify-only mode");
661
0
      Expr *Filler = new (SemaRef.Context) NoInitExpr(Field->getType());
662
35
      if (Init < NumInits)
663
35
        ILE->setInit(Init, Filler);
664
0
      else
665
0
        ILE->updateInit(SemaRef.Context, Init, Filler);
666
35
      return;
667
35
    }
668
    // C++1y [dcl.init.aggr]p7:
669
    //   If there are fewer initializer-clauses in the list than there are
670
    //   members in the aggregate, then each member not explicitly initialized
671
    //   shall be initialized from its brace-or-equal-initializer [...]
672
5.83k
    if (Field->hasInClassInitializer()) {
673
424
      if (VerifyOnly)
674
20
        return;
675
676
404
      ExprResult DIE = SemaRef.BuildCXXDefaultInitExpr(Loc, Field);
677
404
      if (DIE.isInvalid()) {
678
7
        hadError = true;
679
7
        return;
680
7
      }
681
397
      SemaRef.checkInitializerLifetime(MemberEntity, DIE.get());
682
397
      if (Init < NumInits)
683
372
        ILE->setInit(Init, DIE.get());
684
25
      else {
685
25
        ILE->updateInit(SemaRef.Context, Init, DIE.get());
686
25
        RequiresSecondPass = true;
687
25
      }
688
397
      return;
689
404
    }
690
691
5.40k
    if (Field->getType()->isReferenceType()) {
692
12
      if (!VerifyOnly) {
693
        // C++ [dcl.init.aggr]p9:
694
        //   If an incomplete or empty initializer-list leaves a
695
        //   member of reference type uninitialized, the program is
696
        //   ill-formed.
697
8
        SemaRef.Diag(Loc, diag::err_init_reference_member_uninitialized)
698
8
          << Field->getType()
699
8
          << ILE->getSyntacticForm()->getSourceRange();
700
8
        SemaRef.Diag(Field->getLocation(),
701
8
                     diag::note_uninit_reference_member);
702
8
      }
703
12
      hadError = true;
704
12
      return;
705
12
    }
706
707
5.39k
    ExprResult MemberInit = PerformEmptyInit(Loc, MemberEntity);
708
5.39k
    if (MemberInit.isInvalid()) {
709
18
      hadError = true;
710
18
      return;
711
18
    }
712
713
5.37k
    if (hadError || VerifyOnly) {
714
      // Do nothing
715
4.46k
    } else if (Init < NumInits) {
716
4.25k
      ILE->setInit(Init, MemberInit.getAs<Expr>());
717
4.25k
    } else 
if (208
!isa<ImplicitValueInitExpr>(MemberInit.get())208
) {
718
      // Empty initialization requires a constructor call, so
719
      // extend the initializer list to include the constructor
720
      // call and make a note that we'll need to take another pass
721
      // through the initializer list.
722
67
      ILE->updateInit(SemaRef.Context, Init, MemberInit.getAs<Expr>());
723
67
      RequiresSecondPass = true;
724
67
    }
725
42.3k
  } else if (InitListExpr *InnerILE
726
42.3k
               = dyn_cast<InitListExpr>(ILE->getInit(Init))) {
727
3.47k
    FillInEmptyInitializations(MemberEntity, InnerILE,
728
3.47k
                               RequiresSecondPass, ILE, Init, FillWithNoInit);
729
38.9k
  } else if (DesignatedInitUpdateExpr *InnerDIUE =
730
38.9k
                 dyn_cast<DesignatedInitUpdateExpr>(ILE->getInit(Init))) {
731
49
    FillInEmptyInitializations(MemberEntity, InnerDIUE->getUpdater(),
732
49
                               RequiresSecondPass, ILE, Init,
733
49
                               /*FillWithNoInit =*/true);
734
49
  }
735
48.2k
}
736
737
/// Recursively replaces NULL values within the given initializer list
738
/// with expressions that perform value-initialization of the
739
/// appropriate type, and finish off the InitListExpr formation.
740
void
741
InitListChecker::FillInEmptyInitializations(const InitializedEntity &Entity,
742
                                            InitListExpr *ILE,
743
                                            bool &RequiresSecondPass,
744
                                            InitListExpr *OuterILE,
745
                                            unsigned OuterIndex,
746
105k
                                            bool FillWithNoInit) {
747
105k
  assert((ILE->getType() != SemaRef.Context.VoidTy) &&
748
105k
         "Should not have void type");
749
750
  // We don't need to do any checks when just filling NoInitExprs; that can't
751
  // fail.
752
105k
  if (FillWithNoInit && 
VerifyOnly82
)
753
0
    return;
754
755
  // If this is a nested initializer list, we might have changed its contents
756
  // (and therefore some of its properties, such as instantiation-dependence)
757
  // while filling it in. Inform the outer initializer list so that its state
758
  // can be updated to match.
759
  // FIXME: We should fully build the inner initializers before constructing
760
  // the outer InitListExpr instead of mutating AST nodes after they have
761
  // been used as subexpressions of other nodes.
762
105k
  struct UpdateOuterILEWithUpdatedInit {
763
105k
    InitListExpr *Outer;
764
105k
    unsigned OuterIndex;
765
105k
    ~UpdateOuterILEWithUpdatedInit() {
766
105k
      if (Outer)
767
7.38k
        Outer->setInit(OuterIndex, Outer->getInit(OuterIndex));
768
105k
    }
769
105k
  } UpdateOuterRAII = {OuterILE, OuterIndex};
770
771
  // A transparent ILE is not performing aggregate initialization and should
772
  // not be filled in.
773
105k
  if (ILE->isTransparent())
774
1.18k
    return;
775
776
103k
  if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
777
29.0k
    const RecordDecl *RDecl = RType->getDecl();
778
29.0k
    if (RDecl->isUnion() && 
ILE->getInitializedFieldInUnion()1.92k
)
779
1.86k
      FillInEmptyInitForField(0, ILE->getInitializedFieldInUnion(),
780
1.86k
                              Entity, ILE, RequiresSecondPass, FillWithNoInit);
781
27.2k
    else if (RDecl->isUnion() && 
isa<CXXRecordDecl>(RDecl)60
&&
782
27.2k
             
cast<CXXRecordDecl>(RDecl)->hasInClassInitializer()26
) {
783
2
      for (auto *Field : RDecl->fields()) {
784
2
        if (Field->hasInClassInitializer()) {
785
0
          FillInEmptyInitForField(0, Field, Entity, ILE, RequiresSecondPass,
786
0
                                  FillWithNoInit);
787
0
          break;
788
0
        }
789
2
      }
790
27.2k
    } else {
791
      // The fields beyond ILE->getNumInits() are default initialized, so in
792
      // order to leave them uninitialized, the ILE is expanded and the extra
793
      // fields are then filled with NoInitExpr.
794
27.2k
      unsigned NumElems = numStructUnionElements(ILE->getType());
795
27.2k
      if (RDecl->hasFlexibleArrayMember())
796
111
        ++NumElems;
797
27.2k
      if (!VerifyOnly && 
ILE->getNumInits() < NumElems26.0k
)
798
2.27k
        ILE->resizeInits(SemaRef.Context, NumElems);
799
800
27.2k
      unsigned Init = 0;
801
802
27.2k
      if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RDecl)) {
803
22.6k
        for (auto &Base : CXXRD->bases()) {
804
355
          if (hadError)
805
0
            return;
806
807
355
          FillInEmptyInitForBase(Init, Base, Entity, ILE, RequiresSecondPass,
808
355
                                 FillWithNoInit);
809
355
          ++Init;
810
355
        }
811
22.6k
      }
812
813
46.5k
      
for (auto *Field : RDecl->fields())27.2k
{
814
46.5k
        if (Field->isUnnamedBitfield())
815
186
          continue;
816
817
46.3k
        if (hadError)
818
0
          return;
819
820
46.3k
        FillInEmptyInitForField(Init, Field, Entity, ILE, RequiresSecondPass,
821
46.3k
                                FillWithNoInit);
822
46.3k
        if (hadError)
823
37
          return;
824
825
46.3k
        ++Init;
826
827
        // Only look at the first initialization of a union.
828
46.3k
        if (RDecl->isUnion())
829
0
          break;
830
46.3k
      }
831
27.2k
    }
832
833
29.0k
    return;
834
29.0k
  }
835
836
74.8k
  QualType ElementType;
837
838
74.8k
  InitializedEntity ElementEntity = Entity;
839
74.8k
  unsigned NumInits = ILE->getNumInits();
840
74.8k
  unsigned NumElements = NumInits;
841
74.8k
  if (const ArrayType *AType = SemaRef.Context.getAsArrayType(ILE->getType())) {
842
17.2k
    ElementType = AType->getElementType();
843
17.2k
    if (const auto *CAType = dyn_cast<ConstantArrayType>(AType))
844
17.2k
      NumElements = CAType->getSize().getZExtValue();
845
    // For an array new with an unknown bound, ask for one additional element
846
    // in order to populate the array filler.
847
17.2k
    if (Entity.isVariableLengthArrayNew())
848
30
      ++NumElements;
849
17.2k
    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
850
17.2k
                                                         0, Entity);
851
57.5k
  } else if (const VectorType *VType = ILE->getType()->getAs<VectorType>()) {
852
55.9k
    ElementType = VType->getElementType();
853
55.9k
    NumElements = VType->getNumElements();
854
55.9k
    ElementEntity = InitializedEntity::InitializeElement(SemaRef.Context,
855
55.9k
                                                         0, Entity);
856
55.9k
  } else
857
1.61k
    ElementType = ILE->getType();
858
859
74.8k
  bool SkipEmptyInitChecks = false;
860
494k
  for (unsigned Init = 0; Init != NumElements; 
++Init419k
) {
861
426k
    if (hadError)
862
3
      return;
863
864
426k
    if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement ||
865
426k
        
ElementEntity.getKind() == InitializedEntity::EK_VectorElement353k
)
866
426k
      ElementEntity.setElementIndex(Init);
867
868
426k
    if (Init >= NumInits && 
(14.6k
ILE->hasArrayFiller()14.6k
||
SkipEmptyInitChecks13.8k
))
869
934
      return;
870
871
425k
    Expr *InitExpr = (Init < NumInits ? 
ILE->getInit(Init)412k
:
nullptr13.7k
);
872
425k
    if (!InitExpr && 
Init < NumInits19.2k
&&
ILE->hasArrayFiller()5.47k
)
873
1
      ILE->setInit(Init, ILE->getArrayFiller());
874
425k
    else if (!InitExpr && 
!ILE->hasArrayFiller()19.2k
) {
875
      // In VerifyOnly mode, there's no point performing empty initialization
876
      // more than once.
877
19.2k
      if (SkipEmptyInitChecks)
878
5.16k
        continue;
879
880
14.0k
      Expr *Filler = nullptr;
881
882
14.0k
      if (FillWithNoInit)
883
28
        Filler = new (SemaRef.Context) NoInitExpr(ElementType);
884
14.0k
      else {
885
14.0k
        ExprResult ElementInit =
886
14.0k
            PerformEmptyInit(ILE->getEndLoc(), ElementEntity);
887
14.0k
        if (ElementInit.isInvalid()) {
888
18
          hadError = true;
889
18
          return;
890
18
        }
891
892
14.0k
        Filler = ElementInit.getAs<Expr>();
893
14.0k
      }
894
895
14.0k
      if (hadError) {
896
        // Do nothing
897
14.0k
      } else if (VerifyOnly) {
898
191
        SkipEmptyInitChecks = true;
899
13.8k
      } else if (Init < NumInits) {
900
        // For arrays, just set the expression used for value-initialization
901
        // of the "holes" in the array.
902
164
        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement)
903
164
          ILE->setArrayFiller(Filler);
904
0
        else
905
0
          ILE->setInit(Init, Filler);
906
13.6k
      } else {
907
        // For arrays, just set the expression used for value-initialization
908
        // of the rest of elements and exit.
909
13.6k
        if (ElementEntity.getKind() == InitializedEntity::EK_ArrayElement) {
910
6.66k
          ILE->setArrayFiller(Filler);
911
6.66k
          return;
912
6.66k
        }
913
914
7.02k
        if (!isa<ImplicitValueInitExpr>(Filler) && 
!isa<NoInitExpr>(Filler)0
) {
915
          // Empty initialization requires a constructor call, so
916
          // extend the initializer list to include the constructor
917
          // call and make a note that we'll need to take another pass
918
          // through the initializer list.
919
0
          ILE->updateInit(SemaRef.Context, Init, Filler);
920
0
          RequiresSecondPass = true;
921
0
        }
922
7.02k
      }
923
406k
    } else if (InitListExpr *InnerILE
924
406k
                 = dyn_cast_or_null<InitListExpr>(InitExpr)) {
925
3.75k
      FillInEmptyInitializations(ElementEntity, InnerILE, RequiresSecondPass,
926
3.75k
                                 ILE, Init, FillWithNoInit);
927
402k
    } else if (DesignatedInitUpdateExpr *InnerDIUE =
928
402k
                   dyn_cast_or_null<DesignatedInitUpdateExpr>(InitExpr)) {
929
4
      FillInEmptyInitializations(ElementEntity, InnerDIUE->getUpdater(),
930
4
                                 RequiresSecondPass, ILE, Init,
931
4
                                 /*FillWithNoInit =*/true);
932
4
    }
933
425k
  }
934
74.8k
}
935
936
104k
static bool hasAnyDesignatedInits(const InitListExpr *IL) {
937
104k
  for (const Stmt *Init : *IL)
938
441k
    if (Init && isa<DesignatedInitExpr>(Init))
939
1.60k
      return true;
940
102k
  return false;
941
104k
}
942
943
InitListChecker::InitListChecker(Sema &S, const InitializedEntity &Entity,
944
                                 InitListExpr *IL, QualType &T, bool VerifyOnly,
945
                                 bool TreatUnavailableAsInvalid,
946
                                 bool InOverloadResolution)
947
    : SemaRef(S), VerifyOnly(VerifyOnly),
948
      TreatUnavailableAsInvalid(TreatUnavailableAsInvalid),
949
200k
      InOverloadResolution(InOverloadResolution) {
950
200k
  if (!VerifyOnly || 
hasAnyDesignatedInits(IL)104k
) {
951
98.3k
    FullyStructuredList =
952
98.3k
        createInitListExpr(T, IL->getSourceRange(), IL->getNumInits());
953
954
    // FIXME: Check that IL isn't already the semantic form of some other
955
    // InitListExpr. If it is, we'd create a broken AST.
956
98.3k
    if (!VerifyOnly)
957
96.7k
      FullyStructuredList->setSyntacticForm(IL);
958
98.3k
  }
959
960
200k
  CheckExplicitInitList(Entity, IL, T, FullyStructuredList,
961
200k
                        /*TopLevelObject=*/true);
962
963
200k
  if (!hadError && 
FullyStructuredList199k
) {
964
97.6k
    bool RequiresSecondPass = false;
965
97.6k
    FillInEmptyInitializations(Entity, FullyStructuredList, RequiresSecondPass,
966
97.6k
                               /*OuterILE=*/nullptr, /*OuterIndex=*/0);
967
97.6k
    if (RequiresSecondPass && 
!hadError92
)
968
92
      FillInEmptyInitializations(Entity, FullyStructuredList,
969
92
                                 RequiresSecondPass, nullptr, 0);
970
97.6k
  }
971
200k
  if (hadError && 
FullyStructuredList1.22k
)
972
708
    FullyStructuredList->markError();
973
200k
}
974
975
1.03k
int InitListChecker::numArrayElements(QualType DeclType) {
976
  // FIXME: use a proper constant
977
1.03k
  int maxElements = 0x7FFFFFFF;
978
1.03k
  if (const ConstantArrayType *CAT =
979
1.03k
        SemaRef.Context.getAsConstantArrayType(DeclType)) {
980
1.00k
    maxElements = static_cast<int>(CAT->getSize().getZExtValue());
981
1.00k
  }
982
1.03k
  return maxElements;
983
1.03k
}
984
985
54.2k
int InitListChecker::numStructUnionElements(QualType DeclType) {
986
54.2k
  RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
987
54.2k
  int InitializableMembers = 0;
988
54.2k
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(structDecl))
989
45.1k
    InitializableMembers += CXXRD->getNumBases();
990
54.2k
  for (const auto *Field : structDecl->fields())
991
91.2k
    if (!Field->isUnnamedBitfield())
992
90.7k
      ++InitializableMembers;
993
994
54.2k
  if (structDecl->isUnion())
995
1.58k
    return std::min(InitializableMembers, 1);
996
52.6k
  return InitializableMembers - structDecl->hasFlexibleArrayMember();
997
54.2k
}
998
999
/// Determine whether Entity is an entity for which it is idiomatic to elide
1000
/// the braces in aggregate initialization.
1001
1.06k
static bool isIdiomaticBraceElisionEntity(const InitializedEntity &Entity) {
1002
  // Recursive initialization of the one and only field within an aggregate
1003
  // class is considered idiomatic. This case arises in particular for
1004
  // initialization of std::array, where the C++ standard suggests the idiom of
1005
  //
1006
  //   std::array<T, N> arr = {1, 2, 3};
1007
  //
1008
  // (where std::array is an aggregate struct containing a single array field.
1009
1010
1.06k
  if (!Entity.getParent())
1011
0
    return false;
1012
1013
  // Allows elide brace initialization for aggregates with empty base.
1014
1.06k
  if (Entity.getKind() == InitializedEntity::EK_Base) {
1015
65
    auto *ParentRD =
1016
65
        Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1017
65
    CXXRecordDecl *CXXRD = cast<CXXRecordDecl>(ParentRD);
1018
65
    return CXXRD->getNumBases() == 1 && 
CXXRD->field_empty()49
;
1019
65
  }
1020
1021
  // Allow brace elision if the only subobject is a field.
1022
1.00k
  if (Entity.getKind() == InitializedEntity::EK_Member) {
1023
606
    auto *ParentRD =
1024
606
        Entity.getParent()->getType()->castAs<RecordType>()->getDecl();
1025
606
    if (CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(ParentRD)) {
1026
338
      if (CXXRD->getNumBases()) {
1027
4
        return false;
1028
4
      }
1029
338
    }
1030
602
    auto FieldIt = ParentRD->field_begin();
1031
602
    assert(FieldIt != ParentRD->field_end() &&
1032
602
           "no fields but have initializer for member?");
1033
0
    return ++FieldIt == ParentRD->field_end();
1034
606
  }
1035
1036
397
  return false;
1037
1.00k
}
1038
1039
/// Check whether the range of the initializer \p ParentIList from element
1040
/// \p Index onwards can be used to initialize an object of type \p T. Update
1041
/// \p Index to indicate how many elements of the list were consumed.
1042
///
1043
/// This also fills in \p StructuredList, from element \p StructuredIndex
1044
/// onwards, with the fully-braced, desugared form of the initialization.
1045
void InitListChecker::CheckImplicitInitList(const InitializedEntity &Entity,
1046
                                            InitListExpr *ParentIList,
1047
                                            QualType T, unsigned &Index,
1048
                                            InitListExpr *StructuredList,
1049
2.43k
                                            unsigned &StructuredIndex) {
1050
2.43k
  int maxElements = 0;
1051
1052
2.43k
  if (T->isArrayType())
1053
1.03k
    maxElements = numArrayElements(T);
1054
1.39k
  else if (T->isRecordType())
1055
1.36k
    maxElements = numStructUnionElements(T);
1056
28
  else if (T->isVectorType())
1057
28
    maxElements = T->castAs<VectorType>()->getNumElements();
1058
0
  else
1059
0
    llvm_unreachable("CheckImplicitInitList(): Illegal type");
1060
1061
2.43k
  if (maxElements == 0) {
1062
26
    if (!VerifyOnly)
1063
13
      SemaRef.Diag(ParentIList->getInit(Index)->getBeginLoc(),
1064
13
                   diag::err_implicit_empty_initializer);
1065
26
    ++Index;
1066
26
    hadError = true;
1067
26
    return;
1068
26
  }
1069
1070
  // Build a structured initializer list corresponding to this subobject.
1071
2.40k
  InitListExpr *StructuredSubobjectInitList = getStructuredSubobjectInit(
1072
2.40k
      ParentIList, Index, T, StructuredList, StructuredIndex,
1073
2.40k
      SourceRange(ParentIList->getInit(Index)->getBeginLoc(),
1074
2.40k
                  ParentIList->getSourceRange().getEnd()));
1075
2.40k
  unsigned StructuredSubobjectInitIndex = 0;
1076
1077
  // Check the element types and build the structural subobject.
1078
2.40k
  unsigned StartIndex = Index;
1079
2.40k
  CheckListElementTypes(Entity, ParentIList, T,
1080
2.40k
                        /*SubobjectIsDesignatorContext=*/false, Index,
1081
2.40k
                        StructuredSubobjectInitList,
1082
2.40k
                        StructuredSubobjectInitIndex);
1083
1084
2.40k
  if (StructuredSubobjectInitList) {
1085
1.20k
    StructuredSubobjectInitList->setType(T);
1086
1087
1.20k
    unsigned EndIndex = (Index == StartIndex? 
StartIndex0
: Index - 1);
1088
    // Update the structured sub-object initializer so that it's ending
1089
    // range corresponds with the end of the last initializer it used.
1090
1.20k
    if (EndIndex < ParentIList->getNumInits() &&
1091
1.20k
        ParentIList->getInit(EndIndex)) {
1092
1.20k
      SourceLocation EndLoc
1093
1.20k
        = ParentIList->getInit(EndIndex)->getSourceRange().getEnd();
1094
1.20k
      StructuredSubobjectInitList->setRBraceLoc(EndLoc);
1095
1.20k
    }
1096
1097
    // Complain about missing braces.
1098
1.20k
    if (!VerifyOnly && 
(1.13k
T->isArrayType()1.13k
||
T->isRecordType()658
) &&
1099
1.20k
        
!ParentIList->isIdiomaticZeroInitializer(SemaRef.getLangOpts())1.12k
&&
1100
1.20k
        
!isIdiomaticBraceElisionEntity(Entity)1.06k
) {
1101
758
      SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1102
758
                   diag::warn_missing_braces)
1103
758
          << StructuredSubobjectInitList->getSourceRange()
1104
758
          << FixItHint::CreateInsertion(
1105
758
                 StructuredSubobjectInitList->getBeginLoc(), "{")
1106
758
          << FixItHint::CreateInsertion(
1107
758
                 SemaRef.getLocForEndOfToken(
1108
758
                     StructuredSubobjectInitList->getEndLoc()),
1109
758
                 "}");
1110
758
    }
1111
1112
    // Warn if this type won't be an aggregate in future versions of C++.
1113
1.20k
    auto *CXXRD = T->getAsCXXRecordDecl();
1114
1.20k
    if (!VerifyOnly && 
CXXRD1.13k
&&
CXXRD->hasUserDeclaredConstructor()378
) {
1115
3
      SemaRef.Diag(StructuredSubobjectInitList->getBeginLoc(),
1116
3
                   diag::warn_cxx20_compat_aggregate_init_with_ctors)
1117
3
          << StructuredSubobjectInitList->getSourceRange() << T;
1118
3
    }
1119
1.20k
  }
1120
2.40k
}
1121
1122
/// Warn that \p Entity was of scalar type and was initialized by a
1123
/// single-element braced initializer list.
1124
static void warnBracedScalarInit(Sema &S, const InitializedEntity &Entity,
1125
1.00k
                                 SourceRange Braces) {
1126
  // Don't warn during template instantiation. If the initialization was
1127
  // non-dependent, we warned during the initial parse; otherwise, the
1128
  // type might not be scalar in some uses of the template.
1129
1.00k
  if (S.inTemplateInstantiation())
1130
226
    return;
1131
1132
776
  unsigned DiagID = 0;
1133
1134
776
  switch (Entity.getKind()) {
1135
0
  case InitializedEntity::EK_VectorElement:
1136
0
  case InitializedEntity::EK_ComplexElement:
1137
9
  case InitializedEntity::EK_ArrayElement:
1138
39
  case InitializedEntity::EK_Parameter:
1139
39
  case InitializedEntity::EK_Parameter_CF_Audited:
1140
39
  case InitializedEntity::EK_TemplateParameter:
1141
44
  case InitializedEntity::EK_Result:
1142
    // Extra braces here are suspicious.
1143
44
    DiagID = diag::warn_braces_around_init;
1144
44
    break;
1145
1146
110
  case InitializedEntity::EK_Member:
1147
    // Warn on aggregate initialization but not on ctor init list or
1148
    // default member initializer.
1149
110
    if (Entity.getParent())
1150
11
      DiagID = diag::warn_braces_around_init;
1151
110
    break;
1152
1153
376
  case InitializedEntity::EK_Variable:
1154
382
  case InitializedEntity::EK_LambdaCapture:
1155
    // No warning, might be direct-list-initialization.
1156
    // FIXME: Should we warn for copy-list-initialization in these cases?
1157
382
    break;
1158
1159
21
  case InitializedEntity::EK_New:
1160
175
  case InitializedEntity::EK_Temporary:
1161
240
  case InitializedEntity::EK_CompoundLiteralInit:
1162
    // No warning, braces are part of the syntax of the underlying construct.
1163
240
    break;
1164
1165
0
  case InitializedEntity::EK_RelatedResult:
1166
    // No warning, we already warned when initializing the result.
1167
0
    break;
1168
1169
0
  case InitializedEntity::EK_Exception:
1170
0
  case InitializedEntity::EK_Base:
1171
0
  case InitializedEntity::EK_Delegating:
1172
0
  case InitializedEntity::EK_BlockElement:
1173
0
  case InitializedEntity::EK_LambdaToBlockConversionBlockElement:
1174
0
  case InitializedEntity::EK_Binding:
1175
0
  case InitializedEntity::EK_StmtExprResult:
1176
0
    llvm_unreachable("unexpected braced scalar init");
1177
776
  }
1178
1179
776
  if (DiagID) {
1180
55
    S.Diag(Braces.getBegin(), DiagID)
1181
55
        << Entity.getType()->isSizelessBuiltinType() << Braces
1182
55
        << FixItHint::CreateRemoval(Braces.getBegin())
1183
55
        << FixItHint::CreateRemoval(Braces.getEnd());
1184
55
  }
1185
776
}
1186
1187
/// Check whether the initializer \p IList (that was written with explicit
1188
/// braces) can be used to initialize an object of type \p T.
1189
///
1190
/// This also fills in \p StructuredList with the fully-braced, desugared
1191
/// form of the initialization.
1192
void InitListChecker::CheckExplicitInitList(const InitializedEntity &Entity,
1193
                                            InitListExpr *IList, QualType &T,
1194
                                            InitListExpr *StructuredList,
1195
200k
                                            bool TopLevelObject) {
1196
200k
  unsigned Index = 0, StructuredIndex = 0;
1197
200k
  CheckListElementTypes(Entity, IList, T, /*SubobjectIsDesignatorContext=*/true,
1198
200k
                        Index, StructuredList, StructuredIndex, TopLevelObject);
1199
200k
  if (StructuredList) {
1200
98.3k
    QualType ExprTy = T;
1201
98.3k
    if (!ExprTy->isArrayType())
1202
83.4k
      ExprTy = ExprTy.getNonLValueExprType(SemaRef.Context);
1203
98.3k
    if (!VerifyOnly)
1204
96.7k
      IList->setType(ExprTy);
1205
98.3k
    StructuredList->setType(ExprTy);
1206
98.3k
  }
1207
200k
  if (hadError)
1208
1.06k
    return;
1209
1210
  // Don't complain for incomplete types, since we'll get an error elsewhere.
1211
199k
  if (Index < IList->getNumInits() && 
!T->isIncompleteType()233
) {
1212
    // We have leftover initializers
1213
227
    bool ExtraInitsIsError = SemaRef.getLangOpts().CPlusPlus ||
1214
227
          
(120
SemaRef.getLangOpts().OpenCL120
&&
T->isVectorType()6
);
1215
227
    hadError = ExtraInitsIsError;
1216
227
    if (VerifyOnly) {
1217
121
      return;
1218
121
    } else 
if (106
StructuredIndex == 1106
&&
1219
106
               IsStringInit(StructuredList->getInit(0), T, SemaRef.Context) ==
1220
46
                   SIF_None) {
1221
6
      unsigned DK =
1222
6
          ExtraInitsIsError
1223
6
              ? 
diag::err_excess_initializers_in_char_array_initializer0
1224
6
              : diag::ext_excess_initializers_in_char_array_initializer;
1225
6
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1226
6
          << IList->getInit(Index)->getSourceRange();
1227
100
    } else if (T->isSizelessBuiltinType()) {
1228
10
      unsigned DK = ExtraInitsIsError
1229
10
                        ? 
diag::err_excess_initializers_for_sizeless_type7
1230
10
                        : 
diag::ext_excess_initializers_for_sizeless_type3
;
1231
10
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1232
10
          << T << IList->getInit(Index)->getSourceRange();
1233
90
    } else {
1234
90
      int initKind = T->isArrayType() ? 
026
:
1235
90
                     
T->isVectorType()64
?
122
:
1236
64
                     
T->isScalarType()42
?
25
:
1237
42
                     
T->isUnionType()37
?
34
:
1238
37
                     
433
;
1239
1240
90
      unsigned DK = ExtraInitsIsError ? 
diag::err_excess_initializers40
1241
90
                                      : 
diag::ext_excess_initializers50
;
1242
90
      SemaRef.Diag(IList->getInit(Index)->getBeginLoc(), DK)
1243
90
          << initKind << IList->getInit(Index)->getSourceRange();
1244
90
    }
1245
227
  }
1246
1247
199k
  if (!VerifyOnly) {
1248
96.2k
    if (T->isScalarType() && 
IList->getNumInits() == 12.53k
&&
1249
96.2k
        
!isa<InitListExpr>(IList->getInit(0))1.02k
)
1250
1.00k
      warnBracedScalarInit(SemaRef, Entity, IList->getSourceRange());
1251
1252
    // Warn if this is a class type that won't be an aggregate in future
1253
    // versions of C++.
1254
96.2k
    auto *CXXRD = T->getAsCXXRecordDecl();
1255
96.2k
    if (CXXRD && 
CXXRD->hasUserDeclaredConstructor()19.9k
) {
1256
      // Don't warn if there's an equivalent default constructor that would be
1257
      // used instead.
1258
42
      bool HasEquivCtor = false;
1259
42
      if (IList->getNumInits() == 0) {
1260
34
        auto *CD = SemaRef.LookupDefaultConstructor(CXXRD);
1261
34
        HasEquivCtor = CD && 
!CD->isDeleted()22
;
1262
34
      }
1263
1264
42
      if (!HasEquivCtor) {
1265
23
        SemaRef.Diag(IList->getBeginLoc(),
1266
23
                     diag::warn_cxx20_compat_aggregate_init_with_ctors)
1267
23
            << IList->getSourceRange() << T;
1268
23
      }
1269
42
    }
1270
96.2k
  }
1271
199k
}
1272
1273
void InitListChecker::CheckListElementTypes(const InitializedEntity &Entity,
1274
                                            InitListExpr *IList,
1275
                                            QualType &DeclType,
1276
                                            bool SubobjectIsDesignatorContext,
1277
                                            unsigned &Index,
1278
                                            InitListExpr *StructuredList,
1279
                                            unsigned &StructuredIndex,
1280
203k
                                            bool TopLevelObject) {
1281
203k
  if (DeclType->isAnyComplexType() && 
SubobjectIsDesignatorContext244
) {
1282
    // Explicitly braced initializer for complex type can be real+imaginary
1283
    // parts.
1284
244
    CheckComplexType(Entity, IList, DeclType, Index,
1285
244
                     StructuredList, StructuredIndex);
1286
202k
  } else if (DeclType->isScalarType()) {
1287
5.35k
    CheckScalarType(Entity, IList, DeclType, Index,
1288
5.35k
                    StructuredList, StructuredIndex);
1289
197k
  } else if (DeclType->isVectorType()) {
1290
111k
    CheckVectorType(Entity, IList, DeclType, Index,
1291
111k
                    StructuredList, StructuredIndex);
1292
111k
  } else 
if (85.7k
DeclType->isRecordType()85.7k
) {
1293
53.0k
    assert(DeclType->isAggregateType() &&
1294
53.0k
           "non-aggregate records should be handed in CheckSubElementType");
1295
0
    RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
1296
53.0k
    auto Bases =
1297
53.0k
        CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
1298
53.0k
                                        CXXRecordDecl::base_class_iterator());
1299
53.0k
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1300
45.1k
      Bases = CXXRD->bases();
1301
53.0k
    CheckStructUnionTypes(Entity, IList, DeclType, Bases, RD->field_begin(),
1302
53.0k
                          SubobjectIsDesignatorContext, Index, StructuredList,
1303
53.0k
                          StructuredIndex, TopLevelObject);
1304
53.0k
  } else 
if (32.7k
DeclType->isArrayType()32.7k
) {
1305
32.4k
    llvm::APSInt Zero(
1306
32.4k
                    SemaRef.Context.getTypeSize(SemaRef.Context.getSizeType()),
1307
32.4k
                    false);
1308
32.4k
    CheckArrayType(Entity, IList, DeclType, Zero,
1309
32.4k
                   SubobjectIsDesignatorContext, Index,
1310
32.4k
                   StructuredList, StructuredIndex);
1311
32.4k
  } else 
if (270
DeclType->isVoidType()270
||
DeclType->isFunctionType()264
) {
1312
    // This type is invalid, issue a diagnostic.
1313
8
    ++Index;
1314
8
    if (!VerifyOnly)
1315
4
      SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1316
4
          << DeclType;
1317
8
    hadError = true;
1318
262
  } else if (DeclType->isReferenceType()) {
1319
0
    CheckReferenceType(Entity, IList, DeclType, Index,
1320
0
                       StructuredList, StructuredIndex);
1321
262
  } else if (DeclType->isObjCObjectType()) {
1322
2
    if (!VerifyOnly)
1323
1
      SemaRef.Diag(IList->getBeginLoc(), diag::err_init_objc_class) << DeclType;
1324
2
    hadError = true;
1325
260
  } else if (DeclType->isOCLIntelSubgroupAVCType() ||
1326
260
             
DeclType->isSizelessBuiltinType()184
) {
1327
    // Checks for scalar type are sufficient for these types too.
1328
246
    CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1329
246
                    StructuredIndex);
1330
246
  } else {
1331
14
    if (!VerifyOnly)
1332
6
      SemaRef.Diag(IList->getBeginLoc(), diag::err_illegal_initializer_type)
1333
6
          << DeclType;
1334
14
    hadError = true;
1335
14
  }
1336
203k
}
1337
1338
void InitListChecker::CheckSubElementType(const InitializedEntity &Entity,
1339
                                          InitListExpr *IList,
1340
                                          QualType ElemType,
1341
                                          unsigned &Index,
1342
                                          InitListExpr *StructuredList,
1343
                                          unsigned &StructuredIndex,
1344
871k
                                          bool DirectlyDesignated) {
1345
871k
  Expr *expr = IList->getInit(Index);
1346
1347
871k
  if (ElemType->isReferenceType())
1348
1.00k
    return CheckReferenceType(Entity, IList, ElemType, Index,
1349
1.00k
                              StructuredList, StructuredIndex);
1350
1351
870k
  if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(expr)) {
1352
10.8k
    if (SubInitList->getNumInits() == 1 &&
1353
10.8k
        IsStringInit(SubInitList->getInit(0), ElemType, SemaRef.Context) ==
1354
3.99k
        SIF_None) {
1355
      // FIXME: It would be more faithful and no less correct to include an
1356
      // InitListExpr in the semantic form of the initializer list in this case.
1357
75
      expr = SubInitList->getInit(0);
1358
75
    }
1359
    // Nested aggregate initialization and C++ initialization are handled later.
1360
859k
  } else if (isa<ImplicitValueInitExpr>(expr)) {
1361
    // This happens during template instantiation when we see an InitListExpr
1362
    // that we've already checked once.
1363
0
    assert(SemaRef.Context.hasSameType(expr->getType(), ElemType) &&
1364
0
           "found implicit initialization for the wrong type");
1365
0
    UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1366
0
    ++Index;
1367
0
    return;
1368
0
  }
1369
1370
870k
  if (SemaRef.getLangOpts().CPlusPlus || 
isa<InitListExpr>(expr)614k
) {
1371
    // C++ [dcl.init.aggr]p2:
1372
    //   Each member is copy-initialized from the corresponding
1373
    //   initializer-clause.
1374
1375
    // FIXME: Better EqualLoc?
1376
259k
    InitializationKind Kind =
1377
259k
        InitializationKind::CreateCopy(expr->getBeginLoc(), SourceLocation());
1378
1379
    // Vector elements can be initialized from other vectors in which case
1380
    // we need initialization entity with a type of a vector (and not a vector
1381
    // element!) initializing multiple vector elements.
1382
259k
    auto TmpEntity =
1383
259k
        (ElemType->isExtVectorType() && 
!Entity.getType()->isExtVectorType()62
)
1384
259k
            ? 
InitializedEntity::InitializeTemporary(ElemType)20
1385
259k
            : 
Entity259k
;
1386
1387
259k
    InitializationSequence Seq(SemaRef, TmpEntity, Kind, expr,
1388
259k
                               /*TopLevelOfInitList*/ true);
1389
1390
    // C++14 [dcl.init.aggr]p13:
1391
    //   If the assignment-expression can initialize a member, the member is
1392
    //   initialized. Otherwise [...] brace elision is assumed
1393
    //
1394
    // Brace elision is never performed if the element is not an
1395
    // assignment-expression.
1396
259k
    if (Seq || 
isa<InitListExpr>(expr)1.79k
) {
1397
257k
      if (!VerifyOnly) {
1398
124k
        ExprResult Result = Seq.Perform(SemaRef, TmpEntity, Kind, expr);
1399
124k
        if (Result.isInvalid())
1400
60
          hadError = true;
1401
1402
124k
        UpdateStructuredListElement(StructuredList, StructuredIndex,
1403
124k
                                    Result.getAs<Expr>());
1404
133k
      } else if (!Seq) {
1405
63
        hadError = true;
1406
133k
      } else if (StructuredList) {
1407
1.77k
        UpdateStructuredListElement(StructuredList, StructuredIndex,
1408
1.77k
                                    getDummyInit());
1409
1.77k
      }
1410
257k
      ++Index;
1411
257k
      return;
1412
257k
    }
1413
1414
    // Fall through for subaggregate initialization
1415
611k
  } else if (ElemType->isScalarType() || 
ElemType->isAtomicType()1.38k
) {
1416
    // FIXME: Need to handle atomic aggregate types with implicit init lists.
1417
609k
    return CheckScalarType(Entity, IList, ElemType, Index,
1418
609k
                           StructuredList, StructuredIndex);
1419
609k
  } else 
if (const ArrayType *1.35k
arrayType1.35k
=
1420
1.35k
                 SemaRef.Context.getAsArrayType(ElemType)) {
1421
    // arrayType can be incomplete if we're initializing a flexible
1422
    // array member.  There's nothing we can do with the completed
1423
    // type here, though.
1424
1425
569
    if (IsStringInit(expr, arrayType, SemaRef.Context) == SIF_None) {
1426
      // FIXME: Should we do this checking in verify-only mode?
1427
206
      if (!VerifyOnly)
1428
93
        CheckStringInit(expr, ElemType, arrayType, SemaRef);
1429
206
      if (StructuredList)
1430
107
        UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1431
206
      ++Index;
1432
206
      return;
1433
206
    }
1434
1435
    // Fall through for subaggregate initialization.
1436
1437
781
  } else {
1438
781
    assert((ElemType->isRecordType() || ElemType->isVectorType() ||
1439
781
            ElemType->isOpenCLSpecificType()) && "Unexpected type");
1440
1441
    // C99 6.7.8p13:
1442
    //
1443
    //   The initializer for a structure or union object that has
1444
    //   automatic storage duration shall be either an initializer
1445
    //   list as described below, or a single expression that has
1446
    //   compatible structure or union type. In the latter case, the
1447
    //   initial value of the object, including unnamed members, is
1448
    //   that of the expression.
1449
0
    ExprResult ExprRes = expr;
1450
781
    if (SemaRef.CheckSingleAssignmentConstraints(
1451
781
            ElemType, ExprRes, !VerifyOnly) != Sema::Incompatible) {
1452
216
      if (ExprRes.isInvalid())
1453
0
        hadError = true;
1454
216
      else {
1455
216
        ExprRes = SemaRef.DefaultFunctionArrayLvalueConversion(ExprRes.get());
1456
216
        if (ExprRes.isInvalid())
1457
0
          hadError = true;
1458
216
      }
1459
216
      UpdateStructuredListElement(StructuredList, StructuredIndex,
1460
216
                                  ExprRes.getAs<Expr>());
1461
216
      ++Index;
1462
216
      return;
1463
216
    }
1464
565
    ExprRes.get();
1465
    // Fall through for subaggregate initialization
1466
565
  }
1467
1468
  // C++ [dcl.init.aggr]p12:
1469
  //
1470
  //   [...] Otherwise, if the member is itself a non-empty
1471
  //   subaggregate, brace elision is assumed and the initializer is
1472
  //   considered for the initialization of the first member of
1473
  //   the subaggregate.
1474
  // OpenCL vector initializer is handled elsewhere.
1475
2.61k
  if ((!SemaRef.getLangOpts().OpenCL && 
ElemType->isVectorType()2.58k
) ||
1476
2.61k
      
ElemType->isAggregateType()2.58k
) {
1477
2.40k
    CheckImplicitInitList(Entity, IList, ElemType, Index, StructuredList,
1478
2.40k
                          StructuredIndex);
1479
2.40k
    ++StructuredIndex;
1480
1481
    // In C++20, brace elision is not permitted for a designated initializer.
1482
2.40k
    if (DirectlyDesignated && 
SemaRef.getLangOpts().CPlusPlus80
&&
!hadError78
) {
1483
66
      if (InOverloadResolution)
1484
6
        hadError = true;
1485
66
      if (!VerifyOnly) {
1486
30
        SemaRef.Diag(expr->getBeginLoc(),
1487
30
                     diag::ext_designated_init_brace_elision)
1488
30
            << expr->getSourceRange()
1489
30
            << FixItHint::CreateInsertion(expr->getBeginLoc(), "{")
1490
30
            << FixItHint::CreateInsertion(
1491
30
                   SemaRef.getLocForEndOfToken(expr->getEndLoc()), "}");
1492
30
      }
1493
66
    }
1494
2.40k
  } else {
1495
203
    if (!VerifyOnly) {
1496
      // We cannot initialize this element, so let PerformCopyInitialization
1497
      // produce the appropriate diagnostic. We already checked that this
1498
      // initialization will fail.
1499
98
      ExprResult Copy =
1500
98
          SemaRef.PerformCopyInitialization(Entity, SourceLocation(), expr,
1501
98
                                            /*TopLevelOfInitList=*/true);
1502
98
      (void)Copy;
1503
98
      assert(Copy.isInvalid() &&
1504
98
             "expected non-aggregate initialization to fail");
1505
98
    }
1506
0
    hadError = true;
1507
203
    ++Index;
1508
203
    ++StructuredIndex;
1509
203
  }
1510
2.61k
}
1511
1512
void InitListChecker::CheckComplexType(const InitializedEntity &Entity,
1513
                                       InitListExpr *IList, QualType DeclType,
1514
                                       unsigned &Index,
1515
                                       InitListExpr *StructuredList,
1516
244
                                       unsigned &StructuredIndex) {
1517
244
  assert(Index == 0 && "Index in explicit init list must be zero");
1518
1519
  // As an extension, clang supports complex initializers, which initialize
1520
  // a complex number component-wise.  When an explicit initializer list for
1521
  // a complex number contains two two initializers, this extension kicks in:
1522
  // it exepcts the initializer list to contain two elements convertible to
1523
  // the element type of the complex type. The first element initializes
1524
  // the real part, and the second element intitializes the imaginary part.
1525
1526
244
  if (IList->getNumInits() != 2)
1527
52
    return CheckScalarType(Entity, IList, DeclType, Index, StructuredList,
1528
52
                           StructuredIndex);
1529
1530
  // This is an extension in C.  (The builtin _Complex type does not exist
1531
  // in the C++ standard.)
1532
192
  if (!SemaRef.getLangOpts().CPlusPlus && 
!VerifyOnly48
)
1533
21
    SemaRef.Diag(IList->getBeginLoc(), diag::ext_complex_component_init)
1534
21
        << IList->getSourceRange();
1535
1536
  // Initialize the complex number.
1537
192
  QualType elementType = DeclType->castAs<ComplexType>()->getElementType();
1538
192
  InitializedEntity ElementEntity =
1539
192
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1540
1541
576
  for (unsigned i = 0; i < 2; 
++i384
) {
1542
384
    ElementEntity.setElementIndex(Index);
1543
384
    CheckSubElementType(ElementEntity, IList, elementType, Index,
1544
384
                        StructuredList, StructuredIndex);
1545
384
  }
1546
192
}
1547
1548
void InitListChecker::CheckScalarType(const InitializedEntity &Entity,
1549
                                      InitListExpr *IList, QualType DeclType,
1550
                                      unsigned &Index,
1551
                                      InitListExpr *StructuredList,
1552
615k
                                      unsigned &StructuredIndex) {
1553
615k
  if (Index >= IList->getNumInits()) {
1554
2.92k
    if (!VerifyOnly) {
1555
1.44k
      if (DeclType->isSizelessBuiltinType())
1556
13
        SemaRef.Diag(IList->getBeginLoc(),
1557
13
                     SemaRef.getLangOpts().CPlusPlus11
1558
13
                         ? 
diag::warn_cxx98_compat_empty_sizeless_initializer9
1559
13
                         : 
diag::err_empty_sizeless_initializer4
)
1560
13
            << DeclType << IList->getSourceRange();
1561
1.43k
      else
1562
1.43k
        SemaRef.Diag(IList->getBeginLoc(),
1563
1.43k
                     SemaRef.getLangOpts().CPlusPlus11
1564
1.43k
                         ? 
diag::warn_cxx98_compat_empty_scalar_initializer1.42k
1565
1.43k
                         : 
diag::err_empty_scalar_initializer9
)
1566
1.43k
            << IList->getSourceRange();
1567
1.44k
    }
1568
2.92k
    hadError = !SemaRef.getLangOpts().CPlusPlus11;
1569
2.92k
    ++Index;
1570
2.92k
    ++StructuredIndex;
1571
2.92k
    return;
1572
2.92k
  }
1573
1574
612k
  Expr *expr = IList->getInit(Index);
1575
612k
  if (InitListExpr *SubIList = dyn_cast<InitListExpr>(expr)) {
1576
    // FIXME: This is invalid, and accepting it causes overload resolution
1577
    // to pick the wrong overload in some corner cases.
1578
98
    if (!VerifyOnly)
1579
42
      SemaRef.Diag(SubIList->getBeginLoc(), diag::ext_many_braces_around_init)
1580
42
          << DeclType->isSizelessBuiltinType() << SubIList->getSourceRange();
1581
1582
98
    CheckScalarType(Entity, SubIList, DeclType, Index, StructuredList,
1583
98
                    StructuredIndex);
1584
98
    return;
1585
612k
  } else if (isa<DesignatedInitExpr>(expr)) {
1586
24
    if (!VerifyOnly)
1587
11
      SemaRef.Diag(expr->getBeginLoc(),
1588
11
                   diag::err_designator_for_scalar_or_sizeless_init)
1589
11
          << DeclType->isSizelessBuiltinType() << DeclType
1590
11
          << expr->getSourceRange();
1591
24
    hadError = true;
1592
24
    ++Index;
1593
24
    ++StructuredIndex;
1594
24
    return;
1595
24
  }
1596
1597
612k
  ExprResult Result;
1598
612k
  if (VerifyOnly) {
1599
307k
    if (SemaRef.CanPerformCopyInitialization(Entity, expr))
1600
307k
      Result = getDummyInit();
1601
206
    else
1602
206
      Result = ExprError();
1603
307k
  } else {
1604
305k
    Result =
1605
305k
        SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1606
305k
                                          /*TopLevelOfInitList=*/true);
1607
305k
  }
1608
1609
612k
  Expr *ResultExpr = nullptr;
1610
1611
612k
  if (Result.isInvalid())
1612
409
    hadError = true; // types weren't compatible.
1613
612k
  else {
1614
612k
    ResultExpr = Result.getAs<Expr>();
1615
1616
612k
    if (ResultExpr != expr && 
!VerifyOnly597k
) {
1617
      // The type was promoted, update initializer list.
1618
      // FIXME: Why are we updating the syntactic init list?
1619
290k
      IList->setInit(Index, ResultExpr);
1620
290k
    }
1621
612k
  }
1622
612k
  UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1623
612k
  ++Index;
1624
612k
}
1625
1626
void InitListChecker::CheckReferenceType(const InitializedEntity &Entity,
1627
                                         InitListExpr *IList, QualType DeclType,
1628
                                         unsigned &Index,
1629
                                         InitListExpr *StructuredList,
1630
1.00k
                                         unsigned &StructuredIndex) {
1631
1.00k
  if (Index >= IList->getNumInits()) {
1632
    // FIXME: It would be wonderful if we could point at the actual member. In
1633
    // general, it would be useful to pass location information down the stack,
1634
    // so that we know the location (or decl) of the "current object" being
1635
    // initialized.
1636
0
    if (!VerifyOnly)
1637
0
      SemaRef.Diag(IList->getBeginLoc(),
1638
0
                   diag::err_init_reference_member_uninitialized)
1639
0
          << DeclType << IList->getSourceRange();
1640
0
    hadError = true;
1641
0
    ++Index;
1642
0
    ++StructuredIndex;
1643
0
    return;
1644
0
  }
1645
1646
1.00k
  Expr *expr = IList->getInit(Index);
1647
1.00k
  if (isa<InitListExpr>(expr) && 
!SemaRef.getLangOpts().CPlusPlus11227
) {
1648
0
    if (!VerifyOnly)
1649
0
      SemaRef.Diag(IList->getBeginLoc(), diag::err_init_non_aggr_init_list)
1650
0
          << DeclType << IList->getSourceRange();
1651
0
    hadError = true;
1652
0
    ++Index;
1653
0
    ++StructuredIndex;
1654
0
    return;
1655
0
  }
1656
1657
1.00k
  ExprResult Result;
1658
1.00k
  if (VerifyOnly) {
1659
548
    if (SemaRef.CanPerformCopyInitialization(Entity,expr))
1660
538
      Result = getDummyInit();
1661
10
    else
1662
10
      Result = ExprError();
1663
548
  } else {
1664
461
    Result =
1665
461
        SemaRef.PerformCopyInitialization(Entity, expr->getBeginLoc(), expr,
1666
461
                                          /*TopLevelOfInitList=*/true);
1667
461
  }
1668
1669
1.00k
  if (Result.isInvalid())
1670
20
    hadError = true;
1671
1672
1.00k
  expr = Result.getAs<Expr>();
1673
  // FIXME: Why are we updating the syntactic init list?
1674
1.00k
  if (!VerifyOnly && 
expr461
)
1675
451
    IList->setInit(Index, expr);
1676
1677
1.00k
  UpdateStructuredListElement(StructuredList, StructuredIndex, expr);
1678
1.00k
  ++Index;
1679
1.00k
}
1680
1681
void InitListChecker::CheckVectorType(const InitializedEntity &Entity,
1682
                                      InitListExpr *IList, QualType DeclType,
1683
                                      unsigned &Index,
1684
                                      InitListExpr *StructuredList,
1685
111k
                                      unsigned &StructuredIndex) {
1686
111k
  const VectorType *VT = DeclType->castAs<VectorType>();
1687
111k
  unsigned maxElements = VT->getNumElements();
1688
111k
  unsigned numEltsInit = 0;
1689
111k
  QualType elementType = VT->getElementType();
1690
1691
111k
  if (Index >= IList->getNumInits()) {
1692
    // Make sure the element type can be value-initialized.
1693
140
    CheckEmptyInitializable(
1694
140
        InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1695
140
        IList->getEndLoc());
1696
140
    return;
1697
140
  }
1698
1699
111k
  if (!SemaRef.getLangOpts().OpenCL && 
!SemaRef.getLangOpts().HLSL111k
) {
1700
    // If the initializing element is a vector, try to copy-initialize
1701
    // instead of breaking it apart (which is doomed to failure anyway).
1702
111k
    Expr *Init = IList->getInit(Index);
1703
111k
    if (!isa<InitListExpr>(Init) && Init->getType()->isVectorType()) {
1704
11
      ExprResult Result;
1705
11
      if (VerifyOnly) {
1706
6
        if (SemaRef.CanPerformCopyInitialization(Entity, Init))
1707
5
          Result = getDummyInit();
1708
1
        else
1709
1
          Result = ExprError();
1710
6
      } else {
1711
5
        Result =
1712
5
            SemaRef.PerformCopyInitialization(Entity, Init->getBeginLoc(), Init,
1713
5
                                              /*TopLevelOfInitList=*/true);
1714
5
      }
1715
1716
11
      Expr *ResultExpr = nullptr;
1717
11
      if (Result.isInvalid())
1718
4
        hadError = true; // types weren't compatible.
1719
7
      else {
1720
7
        ResultExpr = Result.getAs<Expr>();
1721
1722
7
        if (ResultExpr != Init && !VerifyOnly) {
1723
          // The type was promoted, update initializer list.
1724
          // FIXME: Why are we updating the syntactic init list?
1725
2
          IList->setInit(Index, ResultExpr);
1726
2
        }
1727
7
      }
1728
11
      UpdateStructuredListElement(StructuredList, StructuredIndex, ResultExpr);
1729
11
      ++Index;
1730
11
      return;
1731
11
    }
1732
1733
111k
    InitializedEntity ElementEntity =
1734
111k
      InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1735
1736
801k
    for (unsigned i = 0; i < maxElements; 
++i, ++numEltsInit690k
) {
1737
      // Don't attempt to go past the end of the init list
1738
691k
      if (Index >= IList->getNumInits()) {
1739
747
        CheckEmptyInitializable(ElementEntity, IList->getEndLoc());
1740
747
        break;
1741
747
      }
1742
1743
690k
      ElementEntity.setElementIndex(Index);
1744
690k
      CheckSubElementType(ElementEntity, IList, elementType, Index,
1745
690k
                          StructuredList, StructuredIndex);
1746
690k
    }
1747
1748
111k
    if (VerifyOnly)
1749
55.6k
      return;
1750
1751
55.6k
    bool isBigEndian = SemaRef.Context.getTargetInfo().isBigEndian();
1752
55.6k
    const VectorType *T = Entity.getType()->castAs<VectorType>();
1753
55.6k
    if (isBigEndian && 
(3.53k
T->getVectorKind() == VectorType::NeonVector3.53k
||
1754
3.53k
                        
T->getVectorKind() == VectorType::NeonPolyVector1.70k
)) {
1755
      // The ability to use vector initializer lists is a GNU vector extension
1756
      // and is unrelated to the NEON intrinsics in arm_neon.h. On little
1757
      // endian machines it works fine, however on big endian machines it
1758
      // exhibits surprising behaviour:
1759
      //
1760
      //   uint32x2_t x = {42, 64};
1761
      //   return vget_lane_u32(x, 0); // Will return 64.
1762
      //
1763
      // Because of this, explicitly call out that it is non-portable.
1764
      //
1765
2.00k
      SemaRef.Diag(IList->getBeginLoc(),
1766
2.00k
                   diag::warn_neon_vector_initializer_non_portable);
1767
1768
2.00k
      const char *typeCode;
1769
2.00k
      unsigned typeSize = SemaRef.Context.getTypeSize(elementType);
1770
1771
2.00k
      if (elementType->isFloatingType())
1772
323
        typeCode = "f";
1773
1.67k
      else if (elementType->isSignedIntegerType())
1774
922
        typeCode = "s";
1775
756
      else if (elementType->isUnsignedIntegerType())
1776
756
        typeCode = "u";
1777
0
      else
1778
0
        llvm_unreachable("Invalid element type!");
1779
1780
2.00k
      SemaRef.Diag(IList->getBeginLoc(),
1781
2.00k
                   SemaRef.Context.getTypeSize(VT) > 64
1782
2.00k
                       ? 
diag::note_neon_vector_initializer_non_portable_q737
1783
2.00k
                       : 
diag::note_neon_vector_initializer_non_portable1.26k
)
1784
2.00k
          << typeCode << typeSize;
1785
2.00k
    }
1786
1787
55.6k
    return;
1788
111k
  }
1789
1790
396
  InitializedEntity ElementEntity =
1791
396
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
1792
1793
  // OpenCL and HLSL initializers allow vectors to be constructed from vectors.
1794
1.65k
  for (unsigned i = 0; i < maxElements; 
++i1.26k
) {
1795
    // Don't attempt to go past the end of the init list
1796
1.31k
    if (Index >= IList->getNumInits())
1797
55
      break;
1798
1799
1.26k
    ElementEntity.setElementIndex(Index);
1800
1801
1.26k
    QualType IType = IList->getInit(Index)->getType();
1802
1.26k
    if (!IType->isVectorType()) {
1803
1.19k
      CheckSubElementType(ElementEntity, IList, elementType, Index,
1804
1.19k
                          StructuredList, StructuredIndex);
1805
1.19k
      ++numEltsInit;
1806
1.19k
    } else {
1807
69
      QualType VecType;
1808
69
      const VectorType *IVT = IType->castAs<VectorType>();
1809
69
      unsigned numIElts = IVT->getNumElements();
1810
1811
69
      if (IType->isExtVectorType())
1812
65
        VecType = SemaRef.Context.getExtVectorType(elementType, numIElts);
1813
4
      else
1814
4
        VecType = SemaRef.Context.getVectorType(elementType, numIElts,
1815
4
                                                IVT->getVectorKind());
1816
69
      CheckSubElementType(ElementEntity, IList, VecType, Index,
1817
69
                          StructuredList, StructuredIndex);
1818
69
      numEltsInit += numIElts;
1819
69
    }
1820
1.26k
  }
1821
1822
  // OpenCL and HLSL require all elements to be initialized.
1823
396
  if (numEltsInit != maxElements) {
1824
4
    if (!VerifyOnly)
1825
3
      SemaRef.Diag(IList->getBeginLoc(),
1826
3
                   diag::err_vector_incorrect_num_initializers)
1827
3
          << (numEltsInit < maxElements) << maxElements << numEltsInit;
1828
4
    hadError = true;
1829
4
  }
1830
396
}
1831
1832
/// Check if the type of a class element has an accessible destructor, and marks
1833
/// it referenced. Returns true if we shouldn't form a reference to the
1834
/// destructor.
1835
///
1836
/// Aggregate initialization requires a class element's destructor be
1837
/// accessible per 11.6.1 [dcl.init.aggr]:
1838
///
1839
/// The destructor for each element of class type is potentially invoked
1840
/// (15.4 [class.dtor]) from the context where the aggregate initialization
1841
/// occurs.
1842
static bool checkDestructorReference(QualType ElementType, SourceLocation Loc,
1843
60.8k
                                     Sema &SemaRef) {
1844
60.8k
  auto *CXXRD = ElementType->getAsCXXRecordDecl();
1845
60.8k
  if (!CXXRD)
1846
49.8k
    return false;
1847
1848
11.0k
  CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(CXXRD);
1849
11.0k
  SemaRef.CheckDestructorAccess(Loc, Destructor,
1850
11.0k
                                SemaRef.PDiag(diag::err_access_dtor_temp)
1851
11.0k
                                << ElementType);
1852
11.0k
  SemaRef.MarkFunctionReferenced(Loc, Destructor);
1853
11.0k
  return SemaRef.DiagnoseUseOfDecl(Destructor, Loc);
1854
60.8k
}
1855
1856
void InitListChecker::CheckArrayType(const InitializedEntity &Entity,
1857
                                     InitListExpr *IList, QualType &DeclType,
1858
                                     llvm::APSInt elementIndex,
1859
                                     bool SubobjectIsDesignatorContext,
1860
                                     unsigned &Index,
1861
                                     InitListExpr *StructuredList,
1862
32.6k
                                     unsigned &StructuredIndex) {
1863
32.6k
  const ArrayType *arrayType = SemaRef.Context.getAsArrayType(DeclType);
1864
1865
32.6k
  if (!VerifyOnly) {
1866
15.2k
    if (checkDestructorReference(arrayType->getElementType(),
1867
15.2k
                                 IList->getEndLoc(), SemaRef)) {
1868
0
      hadError = true;
1869
0
      return;
1870
0
    }
1871
15.2k
  }
1872
1873
  // Check for the special-case of initializing an array with a string.
1874
32.6k
  if (Index < IList->getNumInits()) {
1875
31.4k
    if (IsStringInit(IList->getInit(Index), arrayType, SemaRef.Context) ==
1876
31.4k
        SIF_None) {
1877
      // We place the string literal directly into the resulting
1878
      // initializer list. This is the only place where the structure
1879
      // of the structured initializer list doesn't match exactly,
1880
      // because doing so would involve allocating one character
1881
      // constant for each string.
1882
      // FIXME: Should we do these checks in verify-only mode too?
1883
64
      if (!VerifyOnly)
1884
32
        CheckStringInit(IList->getInit(Index), DeclType, arrayType, SemaRef);
1885
64
      if (StructuredList) {
1886
32
        UpdateStructuredListElement(StructuredList, StructuredIndex,
1887
32
                                    IList->getInit(Index));
1888
32
        StructuredList->resizeInits(SemaRef.Context, StructuredIndex);
1889
32
      }
1890
64
      ++Index;
1891
64
      return;
1892
64
    }
1893
31.4k
  }
1894
32.5k
  if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(arrayType)) {
1895
    // Check for VLAs; in standard C it would be possible to check this
1896
    // earlier, but I don't know where clang accepts VLAs (gcc accepts
1897
    // them in all sorts of strange places).
1898
18
    if (!VerifyOnly)
1899
9
      SemaRef.Diag(VAT->getSizeExpr()->getBeginLoc(),
1900
9
                   diag::err_variable_object_no_init)
1901
9
          << VAT->getSizeExpr()->getSourceRange();
1902
18
    hadError = true;
1903
18
    ++Index;
1904
18
    ++StructuredIndex;
1905
18
    return;
1906
18
  }
1907
1908
  // We might know the maximum number of elements in advance.
1909
32.5k
  llvm::APSInt maxElements(elementIndex.getBitWidth(),
1910
32.5k
                           elementIndex.isUnsigned());
1911
32.5k
  bool maxElementsKnown = false;
1912
32.5k
  if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(arrayType)) {
1913
23.3k
    maxElements = CAT->getSize();
1914
23.3k
    elementIndex = elementIndex.extOrTrunc(maxElements.getBitWidth());
1915
23.3k
    elementIndex.setIsUnsigned(maxElements.isUnsigned());
1916
23.3k
    maxElementsKnown = true;
1917
23.3k
  }
1918
1919
32.5k
  QualType elementType = arrayType->getElementType();
1920
138k
  while (Index < IList->getNumInits()) {
1921
106k
    Expr *Init = IList->getInit(Index);
1922
106k
    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
1923
      // If we're not the subobject that matches up with the '{' for
1924
      // the designator, we shouldn't be handling the
1925
      // designator. Return immediately.
1926
638
      if (!SubobjectIsDesignatorContext)
1927
36
        return;
1928
1929
      // Handle this designated initializer. elementIndex will be
1930
      // updated to be the next array element we'll initialize.
1931
602
      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
1932
602
                                     DeclType, nullptr, &elementIndex, Index,
1933
602
                                     StructuredList, StructuredIndex, true,
1934
602
                                     false)) {
1935
26
        hadError = true;
1936
26
        continue;
1937
26
      }
1938
1939
576
      if (elementIndex.getBitWidth() > maxElements.getBitWidth())
1940
0
        maxElements = maxElements.extend(elementIndex.getBitWidth());
1941
576
      else if (elementIndex.getBitWidth() < maxElements.getBitWidth())
1942
98
        elementIndex = elementIndex.extend(maxElements.getBitWidth());
1943
576
      elementIndex.setIsUnsigned(maxElements.isUnsigned());
1944
1945
      // If the array is of incomplete type, keep track of the number of
1946
      // elements in the initializer.
1947
576
      if (!maxElementsKnown && 
elementIndex > maxElements110
)
1948
58
        maxElements = elementIndex;
1949
1950
576
      continue;
1951
602
    }
1952
1953
    // If we know the maximum number of elements, and we've already
1954
    // hit it, stop consuming elements in the initializer list.
1955
106k
    if (maxElementsKnown && 
elementIndex == maxElements75.4k
)
1956
402
      break;
1957
1958
105k
    InitializedEntity ElementEntity =
1959
105k
      InitializedEntity::InitializeElement(SemaRef.Context, StructuredIndex,
1960
105k
                                           Entity);
1961
    // Check this element.
1962
105k
    CheckSubElementType(ElementEntity, IList, elementType, Index,
1963
105k
                        StructuredList, StructuredIndex);
1964
105k
    ++elementIndex;
1965
1966
    // If the array is of incomplete type, keep track of the number of
1967
    // elements in the initializer.
1968
105k
    if (!maxElementsKnown && 
elementIndex > maxElements30.6k
)
1969
30.6k
      maxElements = elementIndex;
1970
105k
  }
1971
32.4k
  if (!hadError && 
DeclType->isIncompleteArrayType()32.3k
&&
!VerifyOnly9.04k
) {
1972
    // If this is an incomplete array type, the actual type needs to
1973
    // be calculated here.
1974
4.50k
    llvm::APSInt Zero(maxElements.getBitWidth(), maxElements.isUnsigned());
1975
4.50k
    if (maxElements == Zero && 
!Entity.isVariableLengthArrayNew()37
) {
1976
      // Sizing an array implicitly to zero is not allowed by ISO C,
1977
      // but is supported by GNU.
1978
29
      SemaRef.Diag(IList->getBeginLoc(), diag::ext_typecheck_zero_array_size);
1979
29
    }
1980
1981
4.50k
    DeclType = SemaRef.Context.getConstantArrayType(
1982
4.50k
        elementType, maxElements, nullptr, ArrayType::Normal, 0);
1983
4.50k
  }
1984
32.4k
  if (!hadError) {
1985
    // If there are any members of the array that get value-initialized, check
1986
    // that is possible. That happens if we know the bound and don't have
1987
    // enough elements, or if we're performing an array new with an unknown
1988
    // bound.
1989
32.3k
    if ((maxElementsKnown && 
elementIndex < maxElements23.2k
) ||
1990
32.3k
        
Entity.isVariableLengthArrayNew()18.0k
)
1991
14.3k
      CheckEmptyInitializable(
1992
14.3k
          InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity),
1993
14.3k
          IList->getEndLoc());
1994
32.3k
  }
1995
32.4k
}
1996
1997
bool InitListChecker::CheckFlexibleArrayInit(const InitializedEntity &Entity,
1998
                                             Expr *InitExpr,
1999
                                             FieldDecl *Field,
2000
101
                                             bool TopLevelObject) {
2001
  // Handle GNU flexible array initializers.
2002
101
  unsigned FlexArrayDiag;
2003
101
  if (isa<InitListExpr>(InitExpr) &&
2004
101
      
cast<InitListExpr>(InitExpr)->getNumInits() == 073
) {
2005
    // Empty flexible array init always allowed as an extension
2006
7
    FlexArrayDiag = diag::ext_flexible_array_init;
2007
94
  } else if (!TopLevelObject) {
2008
    // Disallow flexible array init on non-top-level object
2009
2
    FlexArrayDiag = diag::err_flexible_array_init;
2010
92
  } else if (Entity.getKind() != InitializedEntity::EK_Variable) {
2011
    // Disallow flexible array init on anything which is not a variable.
2012
8
    FlexArrayDiag = diag::err_flexible_array_init;
2013
84
  } else if (cast<VarDecl>(Entity.getDecl())->hasLocalStorage()) {
2014
    // Disallow flexible array init on local variables.
2015
8
    FlexArrayDiag = diag::err_flexible_array_init;
2016
76
  } else {
2017
    // Allow other cases.
2018
76
    FlexArrayDiag = diag::ext_flexible_array_init;
2019
76
  }
2020
2021
101
  if (!VerifyOnly) {
2022
49
    SemaRef.Diag(InitExpr->getBeginLoc(), FlexArrayDiag)
2023
49
        << InitExpr->getBeginLoc();
2024
49
    SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2025
49
      << Field;
2026
49
  }
2027
2028
101
  return FlexArrayDiag != diag::ext_flexible_array_init;
2029
101
}
2030
2031
void InitListChecker::CheckStructUnionTypes(
2032
    const InitializedEntity &Entity, InitListExpr *IList, QualType DeclType,
2033
    CXXRecordDecl::base_class_range Bases, RecordDecl::field_iterator Field,
2034
    bool SubobjectIsDesignatorContext, unsigned &Index,
2035
    InitListExpr *StructuredList, unsigned &StructuredIndex,
2036
53.4k
    bool TopLevelObject) {
2037
53.4k
  RecordDecl *structDecl = DeclType->castAs<RecordType>()->getDecl();
2038
2039
  // If the record is invalid, some of it's members are invalid. To avoid
2040
  // confusion, we forgo checking the initializer for the entire record.
2041
53.4k
  if (structDecl->isInvalidDecl()) {
2042
    // Assume it was supposed to consume a single initializer.
2043
43
    ++Index;
2044
43
    hadError = true;
2045
43
    return;
2046
43
  }
2047
2048
53.4k
  if (DeclType->isUnionType() && 
IList->getNumInits() == 02.68k
) {
2049
706
    RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2050
2051
706
    if (!VerifyOnly)
2052
454
      
for (FieldDecl *FD : RD->fields())267
{
2053
454
        QualType ET = SemaRef.Context.getBaseElementType(FD->getType());
2054
454
        if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2055
0
          hadError = true;
2056
0
          return;
2057
0
        }
2058
454
      }
2059
2060
    // If there's a default initializer, use it.
2061
706
    if (isa<CXXRecordDecl>(RD) &&
2062
706
        
cast<CXXRecordDecl>(RD)->hasInClassInitializer()558
) {
2063
81
      if (!StructuredList)
2064
54
        return;
2065
27
      for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2066
39
           Field != FieldEnd; 
++Field12
) {
2067
37
        if (Field->hasInClassInitializer()) {
2068
25
          StructuredList->setInitializedFieldInUnion(*Field);
2069
          // FIXME: Actually build a CXXDefaultInitExpr?
2070
25
          return;
2071
25
        }
2072
37
      }
2073
27
    }
2074
2075
    // Value-initialize the first member of the union that isn't an unnamed
2076
    // bitfield.
2077
627
    for (RecordDecl::field_iterator FieldEnd = RD->field_end();
2078
671
         Field != FieldEnd; 
++Field44
) {
2079
561
      if (!Field->isUnnamedBitfield()) {
2080
517
        CheckEmptyInitializable(
2081
517
            InitializedEntity::InitializeMember(*Field, &Entity),
2082
517
            IList->getEndLoc());
2083
517
        if (StructuredList)
2084
199
          StructuredList->setInitializedFieldInUnion(*Field);
2085
517
        break;
2086
517
      }
2087
561
    }
2088
627
    return;
2089
706
  }
2090
2091
52.7k
  bool InitializedSomething = false;
2092
2093
  // If we have any base classes, they are initialized prior to the fields.
2094
52.7k
  for (auto &Base : Bases) {
2095
809
    Expr *Init = Index < IList->getNumInits() ? 
IList->getInit(Index)330
:
nullptr479
;
2096
2097
    // Designated inits always initialize fields, so if we see one, all
2098
    // remaining base classes have no explicit initializer.
2099
809
    if (Init && 
isa<DesignatedInitExpr>(Init)330
)
2100
32
      Init = nullptr;
2101
2102
809
    SourceLocation InitLoc = Init ? 
Init->getBeginLoc()298
:
IList->getEndLoc()511
;
2103
809
    InitializedEntity BaseEntity = InitializedEntity::InitializeBase(
2104
809
        SemaRef.Context, &Base, false, &Entity);
2105
809
    if (Init) {
2106
298
      CheckSubElementType(BaseEntity, IList, Base.getType(), Index,
2107
298
                          StructuredList, StructuredIndex);
2108
298
      InitializedSomething = true;
2109
511
    } else {
2110
511
      CheckEmptyInitializable(BaseEntity, InitLoc);
2111
511
    }
2112
2113
809
    if (!VerifyOnly)
2114
347
      if (checkDestructorReference(Base.getType(), InitLoc, SemaRef)) {
2115
2
        hadError = true;
2116
2
        return;
2117
2
      }
2118
809
  }
2119
2120
  // If structDecl is a forward declaration, this loop won't do
2121
  // anything except look at designated initializers; That's okay,
2122
  // because an error should get printed out elsewhere. It might be
2123
  // worthwhile to skip over the rest of the initializer, though.
2124
52.7k
  RecordDecl *RD = DeclType->castAs<RecordType>()->getDecl();
2125
52.7k
  RecordDecl::field_iterator FieldEnd = RD->field_end();
2126
210k
  size_t NumRecordDecls = llvm::count_if(RD->decls(), [&](const Decl *D) {
2127
210k
    return isa<FieldDecl>(D) || 
isa<RecordDecl>(D)123k
;
2128
210k
  });
2129
52.7k
  bool CheckForMissingFields =
2130
52.7k
    !IList->isIdiomaticZeroInitializer(SemaRef.getLangOpts());
2131
52.7k
  bool HasDesignatedInit = false;
2132
2133
125k
  while (Index < IList->getNumInits()) {
2134
73.8k
    Expr *Init = IList->getInit(Index);
2135
73.8k
    SourceLocation InitLoc = Init->getBeginLoc();
2136
2137
73.8k
    if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init)) {
2138
      // If we're not the subobject that matches up with the '{' for
2139
      // the designator, we shouldn't be handling the
2140
      // designator. Return immediately.
2141
3.92k
      if (!SubobjectIsDesignatorContext)
2142
181
        return;
2143
2144
3.74k
      HasDesignatedInit = true;
2145
2146
      // Handle this designated initializer. Field will be updated to
2147
      // the next field that we'll be initializing.
2148
3.74k
      if (CheckDesignatedInitializer(Entity, IList, DIE, 0,
2149
3.74k
                                     DeclType, &Field, nullptr, Index,
2150
3.74k
                                     StructuredList, StructuredIndex,
2151
3.74k
                                     true, TopLevelObject))
2152
106
        hadError = true;
2153
3.63k
      else if (!VerifyOnly) {
2154
        // Find the field named by the designated initializer.
2155
1.63k
        RecordDecl::field_iterator F = RD->field_begin();
2156
2.76k
        while (std::next(F) != Field)
2157
1.12k
          ++F;
2158
1.63k
        QualType ET = SemaRef.Context.getBaseElementType(F->getType());
2159
1.63k
        if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2160
0
          hadError = true;
2161
0
          return;
2162
0
        }
2163
1.63k
      }
2164
2165
3.74k
      InitializedSomething = true;
2166
2167
      // Disable check for missing fields when designators are used.
2168
      // This matches gcc behaviour.
2169
3.74k
      CheckForMissingFields = false;
2170
3.74k
      continue;
2171
3.74k
    }
2172
2173
    // Check if this is an initializer of forms:
2174
    //
2175
    //   struct foo f = {};
2176
    //   struct foo g = {0};
2177
    //
2178
    // These are okay for randomized structures. [C99 6.7.8p19]
2179
    //
2180
    // Also, if there is only one element in the structure, we allow something
2181
    // like this, because it's really not randomized in the tranditional sense.
2182
    //
2183
    //   struct foo h = {bar};
2184
69.8k
    auto IsZeroInitializer = [&](const Expr *I) {
2185
14
      if (IList->getNumInits() == 1) {
2186
8
        if (NumRecordDecls == 1)
2187
6
          return true;
2188
2
        if (const auto *IL = dyn_cast<IntegerLiteral>(I))
2189
2
          return IL->getValue().isZero();
2190
2
      }
2191
6
      return false;
2192
14
    };
2193
2194
    // Don't allow non-designated initializers on randomized structures.
2195
69.8k
    if (RD->isRandomized() && 
!IsZeroInitializer(Init)14
) {
2196
6
      if (!VerifyOnly)
2197
3
        SemaRef.Diag(InitLoc, diag::err_non_designated_init_used);
2198
6
      hadError = true;
2199
6
      break;
2200
6
    }
2201
2202
69.8k
    if (Field == FieldEnd) {
2203
      // We've run out of fields. We're done.
2204
601
      break;
2205
601
    }
2206
2207
    // We've already initialized a member of a union. We're done.
2208
69.2k
    if (InitializedSomething && 
DeclType->isUnionType()38.8k
)
2209
56
      break;
2210
2211
    // If we've hit the flexible array member at the end, we're done.
2212
69.2k
    if (Field->getType()->isIncompleteArrayType())
2213
89
      break;
2214
2215
69.1k
    if (Field->isUnnamedBitfield()) {
2216
      // Don't initialize unnamed bitfields, e.g. "int : 20;"
2217
171
      ++Field;
2218
171
      continue;
2219
171
    }
2220
2221
    // Make sure we can use this declaration.
2222
68.9k
    bool InvalidUse;
2223
68.9k
    if (VerifyOnly)
2224
38.1k
      InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2225
30.8k
    else
2226
30.8k
      InvalidUse = SemaRef.DiagnoseUseOfDecl(
2227
30.8k
          *Field, IList->getInit(Index)->getBeginLoc());
2228
68.9k
    if (InvalidUse) {
2229
0
      ++Index;
2230
0
      ++Field;
2231
0
      hadError = true;
2232
0
      continue;
2233
0
    }
2234
2235
68.9k
    if (!VerifyOnly) {
2236
30.8k
      QualType ET = SemaRef.Context.getBaseElementType(Field->getType());
2237
30.8k
      if (checkDestructorReference(ET, InitLoc, SemaRef)) {
2238
8
        hadError = true;
2239
8
        return;
2240
8
      }
2241
30.8k
    }
2242
2243
68.9k
    InitializedEntity MemberEntity =
2244
68.9k
      InitializedEntity::InitializeMember(*Field, &Entity);
2245
68.9k
    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2246
68.9k
                        StructuredList, StructuredIndex);
2247
68.9k
    InitializedSomething = true;
2248
2249
68.9k
    if (DeclType->isUnionType() && 
StructuredList1.46k
) {
2250
      // Initialize the first field within the union.
2251
559
      StructuredList->setInitializedFieldInUnion(*Field);
2252
559
    }
2253
2254
68.9k
    ++Field;
2255
68.9k
  }
2256
2257
  // Emit warnings for missing struct field initializers.
2258
52.5k
  if (!VerifyOnly && 
InitializedSomething23.7k
&&
CheckForMissingFields14.5k
&&
2259
52.5k
      
Field != FieldEnd13.3k
&&
!Field->getType()->isIncompleteArrayType()887
&&
2260
52.5k
      
!DeclType->isUnionType()825
) {
2261
    // It is possible we have one or more unnamed bitfields remaining.
2262
    // Find first (if any) named field and emit warning.
2263
392
    for (RecordDecl::field_iterator it = Field, end = RD->field_end();
2264
454
         it != end; 
++it62
) {
2265
405
      if (!it->isUnnamedBitfield() && 
!it->hasInClassInitializer()375
) {
2266
343
        SemaRef.Diag(IList->getSourceRange().getEnd(),
2267
343
                     diag::warn_missing_field_initializers) << *it;
2268
343
        break;
2269
343
      }
2270
405
    }
2271
392
  }
2272
2273
  // Check that any remaining fields can be value-initialized if we're not
2274
  // building a structured list. (If we are, we'll check this later.)
2275
52.5k
  if (!StructuredList && 
Field != FieldEnd27.2k
&&
!DeclType->isUnionType()3.71k
&&
2276
52.5k
      
!Field->getType()->isIncompleteArrayType()2.93k
) {
2277
8.62k
    for (; Field != FieldEnd && 
!hadError5.79k
;
++Field5.76k
) {
2278
5.76k
      if (!Field->isUnnamedBitfield() && 
!Field->hasInClassInitializer()5.70k
)
2279
5.17k
        CheckEmptyInitializable(
2280
5.17k
            InitializedEntity::InitializeMember(*Field, &Entity),
2281
5.17k
            IList->getEndLoc());
2282
5.76k
    }
2283
2.85k
  }
2284
2285
  // Check that the types of the remaining fields have accessible destructors.
2286
52.5k
  if (!VerifyOnly) {
2287
    // If the initializer expression has a designated initializer, check the
2288
    // elements for which a designated initializer is not provided too.
2289
23.7k
    RecordDecl::field_iterator I = HasDesignatedInit ? 
RD->field_begin()1.06k
2290
23.7k
                                                     : 
Field22.6k
;
2291
30.8k
    for (RecordDecl::field_iterator E = RD->field_end(); I != E; 
++I7.08k
) {
2292
7.09k
      QualType ET = SemaRef.Context.getBaseElementType(I->getType());
2293
7.09k
      if (checkDestructorReference(ET, IList->getEndLoc(), SemaRef)) {
2294
4
        hadError = true;
2295
4
        return;
2296
4
      }
2297
7.09k
    }
2298
23.7k
  }
2299
2300
52.5k
  if (Field == FieldEnd || 
!Field->getType()->isIncompleteArrayType()4.16k
||
2301
52.5k
      
Index >= IList->getNumInits()172
)
2302
52.4k
    return;
2303
2304
89
  if (CheckFlexibleArrayInit(Entity, IList->getInit(Index), *Field,
2305
89
                             TopLevelObject)) {
2306
12
    hadError = true;
2307
12
    ++Index;
2308
12
    return;
2309
12
  }
2310
2311
77
  InitializedEntity MemberEntity =
2312
77
    InitializedEntity::InitializeMember(*Field, &Entity);
2313
2314
77
  if (isa<InitListExpr>(IList->getInit(Index)))
2315
53
    CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2316
53
                        StructuredList, StructuredIndex);
2317
24
  else
2318
24
    CheckImplicitInitList(MemberEntity, IList, Field->getType(), Index,
2319
24
                          StructuredList, StructuredIndex);
2320
77
}
2321
2322
/// Expand a field designator that refers to a member of an
2323
/// anonymous struct or union into a series of field designators that
2324
/// refers to the field within the appropriate subobject.
2325
///
2326
static void ExpandAnonymousFieldDesignator(Sema &SemaRef,
2327
                                           DesignatedInitExpr *DIE,
2328
                                           unsigned DesigIdx,
2329
34
                                           IndirectFieldDecl *IndirectField) {
2330
34
  typedef DesignatedInitExpr::Designator Designator;
2331
2332
  // Build the replacement designators.
2333
34
  SmallVector<Designator, 4> Replacements;
2334
34
  for (IndirectFieldDecl::chain_iterator PI = IndirectField->chain_begin(),
2335
112
       PE = IndirectField->chain_end(); PI != PE; 
++PI78
) {
2336
78
    if (PI + 1 == PE)
2337
34
      Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2338
34
                                    DIE->getDesignator(DesigIdx)->getDotLoc(),
2339
34
                                DIE->getDesignator(DesigIdx)->getFieldLoc()));
2340
44
    else
2341
44
      Replacements.push_back(Designator((IdentifierInfo *)nullptr,
2342
44
                                        SourceLocation(), SourceLocation()));
2343
78
    assert(isa<FieldDecl>(*PI));
2344
0
    Replacements.back().setField(cast<FieldDecl>(*PI));
2345
78
  }
2346
2347
  // Expand the current designator into the set of replacement
2348
  // designators, so we have a full subobject path down to where the
2349
  // member of the anonymous struct/union is actually stored.
2350
34
  DIE->ExpandDesignator(SemaRef.Context, DesigIdx, &Replacements[0],
2351
34
                        &Replacements[0] + Replacements.size());
2352
34
}
2353
2354
static DesignatedInitExpr *CloneDesignatedInitExpr(Sema &SemaRef,
2355
34
                                                   DesignatedInitExpr *DIE) {
2356
34
  unsigned NumIndexExprs = DIE->getNumSubExprs() - 1;
2357
34
  SmallVector<Expr*, 4> IndexExprs(NumIndexExprs);
2358
34
  for (unsigned I = 0; I < NumIndexExprs; 
++I0
)
2359
0
    IndexExprs[I] = DIE->getSubExpr(I + 1);
2360
34
  return DesignatedInitExpr::Create(SemaRef.Context, DIE->designators(),
2361
34
                                    IndexExprs,
2362
34
                                    DIE->getEqualOrColonLoc(),
2363
34
                                    DIE->usesGNUSyntax(), DIE->getInit());
2364
34
}
2365
2366
namespace {
2367
2368
// Callback to only accept typo corrections that are for field members of
2369
// the given struct or union.
2370
class FieldInitializerValidatorCCC final : public CorrectionCandidateCallback {
2371
 public:
2372
  explicit FieldInitializerValidatorCCC(RecordDecl *RD)
2373
26
      : Record(RD) {}
2374
2375
16
  bool ValidateCandidate(const TypoCorrection &candidate) override {
2376
16
    FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>();
2377
16
    return FD && 
FD->getDeclContext()->getRedeclContext()->Equals(Record)14
;
2378
16
  }
2379
2380
19
  std::unique_ptr<CorrectionCandidateCallback> clone() override {
2381
19
    return std::make_unique<FieldInitializerValidatorCCC>(*this);
2382
19
  }
2383
2384
 private:
2385
  RecordDecl *Record;
2386
};
2387
2388
} // end anonymous namespace
2389
2390
/// Check the well-formedness of a C99 designated initializer.
2391
///
2392
/// Determines whether the designated initializer @p DIE, which
2393
/// resides at the given @p Index within the initializer list @p
2394
/// IList, is well-formed for a current object of type @p DeclType
2395
/// (C99 6.7.8). The actual subobject that this designator refers to
2396
/// within the current subobject is returned in either
2397
/// @p NextField or @p NextElementIndex (whichever is appropriate).
2398
///
2399
/// @param IList  The initializer list in which this designated
2400
/// initializer occurs.
2401
///
2402
/// @param DIE The designated initializer expression.
2403
///
2404
/// @param DesigIdx  The index of the current designator.
2405
///
2406
/// @param CurrentObjectType The type of the "current object" (C99 6.7.8p17),
2407
/// into which the designation in @p DIE should refer.
2408
///
2409
/// @param NextField  If non-NULL and the first designator in @p DIE is
2410
/// a field, this will be set to the field declaration corresponding
2411
/// to the field named by the designator. On input, this is expected to be
2412
/// the next field that would be initialized in the absence of designation,
2413
/// if the complete object being initialized is a struct.
2414
///
2415
/// @param NextElementIndex  If non-NULL and the first designator in @p
2416
/// DIE is an array designator or GNU array-range designator, this
2417
/// will be set to the last index initialized by this designator.
2418
///
2419
/// @param Index  Index into @p IList where the designated initializer
2420
/// @p DIE occurs.
2421
///
2422
/// @param StructuredList  The initializer list expression that
2423
/// describes all of the subobject initializers in the order they'll
2424
/// actually be initialized.
2425
///
2426
/// @returns true if there was an error, false otherwise.
2427
bool
2428
InitListChecker::CheckDesignatedInitializer(const InitializedEntity &Entity,
2429
                                            InitListExpr *IList,
2430
                                            DesignatedInitExpr *DIE,
2431
                                            unsigned DesigIdx,
2432
                                            QualType &CurrentObjectType,
2433
                                          RecordDecl::field_iterator *NextField,
2434
                                            llvm::APSInt *NextElementIndex,
2435
                                            unsigned &Index,
2436
                                            InitListExpr *StructuredList,
2437
                                            unsigned &StructuredIndex,
2438
                                            bool FinishSubobjectInit,
2439
9.40k
                                            bool TopLevelObject) {
2440
9.40k
  if (DesigIdx == DIE->size()) {
2441
    // C++20 designated initialization can result in direct-list-initialization
2442
    // of the designated subobject. This is the only way that we can end up
2443
    // performing direct initialization as part of aggregate initialization, so
2444
    // it needs special handling.
2445
4.33k
    if (DIE->isDirectInit()) {
2446
46
      Expr *Init = DIE->getInit();
2447
46
      assert(isa<InitListExpr>(Init) &&
2448
46
             "designator result in direct non-list initialization?");
2449
0
      InitializationKind Kind = InitializationKind::CreateDirectList(
2450
46
          DIE->getBeginLoc(), Init->getBeginLoc(), Init->getEndLoc());
2451
46
      InitializationSequence Seq(SemaRef, Entity, Kind, Init,
2452
46
                                 /*TopLevelOfInitList*/ true);
2453
46
      if (StructuredList) {
2454
46
        ExprResult Result = VerifyOnly
2455
46
                                ? 
getDummyInit()27
2456
46
                                : 
Seq.Perform(SemaRef, Entity, Kind, Init)19
;
2457
46
        UpdateStructuredListElement(StructuredList, StructuredIndex,
2458
46
                                    Result.get());
2459
46
      }
2460
46
      ++Index;
2461
46
      return !Seq;
2462
46
    }
2463
2464
    // Check the actual initialization for the designated object type.
2465
4.28k
    bool prevHadError = hadError;
2466
2467
    // Temporarily remove the designator expression from the
2468
    // initializer list that the child calls see, so that we don't try
2469
    // to re-process the designator.
2470
4.28k
    unsigned OldIndex = Index;
2471
4.28k
    IList->setInit(OldIndex, DIE->getInit());
2472
2473
4.28k
    CheckSubElementType(Entity, IList, CurrentObjectType, Index, StructuredList,
2474
4.28k
                        StructuredIndex, /*DirectlyDesignated=*/true);
2475
2476
    // Restore the designated initializer expression in the syntactic
2477
    // form of the initializer list.
2478
4.28k
    if (IList->getInit(OldIndex) != DIE->getInit())
2479
231
      DIE->setInit(IList->getInit(OldIndex));
2480
4.28k
    IList->setInit(OldIndex, DIE);
2481
2482
4.28k
    return hadError && 
!prevHadError85
;
2483
4.33k
  }
2484
2485
5.07k
  DesignatedInitExpr::Designator *D = DIE->getDesignator(DesigIdx);
2486
5.07k
  bool IsFirstDesignator = (DesigIdx == 0);
2487
5.07k
  if (IsFirstDesignator ? 
FullyStructuredList4.34k
:
StructuredList732
) {
2488
    // Determine the structural initializer list that corresponds to the
2489
    // current subobject.
2490
5.03k
    if (IsFirstDesignator)
2491
4.34k
      StructuredList = FullyStructuredList;
2492
691
    else {
2493
691
      Expr *ExistingInit = StructuredIndex < StructuredList->getNumInits() ?
2494
691
          StructuredList->getInit(StructuredIndex) : 
nullptr0
;
2495
691
      if (!ExistingInit && 
StructuredList->hasArrayFiller()449
)
2496
1
        ExistingInit = StructuredList->getArrayFiller();
2497
2498
691
      if (!ExistingInit)
2499
448
        StructuredList = getStructuredSubobjectInit(
2500
448
            IList, Index, CurrentObjectType, StructuredList, StructuredIndex,
2501
448
            SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2502
243
      else if (InitListExpr *Result = dyn_cast<InitListExpr>(ExistingInit))
2503
103
        StructuredList = Result;
2504
140
      else {
2505
        // We are creating an initializer list that initializes the
2506
        // subobjects of the current object, but there was already an
2507
        // initialization that completely initialized the current
2508
        // subobject, e.g., by a compound literal:
2509
        //
2510
        // struct X { int a, b; };
2511
        // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
2512
        //
2513
        // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
2514
        // designated initializer re-initializes only its current object
2515
        // subobject [0].b.
2516
140
        diagnoseInitOverride(ExistingInit,
2517
140
                             SourceRange(D->getBeginLoc(), DIE->getEndLoc()),
2518
140
                             /*FullyOverwritten=*/false);
2519
2520
140
        if (!VerifyOnly) {
2521
65
          if (DesignatedInitUpdateExpr *E =
2522
65
                  dyn_cast<DesignatedInitUpdateExpr>(ExistingInit))
2523
12
            StructuredList = E->getUpdater();
2524
53
          else {
2525
53
            DesignatedInitUpdateExpr *DIUE = new (SemaRef.Context)
2526
53
                DesignatedInitUpdateExpr(SemaRef.Context, D->getBeginLoc(),
2527
53
                                         ExistingInit, DIE->getEndLoc());
2528
53
            StructuredList->updateInit(SemaRef.Context, StructuredIndex, DIUE);
2529
53
            StructuredList = DIUE->getUpdater();
2530
53
          }
2531
75
        } else {
2532
          // We don't need to track the structured representation of a
2533
          // designated init update of an already-fully-initialized object in
2534
          // verify-only mode. The only reason we would need the structure is
2535
          // to determine where the uninitialized "holes" are, and in this
2536
          // case, we know there aren't any and we can't introduce any.
2537
75
          StructuredList = nullptr;
2538
75
        }
2539
140
      }
2540
691
    }
2541
5.03k
  }
2542
2543
5.07k
  if (D->isFieldDesignator()) {
2544
    // C99 6.7.8p7:
2545
    //
2546
    //   If a designator has the form
2547
    //
2548
    //      . identifier
2549
    //
2550
    //   then the current object (defined below) shall have
2551
    //   structure or union type and the identifier shall be the
2552
    //   name of a member of that type.
2553
4.29k
    const RecordType *RT = CurrentObjectType->getAs<RecordType>();
2554
4.29k
    if (!RT) {
2555
2
      SourceLocation Loc = D->getDotLoc();
2556
2
      if (Loc.isInvalid())
2557
0
        Loc = D->getFieldLoc();
2558
2
      if (!VerifyOnly)
2559
1
        SemaRef.Diag(Loc, diag::err_field_designator_non_aggr)
2560
1
          << SemaRef.getLangOpts().CPlusPlus << CurrentObjectType;
2561
2
      ++Index;
2562
2
      return true;
2563
2
    }
2564
2565
4.29k
    FieldDecl *KnownField = D->getField();
2566
4.29k
    if (!KnownField) {
2567
4.15k
      IdentifierInfo *FieldName = D->getFieldName();
2568
4.15k
      DeclContext::lookup_result Lookup = RT->getDecl()->lookup(FieldName);
2569
4.15k
      for (NamedDecl *ND : Lookup) {
2570
4.09k
        if (auto *FD = dyn_cast<FieldDecl>(ND)) {
2571
4.06k
          KnownField = FD;
2572
4.06k
          break;
2573
4.06k
        }
2574
38
        if (auto *IFD = dyn_cast<IndirectFieldDecl>(ND)) {
2575
          // In verify mode, don't modify the original.
2576
34
          if (VerifyOnly)
2577
34
            DIE = CloneDesignatedInitExpr(SemaRef, DIE);
2578
34
          ExpandAnonymousFieldDesignator(SemaRef, DIE, DesigIdx, IFD);
2579
34
          D = DIE->getDesignator(DesigIdx);
2580
34
          KnownField = cast<FieldDecl>(*IFD->chain_begin());
2581
34
          break;
2582
34
        }
2583
38
      }
2584
4.15k
      if (!KnownField) {
2585
64
        if (VerifyOnly) {
2586
38
          ++Index;
2587
38
          return true;  // No typo correction when just trying this out.
2588
38
        }
2589
2590
        // Name lookup found something, but it wasn't a field.
2591
26
        if (!Lookup.empty()) {
2592
0
          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_nonfield)
2593
0
            << FieldName;
2594
0
          SemaRef.Diag(Lookup.front()->getLocation(),
2595
0
                       diag::note_field_designator_found);
2596
0
          ++Index;
2597
0
          return true;
2598
0
        }
2599
2600
        // Name lookup didn't find anything.
2601
        // Determine whether this was a typo for another field name.
2602
26
        FieldInitializerValidatorCCC CCC(RT->getDecl());
2603
26
        if (TypoCorrection Corrected = SemaRef.CorrectTypo(
2604
26
                DeclarationNameInfo(FieldName, D->getFieldLoc()),
2605
26
                Sema::LookupMemberName, /*Scope=*/nullptr, /*SS=*/nullptr, CCC,
2606
26
                Sema::CTK_ErrorRecovery, RT->getDecl())) {
2607
8
          SemaRef.diagnoseTypo(
2608
8
              Corrected,
2609
8
              SemaRef.PDiag(diag::err_field_designator_unknown_suggest)
2610
8
                << FieldName << CurrentObjectType);
2611
8
          KnownField = Corrected.getCorrectionDeclAs<FieldDecl>();
2612
8
          hadError = true;
2613
18
        } else {
2614
          // Typo correction didn't find anything.
2615
18
          SemaRef.Diag(D->getFieldLoc(), diag::err_field_designator_unknown)
2616
18
            << FieldName << CurrentObjectType;
2617
18
          ++Index;
2618
18
          return true;
2619
18
        }
2620
26
      }
2621
4.15k
    }
2622
2623
4.24k
    unsigned NumBases = 0;
2624
4.24k
    if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2625
2.99k
      NumBases = CXXRD->getNumBases();
2626
2627
4.24k
    unsigned FieldIndex = NumBases;
2628
2629
6.99k
    for (auto *FI : RT->getDecl()->fields()) {
2630
6.99k
      if (FI->isUnnamedBitfield())
2631
114
        continue;
2632
6.88k
      if (declaresSameEntity(KnownField, FI)) {
2633
4.24k
        KnownField = FI;
2634
4.24k
        break;
2635
4.24k
      }
2636
2.64k
      ++FieldIndex;
2637
2.64k
    }
2638
2639
4.24k
    RecordDecl::field_iterator Field =
2640
4.24k
        RecordDecl::field_iterator(DeclContext::decl_iterator(KnownField));
2641
2642
    // All of the fields of a union are located at the same place in
2643
    // the initializer list.
2644
4.24k
    if (RT->getDecl()->isUnion()) {
2645
684
      FieldIndex = 0;
2646
684
      if (StructuredList) {
2647
676
        FieldDecl *CurrentField = StructuredList->getInitializedFieldInUnion();
2648
676
        if (CurrentField && 
!declaresSameEntity(CurrentField, *Field)91
) {
2649
81
          assert(StructuredList->getNumInits() == 1
2650
81
                 && "A union should never have more than one initializer!");
2651
2652
0
          Expr *ExistingInit = StructuredList->getInit(0);
2653
81
          if (ExistingInit) {
2654
            // We're about to throw away an initializer, emit warning.
2655
81
            diagnoseInitOverride(
2656
81
                ExistingInit, SourceRange(D->getBeginLoc(), DIE->getEndLoc()));
2657
81
          }
2658
2659
          // remove existing initializer
2660
81
          StructuredList->resizeInits(SemaRef.Context, 0);
2661
81
          StructuredList->setInitializedFieldInUnion(nullptr);
2662
81
        }
2663
2664
0
        StructuredList->setInitializedFieldInUnion(*Field);
2665
676
      }
2666
684
    }
2667
2668
    // Make sure we can use this declaration.
2669
0
    bool InvalidUse;
2670
4.24k
    if (VerifyOnly)
2671
2.30k
      InvalidUse = !SemaRef.CanUseDecl(*Field, TreatUnavailableAsInvalid);
2672
1.93k
    else
2673
1.93k
      InvalidUse = SemaRef.DiagnoseUseOfDecl(*Field, D->getFieldLoc());
2674
4.24k
    if (InvalidUse) {
2675
0
      ++Index;
2676
0
      return true;
2677
0
    }
2678
2679
    // C++20 [dcl.init.list]p3:
2680
    //   The ordered identifiers in the designators of the designated-
2681
    //   initializer-list shall form a subsequence of the ordered identifiers
2682
    //   in the direct non-static data members of T.
2683
    //
2684
    // Note that this is not a condition on forming the aggregate
2685
    // initialization, only on actually performing initialization,
2686
    // so it is not checked in VerifyOnly mode.
2687
    //
2688
    // FIXME: This is the only reordering diagnostic we produce, and it only
2689
    // catches cases where we have a top-level field designator that jumps
2690
    // backwards. This is the only such case that is reachable in an
2691
    // otherwise-valid C++20 program, so is the only case that's required for
2692
    // conformance, but for consistency, we should diagnose all the other
2693
    // cases where a designator takes us backwards too.
2694
4.24k
    if (IsFirstDesignator && 
!VerifyOnly3.68k
&&
SemaRef.getLangOpts().CPlusPlus1.65k
&&
2695
4.24k
        
NextField1.24k
&&
2696
4.24k
        
(1.24k
*NextField == RT->getDecl()->field_end()1.24k
||
2697
1.24k
         
(*NextField)->getFieldIndex() > Field->getFieldIndex() + 11.16k
)) {
2698
      // Find the field that we just initialized.
2699
112
      FieldDecl *PrevField = nullptr;
2700
112
      for (auto FI = RT->getDecl()->field_begin();
2701
361
           FI != RT->getDecl()->field_end(); 
++FI249
) {
2702
277
        if (FI->isUnnamedBitfield())
2703
18
          continue;
2704
259
        if (*NextField != RT->getDecl()->field_end() &&
2705
259
            
declaresSameEntity(*FI, **NextField)117
)
2706
28
          break;
2707
231
        PrevField = *FI;
2708
231
      }
2709
2710
112
      if (PrevField &&
2711
112
          PrevField->getFieldIndex() > KnownField->getFieldIndex()) {
2712
76
        SemaRef.Diag(DIE->getBeginLoc(), diag::ext_designated_init_reordered)
2713
76
            << KnownField << PrevField << DIE->getSourceRange();
2714
2715
76
        unsigned OldIndex = NumBases + PrevField->getFieldIndex();
2716
76
        if (StructuredList && OldIndex <= StructuredList->getNumInits()) {
2717
70
          if (Expr *PrevInit = StructuredList->getInit(OldIndex)) {
2718
70
            SemaRef.Diag(PrevInit->getBeginLoc(),
2719
70
                         diag::note_previous_field_init)
2720
70
                << PrevField << PrevInit->getSourceRange();
2721
70
          }
2722
70
        }
2723
76
      }
2724
112
    }
2725
2726
2727
    // Update the designator with the field declaration.
2728
4.24k
    if (!VerifyOnly)
2729
1.93k
      D->setField(*Field);
2730
2731
    // Make sure that our non-designated initializer list has space
2732
    // for a subobject corresponding to this field.
2733
4.24k
    if (StructuredList && 
FieldIndex >= StructuredList->getNumInits()4.15k
)
2734
3.63k
      StructuredList->resizeInits(SemaRef.Context, FieldIndex + 1);
2735
2736
    // This designator names a flexible array member.
2737
4.24k
    if (Field->getType()->isIncompleteArrayType()) {
2738
16
      bool Invalid = false;
2739
16
      if ((DesigIdx + 1) != DIE->size()) {
2740
        // We can't designate an object within the flexible array
2741
        // member (because GCC doesn't allow it).
2742
2
        if (!VerifyOnly) {
2743
1
          DesignatedInitExpr::Designator *NextD
2744
1
            = DIE->getDesignator(DesigIdx + 1);
2745
1
          SemaRef.Diag(NextD->getBeginLoc(),
2746
1
                       diag::err_designator_into_flexible_array_member)
2747
1
              << SourceRange(NextD->getBeginLoc(), DIE->getEndLoc());
2748
1
          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2749
1
            << *Field;
2750
1
        }
2751
2
        Invalid = true;
2752
2
      }
2753
2754
16
      if (!hadError && !isa<InitListExpr>(DIE->getInit()) &&
2755
16
          
!isa<StringLiteral>(DIE->getInit())6
) {
2756
        // The initializer is not an initializer list.
2757
2
        if (!VerifyOnly) {
2758
1
          SemaRef.Diag(DIE->getInit()->getBeginLoc(),
2759
1
                       diag::err_flexible_array_init_needs_braces)
2760
1
              << DIE->getInit()->getSourceRange();
2761
1
          SemaRef.Diag(Field->getLocation(), diag::note_flexible_array_member)
2762
1
            << *Field;
2763
1
        }
2764
2
        Invalid = true;
2765
2
      }
2766
2767
      // Check GNU flexible array initializer.
2768
16
      if (!Invalid && CheckFlexibleArrayInit(Entity, DIE->getInit(), *Field,
2769
12
                                             TopLevelObject))
2770
6
        Invalid = true;
2771
2772
16
      if (Invalid) {
2773
10
        ++Index;
2774
10
        return true;
2775
10
      }
2776
2777
      // Initialize the array.
2778
6
      bool prevHadError = hadError;
2779
6
      unsigned newStructuredIndex = FieldIndex;
2780
6
      unsigned OldIndex = Index;
2781
6
      IList->setInit(Index, DIE->getInit());
2782
2783
6
      InitializedEntity MemberEntity =
2784
6
        InitializedEntity::InitializeMember(*Field, &Entity);
2785
6
      CheckSubElementType(MemberEntity, IList, Field->getType(), Index,
2786
6
                          StructuredList, newStructuredIndex);
2787
2788
6
      IList->setInit(OldIndex, DIE);
2789
6
      if (hadError && 
!prevHadError0
) {
2790
0
        ++Field;
2791
0
        ++FieldIndex;
2792
0
        if (NextField)
2793
0
          *NextField = Field;
2794
0
        StructuredIndex = FieldIndex;
2795
0
        return true;
2796
0
      }
2797
4.22k
    } else {
2798
      // Recurse to check later designated subobjects.
2799
4.22k
      QualType FieldType = Field->getType();
2800
4.22k
      unsigned newStructuredIndex = FieldIndex;
2801
2802
4.22k
      InitializedEntity MemberEntity =
2803
4.22k
        InitializedEntity::InitializeMember(*Field, &Entity);
2804
4.22k
      if (CheckDesignatedInitializer(MemberEntity, IList, DIE, DesigIdx + 1,
2805
4.22k
                                     FieldType, nullptr, nullptr, Index,
2806
4.22k
                                     StructuredList, newStructuredIndex,
2807
4.22k
                                     FinishSubobjectInit, false))
2808
44
        return true;
2809
4.22k
    }
2810
2811
    // Find the position of the next field to be initialized in this
2812
    // subobject.
2813
4.18k
    ++Field;
2814
4.18k
    ++FieldIndex;
2815
2816
    // If this the first designator, our caller will continue checking
2817
    // the rest of this struct/class/union subobject.
2818
4.18k
    if (IsFirstDesignator) {
2819
3.63k
      if (NextField)
2820
3.63k
        *NextField = Field;
2821
3.63k
      StructuredIndex = FieldIndex;
2822
3.63k
      return false;
2823
3.63k
    }
2824
2825
552
    if (!FinishSubobjectInit)
2826
4
      return false;
2827
2828
    // We've already initialized something in the union; we're done.
2829
548
    if (RT->getDecl()->isUnion())
2830
90
      return hadError;
2831
2832
    // Check the remaining fields within this class/struct/union subobject.
2833
458
    bool prevHadError = hadError;
2834
2835
458
    auto NoBases =
2836
458
        CXXRecordDecl::base_class_range(CXXRecordDecl::base_class_iterator(),
2837
458
                                        CXXRecordDecl::base_class_iterator());
2838
458
    CheckStructUnionTypes(Entity, IList, CurrentObjectType, NoBases, Field,
2839
458
                          false, Index, StructuredList, FieldIndex);
2840
458
    return hadError && 
!prevHadError14
;
2841
548
  }
2842
2843
  // C99 6.7.8p6:
2844
  //
2845
  //   If a designator has the form
2846
  //
2847
  //      [ constant-expression ]
2848
  //
2849
  //   then the current object (defined below) shall have array
2850
  //   type and the expression shall be an integer constant
2851
  //   expression. If the array is of unknown size, any
2852
  //   nonnegative value is valid.
2853
  //
2854
  // Additionally, cope with the GNU extension that permits
2855
  // designators of the form
2856
  //
2857
  //      [ constant-expression ... constant-expression ]
2858
776
  const ArrayType *AT = SemaRef.Context.getAsArrayType(CurrentObjectType);
2859
776
  if (!AT) {
2860
2
    if (!VerifyOnly)
2861
1
      SemaRef.Diag(D->getLBracketLoc(), diag::err_array_designator_non_array)
2862
1
        << CurrentObjectType;
2863
2
    ++Index;
2864
2
    return true;
2865
2
  }
2866
2867
774
  Expr *IndexExpr = nullptr;
2868
774
  llvm::APSInt DesignatedStartIndex, DesignatedEndIndex;
2869
774
  if (D->isArrayDesignator()) {
2870
726
    IndexExpr = DIE->getArrayIndex(*D);
2871
726
    DesignatedStartIndex = IndexExpr->EvaluateKnownConstInt(SemaRef.Context);
2872
726
    DesignatedEndIndex = DesignatedStartIndex;
2873
726
  } else {
2874
48
    assert(D->isArrayRangeDesignator() && "Need array-range designator");
2875
2876
0
    DesignatedStartIndex =
2877
48
      DIE->getArrayRangeStart(*D)->EvaluateKnownConstInt(SemaRef.Context);
2878
48
    DesignatedEndIndex =
2879
48
      DIE->getArrayRangeEnd(*D)->EvaluateKnownConstInt(SemaRef.Context);
2880
48
    IndexExpr = DIE->getArrayRangeEnd(*D);
2881
2882
    // Codegen can't handle evaluating array range designators that have side
2883
    // effects, because we replicate the AST value for each initialized element.
2884
    // As such, set the sawArrayRangeDesignator() bit if we initialize multiple
2885
    // elements with something that has a side effect, so codegen can emit an
2886
    // "error unsupported" error instead of miscompiling the app.
2887
48
    if (DesignatedStartIndex.getZExtValue()!=DesignatedEndIndex.getZExtValue()&&
2888
48
        DIE->getInit()->HasSideEffects(SemaRef.Context) && 
!VerifyOnly0
)
2889
0
      FullyStructuredList->sawArrayRangeDesignator();
2890
48
  }
2891
2892
774
  if (isa<ConstantArrayType>(AT)) {
2893
662
    llvm::APSInt MaxElements(cast<ConstantArrayType>(AT)->getSize(), false);
2894
662
    DesignatedStartIndex
2895
662
      = DesignatedStartIndex.extOrTrunc(MaxElements.getBitWidth());
2896
662
    DesignatedStartIndex.setIsUnsigned(MaxElements.isUnsigned());
2897
662
    DesignatedEndIndex
2898
662
      = DesignatedEndIndex.extOrTrunc(MaxElements.getBitWidth());
2899
662
    DesignatedEndIndex.setIsUnsigned(MaxElements.isUnsigned());
2900
662
    if (DesignatedEndIndex >= MaxElements) {
2901
20
      if (!VerifyOnly)
2902
9
        SemaRef.Diag(IndexExpr->getBeginLoc(),
2903
9
                     diag::err_array_designator_too_large)
2904
9
            << toString(DesignatedEndIndex, 10) << toString(MaxElements, 10)
2905
9
            << IndexExpr->getSourceRange();
2906
20
      ++Index;
2907
20
      return true;
2908
20
    }
2909
662
  } else {
2910
112
    unsigned DesignatedIndexBitWidth =
2911
112
      ConstantArrayType::getMaxSizeBits(SemaRef.Context);
2912
112
    DesignatedStartIndex =
2913
112
      DesignatedStartIndex.extOrTrunc(DesignatedIndexBitWidth);
2914
112
    DesignatedEndIndex =
2915
112
      DesignatedEndIndex.extOrTrunc(DesignatedIndexBitWidth);
2916
112
    DesignatedStartIndex.setIsUnsigned(true);
2917
112
    DesignatedEndIndex.setIsUnsigned(true);
2918
112
  }
2919
2920
754
  bool IsStringLiteralInitUpdate =
2921
754
      StructuredList && 
StructuredList->isStringLiteralInit()722
;
2922
754
  if (IsStringLiteralInitUpdate && 
VerifyOnly0
) {
2923
    // We're just verifying an update to a string literal init. We don't need
2924
    // to split the string up into individual characters to do that.
2925
0
    StructuredList = nullptr;
2926
754
  } else if (IsStringLiteralInitUpdate) {
2927
    // We're modifying a string literal init; we have to decompose the string
2928
    // so we can modify the individual characters.
2929
0
    ASTContext &Context = SemaRef.Context;
2930
0
    Expr *SubExpr = StructuredList->getInit(0)->IgnoreParenImpCasts();
2931
2932
    // Compute the character type
2933
0
    QualType CharTy = AT->getElementType();
2934
2935
    // Compute the type of the integer literals.
2936
0
    QualType PromotedCharTy = CharTy;
2937
0
    if (CharTy->isPromotableIntegerType())
2938
0
      PromotedCharTy = Context.getPromotedIntegerType(CharTy);
2939
0
    unsigned PromotedCharTyWidth = Context.getTypeSize(PromotedCharTy);
2940
2941
0
    if (StringLiteral *SL = dyn_cast<StringLiteral>(SubExpr)) {
2942
      // Get the length of the string.
2943
0
      uint64_t StrLen = SL->getLength();
2944
0
      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2945
0
        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2946
0
      StructuredList->resizeInits(Context, StrLen);
2947
2948
      // Build a literal for each character in the string, and put them into
2949
      // the init list.
2950
0
      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2951
0
        llvm::APInt CodeUnit(PromotedCharTyWidth, SL->getCodeUnit(i));
2952
0
        Expr *Init = new (Context) IntegerLiteral(
2953
0
            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2954
0
        if (CharTy != PromotedCharTy)
2955
0
          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2956
0
                                          Init, nullptr, VK_PRValue,
2957
0
                                          FPOptionsOverride());
2958
0
        StructuredList->updateInit(Context, i, Init);
2959
0
      }
2960
0
    } else {
2961
0
      ObjCEncodeExpr *E = cast<ObjCEncodeExpr>(SubExpr);
2962
0
      std::string Str;
2963
0
      Context.getObjCEncodingForType(E->getEncodedType(), Str);
2964
2965
      // Get the length of the string.
2966
0
      uint64_t StrLen = Str.size();
2967
0
      if (cast<ConstantArrayType>(AT)->getSize().ult(StrLen))
2968
0
        StrLen = cast<ConstantArrayType>(AT)->getSize().getZExtValue();
2969
0
      StructuredList->resizeInits(Context, StrLen);
2970
2971
      // Build a literal for each character in the string, and put them into
2972
      // the init list.
2973
0
      for (unsigned i = 0, e = StrLen; i != e; ++i) {
2974
0
        llvm::APInt CodeUnit(PromotedCharTyWidth, Str[i]);
2975
0
        Expr *Init = new (Context) IntegerLiteral(
2976
0
            Context, CodeUnit, PromotedCharTy, SubExpr->getExprLoc());
2977
0
        if (CharTy != PromotedCharTy)
2978
0
          Init = ImplicitCastExpr::Create(Context, CharTy, CK_IntegralCast,
2979
0
                                          Init, nullptr, VK_PRValue,
2980
0
                                          FPOptionsOverride());
2981
0
        StructuredList->updateInit(Context, i, Init);
2982
0
      }
2983
0
    }
2984
0
  }
2985
2986
  // Make sure that our non-designated initializer list has space
2987
  // for a subobject corresponding to this array element.
2988
754
  if (StructuredList &&
2989
754
      
DesignatedEndIndex.getZExtValue() >= StructuredList->getNumInits()722
)
2990
538
    StructuredList->resizeInits(SemaRef.Context,
2991
538
                                DesignatedEndIndex.getZExtValue() + 1);
2992
2993
  // Repeatedly perform subobject initializations in the range
2994
  // [DesignatedStartIndex, DesignatedEndIndex].
2995
2996
  // Move to the next designator
2997
754
  unsigned ElementIndex = DesignatedStartIndex.getZExtValue();
2998
754
  unsigned OldIndex = Index;
2999
3000
754
  InitializedEntity ElementEntity =
3001
754
    InitializedEntity::InitializeElement(SemaRef.Context, 0, Entity);
3002
3003
1.58k
  while (DesignatedStartIndex <= DesignatedEndIndex) {
3004
    // Recurse to check later designated subobjects.
3005
841
    QualType ElementType = AT->getElementType();
3006
841
    Index = OldIndex;
3007
3008
841
    ElementEntity.setElementIndex(ElementIndex);
3009
841
    if (CheckDesignatedInitializer(
3010
841
            ElementEntity, IList, DIE, DesigIdx + 1, ElementType, nullptr,
3011
841
            nullptr, Index, StructuredList, ElementIndex,
3012
841
            FinishSubobjectInit && 
(DesignatedStartIndex == DesignatedEndIndex)833
,
3013
841
            false))
3014
6
      return true;
3015
3016
    // Move to the next index in the array that we'll be initializing.
3017
835
    ++DesignatedStartIndex;
3018
835
    ElementIndex = DesignatedStartIndex.getZExtValue();
3019
835
  }
3020
3021
  // If this the first designator, our caller will continue checking
3022
  // the rest of this array subobject.
3023
748
  if (IsFirstDesignator) {
3024
576
    if (NextElementIndex)
3025
576
      *NextElementIndex = DesignatedStartIndex;
3026
576
    StructuredIndex = ElementIndex;
3027
576
    return false;
3028
576
  }
3029
3030
172
  if (!FinishSubobjectInit)
3031
4
    return false;
3032
3033
  // Check the remaining elements within this array subobject.
3034
168
  bool prevHadError = hadError;
3035
168
  CheckArrayType(Entity, IList, CurrentObjectType, DesignatedStartIndex,
3036
168
                 /*SubobjectIsDesignatorContext=*/false, Index,
3037
168
                 StructuredList, ElementIndex);
3038
168
  return hadError && 
!prevHadError0
;
3039
172
}
3040
3041
// Get the structured initializer list for a subobject of type
3042
// @p CurrentObjectType.
3043
InitListExpr *
3044
InitListChecker::getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
3045
                                            QualType CurrentObjectType,
3046
                                            InitListExpr *StructuredList,
3047
                                            unsigned StructuredIndex,
3048
                                            SourceRange InitRange,
3049
2.85k
                                            bool IsFullyOverwritten) {
3050
2.85k
  if (!StructuredList)
3051
1.20k
    return nullptr;
3052
3053
1.65k
  Expr *ExistingInit = nullptr;
3054
1.65k
  if (StructuredIndex < StructuredList->getNumInits())
3055
530
    ExistingInit = StructuredList->getInit(StructuredIndex);
3056
3057
1.65k
  if (InitListExpr *Result = dyn_cast_or_null<InitListExpr>(ExistingInit))
3058
    // There might have already been initializers for subobjects of the current
3059
    // object, but a subsequent initializer list will overwrite the entirety
3060
    // of the current object. (See DR 253 and C99 6.7.8p21). e.g.,
3061
    //
3062
    // struct P { char x[6]; };
3063
    // struct P l = { .x[2] = 'x', .x = { [0] = 'f' } };
3064
    //
3065
    // The first designated initializer is ignored, and l.x is just "f".
3066
2
    if (!IsFullyOverwritten)
3067
2
      return Result;
3068
3069
1.65k
  if (ExistingInit) {
3070
    // We are creating an initializer list that initializes the
3071
    // subobjects of the current object, but there was already an
3072
    // initialization that completely initialized the current
3073
    // subobject:
3074
    //
3075
    // struct X { int a, b; };
3076
    // struct X xs[] = { [0] = { 1, 2 }, [0].b = 3 };
3077
    //
3078
    // Here, xs[0].a == 1 and xs[0].b == 3, since the second,
3079
    // designated initializer overwrites the [0].b initializer
3080
    // from the prior initialization.
3081
    //
3082
    // When the existing initializer is an expression rather than an
3083
    // initializer list, we cannot decompose and update it in this way.
3084
    // For example:
3085
    //
3086
    // struct X xs[] = { [0] = (struct X) { 1, 2 }, [0].b = 3 };
3087
    //
3088
    // This case is handled by CheckDesignatedInitializer.
3089
0
    diagnoseInitOverride(ExistingInit, InitRange);
3090
0
  }
3091
3092
1.65k
  unsigned ExpectedNumInits = 0;
3093
1.65k
  if (Index < IList->getNumInits()) {
3094
1.65k
    if (auto *Init = dyn_cast_or_null<InitListExpr>(IList->getInit(Index)))
3095
0
      ExpectedNumInits = Init->getNumInits();
3096
1.65k
    else
3097
1.65k
      ExpectedNumInits = IList->getNumInits() - Index;
3098
1.65k
  }
3099
3100
1.65k
  InitListExpr *Result =
3101
1.65k
      createInitListExpr(CurrentObjectType, InitRange, ExpectedNumInits);
3102
3103
  // Link this new initializer list into the structured initializer
3104
  // lists.
3105
1.65k
  StructuredList->updateInit(SemaRef.Context, StructuredIndex, Result);
3106
1.65k
  return Result;
3107
1.65k
}
3108
3109
InitListExpr *
3110
InitListChecker::createInitListExpr(QualType CurrentObjectType,
3111
                                    SourceRange InitRange,
3112
99.9k
                                    unsigned ExpectedNumInits) {
3113
99.9k
  InitListExpr *Result
3114
99.9k
    = new (SemaRef.Context) InitListExpr(SemaRef.Context,
3115
99.9k
                                         InitRange.getBegin(), None,
3116
99.9k
                                         InitRange.getEnd());
3117
3118
99.9k
  QualType ResultType = CurrentObjectType;
3119
99.9k
  if (!ResultType->isArrayType())
3120
84.4k
    ResultType = ResultType.getNonLValueExprType(SemaRef.Context);
3121
99.9k
  Result->setType(ResultType);
3122
3123
  // Pre-allocate storage for the structured initializer list.
3124
99.9k
  unsigned NumElements = 0;
3125
3126
99.9k
  if (const ArrayType *AType
3127
99.9k
      = SemaRef.Context.getAsArrayType(CurrentObjectType)) {
3128
15.5k
    if (const ConstantArrayType *CAType = dyn_cast<ConstantArrayType>(AType)) {
3129
10.8k
      NumElements = CAType->getSize().getZExtValue();
3130
      // Simple heuristic so that we don't allocate a very large
3131
      // initializer with many empty entries at the end.
3132
10.8k
      if (NumElements > ExpectedNumInits)
3133
6.99k
        NumElements = 0;
3134
10.8k
    }
3135
84.4k
  } else if (const VectorType *VType = CurrentObjectType->getAs<VectorType>()) {
3136
55.9k
    NumElements = VType->getNumElements();
3137
55.9k
  } else 
if (28.5k
CurrentObjectType->isRecordType()28.5k
) {
3138
25.6k
    NumElements = numStructUnionElements(CurrentObjectType);
3139
25.6k
  }
3140
3141
99.9k
  Result->reserveInits(SemaRef.Context, NumElements);
3142
3143
99.9k
  return Result;
3144
99.9k
}
3145
3146
/// Update the initializer at index @p StructuredIndex within the
3147
/// structured initializer list to the value @p expr.
3148
void InitListChecker::UpdateStructuredListElement(InitListExpr *StructuredList,
3149
                                                  unsigned &StructuredIndex,
3150
739k
                                                  Expr *expr) {
3151
  // No structured initializer list to update
3152
739k
  if (!StructuredList)
3153
307k
    return;
3154
3155
432k
  if (Expr *PrevInit = StructuredList->updateInit(SemaRef.Context,
3156
432k
                                                  StructuredIndex, expr)) {
3157
    // This initializer overwrites a previous initializer.
3158
    // No need to diagnose when `expr` is nullptr because a more relevant
3159
    // diagnostic has already been issued and this diagnostic is potentially
3160
    // noise.
3161
183
    if (expr)
3162
182
      diagnoseInitOverride(PrevInit, expr->getSourceRange());
3163
183
  }
3164
3165
432k
  ++StructuredIndex;
3166
432k
}
3167
3168
/// Determine whether we can perform aggregate initialization for the purposes
3169
/// of overload resolution.
3170
bool Sema::CanPerformAggregateInitializationForOverloadResolution(
3171
562
    const InitializedEntity &Entity, InitListExpr *From) {
3172
562
  QualType Type = Entity.getType();
3173
562
  InitListChecker Check(*this, Entity, From, Type, /*VerifyOnly=*/true,
3174
562
                        /*TreatUnavailableAsInvalid=*/false,
3175
562
                        /*InOverloadResolution=*/true);
3176
562
  return !Check.HadError();
3177
562
}
3178
3179
/// Check that the given Index expression is a valid array designator
3180
/// value. This is essentially just a wrapper around
3181
/// VerifyIntegerConstantExpression that also checks for negative values
3182
/// and produces a reasonable diagnostic if there is a
3183
/// failure. Returns the index expression, possibly with an implicit cast
3184
/// added, on success.  If everything went okay, Value will receive the
3185
/// value of the constant expression.
3186
static ExprResult
3187
430
CheckArrayDesignatorExpr(Sema &S, Expr *Index, llvm::APSInt &Value) {
3188
430
  SourceLocation Loc = Index->getBeginLoc();
3189
3190
  // Make sure this is an integer constant expression.
3191
430
  ExprResult Result =
3192
430
      S.VerifyIntegerConstantExpression(Index, &Value, Sema::AllowFold);
3193
430
  if (Result.isInvalid())
3194
9
    return Result;
3195
3196
421
  if (Value.isSigned() && 
Value.isNegative()410
)
3197
1
    return S.Diag(Loc, diag::err_array_designator_negative)
3198
1
           << toString(Value, 10) << Index->getSourceRange();
3199
3200
420
  Value.setIsUnsigned(true);
3201
420
  return Result;
3202
421
}
3203
3204
ExprResult Sema::ActOnDesignatedInitializer(Designation &Desig,
3205
                                            SourceLocation EqualOrColonLoc,
3206
                                            bool GNUSyntax,
3207
2.15k
                                            ExprResult Init) {
3208
2.15k
  typedef DesignatedInitExpr::Designator ASTDesignator;
3209
3210
2.15k
  bool Invalid = false;
3211
2.15k
  SmallVector<ASTDesignator, 32> Designators;
3212
2.15k
  SmallVector<Expr *, 32> InitExpressions;
3213
3214
  // Build designators and check array designator expressions.
3215
4.62k
  for (unsigned Idx = 0; Idx < Desig.getNumDesignators(); 
++Idx2.47k
) {
3216
2.47k
    const Designator &D = Desig.getDesignator(Idx);
3217
2.47k
    switch (D.getKind()) {
3218
2.06k
    case Designator::FieldDesignator:
3219
2.06k
      Designators.push_back(ASTDesignator(D.getField(), D.getDotLoc(),
3220
2.06k
                                          D.getFieldLoc()));
3221
2.06k
      break;
3222
3223
387
    case Designator::ArrayDesignator: {
3224
387
      Expr *Index = static_cast<Expr *>(D.getArrayIndex());
3225
387
      llvm::APSInt IndexValue;
3226
387
      if (!Index->isTypeDependent() && !Index->isValueDependent())
3227
380
        Index = CheckArrayDesignatorExpr(*this, Index, IndexValue).get();
3228
387
      if (!Index)
3229
10
        Invalid = true;
3230
377
      else {
3231
377
        Designators.push_back(ASTDesignator(InitExpressions.size(),
3232
377
                                            D.getLBracketLoc(),
3233
377
                                            D.getRBracketLoc()));
3234
377
        InitExpressions.push_back(Index);
3235
377
      }
3236
387
      break;
3237
0
    }
3238
3239
28
    case Designator::ArrayRangeDesignator: {
3240
28
      Expr *StartIndex = static_cast<Expr *>(D.getArrayRangeStart());
3241
28
      Expr *EndIndex = static_cast<Expr *>(D.getArrayRangeEnd());
3242
28
      llvm::APSInt StartValue;
3243
28
      llvm::APSInt EndValue;
3244
28
      bool StartDependent = StartIndex->isTypeDependent() ||
3245
28
                            StartIndex->isValueDependent();
3246
28
      bool EndDependent = EndIndex->isTypeDependent() ||
3247
28
                          EndIndex->isValueDependent();
3248
28
      if (!StartDependent)
3249
25
        StartIndex =
3250
25
            CheckArrayDesignatorExpr(*this, StartIndex, StartValue).get();
3251
28
      if (!EndDependent)
3252
25
        EndIndex = CheckArrayDesignatorExpr(*this, EndIndex, EndValue).get();
3253
3254
28
      if (!StartIndex || !EndIndex)
3255
0
        Invalid = true;
3256
28
      else {
3257
        // Make sure we're comparing values with the same bit width.
3258
28
        if (StartDependent || 
EndDependent25
) {
3259
          // Nothing to compute.
3260
25
        } else if (StartValue.getBitWidth() > EndValue.getBitWidth())
3261
0
          EndValue = EndValue.extend(StartValue.getBitWidth());
3262
25
        else if (StartValue.getBitWidth() < EndValue.getBitWidth())
3263
1
          StartValue = StartValue.extend(EndValue.getBitWidth());
3264
3265
28
        if (!StartDependent && 
!EndDependent25
&&
EndValue < StartValue25
) {
3266
1
          Diag(D.getEllipsisLoc(), diag::err_array_designator_empty_range)
3267
1
            << toString(StartValue, 10) << toString(EndValue, 10)
3268
1
            << StartIndex->getSourceRange() << EndIndex->getSourceRange();
3269
1
          Invalid = true;
3270
27
        } else {
3271
27
          Designators.push_back(ASTDesignator(InitExpressions.size(),
3272
27
                                              D.getLBracketLoc(),
3273
27
                                              D.getEllipsisLoc(),
3274
27
                                              D.getRBracketLoc()));
3275
27
          InitExpressions.push_back(StartIndex);
3276
27
          InitExpressions.push_back(EndIndex);
3277
27
        }
3278
28
      }
3279
28
      break;
3280
0
    }
3281
2.47k
    }
3282
2.47k
  }
3283
3284
2.15k
  if (Invalid || 
Init.isInvalid()2.14k
)
3285
15
    return ExprError();
3286
3287
  // Clear out the expressions within the designation.
3288
2.13k
  Desig.ClearExprs(*this);
3289
3290
2.13k
  return DesignatedInitExpr::Create(Context, Designators, InitExpressions,
3291
2.13k
                                    EqualOrColonLoc, GNUSyntax,
3292
2.13k
                                    Init.getAs<Expr>());
3293
2.15k
}
3294
3295
//===----------------------------------------------------------------------===//
3296
// Initialization entity
3297
//===----------------------------------------------------------------------===//
3298
3299
InitializedEntity::InitializedEntity(ASTContext &Context, unsigned Index,
3300
                                     const InitializedEntity &Parent)
3301
  : Parent(&Parent), Index(Index)
3302
307k
{
3303
307k
  if (const ArrayType *AT = Context.getAsArrayType(Parent.getType())) {
3304
139k
    Kind = EK_ArrayElement;
3305
139k
    Type = AT->getElementType();
3306
168k
  } else if (const VectorType *VT = Parent.getType()->getAs<VectorType>()) {
3307
167k
    Kind = EK_VectorElement;
3308
167k
    Type = VT->getElementType();
3309
167k
  } else {
3310
192
    const ComplexType *CT = Parent.getType()->getAs<ComplexType>();
3311
192
    assert(CT && "Unexpected type");
3312
0
    Kind = EK_ComplexElement;
3313
192
    Type = CT->getElementType();
3314
192
  }
3315
307k
}
3316
3317
InitializedEntity
3318
InitializedEntity::InitializeBase(ASTContext &Context,
3319
                                  const CXXBaseSpecifier *Base,
3320
                                  bool IsInheritedVirtualBase,
3321
42.9k
                                  const InitializedEntity *Parent) {
3322
42.9k
  InitializedEntity Result;
3323
42.9k
  Result.Kind = EK_Base;
3324
42.9k
  Result.Parent = Parent;
3325
42.9k
  Result.Base = {Base, IsInheritedVirtualBase};
3326
42.9k
  Result.Type = Base->getType();
3327
42.9k
  return Result;
3328
42.9k
}
3329
3330
14
DeclarationName InitializedEntity::getName() const {
3331
14
  switch (getKind()) {
3332
0
  case EK_Parameter:
3333
0
  case EK_Parameter_CF_Audited: {
3334
0
    ParmVarDecl *D = Parameter.getPointer();
3335
0
    return (D ? D->getDeclName() : DeclarationName());
3336
0
  }
3337
3338
0
  case EK_Variable:
3339
14
  case EK_Member:
3340
14
  case EK_Binding:
3341
14
  case EK_TemplateParameter:
3342
14
    return Variable.VariableOrMember->getDeclName();
3343
3344
0
  case EK_LambdaCapture:
3345
0
    return DeclarationName(Capture.VarID);
3346
3347
0
  case EK_Result:
3348
0
  case EK_StmtExprResult:
3349
0
  case EK_Exception:
3350
0
  case EK_New:
3351
0
  case EK_Temporary:
3352
0
  case EK_Base:
3353
0
  case EK_Delegating:
3354
0
  case EK_ArrayElement:
3355
0
  case EK_VectorElement:
3356
0
  case EK_ComplexElement:
3357
0
  case EK_BlockElement:
3358
0
  case EK_LambdaToBlockConversionBlockElement:
3359
0
  case EK_CompoundLiteralInit:
3360
0
  case EK_RelatedResult:
3361
0
    return DeclarationName();
3362
14
  }
3363
3364
0
  llvm_unreachable("Invalid EntityKind!");
3365
0
}
3366
3367
15.1M
ValueDecl *InitializedEntity::getDecl() const {
3368
15.1M
  switch (getKind()) {
3369
3.00M
  case EK_Variable:
3370
3.15M
  case EK_Member:
3371
3.15M
  case EK_Binding:
3372
3.15M
  case EK_TemplateParameter:
3373
3.15M
    return Variable.VariableOrMember;
3374
3375
11.8M
  case EK_Parameter:
3376
11.8M
  case EK_Parameter_CF_Audited:
3377
11.8M
    return Parameter.getPointer();
3378
3379
0
  case EK_Result:
3380
0
  case EK_StmtExprResult:
3381
0
  case EK_Exception:
3382
0
  case EK_New:
3383
0
  case EK_Temporary:
3384
0
  case EK_Base:
3385
0
  case EK_Delegating:
3386
0
  case EK_ArrayElement:
3387
0
  case EK_VectorElement:
3388
0
  case EK_ComplexElement:
3389
0
  case EK_BlockElement:
3390
0
  case EK_LambdaToBlockConversionBlockElement:
3391
414
  case EK_LambdaCapture:
3392
56.0k
  case EK_CompoundLiteralInit:
3393
56.0k
  case EK_RelatedResult:
3394
56.0k
    return nullptr;
3395
15.1M
  }
3396
3397
0
  llvm_unreachable("Invalid EntityKind!");
3398
0
}
3399
3400
297k
bool InitializedEntity::allowsNRVO() const {
3401
297k
  switch (getKind()) {
3402
36.1k
  case EK_Result:
3403
41.9k
  case EK_Exception:
3404
41.9k
    return LocAndNRVO.NRVO;
3405
3406
16
  case EK_StmtExprResult:
3407
118k
  case EK_Variable:
3408
156k
  case EK_Parameter:
3409
156k
  case EK_Parameter_CF_Audited:
3410
156k
  case EK_TemplateParameter:
3411
174k
  case EK_Member:
3412
174k
  case EK_Binding:
3413
177k
  case EK_New:
3414
211k
  case EK_Temporary:
3415
211k
  case EK_CompoundLiteralInit:
3416
253k
  case EK_Base:
3417
254k
  case EK_Delegating:
3418
254k
  case EK_ArrayElement:
3419
254k
  case EK_VectorElement:
3420
254k
  case EK_ComplexElement:
3421
255k
  case EK_BlockElement:
3422
255k
  case EK_LambdaToBlockConversionBlockElement:
3423
255k
  case EK_LambdaCapture:
3424
255k
  case EK_RelatedResult:
3425
255k
    break;
3426
297k
  }
3427
3428
255k
  return false;
3429
297k
}
3430
3431
0
unsigned InitializedEntity::dumpImpl(raw_ostream &OS) const {
3432
0
  assert(getParent() != this);
3433
0
  unsigned Depth = getParent() ? getParent()->dumpImpl(OS) : 0;
3434
0
  for (unsigned I = 0; I != Depth; ++I)
3435
0
    OS << "`-";
3436
3437
0
  switch (getKind()) {
3438
0
  case EK_Variable: OS << "Variable"; break;
3439
0
  case EK_Parameter: OS << "Parameter"; break;
3440
0
  case EK_Parameter_CF_Audited: OS << "CF audited function Parameter";
3441
0
    break;
3442
0
  case EK_TemplateParameter: OS << "TemplateParameter"; break;
3443
0
  case EK_Result: OS << "Result"; break;
3444
0
  case EK_StmtExprResult: OS << "StmtExprResult"; break;
3445
0
  case EK_Exception: OS << "Exception"; break;
3446
0
  case EK_Member: OS << "Member"; break;
3447
0
  case EK_Binding: OS << "Binding"; break;
3448
0
  case EK_New: OS << "New"; break;
3449
0
  case EK_Temporary: OS << "Temporary"; break;
3450
0
  case EK_CompoundLiteralInit: OS << "CompoundLiteral";break;
3451
0
  case EK_RelatedResult: OS << "RelatedResult"; break;
3452
0
  case EK_Base: OS << "Base"; break;
3453
0
  case EK_Delegating: OS << "Delegating"; break;
3454
0
  case EK_ArrayElement: OS << "ArrayElement " << Index; break;
3455
0
  case EK_VectorElement: OS << "VectorElement " << Index; break;
3456
0
  case EK_ComplexElement: OS << "ComplexElement " << Index; break;
3457
0
  case EK_BlockElement: OS << "Block"; break;
3458
0
  case EK_LambdaToBlockConversionBlockElement:
3459
0
    OS << "Block (lambda)";
3460
0
    break;
3461
0
  case EK_LambdaCapture:
3462
0
    OS << "LambdaCapture ";
3463
0
    OS << DeclarationName(Capture.VarID);
3464
0
    break;
3465
0
  }
3466
3467
0
  if (auto *D = getDecl()) {
3468
0
    OS << " ";
3469
0
    D->printQualifiedName(OS);
3470
0
  }
3471
3472
0
  OS << " '" << getType() << "'\n";
3473
3474
0
  return Depth + 1;
3475
0
}
3476
3477
0
LLVM_DUMP_METHOD void InitializedEntity::dump() const {
3478
0
  dumpImpl(llvm::errs());
3479
0
}
3480
3481
//===----------------------------------------------------------------------===//
3482
// Initialization sequence
3483
//===----------------------------------------------------------------------===//
3484
3485
12.7M
void InitializationSequence::Step::Destroy() {
3486
12.7M
  switch (Kind) {
3487
99
  case SK_ResolveAddressOfOverloadedFunction:
3488
99
  case SK_CastDerivedToBasePRValue:
3489
1.11k
  case SK_CastDerivedToBaseXValue:
3490
12.1k
  case SK_CastDerivedToBaseLValue:
3491
373k
  case SK_BindReference:
3492
509k
  case SK_BindReferenceToTemporary:
3493
519k
  case SK_FinalCopy:
3494
521k
  case SK_ExtraneousCopyToTemporary:
3495
535k
  case SK_UserConversion:
3496
588k
  case SK_QualificationConversionPRValue:
3497
589k
  case SK_QualificationConversionXValue:
3498
677k
  case SK_QualificationConversionLValue:
3499
677k
  case SK_FunctionReferenceConversion:
3500
677k
  case SK_AtomicConversion:
3501
780k
  case SK_ListInitialization:
3502
780k
  case SK_UnwrapInitList:
3503
781k
  case SK_RewrapInitList:
3504
1.15M
  case SK_ConstructorInitialization:
3505
1.16M
  case SK_ConstructorInitializationFromList:
3506
1.27M
  case SK_ZeroInitialization:
3507
7.96M
  case SK_CAssignment:
3508
7.97M
  case SK_StringInit:
3509
7.97M
  case SK_ObjCObjectConversion:
3510
7.97M
  case SK_ArrayLoopIndex:
3511
7.97M
  case SK_ArrayLoopInit:
3512
7.97M
  case SK_ArrayInit:
3513
7.97M
  case SK_GNUArrayInit:
3514
7.97M
  case SK_ParenthesizedArrayInit:
3515
7.97M
  case SK_PassByIndirectCopyRestore:
3516
7.97M
  case SK_PassByIndirectRestore:
3517
7.97M
  case SK_ProduceObjCObject:
3518
7.97M
  case SK_StdInitializerList:
3519
7.97M
  case SK_StdInitializerListConstructorCall:
3520
7.97M
  case SK_OCLSamplerInit:
3521
7.97M
  case SK_OCLZeroOpaqueType:
3522
7.97M
    break;
3523
3524
4.49M
  case SK_ConversionSequence:
3525
4.73M
  case SK_ConversionSequenceNoNarrowing:
3526
4.73M
    delete ICS;
3527
12.7M
  }
3528
12.7M
}
3529
3530
450
bool InitializationSequence::isDirectReferenceBinding() const {
3531
  // There can be some lvalue adjustments after the SK_BindReference step.
3532
450
  for (const Step &S : llvm::reverse(Steps)) {
3533
286
    if (S.Kind == SK_BindReference)
3534
225
      return true;
3535
61
    if (S.Kind == SK_BindReferenceToTemporary)
3536
47
      return false;
3537
61
  }
3538
178
  return false;
3539
450
}
3540
3541
456
bool InitializationSequence::isAmbiguous() const {
3542
456
  if (!Failed())
3543
85
    return false;
3544
3545
371
  switch (getFailureKind()) {
3546
0
  case FK_TooManyInitsForReference:
3547
0
  case FK_ParenthesizedListInitForReference:
3548
0
  case FK_ArrayNeedsInitList:
3549
13
  case FK_ArrayNeedsInitListOrStringLiteral:
3550
13
  case FK_ArrayNeedsInitListOrWideStringLiteral:
3551
13
  case FK_NarrowStringIntoWideCharArray:
3552
13
  case FK_WideStringIntoCharArray:
3553
13
  case FK_IncompatWideStringIntoWideChar:
3554
13
  case FK_PlainStringIntoUTF8Char:
3555
13
  case FK_UTF8StringIntoPlainChar:
3556
13
  case FK_AddressOfOverloadFailed: // FIXME: Could do better
3557
34
  case FK_NonConstLValueReferenceBindingToTemporary:
3558
34
  case FK_NonConstLValueReferenceBindingToBitfield:
3559
34
  case FK_NonConstLValueReferenceBindingToVectorElement:
3560
34
  case FK_NonConstLValueReferenceBindingToMatrixElement:
3561
137
  case FK_NonConstLValueReferenceBindingToUnrelated:
3562
137
  case FK_RValueReferenceBindingToLValue:
3563
137
  case FK_ReferenceAddrspaceMismatchTemporary:
3564
179
  case FK_ReferenceInitDropsQualifiers:
3565
179
  case FK_ReferenceInitFailed:
3566
179
  case FK_ConversionFailed:
3567
179
  case FK_ConversionFromPropertyFailed:
3568
179
  case FK_TooManyInitsForScalar:
3569
179
  case FK_ParenthesizedListInitForScalar:
3570
179
  case FK_ReferenceBindingToInitList:
3571
179
  case FK_InitListBadDestinationType:
3572
179
  case FK_DefaultInitOfConst:
3573
179
  case FK_Incomplete:
3574
179
  case FK_ArrayTypeMismatch:
3575
179
  case FK_NonConstantArrayInit:
3576
179
  case FK_ListInitializationFailed:
3577
179
  case FK_VariableLengthArrayHasInitializer:
3578
179
  case FK_PlaceholderType:
3579
179
  case FK_ExplicitConstructor:
3580
179
  case FK_AddressOfUnaddressableFunction:
3581
179
    return false;
3582
3583
12
  case FK_ReferenceInitOverloadFailed:
3584
186
  case FK_UserConversionOverloadFailed:
3585
192
  case FK_ConstructorOverloadFailed:
3586
192
  case FK_ListConstructorOverloadFailed:
3587
192
    return FailedOverloadResult == OR_Ambiguous;
3588
371
  }
3589
3590
0
  llvm_unreachable("Invalid EntityKind!");
3591
0
}
3592
3593
6.95M
bool InitializationSequence::isConstructorInitialization() const {
3594
6.95M
  return !Steps.empty() && 
Steps.back().Kind == SK_ConstructorInitialization6.95M
;
3595
6.95M
}
3596
3597
void
3598
InitializationSequence
3599
::AddAddressOverloadResolutionStep(FunctionDecl *Function,
3600
                                   DeclAccessPair Found,
3601
99
                                   bool HadMultipleCandidates) {
3602
99
  Step S;
3603
99
  S.Kind = SK_ResolveAddressOfOverloadedFunction;
3604
99
  S.Type = Function->getType();
3605
99
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3606
99
  S.Function.Function = Function;
3607
99
  S.Function.FoundDecl = Found;
3608
99
  Steps.push_back(S);
3609
99
}
3610
3611
void InitializationSequence::AddDerivedToBaseCastStep(QualType BaseType,
3612
12.0k
                                                      ExprValueKind VK) {
3613
12.0k
  Step S;
3614
12.0k
  switch (VK) {
3615
0
  case VK_PRValue:
3616
0
    S.Kind = SK_CastDerivedToBasePRValue;
3617
0
    break;
3618
1.01k
  case VK_XValue: S.Kind = SK_CastDerivedToBaseXValue; break;
3619
11.0k
  case VK_LValue: S.Kind = SK_CastDerivedToBaseLValue; break;
3620
12.0k
  }
3621
12.0k
  S.Type = BaseType;
3622
12.0k
  Steps.push_back(S);
3623
12.0k
}
3624
3625
void InitializationSequence::AddReferenceBindingStep(QualType T,
3626
497k
                                                     bool BindingTemporary) {
3627
497k
  Step S;
3628
497k
  S.Kind = BindingTemporary? 
SK_BindReferenceToTemporary136k
:
SK_BindReference360k
;
3629
497k
  S.Type = T;
3630
497k
  Steps.push_back(S);
3631
497k
}
3632
3633
9.27k
void InitializationSequence::AddFinalCopy(QualType T) {
3634
9.27k
  Step S;
3635
9.27k
  S.Kind = SK_FinalCopy;
3636
9.27k
  S.Type = T;
3637
9.27k
  Steps.push_back(S);
3638
9.27k
}
3639
3640
2.23k
void InitializationSequence::AddExtraneousCopyToTemporary(QualType T) {
3641
2.23k
  Step S;
3642
2.23k
  S.Kind = SK_ExtraneousCopyToTemporary;
3643
2.23k
  S.Type = T;
3644
2.23k
  Steps.push_back(S);
3645
2.23k
}
3646
3647
void
3648
InitializationSequence::AddUserConversionStep(FunctionDecl *Function,
3649
                                              DeclAccessPair FoundDecl,
3650
                                              QualType T,
3651
14.1k
                                              bool HadMultipleCandidates) {
3652
14.1k
  Step S;
3653
14.1k
  S.Kind = SK_UserConversion;
3654
14.1k
  S.Type = T;
3655
14.1k
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3656
14.1k
  S.Function.Function = Function;
3657
14.1k
  S.Function.FoundDecl = FoundDecl;
3658
14.1k
  Steps.push_back(S);
3659
14.1k
}
3660
3661
void InitializationSequence::AddQualificationConversionStep(QualType Ty,
3662
141k
                                                            ExprValueKind VK) {
3663
141k
  Step S;
3664
141k
  S.Kind = SK_QualificationConversionPRValue; // work around a gcc warning
3665
141k
  switch (VK) {
3666
52.8k
  case VK_PRValue:
3667
52.8k
    S.Kind = SK_QualificationConversionPRValue;
3668
52.8k
    break;
3669
1.53k
  case VK_XValue:
3670
1.53k
    S.Kind = SK_QualificationConversionXValue;
3671
1.53k
    break;
3672
87.2k
  case VK_LValue:
3673
87.2k
    S.Kind = SK_QualificationConversionLValue;
3674
87.2k
    break;
3675
141k
  }
3676
141k
  S.Type = Ty;
3677
141k
  Steps.push_back(S);
3678
141k
}
3679
3680
18
void InitializationSequence::AddFunctionReferenceConversionStep(QualType Ty) {
3681
18
  Step S;
3682
18
  S.Kind = SK_FunctionReferenceConversion;
3683
18
  S.Type = Ty;
3684
18
  Steps.push_back(S);
3685
18
}
3686
3687
32
void InitializationSequence::AddAtomicConversionStep(QualType Ty) {
3688
32
  Step S;
3689
32
  S.Kind = SK_AtomicConversion;
3690
32
  S.Type = Ty;
3691
32
  Steps.push_back(S);
3692
32
}
3693
3694
void InitializationSequence::AddConversionSequenceStep(
3695
    const ImplicitConversionSequence &ICS, QualType T,
3696
4.73M
    bool TopLevelOfInitList) {
3697
4.73M
  Step S;
3698
4.73M
  S.Kind = TopLevelOfInitList ? 
SK_ConversionSequenceNoNarrowing240k
3699
4.73M
                              : 
SK_ConversionSequence4.49M
;
3700
4.73M
  S.Type = T;
3701
4.73M
  S.ICS = new ImplicitConversionSequence(ICS);
3702
4.73M
  Steps.push_back(S);
3703
4.73M
}
3704
3705
102k
void InitializationSequence::AddListInitializationStep(QualType T) {
3706
102k
  Step S;
3707
102k
  S.Kind = SK_ListInitialization;
3708
102k
  S.Type = T;
3709
102k
  Steps.push_back(S);
3710
102k
}
3711
3712
void InitializationSequence::AddConstructorInitializationStep(
3713
    DeclAccessPair FoundDecl, CXXConstructorDecl *Constructor, QualType T,
3714
379k
    bool HadMultipleCandidates, bool FromInitList, bool AsInitList) {
3715
379k
  Step S;
3716
379k
  S.Kind = FromInitList ? 
AsInitList3.50k
?
SK_StdInitializerListConstructorCall401
3717
3.50k
                                     : 
SK_ConstructorInitializationFromList3.10k
3718
379k
                        : 
SK_ConstructorInitialization376k
;
3719
379k
  S.Type = T;
3720
379k
  S.Function.HadMultipleCandidates = HadMultipleCandidates;
3721
379k
  S.Function.Function = Constructor;
3722
379k
  S.Function.FoundDecl = FoundDecl;
3723
379k
  Steps.push_back(S);
3724
379k
}
3725
3726
115k
void InitializationSequence::AddZeroInitializationStep(QualType T) {
3727
115k
  Step S;
3728
115k
  S.Kind = SK_ZeroInitialization;
3729
115k
  S.Type = T;
3730
115k
  Steps.push_back(S);
3731
115k
}
3732
3733
6.69M
void InitializationSequence::AddCAssignmentStep(QualType T) {
3734
6.69M
  Step S;
3735
6.69M
  S.Kind = SK_CAssignment;
3736
6.69M
  S.Type = T;
3737
6.69M
  Steps.push_back(S);
3738
6.69M
}
3739
3740
2.34k
void InitializationSequence::AddStringInitStep(QualType T) {
3741
2.34k
  Step S;
3742
2.34k
  S.Kind = SK_StringInit;
3743
2.34k
  S.Type = T;
3744
2.34k
  Steps.push_back(S);
3745
2.34k
}
3746
3747
15
void InitializationSequence::AddObjCObjectConversionStep(QualType T) {
3748
15
  Step S;
3749
15
  S.Kind = SK_ObjCObjectConversion;
3750
15
  S.Type = T;
3751
15
  Steps.push_back(S);
3752
15
}
3753
3754
23
void InitializationSequence::AddArrayInitStep(QualType T, bool IsGNUExtension) {
3755
23
  Step S;
3756
23
  S.Kind = IsGNUExtension ? 
SK_GNUArrayInit21
:
SK_ArrayInit2
;
3757
23
  S.Type = T;
3758
23
  Steps.push_back(S);
3759
23
}
3760
3761
1.02k
void InitializationSequence::AddArrayInitLoopStep(QualType T, QualType EltT) {
3762
1.02k
  Step S;
3763
1.02k
  S.Kind = SK_ArrayLoopIndex;
3764
1.02k
  S.Type = EltT;
3765
1.02k
  Steps.insert(Steps.begin(), S);
3766
3767
1.02k
  S.Kind = SK_ArrayLoopInit;
3768
1.02k
  S.Type = T;
3769
1.02k
  Steps.push_back(S);
3770
1.02k
}
3771
3772
1
void InitializationSequence::AddParenthesizedArrayInitStep(QualType T) {
3773
1
  Step S;
3774
1
  S.Kind = SK_ParenthesizedArrayInit;
3775
1
  S.Type = T;
3776
1
  Steps.push_back(S);
3777
1
}
3778
3779
void InitializationSequence::AddPassByIndirectCopyRestoreStep(QualType type,
3780
71
                                                              bool shouldCopy) {
3781
71
  Step s;
3782
71
  s.Kind = (shouldCopy ? 
SK_PassByIndirectCopyRestore67
3783
71
                       : 
SK_PassByIndirectRestore4
);
3784
71
  s.Type = type;
3785
71
  Steps.push_back(s);
3786
71
}
3787
3788
704
void InitializationSequence::AddProduceObjCObjectStep(QualType T) {
3789
704
  Step S;
3790
704
  S.Kind = SK_ProduceObjCObject;
3791
704
  S.Type = T;
3792
704
  Steps.push_back(S);
3793
704
}
3794
3795
786
void InitializationSequence::AddStdInitializerListConstructionStep(QualType T) {
3796
786
  Step S;
3797
786
  S.Kind = SK_StdInitializerList;
3798
786
  S.Type = T;
3799
786
  Steps.push_back(S);
3800
786
}
3801
3802
291
void InitializationSequence::AddOCLSamplerInitStep(QualType T) {
3803
291
  Step S;
3804
291
  S.Kind = SK_OCLSamplerInit;
3805
291
  S.Type = T;
3806
291
  Steps.push_back(S);
3807
291
}
3808
3809
102
void InitializationSequence::AddOCLZeroOpaqueTypeStep(QualType T) {
3810
102
  Step S;
3811
102
  S.Kind = SK_OCLZeroOpaqueType;
3812
102
  S.Type = T;
3813
102
  Steps.push_back(S);
3814
102
}
3815
3816
void InitializationSequence::RewrapReferenceInitList(QualType T,
3817
457
                                                     InitListExpr *Syntactic) {
3818
457
  assert(Syntactic->getNumInits() == 1 &&
3819
457
         "Can only rewrap trivial init lists.");
3820
0
  Step S;
3821
457
  S.Kind = SK_UnwrapInitList;
3822
457
  S.Type = Syntactic->getInit(0)->getType();
3823
457
  Steps.insert(Steps.begin(), S);
3824
3825
457
  S.Kind = SK_RewrapInitList;
3826
457
  S.Type = T;
3827
457
  S.WrappingSyntacticList = Syntactic;
3828
457
  Steps.push_back(S);
3829
457
}
3830
3831
void InitializationSequence::SetOverloadFailure(FailureKind Failure,
3832
8.16k
                                                OverloadingResult Result) {
3833
8.16k
  setSequenceKind(FailedSequence);
3834
8.16k
  this->Failure = Failure;
3835
8.16k
  this->FailedOverloadResult = Result;
3836
8.16k
}
3837
3838
//===----------------------------------------------------------------------===//
3839
// Attempt initialization
3840
//===----------------------------------------------------------------------===//
3841
3842
/// Tries to add a zero initializer. Returns true if that worked.
3843
static bool
3844
maybeRecoverWithZeroInitialization(Sema &S, InitializationSequence &Sequence,
3845
92
                                   const InitializedEntity &Entity) {
3846
92
  if (Entity.getKind() != InitializedEntity::EK_Variable)
3847
5
    return false;
3848
3849
87
  VarDecl *VD = cast<VarDecl>(Entity.getDecl());
3850
87
  if (VD->getInit() || VD->getEndLoc().isMacroID())
3851
0
    return false;
3852
3853
87
  QualType VariableTy = VD->getType().getCanonicalType();
3854
87
  SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
3855
87
  std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
3856
87
  if (!Init.empty()) {
3857
74
    Sequence.AddZeroInitializationStep(Entity.getType());
3858
74
    Sequence.SetZeroInitializationFixit(Init, Loc);
3859
74
    return true;
3860
74
  }
3861
13
  return false;
3862
87
}
3863
3864
static void MaybeProduceObjCObject(Sema &S,
3865
                                   InitializationSequence &Sequence,
3866
11.4M
                                   const InitializedEntity &Entity) {
3867
11.4M
  if (!S.getLangOpts().ObjCAutoRefCount) 
return11.3M
;
3868
3869
  /// When initializing a parameter, produce the value if it's marked
3870
  /// __attribute__((ns_consumed)).
3871
43.3k
  if (Entity.isParameterKind()) {
3872
17.9k
    if (!Entity.isParameterConsumed())
3873
17.9k
      return;
3874
3875
33
    assert(Entity.getType()->isObjCRetainableType() &&
3876
33
           "consuming an object of unretainable type?");
3877
0
    Sequence.AddProduceObjCObjectStep(Entity.getType());
3878
3879
  /// When initializing a return value, if the return type is a
3880
  /// retainable type, then returns need to immediately retain the
3881
  /// object.  If an autorelease is required, it will be done at the
3882
  /// last instant.
3883
25.3k
  } else if (Entity.getKind() == InitializedEntity::EK_Result ||
3884
25.3k
             
Entity.getKind() == InitializedEntity::EK_StmtExprResult18.6k
) {
3885
6.70k
    if (!Entity.getType()->isObjCRetainableType())
3886
6.03k
      return;
3887
3888
671
    Sequence.AddProduceObjCObjectStep(Entity.getType());
3889
671
  }
3890
43.3k
}
3891
3892
static void TryListInitialization(Sema &S,
3893
                                  const InitializedEntity &Entity,
3894
                                  const InitializationKind &Kind,
3895
                                  InitListExpr *InitList,
3896
                                  InitializationSequence &Sequence,
3897
                                  bool TreatUnavailableAsInvalid);
3898
3899
/// When initializing from init list via constructor, handle
3900
/// initialization of an object of type std::initializer_list<T>.
3901
///
3902
/// \return true if we have handled initialization of an object of type
3903
/// std::initializer_list<T>, false otherwise.
3904
static bool TryInitializerListConstruction(Sema &S,
3905
                                           InitListExpr *List,
3906
                                           QualType DestType,
3907
                                           InitializationSequence &Sequence,
3908
3.12k
                                           bool TreatUnavailableAsInvalid) {
3909
3.12k
  QualType E;
3910
3.12k
  if (!S.isStdInitializerList(DestType, &E))
3911
2.33k
    return false;
3912
3913
791
  if (!S.isCompleteType(List->getExprLoc(), E)) {
3914
0
    Sequence.setIncompleteTypeFailure(E);
3915
0
    return true;
3916
0
  }
3917
3918
  // Try initializing a temporary array from the init list.
3919
791
  QualType ArrayType = S.Context.getConstantArrayType(
3920
791
      E.withConst(),
3921
791
      llvm::APInt(S.Context.getTypeSize(S.Context.getSizeType()),
3922
791
                  List->getNumInits()),
3923
791
      nullptr, clang::ArrayType::Normal, 0);
3924
791
  InitializedEntity HiddenArray =
3925
791
      InitializedEntity::InitializeTemporary(ArrayType);
3926
791
  InitializationKind Kind = InitializationKind::CreateDirectList(
3927
791
      List->getExprLoc(), List->getBeginLoc(), List->getEndLoc());
3928
791
  TryListInitialization(S, HiddenArray, Kind, List, Sequence,
3929
791
                        TreatUnavailableAsInvalid);
3930
791
  if (Sequence)
3931
786
    Sequence.AddStdInitializerListConstructionStep(DestType);
3932
791
  return true;
3933
791
}
3934
3935
/// Determine if the constructor has the signature of a copy or move
3936
/// constructor for the type T of the class in which it was found. That is,
3937
/// determine if its first parameter is of type T or reference to (possibly
3938
/// cv-qualified) T.
3939
static bool hasCopyOrMoveCtorParam(ASTContext &Ctx,
3940
394k
                                   const ConstructorInfo &Info) {
3941
394k
  if (Info.Constructor->getNumParams() == 0)
3942
55.1k
    return false;
3943
3944
339k
  QualType ParmT =
3945
339k
      Info.Constructor->getParamDecl(0)->getType().getNonReferenceType();
3946
339k
  QualType ClassT =
3947
339k
      Ctx.getRecordType(cast<CXXRecordDecl>(Info.FoundDecl->getDeclContext()));
3948
3949
339k
  return Ctx.hasSameUnqualifiedType(ParmT, ClassT);
3950
394k
}
3951
3952
static OverloadingResult
3953
ResolveConstructorOverload(Sema &S, SourceLocation DeclLoc,
3954
                           MultiExprArg Args,
3955
                           OverloadCandidateSet &CandidateSet,
3956
                           QualType DestType,
3957
                           DeclContext::lookup_result Ctors,
3958
                           OverloadCandidateSet::iterator &Best,
3959
                           bool CopyInitializing, bool AllowExplicit,
3960
                           bool OnlyListConstructors, bool IsListInit,
3961
392k
                           bool SecondStepOfCopyInit = false) {
3962
392k
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByConstructor);
3963
392k
  CandidateSet.setDestAS(DestType.getQualifiers().getAddressSpace());
3964
3965
1.65M
  for (NamedDecl *D : Ctors) {
3966
1.65M
    auto Info = getConstructorInfo(D);
3967
1.65M
    if (!Info.Constructor || 
Info.Constructor->isInvalidDecl()1.65M
)
3968
659
      continue;
3969
3970
1.65M
    if (OnlyListConstructors && 
!S.isInitListConstructor(Info.Constructor)10.4k
)
3971
10.0k
      continue;
3972
3973
    // C++11 [over.best.ics]p4:
3974
    //   ... and the constructor or user-defined conversion function is a
3975
    //   candidate by
3976
    //   - 13.3.1.3, when the argument is the temporary in the second step
3977
    //     of a class copy-initialization, or
3978
    //   - 13.3.1.4, 13.3.1.5, or 13.3.1.6 (in all cases), [not handled here]
3979
    //   - the second phase of 13.3.1.7 when the initializer list has exactly
3980
    //     one element that is itself an initializer list, and the target is
3981
    //     the first parameter of a constructor of class X, and the conversion
3982
    //     is to X or reference to (possibly cv-qualified X),
3983
    //   user-defined conversion sequences are not considered.
3984
1.64M
    bool SuppressUserConversions =
3985
1.64M
        SecondStepOfCopyInit ||
3986
1.64M
        
(1.60M
IsListInit1.60M
&&
Args.size() == 113.1k
&&
isa<InitListExpr>(Args[0])5.39k
&&
3987
1.60M
         
hasCopyOrMoveCtorParam(S.Context, Info)667
);
3988
3989
1.64M
    if (Info.ConstructorTmpl)
3990
413k
      S.AddTemplateOverloadCandidate(
3991
413k
          Info.ConstructorTmpl, Info.FoundDecl,
3992
413k
          /*ExplicitArgs*/ nullptr, Args, CandidateSet, SuppressUserConversions,
3993
413k
          /*PartialOverloading=*/false, AllowExplicit);
3994
1.22M
    else {
3995
      // C++ [over.match.copy]p1:
3996
      //   - When initializing a temporary to be bound to the first parameter
3997
      //     of a constructor [for type T] that takes a reference to possibly
3998
      //     cv-qualified T as its first argument, called with a single
3999
      //     argument in the context of direct-initialization, explicit
4000
      //     conversion functions are also considered.
4001
      // FIXME: What if a constructor template instantiates to such a signature?
4002
1.22M
      bool AllowExplicitConv = AllowExplicit && 
!CopyInitializing836k
&&
4003
1.22M
                               
Args.size() == 1831k
&&
4004
1.22M
                               
hasCopyOrMoveCtorParam(S.Context, Info)311k
;
4005
1.22M
      S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, Args,
4006
1.22M
                             CandidateSet, SuppressUserConversions,
4007
1.22M
                             /*PartialOverloading=*/false, AllowExplicit,
4008
1.22M
                             AllowExplicitConv);
4009
1.22M
    }
4010
1.64M
  }
4011
4012
  // FIXME: Work around a bug in C++17 guaranteed copy elision.
4013
  //
4014
  // When initializing an object of class type T by constructor
4015
  // ([over.match.ctor]) or by list-initialization ([over.match.list])
4016
  // from a single expression of class type U, conversion functions of
4017
  // U that convert to the non-reference type cv T are candidates.
4018
  // Explicit conversion functions are only candidates during
4019
  // direct-initialization.
4020
  //
4021
  // Note: SecondStepOfCopyInit is only ever true in this case when
4022
  // evaluating whether to produce a C++98 compatibility warning.
4023
392k
  if (S.getLangOpts().CPlusPlus17 && 
Args.size() == 128.5k
&&
4024
392k
      
!SecondStepOfCopyInit12.2k
) {
4025
12.2k
    Expr *Initializer = Args[0];
4026
12.2k
    auto *SourceRD = Initializer->getType()->getAsCXXRecordDecl();
4027
12.2k
    if (SourceRD && 
S.isCompleteType(DeclLoc, Initializer->getType())8.05k
) {
4028
7.96k
      const auto &Conversions = SourceRD->getVisibleConversionFunctions();
4029
9.74k
      for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I1.78k
) {
4030
1.78k
        NamedDecl *D = *I;
4031
1.78k
        CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4032
1.78k
        D = D->getUnderlyingDecl();
4033
4034
1.78k
        FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4035
1.78k
        CXXConversionDecl *Conv;
4036
1.78k
        if (ConvTemplate)
4037
33
          Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4038
1.74k
        else
4039
1.74k
          Conv = cast<CXXConversionDecl>(D);
4040
4041
1.78k
        if (ConvTemplate)
4042
33
          S.AddTemplateConversionCandidate(
4043
33
              ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4044
33
              CandidateSet, AllowExplicit, AllowExplicit,
4045
33
              /*AllowResultConversion*/ false);
4046
1.74k
        else
4047
1.74k
          S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Initializer,
4048
1.74k
                                   DestType, CandidateSet, AllowExplicit,
4049
1.74k
                                   AllowExplicit,
4050
1.74k
                                   /*AllowResultConversion*/ false);
4051
1.78k
      }
4052
7.96k
    }
4053
12.2k
  }
4054
4055
  // Perform overload resolution and return the result.
4056
392k
  return CandidateSet.BestViableFunction(S, DeclLoc, Best);
4057
392k
}
4058
4059
/// Attempt initialization by constructor (C++ [dcl.init]), which
4060
/// enumerates the constructors of the initialized entity and performs overload
4061
/// resolution to select the best.
4062
/// \param DestType       The destination class type.
4063
/// \param DestArrayType  The destination type, which is either DestType or
4064
///                       a (possibly multidimensional) array of DestType.
4065
/// \param IsListInit     Is this list-initialization?
4066
/// \param IsInitListCopy Is this non-list-initialization resulting from a
4067
///                       list-initialization from {x} where x is the same
4068
///                       type as the entity?
4069
static void TryConstructorInitialization(Sema &S,
4070
                                         const InitializedEntity &Entity,
4071
                                         const InitializationKind &Kind,
4072
                                         MultiExprArg Args, QualType DestType,
4073
                                         QualType DestArrayType,
4074
                                         InitializationSequence &Sequence,
4075
                                         bool IsListInit = false,
4076
393k
                                         bool IsInitListCopy = false) {
4077
393k
  assert(((!IsListInit && !IsInitListCopy) ||
4078
393k
          (Args.size() == 1 && isa<InitListExpr>(Args[0]))) &&
4079
393k
         "IsListInit/IsInitListCopy must come with a single initializer list "
4080
393k
         "argument.");
4081
0
  InitListExpr *ILE =
4082
393k
      (IsListInit || 
IsInitListCopy390k
) ?
cast<InitListExpr>(Args[0])3.88k
:
nullptr390k
;
4083
393k
  MultiExprArg UnwrappedArgs =
4084
393k
      ILE ? 
MultiExprArg(ILE->getInits(), ILE->getNumInits())3.88k
:
Args390k
;
4085
4086
  // The type we're constructing needs to be complete.
4087
393k
  if (!S.isCompleteType(Kind.getLocation(), DestType)) {
4088
56
    Sequence.setIncompleteTypeFailure(DestType);
4089
56
    return;
4090
56
  }
4091
4092
  // C++17 [dcl.init]p17:
4093
  //     - If the initializer expression is a prvalue and the cv-unqualified
4094
  //       version of the source type is the same class as the class of the
4095
  //       destination, the initializer expression is used to initialize the
4096
  //       destination object.
4097
  // Per DR (no number yet), this does not apply when initializing a base
4098
  // class or delegating to another constructor from a mem-initializer.
4099
  // ObjC++: Lambda captured by the block in the lambda to block conversion
4100
  // should avoid copy elision.
4101
393k
  if (S.getLangOpts().CPlusPlus17 &&
4102
393k
      
Entity.getKind() != InitializedEntity::EK_Base39.2k
&&
4103
393k
      
Entity.getKind() != InitializedEntity::EK_Delegating36.6k
&&
4104
393k
      Entity.getKind() !=
4105
36.5k
          InitializedEntity::EK_LambdaToBlockConversionBlockElement &&
4106
393k
      
UnwrappedArgs.size() == 136.5k
&&
UnwrappedArgs[0]->isPRValue()21.8k
&&
4107
393k
      
S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)14.2k
) {
4108
    // Convert qualifications if necessary.
4109
11.6k
    Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4110
11.6k
    if (ILE)
4111
44
      Sequence.RewrapReferenceInitList(DestType, ILE);
4112
11.6k
    return;
4113
11.6k
  }
4114
4115
382k
  const RecordType *DestRecordType = DestType->getAs<RecordType>();
4116
382k
  assert(DestRecordType && "Constructor initialization requires record type");
4117
0
  CXXRecordDecl *DestRecordDecl
4118
382k
    = cast<CXXRecordDecl>(DestRecordType->getDecl());
4119
4120
  // Build the candidate set directly in the initialization sequence
4121
  // structure, so that it will persist if we fail.
4122
382k
  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4123
4124
  // Determine whether we are allowed to call explicit constructors or
4125
  // explicit conversion operators.
4126
382k
  bool AllowExplicit = Kind.AllowExplicit() || 
IsListInit122k
;
4127
382k
  bool CopyInitialization = Kind.getKind() == InitializationKind::IK_Copy;
4128
4129
  //   - Otherwise, if T is a class type, constructors are considered. The
4130
  //     applicable constructors are enumerated, and the best one is chosen
4131
  //     through overload resolution.
4132
382k
  DeclContext::lookup_result Ctors = S.LookupConstructors(DestRecordDecl);
4133
4134
382k
  OverloadingResult Result = OR_No_Viable_Function;
4135
382k
  OverloadCandidateSet::iterator Best;
4136
382k
  bool AsInitializerList = false;
4137
4138
  // C++11 [over.match.list]p1, per DR1467:
4139
  //   When objects of non-aggregate type T are list-initialized, such that
4140
  //   8.5.4 [dcl.init.list] specifies that overload resolution is performed
4141
  //   according to the rules in this section, overload resolution selects
4142
  //   the constructor in two phases:
4143
  //
4144
  //   - Initially, the candidate functions are the initializer-list
4145
  //     constructors of the class T and the argument list consists of the
4146
  //     initializer list as a single argument.
4147
382k
  if (IsListInit) {
4148
3.62k
    AsInitializerList = true;
4149
4150
    // If the initializer list has no elements and T has a default constructor,
4151
    // the first phase is omitted.
4152
3.62k
    if (!(UnwrappedArgs.empty() && 
S.LookupDefaultConstructor(DestRecordDecl)1.41k
))
4153
2.33k
      Result = ResolveConstructorOverload(S, Kind.getLocation(), Args,
4154
2.33k
                                          CandidateSet, DestType, Ctors, Best,
4155
2.33k
                                          CopyInitialization, AllowExplicit,
4156
2.33k
                                          /*OnlyListConstructors=*/true,
4157
2.33k
                                          IsListInit);
4158
3.62k
  }
4159
4160
  // C++11 [over.match.list]p1:
4161
  //   - If no viable initializer-list constructor is found, overload resolution
4162
  //     is performed again, where the candidate functions are all the
4163
  //     constructors of the class T and the argument list consists of the
4164
  //     elements of the initializer list.
4165
382k
  if (Result == OR_No_Viable_Function) {
4166
381k
    AsInitializerList = false;
4167
381k
    Result = ResolveConstructorOverload(S, Kind.getLocation(), UnwrappedArgs,
4168
381k
                                        CandidateSet, DestType, Ctors, Best,
4169
381k
                                        CopyInitialization, AllowExplicit,
4170
381k
                                        /*OnlyListConstructors=*/false,
4171
381k
                                        IsListInit);
4172
381k
  }
4173
382k
  if (Result) {
4174
2.62k
    Sequence.SetOverloadFailure(
4175
2.62k
        IsListInit ? 
InitializationSequence::FK_ListConstructorOverloadFailed231
4176
2.62k
                   : 
InitializationSequence::FK_ConstructorOverloadFailed2.38k
,
4177
2.62k
        Result);
4178
4179
2.62k
    if (Result != OR_Deleted)
4180
1.96k
      return;
4181
2.62k
  }
4182
4183
380k
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4184
4185
  // In C++17, ResolveConstructorOverload can select a conversion function
4186
  // instead of a constructor.
4187
380k
  if (auto *CD = dyn_cast<CXXConversionDecl>(Best->Function)) {
4188
    // Add the user-defined conversion step that calls the conversion function.
4189
68
    QualType ConvType = CD->getConversionType();
4190
68
    assert(S.Context.hasSameUnqualifiedType(ConvType, DestType) &&
4191
68
           "should not have selected this conversion function");
4192
0
    Sequence.AddUserConversionStep(CD, Best->FoundDecl, ConvType,
4193
68
                                   HadMultipleCandidates);
4194
68
    if (!S.Context.hasSameType(ConvType, DestType))
4195
6
      Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4196
68
    if (IsListInit)
4197
29
      Sequence.RewrapReferenceInitList(Entity.getType(), ILE);
4198
68
    return;
4199
68
  }
4200
4201
380k
  CXXConstructorDecl *CtorDecl = cast<CXXConstructorDecl>(Best->Function);
4202
380k
  if (Result != OR_Deleted) {
4203
    // C++11 [dcl.init]p6:
4204
    //   If a program calls for the default initialization of an object
4205
    //   of a const-qualified type T, T shall be a class type with a
4206
    //   user-provided default constructor.
4207
    // C++ core issue 253 proposal:
4208
    //   If the implicit default constructor initializes all subobjects, no
4209
    //   initializer should be required.
4210
    // The 253 proposal is for example needed to process libstdc++ headers
4211
    // in 5.x.
4212
379k
    if (Kind.getKind() == InitializationKind::IK_Default &&
4213
379k
        
Entity.getType().isConstQualified()85.4k
) {
4214
5.09k
      if (!CtorDecl->getParent()->allowConstDefaultInit()) {
4215
27
        if (!maybeRecoverWithZeroInitialization(S, Sequence, Entity))
4216
3
          Sequence.SetFailed(InitializationSequence::FK_DefaultInitOfConst);
4217
27
        return;
4218
27
      }
4219
5.09k
    }
4220
4221
    // C++11 [over.match.list]p1:
4222
    //   In copy-list-initialization, if an explicit constructor is chosen, the
4223
    //   initializer is ill-formed.
4224
379k
    if (IsListInit && 
!Kind.AllowExplicit()3.36k
&&
CtorDecl->isExplicit()1.63k
) {
4225
87
      Sequence.SetFailed(InitializationSequence::FK_ExplicitConstructor);
4226
87
      return;
4227
87
    }
4228
379k
  }
4229
4230
  // [class.copy.elision]p3:
4231
  // In some copy-initialization contexts, a two-stage overload resolution
4232
  // is performed.
4233
  // If the first overload resolution selects a deleted function, we also
4234
  // need the initialization sequence to decide whether to perform the second
4235
  // overload resolution.
4236
  // For deleted functions in other contexts, there is no need to get the
4237
  // initialization sequence.
4238
380k
  if (Result == OR_Deleted && 
Kind.getKind() != InitializationKind::IK_Copy657
)
4239
436
    return;
4240
4241
  // Add the constructor initialization step. Any cv-qualification conversion is
4242
  // subsumed by the initialization.
4243
379k
  Sequence.AddConstructorInitializationStep(
4244
379k
      Best->FoundDecl, CtorDecl, DestArrayType, HadMultipleCandidates,
4245
379k
      IsListInit | IsInitListCopy, AsInitializerList);
4246
379k
}
4247
4248
static bool
4249
ResolveOverloadedFunctionForReferenceBinding(Sema &S,
4250
                                             Expr *Initializer,
4251
                                             QualType &SourceType,
4252
                                             QualType &UnqualifiedSourceType,
4253
                                             QualType UnqualifiedTargetType,
4254
498k
                                             InitializationSequence &Sequence) {
4255
498k
  if (S.Context.getCanonicalType(UnqualifiedSourceType) ==
4256
498k
        S.Context.OverloadTy) {
4257
113
    DeclAccessPair Found;
4258
113
    bool HadMultipleCandidates = false;
4259
113
    if (FunctionDecl *Fn
4260
113
        = S.ResolveAddressOfOverloadedFunction(Initializer,
4261
113
                                               UnqualifiedTargetType,
4262
113
                                               false, Found,
4263
113
                                               &HadMultipleCandidates)) {
4264
99
      Sequence.AddAddressOverloadResolutionStep(Fn, Found,
4265
99
                                                HadMultipleCandidates);
4266
99
      SourceType = Fn->getType();
4267
99
      UnqualifiedSourceType = SourceType.getUnqualifiedType();
4268
99
    } else 
if (14
!UnqualifiedTargetType->isRecordType()14
) {
4269
14
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4270
14
      return true;
4271
14
    }
4272
113
  }
4273
498k
  return false;
4274
498k
}
4275
4276
static void TryReferenceInitializationCore(Sema &S,
4277
                                           const InitializedEntity &Entity,
4278
                                           const InitializationKind &Kind,
4279
                                           Expr *Initializer,
4280
                                           QualType cv1T1, QualType T1,
4281
                                           Qualifiers T1Quals,
4282
                                           QualType cv2T2, QualType T2,
4283
                                           Qualifiers T2Quals,
4284
                                           InitializationSequence &Sequence);
4285
4286
static void TryValueInitialization(Sema &S,
4287
                                   const InitializedEntity &Entity,
4288
                                   const InitializationKind &Kind,
4289
                                   InitializationSequence &Sequence,
4290
                                   InitListExpr *InitList = nullptr);
4291
4292
/// Attempt list initialization of a reference.
4293
static void TryReferenceListInitialization(Sema &S,
4294
                                           const InitializedEntity &Entity,
4295
                                           const InitializationKind &Kind,
4296
                                           InitListExpr *InitList,
4297
                                           InitializationSequence &Sequence,
4298
1.02k
                                           bool TreatUnavailableAsInvalid) {
4299
  // First, catch C++03 where this isn't possible.
4300
1.02k
  if (!S.getLangOpts().CPlusPlus11) {
4301
0
    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4302
0
    return;
4303
0
  }
4304
  // Can't reference initialize a compound literal.
4305
1.02k
  if (Entity.getKind() == InitializedEntity::EK_CompoundLiteralInit) {
4306
1
    Sequence.SetFailed(InitializationSequence::FK_ReferenceBindingToInitList);
4307
1
    return;
4308
1
  }
4309
4310
1.02k
  QualType DestType = Entity.getType();
4311
1.02k
  QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4312
1.02k
  Qualifiers T1Quals;
4313
1.02k
  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4314
4315
  // Reference initialization via an initializer list works thus:
4316
  // If the initializer list consists of a single element that is
4317
  // reference-related to the referenced type, bind directly to that element
4318
  // (possibly creating temporaries).
4319
  // Otherwise, initialize a temporary with the initializer list and
4320
  // bind to that.
4321
1.02k
  if (InitList->getNumInits() == 1) {
4322
529
    Expr *Initializer = InitList->getInit(0);
4323
529
    QualType cv2T2 = S.getCompletedType(Initializer);
4324
529
    Qualifiers T2Quals;
4325
529
    QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4326
4327
    // If this fails, creating a temporary wouldn't work either.
4328
529
    if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4329
529
                                                     T1, Sequence))
4330
6
      return;
4331
4332
523
    SourceLocation DeclLoc = Initializer->getBeginLoc();
4333
523
    Sema::ReferenceCompareResult RefRelationship
4334
523
      = S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2);
4335
523
    if (RefRelationship >= Sema::Ref_Related) {
4336
      // Try to bind the reference here.
4337
101
      TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4338
101
                                     T1Quals, cv2T2, T2, T2Quals, Sequence);
4339
101
      if (Sequence)
4340
89
        Sequence.RewrapReferenceInitList(cv1T1, InitList);
4341
101
      return;
4342
101
    }
4343
4344
    // Update the initializer if we've resolved an overloaded function.
4345
422
    if (Sequence.step_begin() != Sequence.step_end())
4346
1
      Sequence.RewrapReferenceInitList(cv1T1, InitList);
4347
422
  }
4348
  // Perform address space compatibility check.
4349
920
  QualType cv1T1IgnoreAS = cv1T1;
4350
920
  if (T1Quals.hasAddressSpace()) {
4351
4
    Qualifiers T2Quals;
4352
4
    (void)S.Context.getUnqualifiedArrayType(InitList->getType(), T2Quals);
4353
4
    if (!T1Quals.isAddressSpaceSupersetOf(T2Quals)) {
4354
1
      Sequence.SetFailed(
4355
1
          InitializationSequence::FK_ReferenceInitDropsQualifiers);
4356
1
      return;
4357
1
    }
4358
    // Ignore address space of reference type at this point and perform address
4359
    // space conversion after the reference binding step.
4360
3
    cv1T1IgnoreAS =
4361
3
        S.Context.getQualifiedType(T1, T1Quals.withoutAddressSpace());
4362
3
  }
4363
  // Not reference-related. Create a temporary and bind to that.
4364
919
  InitializedEntity TempEntity =
4365
919
      InitializedEntity::InitializeTemporary(cv1T1IgnoreAS);
4366
4367
919
  TryListInitialization(S, TempEntity, Kind, InitList, Sequence,
4368
919
                        TreatUnavailableAsInvalid);
4369
919
  if (Sequence) {
4370
861
    if (DestType->isRValueReferenceType() ||
4371
861
        
(415
T1Quals.hasConst()415
&&
!T1Quals.hasVolatile()407
)) {
4372
853
      Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
4373
853
                                       /*BindingTemporary=*/true);
4374
853
      if (T1Quals.hasAddressSpace())
4375
3
        Sequence.AddQualificationConversionStep(
4376
3
            cv1T1, DestType->isRValueReferenceType() ? 
VK_XValue0
: VK_LValue);
4377
853
    } else
4378
8
      Sequence.SetFailed(
4379
8
          InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
4380
861
  }
4381
919
}
4382
4383
/// Attempt list initialization (C++0x [dcl.init.list])
4384
static void TryListInitialization(Sema &S,
4385
                                  const InitializedEntity &Entity,
4386
                                  const InitializationKind &Kind,
4387
                                  InitListExpr *InitList,
4388
                                  InitializationSequence &Sequence,
4389
109k
                                  bool TreatUnavailableAsInvalid) {
4390
109k
  QualType DestType = Entity.getType();
4391
4392
  // C++ doesn't allow scalar initialization with more than one argument.
4393
  // But C99 complex numbers are scalars and it makes sense there.
4394
109k
  if (S.getLangOpts().CPlusPlus && 
DestType->isScalarType()54.8k
&&
4395
109k
      
!DestType->isAnyComplexType()2.97k
&&
InitList->getNumInits() > 12.86k
) {
4396
12
    Sequence.SetFailed(InitializationSequence::FK_TooManyInitsForScalar);
4397
12
    return;
4398
12
  }
4399
109k
  if (DestType->isReferenceType()) {
4400
1.02k
    TryReferenceListInitialization(S, Entity, Kind, InitList, Sequence,
4401
1.02k
                                   TreatUnavailableAsInvalid);
4402
1.02k
    return;
4403
1.02k
  }
4404
4405
108k
  if (DestType->isRecordType() &&
4406
108k
      
!S.isCompleteType(InitList->getBeginLoc(), DestType)32.5k
) {
4407
1
    Sequence.setIncompleteTypeFailure(DestType);
4408
1
    return;
4409
1
  }
4410
4411
  // C++11 [dcl.init.list]p3, per DR1467:
4412
  // - If T is a class type and the initializer list has a single element of
4413
  //   type cv U, where U is T or a class derived from T, the object is
4414
  //   initialized from that element (by copy-initialization for
4415
  //   copy-list-initialization, or by direct-initialization for
4416
  //   direct-list-initialization).
4417
  // - Otherwise, if T is a character array and the initializer list has a
4418
  //   single element that is an appropriately-typed string literal
4419
  //   (8.5.2 [dcl.init.string]), initialization is performed as described
4420
  //   in that section.
4421
  // - Otherwise, if T is an aggregate, [...] (continue below).
4422
108k
  if (S.getLangOpts().CPlusPlus11 && 
InitList->getNumInits() == 150.6k
) {
4423
13.1k
    if (DestType->isRecordType()) {
4424
5.31k
      QualType InitType = InitList->getInit(0)->getType();
4425
5.31k
      if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
4426
5.31k
          
S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)5.07k
) {
4427
255
        Expr *InitListAsExpr = InitList;
4428
255
        TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4429
255
                                     DestType, Sequence,
4430
255
                                     /*InitListSyntax*/false,
4431
255
                                     /*IsInitListCopy*/true);
4432
255
        return;
4433
255
      }
4434
5.31k
    }
4435
12.9k
    if (const ArrayType *DestAT = S.Context.getAsArrayType(DestType)) {
4436
5.93k
      Expr *SubInit[1] = {InitList->getInit(0)};
4437
5.93k
      if (!isa<VariableArrayType>(DestAT) &&
4438
5.93k
          IsStringInit(SubInit[0], DestAT, S.Context) == SIF_None) {
4439
129
        InitializationKind SubKind =
4440
129
            Kind.getKind() == InitializationKind::IK_DirectList
4441
129
                ? InitializationKind::CreateDirect(Kind.getLocation(),
4442
28
                                                   InitList->getLBraceLoc(),
4443
28
                                                   InitList->getRBraceLoc())
4444
129
                : 
Kind101
;
4445
129
        Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4446
129
                                /*TopLevelOfInitList*/ true,
4447
129
                                TreatUnavailableAsInvalid);
4448
4449
        // TryStringLiteralInitialization() (in InitializeFrom()) will fail if
4450
        // the element is not an appropriately-typed string literal, in which
4451
        // case we should proceed as in C++11 (below).
4452
129
        if (Sequence) {
4453
129
          Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4454
129
          return;
4455
129
        }
4456
129
      }
4457
5.93k
    }
4458
12.9k
  }
4459
4460
  // C++11 [dcl.init.list]p3:
4461
  //   - If T is an aggregate, aggregate initialization is performed.
4462
108k
  if ((DestType->isRecordType() && 
!DestType->isAggregateType()32.2k
) ||
4463
108k
      
(103k
S.getLangOpts().CPlusPlus11103k
&&
4464
103k
       
S.isStdInitializerList(DestType, nullptr)45.8k
)) {
4465
4.42k
    if (S.getLangOpts().CPlusPlus11) {
4466
      //   - Otherwise, if the initializer list has no elements and T is a
4467
      //     class type with a default constructor, the object is
4468
      //     value-initialized.
4469
4.41k
      if (InitList->getNumInits() == 0) {
4470
1.43k
        CXXRecordDecl *RD = DestType->getAsCXXRecordDecl();
4471
1.43k
        if (S.LookupDefaultConstructor(RD)) {
4472
1.28k
          TryValueInitialization(S, Entity, Kind, Sequence, InitList);
4473
1.28k
          return;
4474
1.28k
        }
4475
1.43k
      }
4476
4477
      //   - Otherwise, if T is a specialization of std::initializer_list<E>,
4478
      //     an initializer_list object constructed [...]
4479
3.12k
      if (TryInitializerListConstruction(S, InitList, DestType, Sequence,
4480
3.12k
                                         TreatUnavailableAsInvalid))
4481
791
        return;
4482
4483
      //   - Otherwise, if T is a class type, constructors are considered.
4484
2.33k
      Expr *InitListAsExpr = InitList;
4485
2.33k
      TryConstructorInitialization(S, Entity, Kind, InitListAsExpr, DestType,
4486
2.33k
                                   DestType, Sequence, /*InitListSyntax*/true);
4487
2.33k
    } else
4488
7
      Sequence.SetFailed(InitializationSequence::FK_InitListBadDestinationType);
4489
2.34k
    return;
4490
4.42k
  }
4491
4492
103k
  if (S.getLangOpts().CPlusPlus && 
!DestType->isAggregateType()49.0k
&&
4493
103k
      
InitList->getNumInits() == 111.2k
) {
4494
1.96k
    Expr *E = InitList->getInit(0);
4495
4496
    //   - Otherwise, if T is an enumeration with a fixed underlying type,
4497
    //     the initializer-list has a single element v, and the initialization
4498
    //     is direct-list-initialization, the object is initialized with the
4499
    //     value T(v); if a narrowing conversion is required to convert v to
4500
    //     the underlying type of T, the program is ill-formed.
4501
1.96k
    auto *ET = DestType->getAs<EnumType>();
4502
1.96k
    if (S.getLangOpts().CPlusPlus17 &&
4503
1.96k
        
Kind.getKind() == InitializationKind::IK_DirectList641
&&
4504
1.96k
        
ET423
&&
ET->getDecl()->isFixed()88
&&
4505
1.96k
        
!S.Context.hasSameUnqualifiedType(E->getType(), DestType)80
&&
4506
1.96k
        
(68
E->getType()->isIntegralOrUnscopedEnumerationType()68
||
4507
68
         
E->getType()->isFloatingType()2
)) {
4508
      // There are two ways that T(v) can work when T is an enumeration type.
4509
      // If there is either an implicit conversion sequence from v to T or
4510
      // a conversion function that can convert from v to T, then we use that.
4511
      // Otherwise, if v is of integral, unscoped enumeration, or floating-point
4512
      // type, it is converted to the enumeration type via its underlying type.
4513
      // There is no overlap possible between these two cases (except when the
4514
      // source value is already of the destination type), and the first
4515
      // case is handled by the general case for single-element lists below.
4516
67
      ImplicitConversionSequence ICS;
4517
67
      ICS.setStandard();
4518
67
      ICS.Standard.setAsIdentityConversion();
4519
67
      if (!E->isPRValue())
4520
8
        ICS.Standard.First = ICK_Lvalue_To_Rvalue;
4521
      // If E is of a floating-point type, then the conversion is ill-formed
4522
      // due to narrowing, but go through the motions in order to produce the
4523
      // right diagnostic.
4524
67
      ICS.Standard.Second = E->getType()->isFloatingType()
4525
67
                                ? 
ICK_Floating_Integral1
4526
67
                                : 
ICK_Integral_Conversion66
;
4527
67
      ICS.Standard.setFromType(E->getType());
4528
67
      ICS.Standard.setToType(0, E->getType());
4529
67
      ICS.Standard.setToType(1, DestType);
4530
67
      ICS.Standard.setToType(2, DestType);
4531
67
      Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2),
4532
67
                                         /*TopLevelOfInitList*/true);
4533
67
      Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4534
67
      return;
4535
67
    }
4536
4537
    //   - Otherwise, if the initializer list has a single element of type E
4538
    //     [...references are handled above...], the object or reference is
4539
    //     initialized from that element (by copy-initialization for
4540
    //     copy-list-initialization, or by direct-initialization for
4541
    //     direct-list-initialization); if a narrowing conversion is required
4542
    //     to convert the element to T, the program is ill-formed.
4543
    //
4544
    // Per core-24034, this is direct-initialization if we were performing
4545
    // direct-list-initialization and copy-initialization otherwise.
4546
    // We can't use InitListChecker for this, because it always performs
4547
    // copy-initialization. This only matters if we might use an 'explicit'
4548
    // conversion operator, or for the special case conversion of nullptr_t to
4549
    // bool, so we only need to handle those cases.
4550
    //
4551
    // FIXME: Why not do this in all cases?
4552
1.89k
    Expr *Init = InitList->getInit(0);
4553
1.89k
    if (Init->getType()->isRecordType() ||
4554
1.89k
        
(1.75k
Init->getType()->isNullPtrType()1.75k
&&
DestType->isBooleanType()24
)) {
4555
150
      InitializationKind SubKind =
4556
150
          Kind.getKind() == InitializationKind::IK_DirectList
4557
150
              ? InitializationKind::CreateDirect(Kind.getLocation(),
4558
75
                                                 InitList->getLBraceLoc(),
4559
75
                                                 InitList->getRBraceLoc())
4560
150
              : 
Kind75
;
4561
150
      Expr *SubInit[1] = { Init };
4562
150
      Sequence.InitializeFrom(S, Entity, SubKind, SubInit,
4563
150
                              /*TopLevelOfInitList*/true,
4564
150
                              TreatUnavailableAsInvalid);
4565
150
      if (Sequence)
4566
98
        Sequence.RewrapReferenceInitList(Entity.getType(), InitList);
4567
150
      return;
4568
150
    }
4569
1.89k
  }
4570
4571
103k
  InitListChecker CheckInitList(S, Entity, InitList,
4572
103k
          DestType, /*VerifyOnly=*/true, TreatUnavailableAsInvalid);
4573
103k
  if (CheckInitList.HadError()) {
4574
572
    Sequence.SetFailed(InitializationSequence::FK_ListInitializationFailed);
4575
572
    return;
4576
572
  }
4577
4578
  // Add the list initialization step with the built init list.
4579
102k
  Sequence.AddListInitializationStep(DestType);
4580
102k
}
4581
4582
/// Try a reference initialization that involves calling a conversion
4583
/// function.
4584
static OverloadingResult TryRefInitWithConversionFunction(
4585
    Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind,
4586
    Expr *Initializer, bool AllowRValues, bool IsLValueRef,
4587
2.17k
    InitializationSequence &Sequence) {
4588
2.17k
  QualType DestType = Entity.getType();
4589
2.17k
  QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4590
2.17k
  QualType T1 = cv1T1.getUnqualifiedType();
4591
2.17k
  QualType cv2T2 = Initializer->getType();
4592
2.17k
  QualType T2 = cv2T2.getUnqualifiedType();
4593
4594
2.17k
  assert(!S.CompareReferenceRelationship(Initializer->getBeginLoc(), T1, T2) &&
4595
2.17k
         "Must have incompatible references when binding via conversion");
4596
4597
  // Build the candidate set directly in the initialization sequence
4598
  // structure, so that it will persist if we fail.
4599
0
  OverloadCandidateSet &CandidateSet = Sequence.getFailedCandidateSet();
4600
2.17k
  CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4601
4602
  // Determine whether we are allowed to call explicit conversion operators.
4603
  // Note that none of [over.match.copy], [over.match.conv], nor
4604
  // [over.match.ref] permit an explicit constructor to be chosen when
4605
  // initializing a reference, not even for direct-initialization.
4606
2.17k
  bool AllowExplicitCtors = false;
4607
2.17k
  bool AllowExplicitConvs = Kind.allowExplicitConversionFunctionsInRefBinding();
4608
4609
2.17k
  const RecordType *T1RecordType = nullptr;
4610
2.17k
  if (AllowRValues && 
(T1RecordType = T1->getAs<RecordType>())1.02k
&&
4611
2.17k
      
S.isCompleteType(Kind.getLocation(), T1)848
) {
4612
    // The type we're converting to is a class type. Enumerate its constructors
4613
    // to see if there is a suitable conversion.
4614
846
    CXXRecordDecl *T1RecordDecl = cast<CXXRecordDecl>(T1RecordType->getDecl());
4615
4616
3.49k
    for (NamedDecl *D : S.LookupConstructors(T1RecordDecl)) {
4617
3.49k
      auto Info = getConstructorInfo(D);
4618
3.49k
      if (!Info.Constructor)
4619
3
        continue;
4620
4621
3.49k
      if (!Info.Constructor->isInvalidDecl() &&
4622
3.49k
          Info.Constructor->isConvertingConstructor(/*AllowExplicit*/true)) {
4623
2.78k
        if (Info.ConstructorTmpl)
4624
967
          S.AddTemplateOverloadCandidate(
4625
967
              Info.ConstructorTmpl, Info.FoundDecl,
4626
967
              /*ExplicitArgs*/ nullptr, Initializer, CandidateSet,
4627
967
              /*SuppressUserConversions=*/true,
4628
967
              /*PartialOverloading*/ false, AllowExplicitCtors);
4629
1.81k
        else
4630
1.81k
          S.AddOverloadCandidate(
4631
1.81k
              Info.Constructor, Info.FoundDecl, Initializer, CandidateSet,
4632
1.81k
              /*SuppressUserConversions=*/true,
4633
1.81k
              /*PartialOverloading*/ false, AllowExplicitCtors);
4634
2.78k
      }
4635
3.49k
    }
4636
846
  }
4637
2.17k
  if (T1RecordType && 
T1RecordType->getDecl()->isInvalidDecl()848
)
4638
0
    return OR_No_Viable_Function;
4639
4640
2.17k
  const RecordType *T2RecordType = nullptr;
4641
2.17k
  if ((T2RecordType = T2->getAs<RecordType>()) &&
4642
2.17k
      S.isCompleteType(Kind.getLocation(), T2)) {
4643
    // The type we're converting from is a class type, enumerate its conversion
4644
    // functions.
4645
2.17k
    CXXRecordDecl *T2RecordDecl = cast<CXXRecordDecl>(T2RecordType->getDecl());
4646
4647
2.17k
    const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4648
3.49k
    for (auto I = Conversions.begin(), E = Conversions.end(); I != E; 
++I1.32k
) {
4649
1.32k
      NamedDecl *D = *I;
4650
1.32k
      CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4651
1.32k
      if (isa<UsingShadowDecl>(D))
4652
0
        D = cast<UsingShadowDecl>(D)->getTargetDecl();
4653
4654
1.32k
      FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
4655
1.32k
      CXXConversionDecl *Conv;
4656
1.32k
      if (ConvTemplate)
4657
216
        Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4658
1.10k
      else
4659
1.10k
        Conv = cast<CXXConversionDecl>(D);
4660
4661
      // If the conversion function doesn't return a reference type,
4662
      // it can't be considered for this conversion unless we're allowed to
4663
      // consider rvalues.
4664
      // FIXME: Do we need to make sure that we only consider conversion
4665
      // candidates with reference-compatible results? That might be needed to
4666
      // break recursion.
4667
1.32k
      if ((AllowRValues ||
4668
1.32k
           
Conv->getConversionType()->isLValueReferenceType()737
)) {
4669
861
        if (ConvTemplate)
4670
149
          S.AddTemplateConversionCandidate(
4671
149
              ConvTemplate, I.getPair(), ActingDC, Initializer, DestType,
4672
149
              CandidateSet,
4673
149
              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4674
712
        else
4675
712
          S.AddConversionCandidate(
4676
712
              Conv, I.getPair(), ActingDC, Initializer, DestType, CandidateSet,
4677
712
              /*AllowObjCConversionOnExplicit=*/false, AllowExplicitConvs);
4678
861
      }
4679
1.32k
    }
4680
2.17k
  }
4681
2.17k
  if (T2RecordType && T2RecordType->getDecl()->isInvalidDecl())
4682
2
    return OR_No_Viable_Function;
4683
4684
2.17k
  SourceLocation DeclLoc = Initializer->getBeginLoc();
4685
4686
  // Perform overload resolution. If it fails, return the failed result.
4687
2.17k
  OverloadCandidateSet::iterator Best;
4688
2.17k
  if (OverloadingResult Result
4689
2.17k
        = CandidateSet.BestViableFunction(S, DeclLoc, Best))
4690
1.04k
    return Result;
4691
4692
1.13k
  FunctionDecl *Function = Best->Function;
4693
  // This is the overload that will be used for this initialization step if we
4694
  // use this initialization. Mark it as referenced.
4695
1.13k
  Function->setReferenced();
4696
4697
  // Compute the returned type and value kind of the conversion.
4698
1.13k
  QualType cv3T3;
4699
1.13k
  if (isa<CXXConversionDecl>(Function))
4700
537
    cv3T3 = Function->getReturnType();
4701
595
  else
4702
595
    cv3T3 = T1;
4703
4704
1.13k
  ExprValueKind VK = VK_PRValue;
4705
1.13k
  if (cv3T3->isLValueReferenceType())
4706
213
    VK = VK_LValue;
4707
919
  else if (const auto *RRef = cv3T3->getAs<RValueReferenceType>())
4708
25
    VK = RRef->getPointeeType()->isFunctionType() ? 
VK_LValue0
: VK_XValue;
4709
1.13k
  cv3T3 = cv3T3.getNonLValueExprType(S.Context);
4710
4711
  // Add the user-defined conversion step.
4712
1.13k
  bool HadMultipleCandidates = (CandidateSet.size() > 1);
4713
1.13k
  Sequence.AddUserConversionStep(Function, Best->FoundDecl, cv3T3,
4714
1.13k
                                 HadMultipleCandidates);
4715
4716
  // Determine whether we'll need to perform derived-to-base adjustments or
4717
  // other conversions.
4718
1.13k
  Sema::ReferenceConversions RefConv;
4719
1.13k
  Sema::ReferenceCompareResult NewRefRelationship =
4720
1.13k
      S.CompareReferenceRelationship(DeclLoc, T1, cv3T3, &RefConv);
4721
4722
  // Add the final conversion sequence, if necessary.
4723
1.13k
  if (NewRefRelationship == Sema::Ref_Incompatible) {
4724
16
    assert(!isa<CXXConstructorDecl>(Function) &&
4725
16
           "should not have conversion after constructor");
4726
4727
0
    ImplicitConversionSequence ICS;
4728
16
    ICS.setStandard();
4729
16
    ICS.Standard = Best->FinalConversion;
4730
16
    Sequence.AddConversionSequenceStep(ICS, ICS.Standard.getToType(2));
4731
4732
    // Every implicit conversion results in a prvalue, except for a glvalue
4733
    // derived-to-base conversion, which we handle below.
4734
16
    cv3T3 = ICS.Standard.getToType(2);
4735
16
    VK = VK_PRValue;
4736
16
  }
4737
4738
  //   If the converted initializer is a prvalue, its type T4 is adjusted to
4739
  //   type "cv1 T4" and the temporary materialization conversion is applied.
4740
  //
4741
  // We adjust the cv-qualifications to match the reference regardless of
4742
  // whether we have a prvalue so that the AST records the change. In this
4743
  // case, T4 is "cv3 T3".
4744
0
  QualType cv1T4 = S.Context.getQualifiedType(cv3T3, cv1T1.getQualifiers());
4745
1.13k
  if (cv1T4.getQualifiers() != cv3T3.getQualifiers())
4746
760
    Sequence.AddQualificationConversionStep(cv1T4, VK);
4747
1.13k
  Sequence.AddReferenceBindingStep(cv1T4, VK == VK_PRValue);
4748
1.13k
  VK = IsLValueRef ? 
VK_LValue929
:
VK_XValue203
;
4749
4750
1.13k
  if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4751
32
    Sequence.AddDerivedToBaseCastStep(cv1T1, VK);
4752
1.10k
  else if (RefConv & Sema::ReferenceConversions::ObjC)
4753
5
    Sequence.AddObjCObjectConversionStep(cv1T1);
4754
1.09k
  else if (RefConv & Sema::ReferenceConversions::Function)
4755
3
    Sequence.AddFunctionReferenceConversionStep(cv1T1);
4756
1.09k
  else if (RefConv & Sema::ReferenceConversions::Qualification) {
4757
41
    if (!S.Context.hasSameType(cv1T4, cv1T1))
4758
0
      Sequence.AddQualificationConversionStep(cv1T1, VK);
4759
41
  }
4760
4761
1.13k
  return OR_Success;
4762
2.17k
}
4763
4764
static void CheckCXX98CompatAccessibleCopy(Sema &S,
4765
                                           const InitializedEntity &Entity,
4766
                                           Expr *CurInitExpr);
4767
4768
/// Attempt reference initialization (C++0x [dcl.init.ref])
4769
static void TryReferenceInitialization(Sema &S,
4770
                                       const InitializedEntity &Entity,
4771
                                       const InitializationKind &Kind,
4772
                                       Expr *Initializer,
4773
497k
                                       InitializationSequence &Sequence) {
4774
497k
  QualType DestType = Entity.getType();
4775
497k
  QualType cv1T1 = DestType->castAs<ReferenceType>()->getPointeeType();
4776
497k
  Qualifiers T1Quals;
4777
497k
  QualType T1 = S.Context.getUnqualifiedArrayType(cv1T1, T1Quals);
4778
497k
  QualType cv2T2 = S.getCompletedType(Initializer);
4779
497k
  Qualifiers T2Quals;
4780
497k
  QualType T2 = S.Context.getUnqualifiedArrayType(cv2T2, T2Quals);
4781
4782
  // If the initializer is the address of an overloaded function, try
4783
  // to resolve the overloaded function. If all goes well, T2 is the
4784
  // type of the resulting function.
4785
497k
  if (ResolveOverloadedFunctionForReferenceBinding(S, Initializer, cv2T2, T2,
4786
497k
                                                   T1, Sequence))
4787
8
    return;
4788
4789
  // Delegate everything else to a subfunction.
4790
497k
  TryReferenceInitializationCore(S, Entity, Kind, Initializer, cv1T1, T1,
4791
497k
                                 T1Quals, cv2T2, T2, T2Quals, Sequence);
4792
497k
}
4793
4794
/// Determine whether an expression is a non-referenceable glvalue (one to
4795
/// which a reference can never bind). Attempting to bind a reference to
4796
/// such a glvalue will always create a temporary.
4797
363k
static bool isNonReferenceableGLValue(Expr *E) {
4798
363k
  return E->refersToBitField() || 
E->refersToVectorElement()362k
||
4799
363k
         
E->refersToMatrixElement()362k
;
4800
363k
}
4801
4802
/// Reference initialization without resolving overloaded functions.
4803
///
4804
/// We also can get here in C if we call a builtin which is declared as
4805
/// a function with a parameter of reference type (such as __builtin_va_end()).
4806
static void TryReferenceInitializationCore(Sema &S,
4807
                                           const InitializedEntity &Entity,
4808
                                           const InitializationKind &Kind,
4809
                                           Expr *Initializer,
4810
                                           QualType cv1T1, QualType T1,
4811
                                           Qualifiers T1Quals,
4812
                                           QualType cv2T2, QualType T2,
4813
                                           Qualifiers T2Quals,
4814
497k
                                           InitializationSequence &Sequence) {
4815
497k
  QualType DestType = Entity.getType();
4816
497k
  SourceLocation DeclLoc = Initializer->getBeginLoc();
4817
4818
  // Compute some basic properties of the types and the initializer.
4819
497k
  bool isLValueRef = DestType->isLValueReferenceType();
4820
497k
  bool isRValueRef = !isLValueRef;
4821
497k
  Expr::Classification InitCategory = Initializer->Classify(S.Context);
4822
4823
497k
  Sema::ReferenceConversions RefConv;
4824
497k
  Sema::ReferenceCompareResult RefRelationship =
4825
497k
      S.CompareReferenceRelationship(DeclLoc, cv1T1, cv2T2, &RefConv);
4826
4827
  // C++0x [dcl.init.ref]p5:
4828
  //   A reference to type "cv1 T1" is initialized by an expression of type
4829
  //   "cv2 T2" as follows:
4830
  //
4831
  //     - If the reference is an lvalue reference and the initializer
4832
  //       expression
4833
  // Note the analogous bullet points for rvalue refs to functions. Because
4834
  // there are no function rvalues in C++, rvalue refs to functions are treated
4835
  // like lvalue refs.
4836
497k
  OverloadingResult ConvOvlResult = OR_Success;
4837
497k
  bool T1Function = T1->isFunctionType();
4838
497k
  if (isLValueRef || 
T1Function118k
) {
4839
379k
    if (InitCategory.isLValue() && 
!isNonReferenceableGLValue(Initializer)320k
&&
4840
379k
        
(320k
RefRelationship == Sema::Ref_Compatible320k
||
4841
320k
         
(2.20k
Kind.isCStyleOrFunctionalCast()2.20k
&&
4842
318k
          
RefRelationship == Sema::Ref_Related269
))) {
4843
      //   - is an lvalue (but is not a bit-field), and "cv1 T1" is
4844
      //     reference-compatible with "cv2 T2," or
4845
318k
      if (RefConv & (Sema::ReferenceConversions::DerivedToBase |
4846
318k
                     Sema::ReferenceConversions::ObjC)) {
4847
        // If we're converting the pointee, add any qualifiers first;
4848
        // these qualifiers must all be top-level, so just convert to "cv1 T2".
4849
10.8k
        if (RefConv & (Sema::ReferenceConversions::Qualification))
4850
10.8k
          Sequence.AddQualificationConversionStep(
4851
10.8k
              S.Context.getQualifiedType(T2, T1Quals),
4852
10.8k
              Initializer->getValueKind());
4853
10.8k
        if (RefConv & Sema::ReferenceConversions::DerivedToBase)
4854
10.8k
          Sequence.AddDerivedToBaseCastStep(cv1T1, VK_LValue);
4855
10
        else
4856
10
          Sequence.AddObjCObjectConversionStep(cv1T1);
4857
307k
      } else if (RefConv & Sema::ReferenceConversions::Qualification) {
4858
        // Perform a (possibly multi-level) qualification conversion.
4859
76.3k
        Sequence.AddQualificationConversionStep(cv1T1,
4860
76.3k
                                                Initializer->getValueKind());
4861
230k
      } else if (RefConv & Sema::ReferenceConversions::Function) {
4862
15
        Sequence.AddFunctionReferenceConversionStep(cv1T1);
4863
15
      }
4864
4865
      // We only create a temporary here when binding a reference to a
4866
      // bit-field or vector element. Those cases are't supposed to be
4867
      // handled by this bullet, but the outcome is the same either way.
4868
318k
      Sequence.AddReferenceBindingStep(cv1T1, false);
4869
318k
      return;
4870
318k
    }
4871
4872
    //     - has a class type (i.e., T2 is a class type), where T1 is not
4873
    //       reference-related to T2, and can be implicitly converted to an
4874
    //       lvalue of type "cv3 T3," where "cv1 T1" is reference-compatible
4875
    //       with "cv3 T3" (this conversion is selected by enumerating the
4876
    //       applicable conversion functions (13.3.1.6) and choosing the best
4877
    //       one through overload resolution (13.3)),
4878
    // If we have an rvalue ref to function type here, the rhs must be
4879
    // an rvalue. DR1287 removed the "implicitly" here.
4880
61.5k
    if (RefRelationship == Sema::Ref_Incompatible && 
T2->isRecordType()4.46k
&&
4881
61.5k
        
(1.16k
isLValueRef1.16k
||
InitCategory.isRValue()10
)) {
4882
1.16k
      if (S.getLangOpts().CPlusPlus) {
4883
        // Try conversion functions only for C++.
4884
1.16k
        ConvOvlResult = TryRefInitWithConversionFunction(
4885
1.16k
            S, Entity, Kind, Initializer, /*AllowRValues*/ isRValueRef,
4886
1.16k
            /*IsLValueRef*/ isLValueRef, Sequence);
4887
1.16k
        if (ConvOvlResult == OR_Success)
4888
213
          return;
4889
947
        if (ConvOvlResult != OR_No_Viable_Function)
4890
6
          Sequence.SetOverloadFailure(
4891
6
              InitializationSequence::FK_ReferenceInitOverloadFailed,
4892
6
              ConvOvlResult);
4893
947
      } else {
4894
1
        ConvOvlResult = OR_No_Viable_Function;
4895
1
      }
4896
1.16k
    }
4897
61.5k
  }
4898
4899
  //     - Otherwise, the reference shall be an lvalue reference to a
4900
  //       non-volatile const type (i.e., cv1 shall be const), or the reference
4901
  //       shall be an rvalue reference.
4902
  //       For address spaces, we interpret this to mean that an addr space
4903
  //       of a reference "cv1 T1" is a superset of addr space of "cv2 T2".
4904
179k
  if (isLValueRef && 
!(61.3k
T1Quals.hasConst()61.3k
&&
!T1Quals.hasVolatile()60.6k
&&
4905
61.3k
                       
T1Quals.isAddressSpaceSupersetOf(T2Quals)60.6k
)) {
4906
773
    if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy)
4907
0
      Sequence.SetFailed(InitializationSequence::FK_AddressOfOverloadFailed);
4908
773
    else if (ConvOvlResult && 
!Sequence.getFailedCandidateSet().empty()158
)
4909
15
      Sequence.SetOverloadFailure(
4910
15
                        InitializationSequence::FK_ReferenceInitOverloadFailed,
4911
15
                                  ConvOvlResult);
4912
758
    else if (!InitCategory.isLValue())
4913
190
      Sequence.SetFailed(
4914
190
          T1Quals.isAddressSpaceSupersetOf(T2Quals)
4915
190
              ? InitializationSequence::
4916
189
                    FK_NonConstLValueReferenceBindingToTemporary
4917
190
              : 
InitializationSequence::FK_ReferenceInitDropsQualifiers1
);
4918
568
    else {
4919
568
      InitializationSequence::FailureKind FK;
4920
568
      switch (RefRelationship) {
4921
56
      case Sema::Ref_Compatible:
4922
56
        if (Initializer->refersToBitField())
4923
49
          FK = InitializationSequence::
4924
49
              FK_NonConstLValueReferenceBindingToBitfield;
4925
7
        else if (Initializer->refersToVectorElement())
4926
6
          FK = InitializationSequence::
4927
6
              FK_NonConstLValueReferenceBindingToVectorElement;
4928
1
        else if (Initializer->refersToMatrixElement())
4929
1
          FK = InitializationSequence::
4930
1
              FK_NonConstLValueReferenceBindingToMatrixElement;
4931
0
        else
4932
0
          llvm_unreachable("unexpected kind of compatible initializer");
4933
56
        break;
4934
98
      case Sema::Ref_Related:
4935
98
        FK = InitializationSequence::FK_ReferenceInitDropsQualifiers;
4936
98
        break;
4937
414
      case Sema::Ref_Incompatible:
4938
414
        FK = InitializationSequence::
4939
414
            FK_NonConstLValueReferenceBindingToUnrelated;
4940
414
        break;
4941
568
      }
4942
568
      Sequence.SetFailed(FK);
4943
568
    }
4944
773
    return;
4945
773
  }
4946
4947
  //    - If the initializer expression
4948
  //      - is an
4949
  // [<=14] xvalue (but not a bit-field), class prvalue, array prvalue, or
4950
  // [1z]   rvalue (but not a bit-field) or
4951
  //        function lvalue and "cv1 T1" is reference-compatible with "cv2 T2"
4952
  //
4953
  // Note: functions are handled above and below rather than here...
4954
178k
  if (!T1Function &&
4955
178k
      
(178k
RefRelationship == Sema::Ref_Compatible178k
||
4956
178k
       
(4.91k
Kind.isCStyleOrFunctionalCast()4.91k
&&
4957
4.91k
        
RefRelationship == Sema::Ref_Related27
)) &&
4958
178k
      
(173k
(173k
InitCategory.isXValue()173k
&&
!isNonReferenceableGLValue(Initializer)42.5k
) ||
4959
173k
       
(131k
InitCategory.isPRValue()131k
&&
4960
131k
        
(131k
S.getLangOpts().CPlusPlus17131k
||
T2->isRecordType()125k
||
4961
150k
         
T2->isArrayType()23.4k
)))) {
4962
150k
    ExprValueKind ValueKind = InitCategory.isXValue() ? 
VK_XValue42.5k
:
VK_PRValue107k
;
4963
150k
    if (InitCategory.isPRValue() && 
T2->isRecordType()107k
) {
4964
      // The corresponding bullet in C++03 [dcl.init.ref]p5 gives the
4965
      // compiler the freedom to perform a copy here or bind to the
4966
      // object, while C++0x requires that we bind directly to the
4967
      // object. Hence, we always bind to the object without making an
4968
      // extra copy. However, in C++03 requires that we check for the
4969
      // presence of a suitable copy constructor:
4970
      //
4971
      //   The constructor that would be used to make the copy shall
4972
      //   be callable whether or not the copy is actually done.
4973
105k
      if (!S.getLangOpts().CPlusPlus11 && 
!S.getLangOpts().MicrosoftExt2.26k
)
4974
2.23k
        Sequence.AddExtraneousCopyToTemporary(cv2T2);
4975
103k
      else if (S.getLangOpts().CPlusPlus11)
4976
103k
        CheckCXX98CompatAccessibleCopy(S, Entity, Initializer);
4977
105k
    }
4978
4979
    // C++1z [dcl.init.ref]/5.2.1.2:
4980
    //   If the converted initializer is a prvalue, its type T4 is adjusted
4981
    //   to type "cv1 T4" and the temporary materialization conversion is
4982
    //   applied.
4983
    // Postpone address space conversions to after the temporary materialization
4984
    // conversion to allow creating temporaries in the alloca address space.
4985
150k
    auto T1QualsIgnoreAS = T1Quals;
4986
150k
    auto T2QualsIgnoreAS = T2Quals;
4987
150k
    if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4988
3
      T1QualsIgnoreAS.removeAddressSpace();
4989
3
      T2QualsIgnoreAS.removeAddressSpace();
4990
3
    }
4991
150k
    QualType cv1T4 = S.Context.getQualifiedType(cv2T2, T1QualsIgnoreAS);
4992
150k
    if (T1QualsIgnoreAS != T2QualsIgnoreAS)
4993
41.8k
      Sequence.AddQualificationConversionStep(cv1T4, ValueKind);
4994
150k
    Sequence.AddReferenceBindingStep(cv1T4, ValueKind == VK_PRValue);
4995
150k
    ValueKind = isLValueRef ? 
VK_LValue42.0k
:
VK_XValue108k
;
4996
    // Add addr space conversion if required.
4997
150k
    if (T1Quals.getAddressSpace() != T2Quals.getAddressSpace()) {
4998
3
      auto T4Quals = cv1T4.getQualifiers();
4999
3
      T4Quals.addAddressSpace(T1Quals.getAddressSpace());
5000
3
      QualType cv1T4WithAS = S.Context.getQualifiedType(T2, T4Quals);
5001
3
      Sequence.AddQualificationConversionStep(cv1T4WithAS, ValueKind);
5002
3
      cv1T4 = cv1T4WithAS;
5003
3
    }
5004
5005
    //   In any case, the reference is bound to the resulting glvalue (or to
5006
    //   an appropriate base class subobject).
5007
150k
    if (RefConv & Sema::ReferenceConversions::DerivedToBase)
5008
1.12k
      Sequence.AddDerivedToBaseCastStep(cv1T1, ValueKind);
5009
148k
    else if (RefConv & Sema::ReferenceConversions::ObjC)
5010
0
      Sequence.AddObjCObjectConversionStep(cv1T1);
5011
148k
    else if (RefConv & Sema::ReferenceConversions::Qualification) {
5012
41.7k
      if (!S.Context.hasSameType(cv1T4, cv1T1))
5013
0
        Sequence.AddQualificationConversionStep(cv1T1, ValueKind);
5014
41.7k
    }
5015
150k
    return;
5016
150k
  }
5017
5018
  //       - has a class type (i.e., T2 is a class type), where T1 is not
5019
  //         reference-related to T2, and can be implicitly converted to an
5020
  //         xvalue, class prvalue, or function lvalue of type "cv3 T3",
5021
  //         where "cv1 T1" is reference-compatible with "cv3 T3",
5022
  //
5023
  // DR1287 removes the "implicitly" here.
5024
28.5k
  if (T2->isRecordType()) {
5025
1.10k
    if (RefRelationship == Sema::Ref_Incompatible) {
5026
1.01k
      ConvOvlResult = TryRefInitWithConversionFunction(
5027
1.01k
          S, Entity, Kind, Initializer, /*AllowRValues*/ true,
5028
1.01k
          /*IsLValueRef*/ isLValueRef, Sequence);
5029
1.01k
      if (ConvOvlResult)
5030
95
        Sequence.SetOverloadFailure(
5031
95
            InitializationSequence::FK_ReferenceInitOverloadFailed,
5032
95
            ConvOvlResult);
5033
5034
1.01k
      return;
5035
1.01k
    }
5036
5037
87
    if (RefRelationship == Sema::Ref_Compatible &&
5038
87
        
isRValueRef74
&&
InitCategory.isLValue()74
) {
5039
74
      Sequence.SetFailed(
5040
74
        InitializationSequence::FK_RValueReferenceBindingToLValue);
5041
74
      return;
5042
74
    }
5043
5044
13
    Sequence.SetFailed(InitializationSequence::FK_ReferenceInitDropsQualifiers);
5045
13
    return;
5046
87
  }
5047
5048
  //      - Otherwise, a temporary of type "cv1 T1" is created and initialized
5049
  //        from the initializer expression using the rules for a non-reference
5050
  //        copy-initialization (8.5). The reference is then bound to the
5051
  //        temporary. [...]
5052
5053
  // Ignore add