Coverage Report

Created: 2021-08-24 07:12

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/CodeGen/CGExprConstant.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
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 contains code to emit Constant Expr nodes as LLVM code.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "CGCXXABI.h"
14
#include "CGObjCRuntime.h"
15
#include "CGRecordLayout.h"
16
#include "CodeGenFunction.h"
17
#include "CodeGenModule.h"
18
#include "ConstantEmitter.h"
19
#include "TargetInfo.h"
20
#include "clang/AST/APValue.h"
21
#include "clang/AST/ASTContext.h"
22
#include "clang/AST/Attr.h"
23
#include "clang/AST/RecordLayout.h"
24
#include "clang/AST/StmtVisitor.h"
25
#include "clang/Basic/Builtins.h"
26
#include "llvm/ADT/STLExtras.h"
27
#include "llvm/ADT/Sequence.h"
28
#include "llvm/IR/Constants.h"
29
#include "llvm/IR/DataLayout.h"
30
#include "llvm/IR/Function.h"
31
#include "llvm/IR/GlobalVariable.h"
32
using namespace clang;
33
using namespace CodeGen;
34
35
//===----------------------------------------------------------------------===//
36
//                            ConstantAggregateBuilder
37
//===----------------------------------------------------------------------===//
38
39
namespace {
40
class ConstExprEmitter;
41
42
struct ConstantAggregateBuilderUtils {
43
  CodeGenModule &CGM;
44
45
11.7k
  ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
46
47
23.2k
  CharUnits getAlignment(const llvm::Constant *C) const {
48
23.2k
    return CharUnits::fromQuantity(
49
23.2k
        CGM.getDataLayout().getABITypeAlignment(C->getType()));
50
23.2k
  }
51
52
17.7k
  CharUnits getSize(llvm::Type *Ty) const {
53
17.7k
    return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
54
17.7k
  }
55
56
11.9k
  CharUnits getSize(const llvm::Constant *C) const {
57
11.9k
    return getSize(C->getType());
58
11.9k
  }
59
60
472
  llvm::Constant *getPadding(CharUnits PadSize) const {
61
472
    llvm::Type *Ty = CGM.CharTy;
62
472
    if (PadSize > CharUnits::One())
63
434
      Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
64
472
    return llvm::UndefValue::get(Ty);
65
472
  }
66
67
8
  llvm::Constant *getZeroes(CharUnits ZeroSize) const {
68
8
    llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity());
69
8
    return llvm::ConstantAggregateZero::get(Ty);
70
8
  }
71
};
72
73
/// Incremental builder for an llvm::Constant* holding a struct or array
74
/// constant.
75
class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
76
  /// The elements of the constant. These two arrays must have the same size;
77
  /// Offsets[i] describes the offset of Elems[i] within the constant. The
78
  /// elements are kept in increasing offset order, and we ensure that there
79
  /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
80
  ///
81
  /// This may contain explicit padding elements (in order to create a
82
  /// natural layout), but need not. Gaps between elements are implicitly
83
  /// considered to be filled with undef.
84
  llvm::SmallVector<llvm::Constant*, 32> Elems;
85
  llvm::SmallVector<CharUnits, 32> Offsets;
86
87
  /// The size of the constant (the maximum end offset of any added element).
88
  /// May be larger than the end of Elems.back() if we split the last element
89
  /// and removed some trailing undefs.
90
  CharUnits Size = CharUnits::Zero();
91
92
  /// This is true only if laying out Elems in order as the elements of a
93
  /// non-packed LLVM struct will give the correct layout.
94
  bool NaturalLayout = true;
95
96
  bool split(size_t Index, CharUnits Hint);
97
  Optional<size_t> splitAt(CharUnits Pos);
98
99
  static llvm::Constant *buildFrom(CodeGenModule &CGM,
100
                                   ArrayRef<llvm::Constant *> Elems,
101
                                   ArrayRef<CharUnits> Offsets,
102
                                   CharUnits StartOffset, CharUnits Size,
103
                                   bool NaturalLayout, llvm::Type *DesiredTy,
104
                                   bool AllowOversized);
105
106
public:
107
  ConstantAggregateBuilder(CodeGenModule &CGM)
108
5.90k
      : ConstantAggregateBuilderUtils(CGM) {}
109
110
  /// Update or overwrite the value starting at \p Offset with \c C.
111
  ///
112
  /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
113
  ///        a constant that has already been added. This flag is only used to
114
  ///        detect bugs.
115
  bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
116
117
  /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
118
  bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
119
120
  /// Attempt to condense the value starting at \p Offset to a constant of type
121
  /// \p DesiredTy.
122
  void condense(CharUnits Offset, llvm::Type *DesiredTy);
123
124
  /// Produce a constant representing the entire accumulated value, ideally of
125
  /// the specified type. If \p AllowOversized, the constant might be larger
126
  /// than implied by \p DesiredTy (eg, if there is a flexible array member).
127
  /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
128
  /// even if we can't represent it as that type.
129
5.86k
  llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
130
5.86k
    return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
131
5.86k
                     NaturalLayout, DesiredTy, AllowOversized);
132
5.86k
  }
133
};
134
135
template<typename Container, typename Range = std::initializer_list<
136
                                 typename Container::value_type>>
137
322
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
322
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
322
}
CGExprConstant.cpp:void (anonymous namespace)::replace<llvm::SmallVector<llvm::Constant*, 32u>, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_0, llvm::Constant*> > >(llvm::SmallVector<llvm::Constant*, 32u>&, unsigned long, unsigned long, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_0, llvm::Constant*> >)
Line
Count
Source
137
34
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
34
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
34
}
CGExprConstant.cpp:void (anonymous namespace)::replace<llvm::SmallVector<clang::CharUnits, 32u>, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_1, clang::CharUnits> > >(llvm::SmallVector<clang::CharUnits, 32u>&, unsigned long, unsigned long, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_1, clang::CharUnits> >)
Line
Count
Source
137
2
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
2
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
2
}
CGExprConstant.cpp:void (anonymous namespace)::replace<llvm::SmallVector<clang::CharUnits, 32u>, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_2, clang::CharUnits> > >(llvm::SmallVector<clang::CharUnits, 32u>&, unsigned long, unsigned long, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_2, clang::CharUnits> >)
Line
Count
Source
137
32
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
32
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
32
}
CGExprConstant.cpp:void (anonymous namespace)::replace<llvm::SmallVector<llvm::Constant*, 32u>, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_3, llvm::Constant*> > >(llvm::SmallVector<llvm::Constant*, 32u>&, unsigned long, unsigned long, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_3, llvm::Constant*> >)
Line
Count
Source
137
15
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
15
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
15
}
CGExprConstant.cpp:void (anonymous namespace)::replace<llvm::SmallVector<clang::CharUnits, 32u>, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_4, clang::CharUnits> > >(llvm::SmallVector<clang::CharUnits, 32u>&, unsigned long, unsigned long, llvm::iterator_range<llvm::mapped_iterator<llvm::detail::SafeIntIterator<unsigned int, false>, (anonymous namespace)::ConstantAggregateBuilder::split(unsigned long, clang::CharUnits)::$_4, clang::CharUnits> >)
Line
Count
Source
137
15
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
15
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
15
}
CGExprConstant.cpp:void (anonymous namespace)::replace<llvm::SmallVector<llvm::Constant*, 32u>, std::initializer_list<llvm::Constant*> >(llvm::SmallVector<llvm::Constant*, 32u>&, unsigned long, unsigned long, std::initializer_list<llvm::Constant*>)
Line
Count
Source
137
112
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
112
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
112
}
CGExprConstant.cpp:void (anonymous namespace)::replace<llvm::SmallVector<clang::CharUnits, 32u>, std::initializer_list<clang::CharUnits> >(llvm::SmallVector<clang::CharUnits, 32u>&, unsigned long, unsigned long, std::initializer_list<clang::CharUnits>)
Line
Count
Source
137
112
static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138
112
  assert(BeginOff <= EndOff && "invalid replacement range");
139
0
  llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140
112
}
141
142
bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
143
11.5k
                          bool AllowOverwrite) {
144
  // Common case: appending to a layout.
145
11.5k
  if (Offset >= Size) {
146
11.4k
    CharUnits Align = getAlignment(C);
147
11.4k
    CharUnits AlignedSize = Size.alignTo(Align);
148
11.4k
    if (AlignedSize > Offset || 
Offset.alignTo(Align) != Offset11.3k
)
149
104
      NaturalLayout = false;
150
11.3k
    else if (AlignedSize < Offset) {
151
57
      Elems.push_back(getPadding(Offset - Size));
152
57
      Offsets.push_back(Size);
153
57
    }
154
11.4k
    Elems.push_back(C);
155
11.4k
    Offsets.push_back(Offset);
156
11.4k
    Size = Offset + getSize(C);
157
11.4k
    return true;
158
11.4k
  }
159
160
  // Uncommon case: constant overlaps what we've already created.
161
94
  llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
162
94
  if (!FirstElemToReplace)
163
0
    return false;
164
165
94
  CharUnits CSize = getSize(C);
166
94
  llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
167
94
  if (!LastElemToReplace)
168
0
    return false;
169
170
94
  assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
171
94
         "unexpectedly overwriting field");
172
173
0
  replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
174
94
  replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
175
94
  Size = std::max(Size, Offset + CSize);
176
94
  NaturalLayout = false;
177
94
  return true;
178
94
}
179
180
bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
181
283
                              bool AllowOverwrite) {
182
283
  const ASTContext &Context = CGM.getContext();
183
283
  const uint64_t CharWidth = CGM.getContext().getCharWidth();
184
185
  // Offset of where we want the first bit to go within the bits of the
186
  // current char.
187
283
  unsigned OffsetWithinChar = OffsetInBits % CharWidth;
188
189
  // We split bit-fields up into individual bytes. Walk over the bytes and
190
  // update them.
191
283
  for (CharUnits OffsetInChars =
192
283
           Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
193
507
       /**/; 
++OffsetInChars224
) {
194
    // Number of bits we want to fill in this char.
195
507
    unsigned WantedBits =
196
507
        std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
197
198
    // Get a char containing the bits we want in the right places. The other
199
    // bits have unspecified values.
200
507
    llvm::APInt BitsThisChar = Bits;
201
507
    if (BitsThisChar.getBitWidth() < CharWidth)
202
255
      BitsThisChar = BitsThisChar.zext(CharWidth);
203
507
    if (CGM.getDataLayout().isBigEndian()) {
204
      // Figure out how much to shift by. We may need to left-shift if we have
205
      // less than one byte of Bits left.
206
19
      int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
207
19
      if (Shift > 0)
208
10
        BitsThisChar.lshrInPlace(Shift);
209
9
      else if (Shift < 0)
210
8
        BitsThisChar = BitsThisChar.shl(-Shift);
211
488
    } else {
212
488
      BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
213
488
    }
214
507
    if (BitsThisChar.getBitWidth() > CharWidth)
215
221
      BitsThisChar = BitsThisChar.trunc(CharWidth);
216
217
507
    if (WantedBits == CharWidth) {
218
      // Got a full byte: just add it directly.
219
238
      add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
220
238
          OffsetInChars, AllowOverwrite);
221
269
    } else {
222
      // Partial byte: update the existing integer if there is one. If we
223
      // can't split out a 1-CharUnit range to update, then we can't add
224
      // these bits and fail the entire constant emission.
225
269
      llvm::Optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
226
269
      if (!FirstElemToUpdate)
227
0
        return false;
228
269
      llvm::Optional<size_t> LastElemToUpdate =
229
269
          splitAt(OffsetInChars + CharUnits::One());
230
269
      if (!LastElemToUpdate)
231
0
        return false;
232
269
      assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
233
269
             "should have at most one element covering one byte");
234
235
      // Figure out which bits we want and discard the rest.
236
0
      llvm::APInt UpdateMask(CharWidth, 0);
237
269
      if (CGM.getDataLayout().isBigEndian())
238
8
        UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
239
8
                           CharWidth - OffsetWithinChar);
