Coverage Report

Created: 2021-01-23 06:44

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