Coverage Report

Created: 2020-02-15 09:57

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