240
261
      else
241
261
        UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
242
269
      BitsThisChar &= UpdateMask;
243
244
269
      if (*FirstElemToUpdate == *LastElemToUpdate ||
245
269
          
Elems[*FirstElemToUpdate]->isNullValue()82
||
246
269
          
isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])39
) {
247
        // All existing bits are either zero or undef.
248
232
        add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
249
232
            OffsetInChars, /*AllowOverwrite*/ true);
250
232
      } else {
251
37
        llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
252
        // In order to perform a partial update, we need the existing bitwise
253
        // value, which we can only extract for a constant int.
254
37
        auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
255
37
        if (!CI)
256
0
          return false;
257
        // Because this is a 1-CharUnit range, the constant occupying it must
258
        // be exactly one CharUnit wide.
259
37
        assert(CI->getBitWidth() == CharWidth && "splitAt failed");
260
0
        assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
261
37
               "unexpectedly overwriting bitfield");
262
0
        BitsThisChar |= (CI->getValue() & ~UpdateMask);
263
37
        ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
264
37
      }
265
269
    }
266
267
    // Stop if we've added all the bits.
268
507
    if (WantedBits == Bits.getBitWidth())
269
283
      break;
270
271
    // Remove the consumed bits from Bits.
272
224
    if (!CGM.getDataLayout().isBigEndian())
273
214
      Bits.lshrInPlace(WantedBits);
274
224
    Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
275
276
    // The remanining bits go at the start of the following bytes.
277
224
    OffsetWithinChar = 0;
278
224
  }
279
280
283
  return true;
281
283
}
282
283
/// Returns a position within Elems and Offsets such that all elements
284
/// before the returned index end before Pos and all elements at or after
285
/// the returned index begin at or after Pos. Splits elements as necessary
286
/// to ensure this. Returns None if we find something we can't split.
287
762
Optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
288
762
  if (Pos >= Size)
289
523
    return Offsets.size();
290
291
292
  
while (239
true) {
292
292
    auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
293
292
    if (FirstAfterPos == Offsets.begin())
294
0
      return 0;
295
296
    // If we already have an element starting at Pos, we're done.
297
292
    size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
298
292
    if (Offsets[LastAtOrBeforePosIndex] == Pos)
299
235
      return LastAtOrBeforePosIndex;
300
301
    // We found an element starting before Pos. Check for overlap.
302
57
    if (Offsets[LastAtOrBeforePosIndex] +
303
57
        getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
304
4
      return LastAtOrBeforePosIndex + 1;
305
306
    // Try to decompose it into smaller constants.
307
53
    if (!split(LastAtOrBeforePosIndex, Pos))
308
0
      return None;
309
53
  }
310
239
}
311
312
/// Split the constant at index Index, if possible. Return true if we did.
313
/// Hint indicates the location at which we'd like to split, but may be
314
/// ignored.
315
53
bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
316
53
  NaturalLayout = false;
317
53
  llvm::Constant *C = Elems[Index];
318
53
  CharUnits Offset = Offsets[Index];
319
320
53
  if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
321
    // Expand the sequence into its contained elements.
322
    // FIXME: This assumes vector elements are byte-sized.
323
34
    replace(Elems, Index, Index + 1,
324
34
            llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
325
75
                            [&](unsigned Op) { return CA->getOperand(Op); }));
326
34
    if (isa<llvm::ArrayType>(CA->getType()) ||
327
34
        
isa<llvm::VectorType>(CA->getType())32
) {
328
      // Array or vector.
329
2
      llvm::Type *ElemTy =
330
2
          llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0);
331
2
      CharUnits ElemSize = getSize(ElemTy);
332
2
      replace(
333
2
          Offsets, Index, Index + 1,
334
2
          llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
335
6
                          [&](unsigned Op) { return Offset + Op * ElemSize; }));
336
32
    } else {
337
      // Must be a struct.
338
32
      auto *ST = cast<llvm::StructType>(CA->getType());
339
32
      const llvm::StructLayout *Layout =
340
32
          CGM.getDataLayout().getStructLayout(ST);
341
32
      replace(Offsets, Index, Index + 1,
342
32
              llvm::map_range(
343
69
                  llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
344
69
                    return Offset + CharUnits::fromQuantity(
345
69
                                        Layout->getElementOffset(Op));
346
69
                  }));
347
32
    }
348
34
    return true;
349
34
  }
350
351
19
  if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
352
    // Expand the sequence into its contained elements.
353
    // FIXME: This assumes vector elements are byte-sized.
354
    // FIXME: If possible, split into two ConstantDataSequentials at Hint.
355
15
    CharUnits ElemSize = getSize(CDS->getElementType());
356
15
    replace(Elems, Index, Index + 1,
357
15
            llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
358
87
                            [&](unsigned Elem) {
359
87
                              return CDS->getElementAsConstant(Elem);
360
87
                            }));
361
15
    replace(Offsets, Index, Index + 1,
362
15
            llvm::map_range(
363
15
                llvm::seq(0u, CDS->getNumElements()),
364
87
                [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
365
15
    return true;
366
15
  }
367
368
4
  if (isa<llvm::ConstantAggregateZero>(C)) {
369
    // Split into two zeros at the hinted offset.
370
4
    CharUnits ElemSize = getSize(C);
371
4
    assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
372
0
    replace(Elems, Index, Index + 1,
373
4
            {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
374
4
    replace(Offsets, Index, Index + 1, {Offset, Hint});
375
4
    return true;
376
4
  }
377
378
0
  if (isa<llvm::UndefValue>(C)) {
379
    // Drop undef; it doesn't contribute to the final layout.
380
0
    replace(Elems, Index, Index + 1, {});
381
0
    replace(Offsets, Index, Index + 1, {});
382
0
    return true;
383
0
  }
384
385
  // FIXME: We could split a ConstantInt if the need ever arose.
386
  // We don't need to do this to handle bit-fields because we always eagerly
387
  // split them into 1-byte chunks.
388
389
0
  return false;
390
0
}
391
392
static llvm::Constant *
393
EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
394
                  llvm::Type *CommonElementType, unsigned ArrayBound,
395
                  SmallVectorImpl<llvm::Constant *> &Elements,
396
                  llvm::Constant *Filler);
397
398
llvm::Constant *ConstantAggregateBuilder::buildFrom(
399
    CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
400
    ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
401
5.87k
    bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
402
5.87k
  ConstantAggregateBuilderUtils Utils(CGM);
403
404
5.87k
  if (Elems.empty())
405
95
    return llvm::UndefValue::get(DesiredTy);
406
407
5.78k
  auto Offset = [&](size_t I) 
{ return Offsets[I] - StartOffset; }471
;
408
409
  // If we want an array type, see if all the elements are the same type and
410
  // appropriately spaced.
411
5.78k
  if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
412
21
    assert(!AllowOversized && "oversized array emission not supported");
413
414
0
    bool CanEmitArray = true;
415
21
    llvm::Type *CommonType = Elems[0]->getType();
416
21
    llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
417
21
    CharUnits ElemSize = Utils.getSize(ATy->getElementType());
418
21
    SmallVector<llvm::Constant*, 32> ArrayElements;
419
128
    for (size_t I = 0; I != Elems.size(); 
++I107
) {
420
      // Skip zeroes; we'll use a zero value as our array filler.
421
109
      if (Elems[I]->isNullValue())
422
35
        continue;
423
424
      // All remaining elements must be the same type.
425
74
      if (Elems[I]->getType() != CommonType ||
426
74
          
Offset(I) % ElemSize != 072
) {
427
2
        CanEmitArray = false;
428
2
        break;
429
2
      }
430
72
      ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
431
72
      ArrayElements.back() = Elems[I];
432
72
    }
433
434
21
    if (CanEmitArray) {
435
19
      return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
436
19
                               ArrayElements, Filler);
437
19
    }
438
439
    // Can't emit as an array, carry on to emit as a struct.
440
21
  }
441
442
5.76k
  CharUnits DesiredSize = Utils.getSize(DesiredTy);
443
5.76k
  CharUnits Align = CharUnits::One();
444
5.76k
  for (llvm::Constant *C : Elems)
445
11.5k
    Align = std::max(Align, Utils.getAlignment(C));
446
5.76k
  CharUnits AlignedSize = Size.alignTo(Align);
447
448
5.76k
  bool Packed = false;
449
5.76k
  ArrayRef<llvm::Constant*> UnpackedElems = Elems;
450
5.76k
  llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
451
5.76k
  if ((DesiredSize < AlignedSize && 
!AllowOversized116
) ||
452
5.76k
      
DesiredSize.alignTo(Align) != DesiredSize5.65k
) {
453
    // The natural layout would be the wrong size; force use of a packed layout.
454
113
    NaturalLayout = false;
455
113
    Packed = true;
456
5.65k
  } else if (DesiredSize > AlignedSize) {
457
    // The constant would be too small. Add padding to fix it.
458
403
    UnpackedElemStorage.assign(Elems.begin(), Elems.end());
459
403
    UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
460
403
    UnpackedElems = UnpackedElemStorage;
461
403
  }
462
463
  // If we don't have a natural layout, insert padding as necessary.
464
  // As we go, double-check to see if we can actually just emit Elems
465
  // as a non-packed struct and do so opportunistically if possible.
466
5.76k
  llvm::SmallVector<llvm::Constant*, 32> PackedElems;
467
5.76k
  if (!NaturalLayout) {
468
162
    CharUnits SizeSoFar = CharUnits::Zero();
469
489
    for (size_t I = 0; I != Elems.size(); 
++I327
) {
470
327
      CharUnits Align = Utils.getAlignment(Elems[I]);
471
327
      CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
472
327
      CharUnits DesiredOffset = Offset(I);
473
327
      assert(DesiredOffset >= SizeSoFar && "elements out of order");
474
475
327
      if (DesiredOffset != NaturalOffset)
476
106
        Packed = true;
477
327
      if (DesiredOffset != SizeSoFar)
478
3
        PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
479
327
      PackedElems.push_back(Elems[I]);
480
327
      SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
481
327
    }
482
    // If we're using the packed layout, pad it out to the desired size if
483
    // necessary.
484
162
    if (Packed) {
485
116
      assert((SizeSoFar <= DesiredSize || AllowOversized) &&
486
116
             "requested size is too small for contents");
487
116
      if (SizeSoFar < DesiredSize)
488
9
        PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
489
116
    }
490
162
  }
491
492
0
  llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
493
5.76k
      CGM.getLLVMContext(), Packed ? 
PackedElems116
:
UnpackedElems5.64k
, Packed);
494
495
  // Pick the type to use.  If the type is layout identical to the desired
496
  // type then use it, otherwise use whatever the builder produced for us.
497
5.76k
  if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
498
5.76k
    if (DesiredSTy->isLayoutIdentical(STy))
499
4.80k
      STy = DesiredSTy;
500
5.76k
  }
501
502
5.76k
  return llvm::ConstantStruct::get(STy, Packed ? 
PackedElems116
:
UnpackedElems5.64k
);
503
5.78k
}
504
505
void ConstantAggregateBuilder::condense(CharUnits Offset,
506
18
                                        llvm::Type *DesiredTy) {
507
18
  CharUnits Size = getSize(DesiredTy);
508
509
18
  llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
510
18
  if (!FirstElemToReplace)
511
0
    return;
512
18
  size_t First = *FirstElemToReplace;
513
514
18
  llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size);
