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

source code of clang/lib/CodeGen/CGExprConstant.cpp