Coverage Report

Created: 2020-09-22 08:39

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