515
18
  if (!LastElemToReplace)
516
0
    return;
517
18
  size_t Last = *LastElemToReplace;
518
519
18
  size_t Length = Last - First;
520
18
  if (Length == 0)
521
0
    return;
522
523
18
  if (Length == 1 && 
Offsets[First] == Offset4
&&
524
18
      
getSize(Elems[First]) == Size4
) {
525
    // Re-wrap single element structs if necessary. Otherwise, leave any single
526
    // element constant of the right size alone even if it has the wrong type.
527
4
    auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
528
4
    if (STy && STy->getNumElements() == 1 &&
529
4
        STy->getElementType(0) == Elems[First]->getType())
530
2
      Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
531
4
    return;
532
4
  }
533
534
14
  llvm::Constant *Replacement = buildFrom(
535
14
      CGM, makeArrayRef(Elems).slice(First, Length),
536
14
      makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
537
14
      /*known to have natural layout=*/false, DesiredTy, false);
538
14
  replace(Elems, First, Last, {Replacement});
539
14
  replace(Offsets, First, Last, {Offset});
540
14
}
541
542
//===----------------------------------------------------------------------===//
543
//                            ConstStructBuilder
544
//===----------------------------------------------------------------------===//
545
546
class ConstStructBuilder {
547
  CodeGenModule &CGM;
548
  ConstantEmitter &Emitter;
549
  ConstantAggregateBuilder &Builder;
550
  CharUnits StartOffset;
551
552
public:
553
  static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
554
                                     InitListExpr *ILE, QualType StructTy);
555
  static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
556
                                     const APValue &Value, QualType ValTy);
557
  static bool UpdateStruct(ConstantEmitter &Emitter,
558
                           ConstantAggregateBuilder &Const, CharUnits Offset,
559
                           InitListExpr *Updater);
560
561
private:
562
  ConstStructBuilder(ConstantEmitter &Emitter,
563
                     ConstantAggregateBuilder &Builder, CharUnits StartOffset)
564
      : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
565
5.90k
        StartOffset(StartOffset) {}
566
567
  bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
568
                   llvm::Constant *InitExpr, bool AllowOverwrite = false);
569
570
  bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
571
                   bool AllowOverwrite = false);
572
573
  bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
574
                      llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
575
576
  bool Build(InitListExpr *ILE, bool AllowOverwrite);
577
  bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
578
             const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
579
  llvm::Constant *Finalize(QualType Ty);
580
};
581
582
bool ConstStructBuilder::AppendField(
583
    const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
584
10.6k
    bool AllowOverwrite) {
585
10.6k
  const ASTContext &Context = CGM.getContext();
586
587
10.6k
  CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
588
589
10.6k
  return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
590
10.6k
}
591
592
bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
593
                                     llvm::Constant *InitCst,
594
10.9k
                                     bool AllowOverwrite) {
595
10.9k
  return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
596
10.9k
}
597
598
bool ConstStructBuilder::AppendBitField(
599
    const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
600
283
    bool AllowOverwrite) {
601
283
  const CGRecordLayout &RL =
602
283
      CGM.getTypes().getCGRecordLayout(Field->getParent());
603
283
  const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
604
283
  llvm::APInt FieldValue = CI->getValue();
605
606
  // Promote the size of FieldValue if necessary
607
  // FIXME: This should never occur, but currently it can because initializer
608
  // constants are cast to bool, and because clang is not enforcing bitfield
609
  // width limits.
610
283
  if (Info.Size > FieldValue.getBitWidth())
611
5
    FieldValue = FieldValue.zext(Info.Size);
612
613
  // Truncate the size of FieldValue to the bit field size.
614
283
  if (Info.Size < FieldValue.getBitWidth())
615
266
    FieldValue = FieldValue.trunc(Info.Size);
616
617
283
  return Builder.addBits(FieldValue,
618
283
                         CGM.getContext().toBits(StartOffset) + FieldOffset,
619
283
                         AllowOverwrite);
620
283
}
621
622
static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
623
                                      ConstantAggregateBuilder &Const,
624
                                      CharUnits Offset, QualType Type,
625
46
                                      InitListExpr *Updater) {
626
46
  if (Type->isRecordType())
627
25
    return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
628
629
21
  auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
630
21
  if (!CAT)
631
0
    return false;
632
21
  QualType ElemType = CAT->getElementType();
633
21
  CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
634
21
  llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
635
636
21
  llvm::Constant *FillC = nullptr;
637
21
  if (Expr *Filler = Updater->getArrayFiller()) {
638
21
    if (!isa<NoInitExpr>(Filler)) {
639
3
      FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
640
3
      if (!FillC)
641
0
        return false;
642
3
    }
643
21
  }
644
645
21
  unsigned NumElementsToUpdate =
646
21
      FillC ? 
CAT->getSize().getZExtValue()3
:
Updater->getNumInits()18
;
647
111
  for (unsigned I = 0; I != NumElementsToUpdate; 
++I, Offset += ElemSize90
) {
648
90
    Expr *Init = nullptr;
649
90
    if (I < Updater->getNumInits())
650
78
      Init = Updater->getInit(I);
651
652
90
    if (!Init && 
FillC12
) {
653
12
      if (!Const.add(FillC, Offset, true))
654
0
        return false;
655
78
    } else if (!Init || isa<NoInitExpr>(Init)) {
656
52
      continue;
657
52
    } else 
if (InitListExpr *26
ChildILE26
= dyn_cast<InitListExpr>(Init)) {
658
4
      if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
659
4
                                     ChildILE))
660
0
        return false;
661
      // Attempt to reduce the array element to a single constant if necessary.
662
4
      Const.condense(Offset, ElemTy);
663
22
    } else {
664
22
      llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
665
22
      if (!Const.add(Val, Offset, true))
666
0
        return false;
667
22
    }
668
90
  }
669
670
21
  return true;
671
21
}
672
673
2.41k
bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
674
2.41k
  RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
675
2.41k
  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
676
677
2.41k
  unsigned FieldNo = -1;
678
2.41k
  unsigned ElementNo = 0;
679
680
  // Bail out if we have base classes. We could support these, but they only
681
  // arise in C++1z where we will have already constant folded most interesting
682
  // cases. FIXME: There are still a few more cases we can handle this way.
683
2.41k
  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
684
125
    if (CXXRD->getNumBases())
685
6
      return false;
686
687
5.32k
  
for (FieldDecl *Field : RD->fields())2.40k
{
688
5.32k
    ++FieldNo;
689
690
    // If this is a union, skip all the fields that aren't being initialized.
691
5.32k
    if (RD->isUnion() &&
692
5.32k
        
!declaresSameEntity(ILE->getInitializedFieldInUnion(), Field)254
)
693
125
      continue;
694
695
    // Don't emit anonymous bitfields or zero-sized fields.
696
5.20k
    if (Field->isUnnamedBitfield() || 
Field->isZeroSize(CGM.getContext())5.17k
)
697
26
      continue;
698
699
    // Get the initializer.  A struct can include fields without initializers,
700
    // we just use explicit null values for them.
701
5.17k
    Expr *Init = nullptr;
702
5.17k
    if (ElementNo < ILE->getNumInits())
703
5.13k
      Init = ILE->getInit(ElementNo++);
704
5.17k
    if (Init && 
isa<NoInitExpr>(Init)5.13k
)
705
15
      continue;
706
707
    // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
708
    // represents additional overwriting of our current constant value, and not
709
    // a new constant to emit independently.
710
5.16k
    if (AllowOverwrite &&
711
5.16k
        
(27
Field->getType()->isArrayType()27
||
Field->getType()->isRecordType()13
)) {
712
15
      if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
713
14
        CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
714
14
            Layout.getFieldOffset(FieldNo));
715
14
        if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
716
14
                                       Field->getType(), SubILE))
717
0
          return false;
718
        // If we split apart the field's value, try to collapse it down to a
719
        // single value now.
720
14
        Builder.condense(StartOffset + Offset,
721
14
                         CGM.getTypes().ConvertTypeForMem(Field->getType()));
722
14
        continue;
723
14
      }
724
15
    }
725
726
5.14k
    llvm::Constant *EltInit =
727
5.14k
        Init ? 
Emitter.tryEmitPrivateForMemory(Init, Field->getType())5.10k
728
5.14k
             : 
Emitter.emitNullForMemory(Field->getType())46
;
729
5.14k
    if (!EltInit)
730
29
      return false;
731
732
5.12k
    if (!Field->isBitField()) {
733
      // Handle non-bitfield members.
734
4.97k
      if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
735
4.97k
                       AllowOverwrite))
736
0
        return false;
737
      // After emitting a non-empty field with [[no_unique_address]], we may
738
      // need to overwrite its tail padding.
739
4.97k
      if (Field->hasAttr<NoUniqueAddressAttr>())
740
0
        AllowOverwrite = true;
741
4.97k
    } else {
742
      // Otherwise we have a bitfield.
743
144
      if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
744
141
        if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
745
141
                            AllowOverwrite))
746
0
          return false;
747
141
      } else {
748
        // We are trying to initialize a bitfield with a non-trivial constant,
749
        // this must require run-time code.
750
3
        return false;
751
3
      }
752
144
    }
753
5.12k
  }
754
755
2.37k
  return true;
756
2.40k
}
757
758
namespace {
759
struct BaseInfo {
760
  BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
761
418
    : Decl(Decl), Offset(Offset), Index(Index) {
762
418
  }
763
764
  const CXXRecordDecl *Decl;
765
  CharUnits Offset;
766
  unsigned Index;
767
768
63
  bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
769
};
770
}
771
772
bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
773
                               bool IsPrimaryBase,
774
                               const CXXRecordDecl *VTableClass,
775
3.90k
                               CharUnits Offset) {
776
3.90k
  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
777
778
3.90k
  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
779
    // Add a vtable pointer, if we need one and it hasn't already been added.
780
3.90k
    if (Layout.hasOwnVFPtr()) {
781
348
      llvm::Constant *VTableAddressPoint =
782
348
          CGM.getCXXABI().getVTableAddressPointForConstExpr(
783
348
              BaseSubobject(CD, Offset), VTableClass);
784
348
      if (!AppendBytes(Offset, VTableAddressPoint))
785
0
        return false;
786
348
    }
787
788
    // Accumulate and sort bases, in order to visit them in address order, which
789
    // may not be the same as declaration order.
790
3.90k
    SmallVector<BaseInfo, 8> Bases;
791
3.90k
    Bases.reserve(CD->getNumBases());
792
3.90k
    unsigned BaseNo = 0;
793
3.90k
    for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
794
4.32k
         BaseEnd = CD->bases_end(); Base != BaseEnd; 
++Base, ++BaseNo418
) {
795
418
      assert(!Base->isVirtual() && "should not have virtual bases here");
796
0
      const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
797
418
      CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
798
418
      Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
799
418
    }
800
3.90k
    llvm::stable_sort(Bases);
801
802
4.32k
    for (unsigned I = 0, N = Bases.size(); I != N; 
++I418
) {
803
418
      BaseInfo &Base = Bases[I];
804
805
418
      bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
806
418
      Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
807
418
            VTableClass, Offset + Base.Offset);
808
418
    }
809
3.90k
  }
810
811
3.90k
  unsigned FieldNo = 0;
812
3.90k
  uint64_t OffsetBits = CGM.getContext().toBits(Offset);
813
814
3.90k
  bool AllowOverwrite = false;
815
3.90k
  for (RecordDecl::field_iterator Field = RD->field_begin(),
816
10.2k
       FieldEnd = RD->field_end(); Field != FieldEnd; 
++Field, ++FieldNo6.30k
) {
817
    // If this is a union, skip all the fields that aren't being initialized.
818
6.30k
    if (RD->isUnion() && 
!declaresSameEntity(Val.getUnionField(), *Field)953
)
819
454
      continue;
820
821
    // Don't emit anonymous bitfields or zero-sized fields.
822
5.85k
    if (Field->isUnnamedBitfield() || 
Field->isZeroSize(CGM.getContext())5.83k
)
823
43
      continue;
824
825
    // Emit the value of the initializer.
826
5.81k
    const APValue &FieldValue =
827
5.81k
      RD->isUnion() ? 
Val.getUnionValue()499
:
Val.getStructField(FieldNo)5.31k
;
828
5.81k
    llvm::Constant *EltInit =
829
5.81k
      Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
830
5.81k
    if (!EltInit)
831
0
      return false;
832
833
5.81k
    if (!Field->isBitField()) {
834
      // Handle non-bitfield members.
835
5.67k
      if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
836
5.67k
                       EltInit, AllowOverwrite))
837
0
        return false;
838
      // After emitting a non-empty field with [[no_unique_address]], we may
839
      // need to overwrite its tail padding.
840
5.67k
      if (Field->hasAttr<NoUniqueAddressAttr>())
841
6
        AllowOverwrite = true;
842
5.67k
    } else {
843
      // Otherwise we have a bitfield.
844
142
      if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
845
142
                          cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
846
0
        return false;
847
142
    }
848
5.81k
  }
849
850
3.90k
  return true;
851
3.90k
}
852
853
5.83k
llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
854
5.83k
  RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
855
5.83k
  llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
856
5.83k
  return Builder.build(ValTy, RD->hasFlexibleArrayMember());
857
5.83k
}
858
859
llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
860
                                                InitListExpr *ILE,
861
2.38k
                                                QualType ValTy) {
862
2.38k
  ConstantAggregateBuilder Const(Emitter.CGM);
863
2.38k
  ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
864
865
2.38k
  if (!Builder.Build(ILE, /*AllowOverwrite*/false))
866
38
    return nullptr;
867
868
2.35k
  return Builder.Finalize(ValTy);
869
2.38k
}
870
871
llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
872
                                                const APValue &Val,
873
3.48k
                                                QualType ValTy) {
874
3.48k
  ConstantAggregateBuilder Const(Emitter.CGM);
875
3.48k
  ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
876
877
3.48k
  const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
878
3.48k
  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
879
3.48k
  if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
880
0
    return nullptr;
881
882
3.48k
  return Builder.Finalize(ValTy);
883
3.48k
}
884
885
bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
886
                                      ConstantAggregateBuilder &Const,
887
25
                                      CharUnits Offset, InitListExpr *Updater) {
888
25
  return ConstStructBuilder(Emitter, Const, Offset)
889
25
      .Build(Updater, /*AllowOverwrite*/ true);
890
25
}
891
892
//===----------------------------------------------------------------------===//
893
//                             ConstExprEmitter
894
//===----------------------------------------------------------------------===//
895
896
static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
897
                                                    CodeGenFunction *CGF,
898
17
                                              const CompoundLiteralExpr *E) {
899
17
  CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
900
17
  if (llvm::GlobalVariable *Addr =
901
17
          CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
902
2
    return ConstantAddress(Addr, Align);
903
904
15
  LangAS addressSpace = E->getType().getAddressSpace();
905
906
15
  ConstantEmitter emitter(CGM, CGF);
907
15
  llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
908
15
                                                    addressSpace, E->getType());
909
15
  if (!C) {
910
0
    assert(!E->isFileScope() &&
911
0
           "file-scope compound literal did not have constant initializer!");
912
0
    return ConstantAddress::invalid();
913
0
  }
914
915
15
  auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
916
15
                                     CGM.isTypeConstant(E->getType(), true),
917
15
                                     llvm::GlobalValue::InternalLinkage,
918
15
                                     C, ".compoundliteral", nullptr,
919
15
                                     llvm::GlobalVariable::NotThreadLocal,
920
15
                    CGM.getContext().getTargetAddressSpace(addressSpace));
921
15
  emitter.finalize(GV);
922
15
  GV->setAlignment(Align.getAsAlign());
923
15
  CGM.setAddrOfConstantCompoundLiteral(E, GV);
924
15
  return ConstantAddress(GV, Align);
925
15
}
926
927
static llvm::Constant *
928
EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
929
                  llvm::Type *CommonElementType, unsigned ArrayBound,
930
                  SmallVectorImpl<llvm::Constant *> &Elements,
931
3.81k
                  llvm::Constant *Filler) {
932
  // Figure out how long the initial prefix of non-zero elements is.
933
3.81k
  unsigned NonzeroLength = ArrayBound;
934
3.81k
  if (Elements.size() < NonzeroLength && 
Filler->isNullValue()782
)
935
774
    NonzeroLength = Elements.size();
936
3.81k
  if (NonzeroLength == Elements.size()) {
937
4.34k
    while (NonzeroLength > 0 && 
Elements[NonzeroLength - 1]->isNullValue()3.69k
)
938
529
      --NonzeroLength;
939
3.81k
  }
940
941
3.81k
  if (NonzeroLength == 0)
942
641
    return llvm::ConstantAggregateZero::get(DesiredType);
943
944
  // Add a zeroinitializer array filler if we have lots of trailing zeroes.
945
3.17k
  unsigned TrailingZeroes = ArrayBound - NonzeroLength;
946
3.17k
  if (TrailingZeroes >= 8) {
947
62
    assert(Elements.size() >= NonzeroLength &&
948
62
           "missing initializer for non-zero element");
949
950
    // If all the elements had the same type up to the trailing zeroes, emit a
951
    // struct of two arrays (the nonzero data and the zeroinitializer).
952
62
    if (CommonElementType && 
NonzeroLength >= 860
) {
953
17
      llvm::Constant *Initial = llvm::ConstantArray::get(
954
17
          llvm::ArrayType::get(CommonElementType, NonzeroLength),
955
17
          makeArrayRef(Elements).take_front(NonzeroLength));
956
17
      Elements.resize(2);
957
17
      Elements[0] = Initial;
958
45
    } else {
959
45
      Elements.resize(NonzeroLength + 1);
960
45
    }
961
962
62
    auto *FillerType =
963
62
        CommonElementType ? 
CommonElementType60
:
DesiredType->getElementType()2
;
964
62
    FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
965
62
    Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
966
62
    CommonElementType = nullptr;
967
3.11k
  } else if (Elements.size() != ArrayBound) {
968
    // Otherwise pad to the right size with the filler if necessary.
969
185
    Elements.resize(ArrayBound, Filler);
970
185
    if (Filler->getType() != CommonElementType)
971
8
      CommonElementType = nullptr;
972
185
  }
973
974
  // If all elements have the same type, just emit an array constant.
975
3.17k
  if (CommonElementType)
976
3.10k
    return llvm::ConstantArray::get(
977
3.10k
        llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
978
979
  // We have mixed types. Use a packed struct.
980
75
  llvm::SmallVector<llvm::Type *, 16> Types;
981
75
  Types.reserve(Elements.size());
982
75
  for (llvm::Constant *Elt : Elements)
983
241
    Types.push_back(Elt->getType());
984
75
  llvm::StructType *SType =
985
75
      llvm::StructType::get(CGM.getLLVMContext(), Types, true);
986
75
  return llvm::ConstantStruct::get(SType, Elements);
987
3.17k
}
988
989
// This class only needs to handle arrays, structs and unions. Outside C++11
990
// mode, we don't currently constant fold those types.  All other types are
991
// handled by constant folding.
992
//
993
// Constant folding is currently missing support for a few features supported
994
// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
995
class ConstExprEmitter :
996
  public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
997
  CodeGenModule &CGM;
998
  ConstantEmitter &Emitter;
999
  llvm::LLVMContext &VMContext;
1000
public:
1001
  ConstExprEmitter(ConstantEmitter &emitter)
1002
31.0k
    : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
1003
31.0k
  }
1004
1005
  //===--------------------------------------------------------------------===//
1006
  //                            Visitor Methods
1007
  //===--------------------------------------------------------------------===//
1008
1009
21.9k
  llvm::Constant *VisitStmt(Stmt *S, QualType T) {
1010
21.9k
    return nullptr;
1011
21.9k
  }
1012
1013
16
  llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
1014
16
    if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE))
1015
0
      return Result;
1016
16
    return Visit(CE->getSubExpr(), T);
1017
16
  }
1018
1019
87
  llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
1020
87
    return Visit(PE->getSubExpr(), T);
1021
87
  }
1022
1023
  llvm::Constant *
1024
  VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
1025
0
                                    QualType T) {
1026
0
    return Visit(PE->getReplacement(), T);
1027
0
  }
1028
1029
  llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
1030
1
                                            QualType T) {
1031
1
    return Visit(GE->getResultExpr(), T);
1032
1
  }
1033
1034
1
  llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
1035
1
    return Visit(CE->getChosenSubExpr(), T);
1036
1
  }
1037
1038
38
  llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
1039
38
    return Visit(E->getInitializer(), T);
1040
38
  }
1041
1042
8.86k
  llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
1043
8.86k
    if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
1044
396
      CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
1045
8.86k
    Expr *subExpr = E->getSubExpr();
1046
1047
8.86k
    switch (E->getCastKind()) {
1048
4
    case CK_ToUnion: {
1049
      // GCC cast to union extension
1050
4
      assert(E->getType()->isUnionType() &&
1051
4
             "Destination type is not union type!");
1052
1053
0
      auto field = E->getTargetUnionField();
1054
1055
4
      auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1056
4
      if (!C) 
return nullptr0
;
1057
1058
4
      auto destTy = ConvertType(destType);
1059
4
      if (C->getType() == destTy) 
return C0
;
1060
1061
      // Build a struct with the union sub-element as the first member,
1062
      // and padded to the appropriate size.
1063
4
      SmallVector<llvm::Constant*, 2> Elts;
1064
4
      SmallVector<llvm::Type*, 2> Types;
1065
4
      Elts.push_back(C);
1066
4
      Types.push_back(C->getType());
1067
4
      unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
1068
4
      unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
1069
1070
4
      assert(CurSize <= TotalSize && "Union size mismatch!");
1071
4
      if (unsigned NumPadBytes = TotalSize - CurSize) {
1072
2
        llvm::Type *Ty = CGM.CharTy;
1073
2
        if (NumPadBytes > 1)
1074
2
          Ty = llvm::ArrayType::get(Ty, NumPadBytes);
1075
1076
2
        Elts.push_back(llvm::UndefValue::get(Ty));
1077
2
        Types.push_back(Ty);
1078
2
      }
1079
1080
4
      llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
1081
4
      return llvm::ConstantStruct::get(STy, Elts);
1082
4
    }
1083
1084
0
    case CK_AddressSpaceConversion: {
1085
0
      auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1086
0
      if (!C) return nullptr;
1087
0
      LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1088
0
      LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
1089
0
      llvm::Type *destTy = ConvertType(E->getType());
1090
0
      return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1091
0
                                                             destAS, destTy);
1092
0
    }
1093
1094
7.98k
    case CK_LValueToRValue:
1095
7.98k
    case CK_AtomicToNonAtomic:
1096
7.98k
    case CK_NonAtomicToAtomic:
1097
8.39k
    case CK_NoOp:
1098
8.41k
    case CK_ConstructorConversion:
1099
8.41k
      return Visit(subExpr, destType);
1100
1101
0
    case CK_IntToOCLSampler:
1102
0
      llvm_unreachable("global sampler variables are not generated");
1103
1104
0
    case CK_Dependent: llvm_unreachable("saw dependent cast!");
1105
1106
0
    case CK_BuiltinFnToFnPtr:
1107
0
      llvm_unreachable("builtin functions are handled elsewhere");
1108
1109
39
    case CK_ReinterpretMemberPointer:
1110
41
    case CK_DerivedToBaseMemberPointer:
1111
52
    case CK_BaseToDerivedMemberPointer: {
1112
52
      auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1113
52
      if (!C) 
return nullptr0
;
1114
52
      return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
1115
52
    }
1116
1117
    // These will never be supported.
1118
0
    case CK_ObjCObjectLValueCast:
1119
0
    case CK_ARCProduceObject:
1120
3
    case CK_ARCConsumeObject:
1121
34
    case CK_ARCReclaimReturnedObject:
1122
34
    case CK_ARCExtendBlockObject:
1123
34
    case CK_CopyAndAutoreleaseBlockObject:
1124
34
      return nullptr;
1125
1126
    // These don't need to be handled here because Evaluate knows how to
1127
    // evaluate them in the cases where they can be folded.
1128
70
    case CK_BitCast:
1129
70
    case CK_ToVoid:
1130
70
    case CK_Dynamic:
1131
73
    case CK_LValueBitCast:
1132
73
    case CK_LValueToRValueBitCast:
1133
74
    case CK_NullToMemberPointer:
1134
123
    case CK_UserDefinedConversion:
1135
126
    case CK_CPointerToObjCPointerCast:
1136
126
    case CK_BlockPointerToObjCPointerCast:
1137
126
    case CK_AnyPointerToBlockPointerCast:
1138
128
    case CK_ArrayToPointerDecay:
1139
128
    case CK_FunctionToPointerDecay:
1140
128
    case CK_BaseToDerived:
1141
140
    case CK_DerivedToBase:
1142
140
    case CK_UncheckedDerivedToBase:
1143
140
    case CK_MemberPointerToBoolean:
1144
140
    case CK_VectorSplat:
1145
140
    case CK_FloatingRealToComplex:
1146
140
    case CK_FloatingComplexToReal:
1147
140
    case CK_FloatingComplexToBoolean:
1148
140
    case CK_FloatingComplexCast:
1149
140
    case CK_FloatingComplexToIntegralComplex:
1150
140
    case CK_IntegralRealToComplex:
1151
140
    case CK_IntegralComplexToReal:
1152
140
    case CK_IntegralComplexToBoolean:
1153
140
    case CK_IntegralComplexCast:
1154
140
    case CK_IntegralComplexToFloatingComplex:
1155
145
    case CK_PointerToIntegral:
1156
145
    case CK_PointerToBoolean:
1157
146
    case CK_NullToPointer:
1158
347
    case CK_IntegralCast:
1159
347
    case CK_BooleanToSignedIntegral:
1160
350
    case CK_IntegralToPointer:
1161
350
    case CK_IntegralToBoolean:
1162
355
    case CK_IntegralToFloating:
1163
357
    case CK_FloatingToIntegral:
1164
357
    case CK_FloatingToBoolean:
1165
357
    case CK_FloatingCast:
1166
357
    case CK_FloatingToFixedPoint:
1167
357
    case CK_FixedPointToFloating:
1168
357
    case CK_FixedPointCast:
1169
357
    case CK_FixedPointToBoolean:
1170
357
    case CK_FixedPointToIntegral:
1171
357
    case CK_IntegralToFixedPoint:
1172
357
    case CK_ZeroToOCLOpaqueType:
1173
357
    case CK_MatrixCast:
1174
357
      return nullptr;
1175
8.86k
    }
1176
0
    llvm_unreachable("Invalid CastKind");
1177
0
  }
1178
1179
3
  llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
1180
    // No need for a DefaultInitExprScope: we don't handle 'this' in a
1181
    // constant expression.
1182
3
    return Visit(DIE->getExpr(), T);
1183
3
  }
1184
1185
732
  llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
1186
732
    return Visit(E->getSubExpr(), T);
1187
732
  }
1188
1189
  llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
1190
175
                                                QualType T) {
1191
175
    return Visit(E->getSubExpr(), T);
1192
175
  }
1193
1194
1.16k
  llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
1195
1.16k
    auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
1196
1.16k
    assert(CAT && "can't emit array init for non-constant-bound array");
1197
0
    unsigned NumInitElements = ILE->getNumInits();
1198
1.16k
    unsigned NumElements = CAT->getSize().getZExtValue();
1199
1200
    // Initialising an array requires us to automatically
1201
    // initialise any elements that have not been initialised explicitly
1202
1.16k
    unsigned NumInitableElts = std::min(NumInitElements, NumElements);
1203
1204
1.16k
    QualType EltType = CAT->getElementType();
1205
1206
    // Initialize remaining array elements.
1207
1.16k
    llvm::Constant *fillC = nullptr;
1208
1.16k
    if (Expr *filler = ILE->getArrayFiller()) {
1209
156
      fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
1210
156
      if (!fillC)
1211
11
        return nullptr;
1212
156
    }
1213
1214
    // Copy initializer elements.
1215
1.15k
    SmallVector<llvm::Constant*, 16> Elts;
1216
1.15k
    if (fillC && 
fillC->isNullValue()145
)
1217
145
      Elts.reserve(NumInitableElts + 1);
1218
1.01k
    else
1219
1.01k
      Elts.reserve(NumElements);
1220
1221
1.15k
    llvm::Type *CommonElementType = nullptr;
1222
6.83k
    for (unsigned i = 0; i < NumInitableElts; 
++i5.67k
) {
1223
6.06k
      Expr *Init = ILE->getInit(i);
1224
6.06k
      llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
1225
6.06k
      if (!C)
1226
387
        return nullptr;
1227
5.67k
      if (i == 0)
1228
752
        CommonElementType = C->getType();
1229
4.92k
      else if (C->getType() != CommonElementType)
1230
4
        CommonElementType = nullptr;
1231
5.67k
      Elts.push_back(C);
1232
5.67k
    }
1233
1234
770
    llvm::ArrayType *Desired =
1235
770
        cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
1236
770
    return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
1237
770
                             fillC);
1238
1.15k
  }
1239
1240
2.38k
  llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
1241
2.38k
    return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
1242
2.38k
  }
1243
1244
  llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
1245
58
                                             QualType T) {
1246
58
    return CGM.EmitNullConstant(T);
1247
58
  }
1248
1249
3.57k
  llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
1250
3.57k
    if (ILE->isTransparent())
1251
16
      return Visit(ILE->getInit(0), T);
1252
1253
3.55k
    if (ILE->getType()->isArrayType())
1254
1.16k
      return EmitArrayInitialization(ILE, T);
1255
1256
2.38k
    if (ILE->getType()->isRecordType())
1257
2.38k
      return EmitRecordInitialization(ILE, T);
1258
1259
0
    return nullptr;
1260
2.38k
  }
1261
1262
  llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1263
28
                                                QualType destType) {
1264
28
    auto C = Visit(E->getBase(), destType);
1265
28
    if (!C)
1266
0
      return nullptr;
1267
1268
28
    ConstantAggregateBuilder Const(CGM);
1269
28
    Const.add(C, CharUnits::Zero(), false);
1270
1271
28
    if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
1272
28
                                   E->getUpdater()))
1273
0
      return nullptr;
1274
1275
28
    llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
1276
28
    bool HasFlexibleArray = false;
1277
28
    if (auto *RT = destType->getAs<RecordType>())
1278
20
      HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1279
28
    return Const.build(ValTy, HasFlexibleArray);
1280
28
  }
1281
1282
5.03k
  llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
1283
5.03k
    if (!E->getConstructor()->isTrivial())
1284
4.81k
      return nullptr;
1285
1286
    // Only default and copy/move constructors can be trivial.
1287
219
    if (E->getNumArgs()) {
1288
217
      assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
1289
0
      assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1290
217
             "trivial ctor has argument but isn't a copy/move ctor");
1291
1292
0
      Expr *Arg = E->getArg(0);
1293
217
      assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1294
217
             "argument to copy ctor is of wrong type");
1295
1296
0
      return Visit(Arg, Ty);
1297
217
    }
1298
1299
2
    return CGM.EmitNullConstant(Ty);
1300
219
  }
1301
1302
96
  llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1303
    // This is a string literal initializing an array in an initializer.
1304
96
    return CGM.GetConstantArrayFromStringLiteral(E);
1305
96
  }
1306
1307
64
  llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1308
    // This must be an @encode initializing an array in a static initializer.
1309
    // Don't emit it as the address of the string, emit the string data itself
1310
    // as an inline array.
1311
64
    std::string Str;
1312
64
    CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1313
64
    const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1314
1315
    // Resize the string to the right size, adding zeros at the end, or
1316
    // truncating as needed.
1317
64
    Str.resize(CAT->getSize().getZExtValue(), '\0');
1318
64
    return llvm::ConstantDataArray::getString(VMContext, Str, false);
1319
64
  }
1320
1321
1
  llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1322
1
    return Visit(E->getSubExpr(), T);
1323
1
  }
1324
1325
  // Utility methods
1326
4
  llvm::Type *ConvertType(QualType T) {
1327
4
    return CGM.getTypes().ConvertType(T);
1328
4
  }
1329
};
1330
1331
}  // end anonymous namespace.
1332
1333
llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1334
28.8k
                                                        AbstractState saved) {
1335
28.8k
  Abstract = saved.OldValue;
1336
1337
28.8k
  assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1338
28.8k
         "created a placeholder while doing an abstract emission?");
1339
1340
  // No validation necessary for now.
1341
  // No cleanup to do for now.
1342
0
  return C;
1343
28.8k
}
1344
1345
llvm::Constant *
1346
20.0k
ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1347
20.0k
  auto state = pushAbstract();
1348
20.0k
  auto C = tryEmitPrivateForVarInit(D);
1349
20.0k
  return validateAndPopAbstract(C, state);
1350
20.0k
}
1351
1352
llvm::Constant *
1353
584
ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1354
584
  auto state = pushAbstract();
1355
584
  auto C = tryEmitPrivate(E, destType);
1356
584
  return validateAndPopAbstract(C, state);
1357
584
}
1358
1359
llvm::Constant *
1360
630
ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1361
630
  auto state = pushAbstract();
1362
630
  auto C = tryEmitPrivate(value, destType);
1363
630
  return validateAndPopAbstract(C, state);
1364
630
}
1365
1366
600
llvm::Constant *ConstantEmitter::tryEmitConstantExpr(const ConstantExpr *CE) {
1367
600
  if (!CE->hasAPValueResult())
1368
17
    return nullptr;
1369
583
  const Expr *Inner = CE->getSubExpr()->IgnoreImplicit();
1370
583
  QualType RetType;
1371
583
  if (auto *Call = dyn_cast<CallExpr>(Inner))
1372
26
    RetType = Call->getCallReturnType(CGF->getContext());
1373
557
  else if (auto *Ctor = dyn_cast<CXXConstructExpr>(Inner))
1374
2
    RetType = Ctor->getType();
1375
583
  llvm::Constant *Res =
1376
583
      emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), RetType);
1377
583
  return Res;
1378
600
}
1379
1380
llvm::Constant *
1381
284
ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1382
284
  auto state = pushAbstract();
1383
284
  auto C = tryEmitPrivate(E, destType);
1384
284
  C = validateAndPopAbstract(C, state);
1385
284
  if (!C) {
1386
0
    CGM.Error(E->getExprLoc(),
1387
0
              "internal error: could not emit constant value \"abstractly\"");
1388
0
    C = CGM.EmitNullConstant(destType);
1389
0
  }
1390
284
  return C;
1391
284
}
1392
1393
llvm::Constant *
1394
ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1395
7.33k
                              QualType destType) {
1396
7.33k
  auto state = pushAbstract();
1397
7.33k
  auto C = tryEmitPrivate(value, destType);
1398
7.33k
  C = validateAndPopAbstract(C, state);
1399
7.33k
  if (!C) {
1400
0
    CGM.Error(loc,
1401
0
              "internal error: could not emit constant value \"abstractly\"");
1402
0
    C = CGM.EmitNullConstant(destType);
1403
0
  }
1404
7.33k
  return C;
1405
7.33k
}
1406
1407
27.9k
llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1408
27.9k
  initializeNonAbstract(D.getType().getAddressSpace());
1409
27.9k
  return markIfFailed(tryEmitPrivateForVarInit(D));
1410
27.9k
}
1411
1412
llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1413
                                                       LangAS destAddrSpace,
1414
101
                                                       QualType destType) {
1415
101
  initializeNonAbstract(destAddrSpace);
1416
101
  return markIfFailed(tryEmitPrivateForMemory(E, destType));
1417
101
}
1418
1419
llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1420
                                                    LangAS destAddrSpace,
1421
159
                                                    QualType destType) {
1422
159
  initializeNonAbstract(destAddrSpace);
1423
159
  auto C = tryEmitPrivateForMemory(value, destType);
1424
159
  assert(C && "couldn't emit constant value non-abstractly?");
1425
0
  return C;
1426
159
}
1427
1428
0
llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1429
0
  assert(!Abstract && "cannot get current address for abstract constant");
1430
1431
1432
1433
  // Make an obviously ill-formed global that should blow up compilation
1434
  // if it survives.
1435
0
  auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1436
0
                                         llvm::GlobalValue::PrivateLinkage,
1437
0
                                         /*init*/ nullptr,
1438
0
                                         /*name*/ "",
1439
0
                                         /*before*/ nullptr,
1440
0
                                         llvm::GlobalVariable::NotThreadLocal,
1441
0
                                         CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1442
1443
0
  PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1444
1445
0
  return global;
1446
0
}
1447
1448
void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1449
0
                                           llvm::GlobalValue *placeholder) {
1450
0
  assert(!PlaceholderAddresses.empty());
1451
0
  assert(PlaceholderAddresses.back().first == nullptr);
1452
0
  assert(PlaceholderAddresses.back().second == placeholder);
1453
0
  PlaceholderAddresses.back().first = signal;
1454
0
}
1455
1456
namespace {
1457
  struct ReplacePlaceholders {
1458
    CodeGenModule &CGM;
1459
1460
    /// The base address of the global.
1461
    llvm::Constant *Base;
1462
    llvm::Type *BaseValueTy = nullptr;
1463
1464
    /// The placeholder addresses that were registered during emission.
1465
    llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1466
1467
    /// The locations of the placeholder signals.
1468
    llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1469
1470
    /// The current index stack.  We use a simple unsigned stack because
1471
    /// we assume that placeholders will be relatively sparse in the
1472
    /// initializer, but we cache the index values we find just in case.
1473
    llvm::SmallVector<unsigned, 8> Indices;
1474
    llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1475
1476
    ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1477
                        ArrayRef<std::pair<llvm::Constant*,
1478
                                           llvm::GlobalVariable*>> addresses)
1479
        : CGM(CGM), Base(base),
1480
0
          PlaceholderAddresses(addresses.begin(), addresses.end()) {
1481
0
    }
1482
1483
0
    void replaceInInitializer(llvm::Constant *init) {
1484
      // Remember the type of the top-most initializer.
1485
0
      BaseValueTy = init->getType();
1486
1487
      // Initialize the stack.
1488
0
      Indices.push_back(0);
1489
0
      IndexValues.push_back(nullptr);
1490
1491
      // Recurse into the initializer.
1492
0
      findLocations(init);
1493
1494
      // Check invariants.
1495
0
      assert(IndexValues.size() == Indices.size() && "mismatch");
1496
0
      assert(Indices.size() == 1 && "didn't pop all indices");
1497
1498
      // Do the replacement; this basically invalidates 'init'.
1499
0
      assert(Locations.size() == PlaceholderAddresses.size() &&
1500
0
             "missed a placeholder?");
1501
1502
      // We're iterating over a hashtable, so this would be a source of
1503
      // non-determinism in compiler output *except* that we're just
1504
      // messing around with llvm::Constant structures, which never itself
1505
      // does anything that should be visible in compiler output.
1506
0
      for (auto &entry : Locations) {
1507
0
        assert(entry.first->getParent() == nullptr && "not a placeholder!");
1508
0
        entry.first->replaceAllUsesWith(entry.second);
1509
0
        entry.first->eraseFromParent();
1510
0
      }
1511
0
    }
1512
1513
  private:
1514
0
    void findLocations(llvm::Constant *init) {
1515
      // Recurse into aggregates.
1516
0
      if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1517
0
        for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1518
0
          Indices.push_back(i);
1519
0
          IndexValues.push_back(nullptr);
1520
1521
0
          findLocations(agg->getOperand(i));
1522
1523
0
          IndexValues.pop_back();
1524
0
          Indices.pop_back();
1525
0
        }
1526
0
        return;
1527
0
      }
1528
1529
      // Otherwise, check for registered constants.
1530
0
      while (true) {
1531
0
        auto it = PlaceholderAddresses.find(init);
1532
0
        if (it != PlaceholderAddresses.end()) {
1533
0
          setLocation(it->second);
1534
0
          break;
1535
0
        }
1536
1537
        // Look through bitcasts or other expressions.
1538
0
        if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1539
0
          init = expr->getOperand(0);
1540
0
        } else {
1541
0
          break;
1542
0
        }
1543
0
      }
1544
0
    }
1545
1546
0
    void setLocation(llvm::GlobalVariable *placeholder) {
1547
0
      assert(Locations.find(placeholder) == Locations.end() &&
1548
0
             "already found location for placeholder!");
1549
1550
      // Lazily fill in IndexValues with the values from Indices.
1551
      // We do this in reverse because we should always have a strict
1552
      // prefix of indices from the start.
1553
0
      assert(Indices.size() == IndexValues.size());
1554
0
      for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1555
0
        if (IndexValues[i]) {
1556
0
#ifndef NDEBUG
1557
0
          for (size_t j = 0; j != i + 1; ++j) {
1558
0
            assert(IndexValues[j] &&
1559
0
                   isa<llvm::ConstantInt>(IndexValues[j]) &&
1560
0
                   cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1561
0
                     == Indices[j]);
1562
0
          }
1563
0
#endif
1564
0
          break;
1565
0
        }
1566
1567
0
        IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1568
0
      }
1569
1570
      // Form a GEP and then bitcast to the placeholder type so that the
1571
      // replacement will succeed.
1572
0
      llvm::Constant *location =
1573
0
        llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1574
0
                                                     Base, IndexValues);
1575
0
      location = llvm::ConstantExpr::getBitCast(location,
1576
0
                                                placeholder->getType());
1577
1578
0
      Locations.insert({placeholder, location});
1579
0
    }
1580
  };
1581
}
1582
1583
18.1k
void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1584
18.1k
  assert(InitializedNonAbstract &&
1585
18.1k
         "finalizing emitter that was used for abstract emission?");
1586
0
  assert(!Finalized && "finalizing emitter multiple times");
1587
0
  assert(global->getInitializer());
1588
1589
  // Note that we might also be Failed.
1590
0
  Finalized = true;
1591
1592
18.1k
  if (!PlaceholderAddresses.empty()) {
1593
0
    ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1594
0
      .replaceInInitializer(global->getInitializer());
1595
0
    PlaceholderAddresses.clear(); // satisfy
1596
0
  }
1597
18.1k
}
1598
1599
56.2k
ConstantEmitter::~ConstantEmitter() {
1600
56.2k
  assert((!InitializedNonAbstract || Finalized || Failed) &&
1601
56.2k
         "not finalized after being initialized for non-abstract emission");
1602
0
  assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1603
56.2k
}
1604
1605
70.9k
static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1606
70.9k
  if (auto AT = type->getAs<AtomicType>()) {
1607
101
    return CGM.getContext().getQualifiedType(AT->getValueType(),
1608
101
                                             type.getQualifiers());
1609
101
  }
1610
70.8k
  return type;
1611
70.9k
}
1612
1613
47.9k
llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1614
  // Make a quick check if variable can be default NULL initialized
1615
  // and avoid going through rest of code which may do, for c++11,
1616
  // initialization of memory to all NULLs.
1617
47.9k
  if (!D.hasLocalStorage()) {
1618
27.9k
    QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1619
27.9k
    if (Ty->isRecordType())
1620
7.31k
      if (const CXXConstructExpr *E =
1621
7.31k
          dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1622
6.21k
        const CXXConstructorDecl *CD = E->getConstructor();
1623
6.21k
        if (CD->isTrivial() && 
CD->isDefaultConstructor()1.24k
)
1624
1.21k
          return CGM.EmitNullConstant(D.getType());
1625
6.21k
      }
1626
27.9k
  }
1627
46.7k
  InConstantContext = D.hasConstantInitialization();
1628
1629
46.7k
  QualType destType = D.getType();
1630
1631
  // Try to emit the initializer.  Note that this can allow some things that
1632
  // are not allowed by tryEmitPrivateForMemory alone.
1633
46.7k
  if (auto value = D.evaluateValue()) {
1634
14.0k
    return tryEmitPrivateForMemory(*value, destType);
1635
14.0k
  }
1636
1637
  // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1638
  // reference is a constant expression, and the reference binds to a temporary,
1639
  // then constant initialization is performed. ConstExprEmitter will
1640
  // incorrectly emit a prvalue constant in this case, and the calling code
1641
  // interprets that as the (pointer) value of the reference, rather than the
1642
  // desired value of the referee.
1643
32.7k
  if (destType->isReferenceType())
1644
3.44k
    return nullptr;
1645
1646
29.2k
  const Expr *E = D.getInit();
1647
29.2k
  assert(E && "No initializer to emit");
1648
1649
0
  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1650
29.2k
  auto C =
1651
29.2k
    ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1652
29.2k
  return (C ? 
emitForMemory(C, destType)2.30k
:
nullptr26.9k
);
1653
32.7k
}
1654
1655
llvm::Constant *
1656
159
ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1657
159
  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1658
159
  auto C = tryEmitAbstract(E, nonMemoryDestType);
1659
159
  return (C ? 
emitForMemory(C, destType)148
:
nullptr11
);
1660
159
}
1661
1662
llvm::Constant *
1663
ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1664
630
                                          QualType destType) {
1665
630
  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1666
630
  auto C = tryEmitAbstract(value, nonMemoryDestType);
1667
630
  return (C ? emitForMemory(C, destType) : 
nullptr0
);
1668
630
}
1669
1670
llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1671
11.2k
                                                         QualType destType) {
1672
11.2k
  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1673
11.2k
  llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1674
11.2k
  return (C ? 
emitForMemory(C, destType)10.8k
:
nullptr470
);
1675
11.2k
}
1676
1677
llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1678
29.6k
                                                         QualType destType) {
1679
29.6k
  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1680
29.6k
  auto C = tryEmitPrivate(value, nonMemoryDestType);
1681
29.6k
  return (C ? emitForMemory(C, destType) : 
nullptr0
);
1682
29.6k
}
1683
1684
llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1685
                                               llvm::Constant *C,
1686
43.6k
                                               QualType destType) {
1687
  // For an _Atomic-qualified constant, we may need to add tail padding.
1688
43.6k
  if (auto AT = destType->getAs<AtomicType>()) {
1689
97
    QualType destValueType = AT->getValueType();
1690
97
    C = emitForMemory(CGM, C, destValueType);
1691
1692
97
    uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1693
97
    uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1694
97
    if (innerSize == outerSize)
1695
96
      return C;
1696
1697
1
    assert(innerSize < outerSize && "emitted over-large constant for atomic");
1698
0
    llvm::Constant *elts[] = {
1699
1
      C,
1700
1
      llvm::ConstantAggregateZero::get(
1701
1
          llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1702
1
    };
1703
1
    return llvm::ConstantStruct::getAnon(elts);
1704
97
  }
1705
1706
  // Zero-extend bool.
1707
43.6k
  if (C->getType()->isIntegerTy(1)) {
1708
412
    llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1709
412
    return llvm::ConstantExpr::getZExt(C, boolTy);
1710
412
  }
1711
1712
43.1k
  return C;
1713
43.6k
}
1714
1715
llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1716
12.2k
                                                QualType destType) {
1717
12.2k
  Expr::EvalResult Result;
1718
1719
12.2k
  bool Success = false;
1720
1721
12.2k
  if (destType->isReferenceType())
1722
10
    Success = E->EvaluateAsLValue(Result, CGM.getContext());
1723
12.2k
  else
1724
12.2k
    Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1725
1726
12.2k
  llvm::Constant *C;
1727
12.2k
  if (Success && 
!Result.HasSideEffects10.5k
)
1728
10.5k
    C = tryEmitPrivate(Result.Val, destType);
1729
1.72k
  else
1730
1.72k
    C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1731
1732
12.2k
  return C;
1733
12.2k
}
1734
1735
35.7k
llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1736
35.7k
  return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1737
35.7k
}
1738
1739
namespace {
1740
/// A struct which can be used to peephole certain kinds of finalization
1741
/// that normally happen during l-value emission.
1742
struct ConstantLValue {
1743
  llvm::Constant *Value;
1744
  bool HasOffsetApplied;
1745
1746
  /*implicit*/ ConstantLValue(llvm::Constant *value,
1747
                              bool hasOffsetApplied = false)
1748
5.44k
    : Value(value), HasOffsetApplied(hasOffsetApplied) {}
1749
1750
  /*implicit*/ ConstantLValue(ConstantAddress address)
1751
2.05k
    : ConstantLValue(address.getPointer()) {}
1752
};
1753
1754
/// A helper class for emitting constant l-values.
1755
class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1756
                                                      ConstantLValue> {
1757
  CodeGenModule &CGM;
1758
  ConstantEmitter &Emitter;
1759
  const APValue &Value;
1760
  QualType DestType;
1761
1762
  // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1763
  friend StmtVisitorBase;
1764
1765
public:
1766
  ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1767
                        QualType destType)
1768
6.19k
    : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1769
1770
  llvm::Constant *tryEmit();
1771
1772
private:
1773
  llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1774
  ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1775
1776
0
  ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1777
  ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1778
  ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1779
  ConstantLValue VisitStringLiteral(const StringLiteral *E);
1780
  ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
1781
  ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1782
  ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1783
  ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1784
  ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1785
  ConstantLValue VisitCallExpr(const CallExpr *E);
1786
  ConstantLValue VisitBlockExpr(const BlockExpr *E);
1787
  ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1788
  ConstantLValue VisitMaterializeTemporaryExpr(
1789
                                         const MaterializeTemporaryExpr *E);
1790
1791
5.44k
  bool hasNonZeroOffset() const {
1792
5.44k
    return !Value.getLValueOffset().isZero();
1793
5.44k
  }
1794
1795
  /// Return the value offset.
1796
266
  llvm::Constant *getOffset() {
1797
266
    return llvm::ConstantInt::get(CGM.Int64Ty,
1798
266
                                  Value.getLValueOffset().getQuantity());
1799
266
  }
1800
1801
  /// Apply the value offset to the given constant.
1802
5.44k
  llvm::Constant *applyOffset(llvm::Constant *C) {
1803
5.44k
    if (!hasNonZeroOffset())
1804
5.39k
      return C;
1805
1806
56
    llvm::Type *origPtrTy = C->getType();
1807
56
    unsigned AS = origPtrTy->getPointerAddressSpace();
1808
56
    llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1809
56
    C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1810
56
    C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1811
56
    C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1812
56
    return C;
1813
5.44k
  }
1814
};
1815
1816
}
1817
1818
6.19k
llvm::Constant *ConstantLValueEmitter::tryEmit() {
1819
6.19k
  const APValue::LValueBase &base = Value.getLValueBase();
1820
1821
  // The destination type should be a pointer or reference
1822
  // type, but it might also be a cast thereof.
1823
  //
1824
  // FIXME: the chain of casts required should be reflected in the APValue.
1825
  // We need this in order to correctly handle things like a ptrtoint of a
1826
  // non-zero null pointer and addrspace casts that aren't trivially
1827
  // represented in LLVM IR.
1828
6.19k
  auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1829
6.19k
  assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1830
1831
  // If there's no base at all, this is a null or absolute pointer,
1832
  // possibly cast back to an integer type.
1833
6.19k
  if (!base) {
1834
741
    return tryEmitAbsolute(destTy);
1835
741
  }
1836
1837
  // Otherwise, try to emit the base.
1838
5.44k
  ConstantLValue result = tryEmitBase(base);
1839
1840
  // If that failed, we're done.
1841
5.44k
  llvm::Constant *value = result.Value;
1842
5.44k
  if (!value) 
return nullptr0
;
1843
1844
  // Apply the offset if necessary and not already done.
1845
5.44k
  if (!result.HasOffsetApplied) {
1846
5.44k
    value = applyOffset(value);
1847
5.44k
  }
1848
1849
  // Convert to the appropriate type; this could be an lvalue for
1850
  // an integer.  FIXME: performAddrSpaceCast
1851
5.44k
  if (isa<llvm::PointerType>(destTy))
1852
5.43k
    return llvm::ConstantExpr::getPointerCast(value, destTy);
1853
1854
19
  return llvm::ConstantExpr::getPtrToInt(value, destTy);
1855
5.44k
}
1856
1857
/// Try to emit an absolute l-value, such as a null pointer or an integer
1858
/// bitcast to pointer type.
1859
llvm::Constant *
1860
741
ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1861
  // If we're producing a pointer, this is easy.
1862
741
  auto destPtrTy = cast<llvm::PointerType>(destTy);
1863
741
  if (Value.isNullPointer()) {
1864
    // FIXME: integer offsets from non-zero null pointers.
1865
531
    return CGM.getNullPointer(destPtrTy, DestType);
1866
531
  }
1867
1868
  // Convert the integer to a pointer-sized integer before converting it
1869
  // to a pointer.
1870
  // FIXME: signedness depends on the original integer type.
1871
210
  auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1872
210
  llvm::Constant *C;
1873
210
  C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1874
210
                                         /*isSigned*/ false);
1875
210
  C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1876
210
  return C;
1877
741
}
1878
1879
ConstantLValue
1880
5.44k
ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1881
  // Handle values.
1882
5.44k
  if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1883
    // The constant always points to the canonical declaration. We want to look
1884
    // at properties of the most recent declaration at the point of emission.
1885
3.18k
    D = cast<ValueDecl>(D->getMostRecentDecl());
1886
1887
3.18k
    if (D->hasAttr<WeakRefAttr>())
1888
5
      return CGM.GetWeakRefReference(D).getPointer();
1889
1890
3.17k
    if (auto FD = dyn_cast<FunctionDecl>(D))
1891
2.34k
      return CGM.GetAddrOfFunction(FD);
1892
1893
831
    if (auto VD = dyn_cast<VarDecl>(D)) {
1894
      // We can never refer to a variable with local storage.
1895
791
      if (!VD->hasLocalStorage()) {
1896
791
        if (VD->isFileVarDecl() || 
VD->hasExternalStorage()16
)
1897
776
          return CGM.GetAddrOfGlobalVar(VD);
1898
1899
15
        if (VD->isLocalVarDecl()) {
1900
15
          return CGM.getOrCreateStaticVarDecl(
1901
15
              *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
1902
15
        }
1903
15
      }
1904
791
    }
1905
1906
40
    if (auto *GD = dyn_cast<MSGuidDecl>(D))
1907
36
      return CGM.GetAddrOfMSGuidDecl(GD);
1908
1909
4
    if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D))
1910
4
      return CGM.GetAddrOfTemplateParamObject(TPO);
1911
1912
0
    return nullptr;
1913
4
  }
1914
1915
  // Handle typeid(T).
1916
2.26k
  if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1917
142
    llvm::Type *StdTypeInfoPtrTy =
1918
142
        CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1919
142
    llvm::Constant *TypeInfo =
1920
142
        CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1921
142
    if (TypeInfo->getType() != StdTypeInfoPtrTy)
1922
142
      TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1923
142
    return TypeInfo;
1924
142
  }
1925
1926
  // Otherwise, it must be an expression.
1927
2.12k
  return Visit(base.get<const Expr*>());
1928
2.26k
}
1929
1930
ConstantLValue
1931
0
ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1932
0
  if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(E))
1933
0
    return Result;
1934
0
  return Visit(E->getSubExpr());
1935
0
}
1936
1937
ConstantLValue
1938
14
ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1939
14
  return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1940
14
}
1941
1942
ConstantLValue
1943
1.15k
ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1944
1.15k
  return CGM.GetAddrOfConstantStringFromLiteral(E);
1945
1.15k
}
1946
1947
ConstantLValue
1948
54
ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1949
54
  return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1950
54
}
1951
1952
static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1953
                                                    QualType T,
1954
292
                                                    CodeGenModule &CGM) {
1955
292
  auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1956
292
  return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1957
292
}
1958
1959
ConstantLValue
1960
289
ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1961
289
  return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1962
289
}
1963
1964
ConstantLValue
1965
3
ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1966
3
  assert(E->isExpressibleAsConstantInitializer() &&
1967
3
         "this boxed expression can't be emitted as a compile-time constant");
1968
0
  auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1969
3
  return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
1970
3
}
1971
1972
ConstantLValue
1973
3
ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1974
3
  return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
1975
3
}
1976
1977
ConstantLValue
1978
36
ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1979
36
  assert(Emitter.CGF && "Invalid address of label expression outside function");
1980
0
  llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1981
36
  Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1982
36
                                   CGM.getTypes().ConvertType(E->getType()));
1983
36
  return Ptr;
1984
36
}
1985
1986
ConstantLValue
1987
341
ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1988
341
  unsigned builtin = E->getBuiltinCallee();
1989
341
  if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1990
341
      
builtin != Builtin::BI__builtin___NSStringMakeConstantString0
)
1991
0
    return nullptr;
1992
1993
341
  auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1994
341
  if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1995
0
    return CGM.getObjCRuntime().GenerateConstantString(literal);
1996
341
  } else {
1997
    // FIXME: need to deal with UCN conversion issues.
1998
341
    return CGM.GetAddrOfConstantCFString(literal);
1999
341
  }
2000
341
}
2001
2002
ConstantLValue
2003
80
ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
2004
80
  StringRef functionName;
2005
80
  if (auto CGF = Emitter.CGF)
2006
38
    functionName = CGF->CurFn->getName();
2007
42
  else
2008
42
    functionName = "global";
2009
2010
80
  return CGM.GetAddrOfGlobalBlock(E, functionName);
2011
80
}
2012
2013
ConstantLValue
2014
0
ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2015
0
  QualType T;
2016
0
  if (E->isTypeOperand())
2017
0
    T = E->getTypeOperand(CGM.getContext());
2018
0
  else
2019
0
    T = E->getExprOperand()->getType();
2020
0
  return CGM.GetAddrOfRTTIDescriptor(T);
2021
0
}
2022
2023
ConstantLValue
2024
ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
2025
147
                                            const MaterializeTemporaryExpr *E) {
2026
147
  assert(E->getStorageDuration() == SD_Static);
2027
0
  SmallVector<const Expr *, 2> CommaLHSs;
2028
147
  SmallVector<SubobjectAdjustment, 2> Adjustments;
2029
147
  const Expr *Inner =
2030
147
      E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
2031
147
  return CGM.GetAddrOfGlobalTemporary(E, Inner);
2032
147
}
2033
2034
llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
2035
48.1k
                                                QualType DestType) {
2036
48.1k
  switch (Value.getKind()) {
2037
0
  case APValue::None:
2038
0
  case APValue::Indeterminate:
2039
    // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2040
0
    return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
2041
6.19k
  case APValue::LValue:
2042
6.19k
    return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
2043
30.5k
  case APValue::Int:
2044
30.5k
    return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
2045
344
  case APValue::FixedPoint:
2046
344
    return llvm::ConstantInt::get(CGM.getLLVMContext(),
2047
344
                                  Value.getFixedPoint().getValue());
2048
7
  case APValue::ComplexInt: {
2049
7
    llvm::Constant *Complex[2];
2050
2051
7
    Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2052
7
                                        Value.getComplexIntReal());
2053
7
    Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
2054
7
                                        Value.getComplexIntImag());
2055
2056
    // FIXME: the target may want to specify that this is packed.
2057
7
    llvm::StructType *STy =
2058
7
        llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2059
7
    return llvm::ConstantStruct::get(STy, Complex);
2060
0
  }
2061
2.81k
  case APValue::Float: {
2062
2.81k
    const llvm::APFloat &Init = Value.getFloat();
2063
2.81k
    if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
2064
2.81k
        
!CGM.getContext().getLangOpts().NativeHalfType87
&&
2065
2.81k
        
CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics()75
)
2066
1
      return llvm::ConstantInt::get(CGM.getLLVMContext(),
2067
1
                                    Init.bitcastToAPInt());
2068
2.81k
    else
2069
2.81k
      return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
2070
2.81k
  }
2071
40
  case APValue::ComplexFloat: {
2072
40
    llvm::Constant *Complex[2];
2073
2074
40
    Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2075
40
                                       Value.getComplexFloatReal());
2076
40
    Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
2077
40
                                       Value.getComplexFloatImag());
2078
2079
    // FIXME: the target may want to specify that this is packed.
2080
40
    llvm::StructType *STy =
2081
40
        llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
2082
40
    return llvm::ConstantStruct::get(STy, Complex);
2083
2.81k
  }
2084
1.37k
  case APValue::Vector: {
2085
1.37k
    unsigned NumElts = Value.getVectorLength();
2086
1.37k
    SmallVector<llvm::Constant *, 4> Inits(NumElts);
2087
2088
10.3k
    for (unsigned I = 0; I != NumElts; 
++I8.95k
) {
2089
8.95k
      const APValue &Elt = Value.getVectorElt(I);
2090
8.95k
      if (Elt.isInt())
2091
7.83k
        Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
2092
1.11k
      else if (Elt.isFloat())
2093
1.11k
        Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
2094
0
      else
2095
0
        llvm_unreachable("unsupported vector element type");
2096
8.95k
    }
2097
1.37k
    return llvm::ConstantVector::get(Inits);
2098
2.81k
  }
2099
5
  case APValue::AddrLabelDiff: {
2100
5
    const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2101
5
    const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
2102
5
    llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2103
5
    llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2104
5
    if (!LHS || !RHS) 
return nullptr0
;
2105
2106
    // Compute difference
2107
5
    llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2108
5
    LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2109
5
    RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
2110
5
    llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2111
2112
    // LLVM is a bit sensitive about the exact format of the
2113
    // address-of-label difference; make sure to truncate after
2114
    // the subtraction.
2115
5
    return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2116
5
  }
2117
2.98k
  case APValue::Struct:
2118
3.48k
  case APValue::Union:
2119
3.48k
    return ConstStructBuilder::BuildStruct(*this, Value, DestType);
2120
3.03k
  case APValue::Array: {
2121
3.03k
    const ArrayType *ArrayTy = CGM.getContext().getAsArrayType(DestType);
2122
3.03k
    unsigned NumElements = Value.getArraySize();
2123
3.03k
    unsigned NumInitElts = Value.getArrayInitializedElts();
2124
2125
    // Emit array filler, if there is one.
2126
3.03k
    llvm::Constant *Filler = nullptr;
2127
3.03k
    if (Value.hasArrayFiller()) {
2128
630
      Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2129
630
                                        ArrayTy->getElementType());
2130
630
      if (!Filler)
2131
0
        return nullptr;
2132
630
    }
2133
2134
    // Emit initializer elements.
2135
3.03k
    SmallVector<llvm::Constant*, 16> Elts;
2136
3.03k
    if (Filler && 
Filler->isNullValue()630
)
2137
622
      Elts.reserve(NumInitElts + 1);
2138
2.40k
    else
2139
2.40k
      Elts.reserve(NumElements);
2140
2141
3.03k
    llvm::Type *CommonElementType = nullptr;
2142
12.6k
    for (unsigned I = 0; I < NumInitElts; 
++I9.62k
) {
2143
9.62k
      llvm::Constant *C = tryEmitPrivateForMemory(
2144
9.62k
          Value.getArrayInitializedElt(I), ArrayTy->getElementType());
2145
9.62k
      if (!C) 
return nullptr0
;
2146
2147
9.62k
      if (I == 0)
2148
2.79k
        CommonElementType = C->getType();
2149
6.82k
      else if (C->getType() != CommonElementType)
2150
11
        CommonElementType = nullptr;
2151
9.62k
      Elts.push_back(C);
2152
9.62k
    }
2153
2154
3.03k
    llvm::ArrayType *Desired =
2155
3.03k
        cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2156
3.03k
    return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
2157
3.03k
                             Filler);
2158
3.03k
  }
2159
251
  case APValue::MemberPointer:
2160
251
    return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
2161
48.1k
  }
2162
0
  llvm_unreachable("Unknown APValue kind");
2163
0
}
2164
2165
llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2166
17
    const CompoundLiteralExpr *E) {
2167
17
  return EmittedCompoundLiterals.lookup(E);
2168
17
}
2169
2170
void CodeGenModule::setAddrOfConstantCompoundLiteral(
2171
15
    const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2172
15
  bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2173
15
  (void)Ok;
2174
15
  assert(Ok && "CLE has already been emitted!");
2175
15
}
2176
2177
ConstantAddress
2178
3
CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2179
3
  assert(E->isFileScope() && "not a file-scope compound literal expr");
2180
0
  return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
2181
3
}
2182
2183
llvm::Constant *
2184
607
CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2185
  // Member pointer constants always have a very particular form.
2186
607
  const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2187
607
  const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2188
2189
  // A member function pointer.
2190
607
  if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2191
552
    return getCXXABI().EmitMemberFunctionPointer(method);
2192
2193
  // Otherwise, a member data pointer.
2194
55
  uint64_t fieldOffset = getContext().getFieldOffset(decl);
2195
55
  CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2196
55
  return getCXXABI().EmitMemberDataPointer(type, chars);
2197
607
}
2198
2199
static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2200
                                               llvm::Type *baseType,
2201
                                               const CXXRecordDecl *base);
2202
2203
static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2204
                                        const RecordDecl *record,
2205
73
                                        bool asCompleteObject) {
2206
73
  const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2207
73
  llvm::StructType *structure =
2208
73
    (asCompleteObject ? 
layout.getLLVMType()45
2209
73
                      : 
layout.getBaseSubobjectLLVMType()28
);
2210
2211
73
  unsigned numElements = structure->getNumElements();
2212
73
  std::vector<llvm::Constant *> elements(numElements);
2213
2214
73
  auto CXXR = dyn_cast<CXXRecordDecl>(record);
2215
  // Fill in all the bases.
2216
73
  if (CXXR) {
2217
57
    for (const auto &I : CXXR->bases()) {
2218
26
      if (I.isVirtual()) {
2219
        // Ignore virtual bases; if we're laying out for a complete
2220
        // object, we'll lay these out later.
2221
17
        continue;
2222
17
      }
2223
2224
9
      const CXXRecordDecl *base =
2225
9
        cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2226
2227
      // Ignore empty bases.
2228
9
      if (base->isEmpty() ||
2229
9
          CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2230
9
              .isZero())
2231
1
        continue;
2232
2233
8
      unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2234
8
      llvm::Type *baseType = structure->getElementType(fieldIndex);
2235
8
      elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2236
8
    }
2237
57
  }
2238
2239
  // Fill in all the fields.
2240
144
  for (const auto *Field : record->fields()) {
2241
    // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2242
    // will fill in later.)
2243
144
    if (!Field->isBitField() && 
!Field->isZeroSize(CGM.getContext())142
) {
2244
142
      unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2245
142
      elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2246
142
    }
2247
2248
    // For unions, stop after the first named field.
2249
144
    if (record->isUnion()) {
2250
4
      if (Field->getIdentifier())
2251
3
        break;
2252
1
      if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2253
1
        if (FieldRD->findFirstNamedDataMember())
2254
1
          break;
2255
1
    }
2256
144
  }
2257
2258
  // Fill in the virtual bases, if we're working with the complete object.
2259
73
  if (CXXR && 
asCompleteObject57
) {
2260
29
    for (const auto &I : CXXR->vbases()) {
2261
5
      const CXXRecordDecl *base =
2262
5
        cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2263
2264
      // Ignore empty bases.
2265
5
      if (base->isEmpty())
2266
0
        continue;
2267
2268
5
      unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2269
2270
      // We might have already laid this field out.
2271
5
      if (elements[fieldIndex]) 
continue0
;
2272
2273
5
      llvm::Type *baseType = structure->getElementType(fieldIndex);
2274
5
      elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2275
5
    }
2276
29
  }
2277
2278
  // Now go through all other fields and zero them out.
2279
257
  for (unsigned i = 0; i != numElements; 
++i184
) {
2280
184
    if (!elements[i])
2281
29
      elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2282
184
  }
2283
2284
73
  return llvm::ConstantStruct::get(structure, elements);
2285
73
}
2286
2287
/// Emit the null constant for a base subobject.
2288
static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2289
                                               llvm::Type *baseType,
2290
13
                                               const CXXRecordDecl *base) {
2291
13
  const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2292
2293
  // Just zero out bases that don't have any pointer to data members.
2294
13
  if (baseLayout.isZeroInitializableAsBase())
2295
4
    return llvm::Constant::getNullValue(baseType);
2296
2297
  // Otherwise, we can just use its null constant.
2298
9
  return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2299
13
}
2300
2301
llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2302
57
                                                   QualType T) {
2303
57
  return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2304
57
}
2305
2306
39.4k
llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2307
39.4k
  if (T->getAs<PointerType>())
2308
10.1k
    return getNullPointer(
2309
10.1k
        cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2310
2311
29.2k
  if (getTypes().isZeroInitializable(T))
2312
29.1k
    return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2313
2314
147
  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2315
11
    llvm::ArrayType *ATy =
2316
11
      cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2317
2318
11
    QualType ElementTy = CAT->getElementType();
2319
2320
11
    llvm::Constant *Element =
2321
11
      ConstantEmitter::emitNullForMemory(*this, ElementTy);
2322
11
    unsigned NumElements = CAT->getSize().getZExtValue();
2323
11
    SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2324
11
    return llvm::ConstantArray::get(ATy, Array);
2325
11
  }
2326
2327
136
  if (const RecordType *RT = T->getAs<RecordType>())
2328
45
    return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2329
2330
91
  assert(T->isMemberDataPointerType() &&
2331
91
         "Should only see pointers to data members here!");
2332
2333
0
  return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2334
136
}
2335
2336
llvm::Constant *
2337
19
CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2338
19
  return ::EmitNullConstant(*this, Record, false);
2339
19
}