blob: e94fc67a4cb4aa68129c839931ead4405d076d72 [file] [log] [blame]
Anders Carlsson610ee712008-01-26 01:36:00 +00001//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Anders Carlsson610ee712008-01-26 01:36:00 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Constant Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000014#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000015#include "CGObjCRuntime.h"
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000016#include "CGRecordLayout.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000018#include "ConstantEmitter.h"
Yaxun Liu402804b2016-12-15 08:09:08 +000019#include "TargetInfo.h"
Chris Lattnere50e9012008-10-06 05:59:01 +000020#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Anders Carlssone1d5ca52009-07-24 15:20:52 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000024#include "clang/Basic/Builtins.h"
Richard Smith5745feb2019-06-17 21:08:30 +000025#include "llvm/ADT/Sequence.h"
26#include "llvm/ADT/STLExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalVariable.h"
Anders Carlsson610ee712008-01-26 01:36:00 +000031using namespace clang;
32using namespace CodeGen;
33
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000034//===----------------------------------------------------------------------===//
Richard Smith5745feb2019-06-17 21:08:30 +000035// ConstantAggregateBuilder
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000036//===----------------------------------------------------------------------===//
37
38namespace {
Yunzhong Gaocb779302015-06-10 00:27:52 +000039class ConstExprEmitter;
Richard Smith5745feb2019-06-17 21:08:30 +000040
41struct ConstantAggregateBuilderUtils {
Anders Carlssone1d5ca52009-07-24 15:20:52 +000042 CodeGenModule &CGM;
Anders Carlssone1d5ca52009-07-24 15:20:52 +000043
Richard Smith5745feb2019-06-17 21:08:30 +000044 ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
Mike Stump11289f42009-09-09 15:08:12 +000045
Ken Dycka1b35102011-03-18 01:26:17 +000046 CharUnits getAlignment(const llvm::Constant *C) const {
Ken Dycka1b35102011-03-18 01:26:17 +000047 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000048 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000049 }
Mike Stump11289f42009-09-09 15:08:12 +000050
Richard Smith5745feb2019-06-17 21:08:30 +000051 CharUnits getSize(llvm::Type *Ty) const {
52 return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
53 }
54
55 CharUnits getSize(const llvm::Constant *C) const {
56 return getSize(C->getType());
57 }
58
59 llvm::Constant *getPadding(CharUnits PadSize) const {
60 llvm::Type *Ty = CGM.Int8Ty;
61 if (PadSize > CharUnits::One())
62 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
63 return llvm::UndefValue::get(Ty);
64 }
65
66 llvm::Constant *getZeroes(CharUnits ZeroSize) const {
67 llvm::Type *Ty = llvm::ArrayType::get(CGM.Int8Ty, ZeroSize.getQuantity());
68 return llvm::ConstantAggregateZero::get(Ty);
Anders Carlssone1d5ca52009-07-24 15:20:52 +000069 }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000070};
Mike Stump11289f42009-09-09 15:08:12 +000071
Richard Smith5745feb2019-06-17 21:08:30 +000072/// Incremental builder for an llvm::Constant* holding a struct or array
73/// constant.
74class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
75 /// The elements of the constant. These two arrays must have the same size;
76 /// Offsets[i] describes the offset of Elems[i] within the constant. The
77 /// elements are kept in increasing offset order, and we ensure that there
78 /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
79 ///
80 /// This may contain explicit padding elements (in order to create a
81 /// natural layout), but need not. Gaps between elements are implicitly
82 /// considered to be filled with undef.
83 llvm::SmallVector<llvm::Constant*, 32> Elems;
84 llvm::SmallVector<CharUnits, 32> Offsets;
85
86 /// The size of the constant (the maximum end offset of any added element).
87 /// May be larger than the end of Elems.back() if we split the last element
88 /// and removed some trailing undefs.
89 CharUnits Size = CharUnits::Zero();
90
91 /// This is true only if laying out Elems in order as the elements of a
92 /// non-packed LLVM struct will give the correct layout.
93 bool NaturalLayout = true;
94
95 bool split(size_t Index, CharUnits Hint);
96 Optional<size_t> splitAt(CharUnits Pos);
97
98 static llvm::Constant *buildFrom(CodeGenModule &CGM,
99 ArrayRef<llvm::Constant *> Elems,
100 ArrayRef<CharUnits> Offsets,
101 CharUnits StartOffset, CharUnits Size,
102 bool NaturalLayout, llvm::Type *DesiredTy,
103 bool AllowOversized);
104
105public:
106 ConstantAggregateBuilder(CodeGenModule &CGM)
107 : ConstantAggregateBuilderUtils(CGM) {}
108
109 /// Update or overwrite the value starting at \p Offset with \c C.
110 ///
111 /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
112 /// a constant that has already been added. This flag is only used to
113 /// detect bugs.
114 bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
115
116 /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
117 bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
118
119 /// Attempt to condense the value starting at \p Offset to a constant of type
120 /// \p DesiredTy.
121 void condense(CharUnits Offset, llvm::Type *DesiredTy);
122
123 /// Produce a constant representing the entire accumulated value, ideally of
124 /// the specified type. If \p AllowOversized, the constant might be larger
125 /// than implied by \p DesiredTy (eg, if there is a flexible array member).
126 /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
127 /// even if we can't represent it as that type.
128 llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
129 return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
130 NaturalLayout, DesiredTy, AllowOversized);
131 }
132};
133
134template<typename Container, typename Range = std::initializer_list<
135 typename Container::value_type>>
136static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
137 assert(BeginOff <= EndOff && "invalid replacement range");
138 llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
139}
140
141bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
142 bool AllowOverwrite) {
143 // Common case: appending to a layout.
144 if (Offset >= Size) {
145 CharUnits Align = getAlignment(C);
146 CharUnits AlignedSize = Size.alignTo(Align);
147 if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
148 NaturalLayout = false;
149 else if (AlignedSize < Offset) {
150 Elems.push_back(getPadding(Offset - Size));
151 Offsets.push_back(Size);
152 }
153 Elems.push_back(C);
154 Offsets.push_back(Offset);
155 Size = Offset + getSize(C);
156 return true;
157 }
158
159 // Uncommon case: constant overlaps what we've already created.
160 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
161 if (!FirstElemToReplace)
162 return false;
163
164 CharUnits CSize = getSize(C);
165 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
166 if (!LastElemToReplace)
167 return false;
168
169 assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
170 "unexpectedly overwriting field");
171
172 replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
173 replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
174 Size = std::max(Size, Offset + CSize);
175 NaturalLayout = false;
176 return true;
177}
178
179bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
180 bool AllowOverwrite) {
181 const ASTContext &Context = CGM.getContext();
182 const uint64_t CharWidth = CGM.getContext().getCharWidth();
183
184 // Offset of where we want the first bit to go within the bits of the
185 // current char.
186 unsigned OffsetWithinChar = OffsetInBits % CharWidth;
187
188 // We split bit-fields up into individual bytes. Walk over the bytes and
189 // update them.
190 for (CharUnits OffsetInChars = Context.toCharUnitsFromBits(OffsetInBits);
191 /**/; ++OffsetInChars) {
192 // Number of bits we want to fill in this char.
193 unsigned WantedBits =
194 std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
195
196 // Get a char containing the bits we want in the right places. The other
197 // bits have unspecified values.
198 llvm::APInt BitsThisChar = Bits;
199 if (BitsThisChar.getBitWidth() < CharWidth)
200 BitsThisChar = BitsThisChar.zext(CharWidth);
201 if (CGM.getDataLayout().isBigEndian()) {
202 // Figure out how much to shift by. We may need to left-shift if we have
203 // less than one byte of Bits left.
204 int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
205 if (Shift > 0)
206 BitsThisChar.lshrInPlace(Shift);
207 else if (Shift < 0)
208 BitsThisChar = BitsThisChar.shl(-Shift);
209 } else {
210 BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
211 }
212 if (BitsThisChar.getBitWidth() > CharWidth)
213 BitsThisChar = BitsThisChar.trunc(CharWidth);
214
215 if (WantedBits == CharWidth) {
216 // Got a full byte: just add it directly.
217 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
218 OffsetInChars, AllowOverwrite);
219 } else {
220 // Partial byte: update the existing integer if there is one. If we
221 // can't split out a 1-CharUnit range to update, then we can't add
222 // these bits and fail the entire constant emission.
223 llvm::Optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
224 if (!FirstElemToUpdate)
225 return false;
226 llvm::Optional<size_t> LastElemToUpdate =
227 splitAt(OffsetInChars + CharUnits::One());
228 if (!LastElemToUpdate)
229 return false;
230 assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
231 "should have at most one element covering one byte");
232
233 // Figure out which bits we want and discard the rest.
234 llvm::APInt UpdateMask(CharWidth, 0);
235 if (CGM.getDataLayout().isBigEndian())
236 UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
237 CharWidth - OffsetWithinChar);
238 else
239 UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
240 BitsThisChar &= UpdateMask;
241
242 if (*FirstElemToUpdate == *LastElemToUpdate ||
243 Elems[*FirstElemToUpdate]->isNullValue() ||
244 isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
245 // All existing bits are either zero or undef.
246 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
247 OffsetInChars, /*AllowOverwrite*/ true);
248 } else {
249 llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
250 // In order to perform a partial update, we need the existing bitwise
251 // value, which we can only extract for a constant int.
252 auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
253 if (!CI)
254 return false;
255 // Because this is a 1-CharUnit range, the constant occupying it must
256 // be exactly one CharUnit wide.
257 assert(CI->getBitWidth() == CharWidth && "splitAt failed");
258 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
259 "unexpectedly overwriting bitfield");
260 BitsThisChar |= (CI->getValue() & ~UpdateMask);
261 ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
262 }
263 }
264
265 // Stop if we've added all the bits.
266 if (WantedBits == Bits.getBitWidth())
267 break;
268
269 // Remove the consumed bits from Bits.
270 if (!CGM.getDataLayout().isBigEndian())
271 Bits.lshrInPlace(WantedBits);
272 Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
273
274 // The remanining bits go at the start of the following bytes.
275 OffsetWithinChar = 0;
276 }
277
278 return true;
279}
280
281/// Returns a position within Elems and Offsets such that all elements
282/// before the returned index end before Pos and all elements at or after
283/// the returned index begin at or after Pos. Splits elements as necessary
284/// to ensure this. Returns None if we find something we can't split.
285Optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
286 if (Pos >= Size)
287 return Offsets.size();
288
289 while (true) {
290 auto FirstAfterPos = std::upper_bound(Offsets.begin(), Offsets.end(), Pos);
291 if (FirstAfterPos == Offsets.begin())
292 return 0;
293
294 // If we already have an element starting at Pos, we're done.
295 size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
296 if (Offsets[LastAtOrBeforePosIndex] == Pos)
297 return LastAtOrBeforePosIndex;
298
299 // We found an element starting before Pos. Check for overlap.
300 if (Offsets[LastAtOrBeforePosIndex] +
301 getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
302 return LastAtOrBeforePosIndex + 1;
303
304 // Try to decompose it into smaller constants.
305 if (!split(LastAtOrBeforePosIndex, Pos))
306 return None;
307 }
308}
309
310/// Split the constant at index Index, if possible. Return true if we did.
311/// Hint indicates the location at which we'd like to split, but may be
312/// ignored.
313bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
314 NaturalLayout = false;
315 llvm::Constant *C = Elems[Index];
316 CharUnits Offset = Offsets[Index];
317
318 if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
319 replace(Elems, Index, Index + 1,
320 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
321 [&](unsigned Op) { return CA->getOperand(Op); }));
322 if (auto *Seq = dyn_cast<llvm::SequentialType>(CA->getType())) {
323 // Array or vector.
324 CharUnits ElemSize = getSize(Seq->getElementType());
325 replace(
326 Offsets, Index, Index + 1,
327 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
328 [&](unsigned Op) { return Offset + Op * ElemSize; }));
329 } else {
330 // Must be a struct.
331 auto *ST = cast<llvm::StructType>(CA->getType());
332 const llvm::StructLayout *Layout =
333 CGM.getDataLayout().getStructLayout(ST);
334 replace(Offsets, Index, Index + 1,
335 llvm::map_range(
336 llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
337 return Offset + CharUnits::fromQuantity(
338 Layout->getElementOffset(Op));
339 }));
340 }
341 return true;
342 }
343
344 if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
345 // FIXME: If possible, split into two ConstantDataSequentials at Hint.
346 CharUnits ElemSize = getSize(CDS->getElementType());
347 replace(Elems, Index, Index + 1,
348 llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
349 [&](unsigned Elem) {
350 return CDS->getElementAsConstant(Elem);
351 }));
352 replace(Offsets, Index, Index + 1,
353 llvm::map_range(
354 llvm::seq(0u, CDS->getNumElements()),
355 [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
356 return true;
357 }
358
Mikael Holmen5136ea42019-06-18 06:41:56 +0000359 if (isa<llvm::ConstantAggregateZero>(C)) {
Richard Smith5745feb2019-06-17 21:08:30 +0000360 CharUnits ElemSize = getSize(C);
361 assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
362 replace(Elems, Index, Index + 1,
363 {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
364 replace(Offsets, Index, Index + 1, {Offset, Hint});
365 return true;
366 }
367
368 if (isa<llvm::UndefValue>(C)) {
369 replace(Elems, Index, Index + 1, {});
370 replace(Offsets, Index, Index + 1, {});
371 return true;
372 }
373
374 // FIXME: We could split a ConstantInt if the need ever arose.
375 // We don't need to do this to handle bit-fields because we always eagerly
376 // split them into 1-byte chunks.
377
378 return false;
379}
380
381static llvm::Constant *
382EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
383 llvm::Type *CommonElementType, unsigned ArrayBound,
384 SmallVectorImpl<llvm::Constant *> &Elements,
385 llvm::Constant *Filler);
386
387llvm::Constant *ConstantAggregateBuilder::buildFrom(
388 CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
389 ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
390 bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
391 ConstantAggregateBuilderUtils Utils(CGM);
392
393 if (Elems.empty())
394 return llvm::UndefValue::get(DesiredTy);
395
396 auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
397
398 // If we want an array type, see if all the elements are the same type and
399 // appropriately spaced.
400 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
401 assert(!AllowOversized && "oversized array emission not supported");
402
403 bool CanEmitArray = true;
404 llvm::Type *CommonType = Elems[0]->getType();
405 llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
406 CharUnits ElemSize = Utils.getSize(ATy->getElementType());
407 SmallVector<llvm::Constant*, 32> ArrayElements;
408 for (size_t I = 0; I != Elems.size(); ++I) {
409 // Skip zeroes; we'll use a zero value as our array filler.
410 if (Elems[I]->isNullValue())
411 continue;
412
413 // All remaining elements must be the same type.
414 if (Elems[I]->getType() != CommonType ||
415 Offset(I) % ElemSize != 0) {
416 CanEmitArray = false;
417 break;
418 }
419 ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
420 ArrayElements.back() = Elems[I];
421 }
422
423 if (CanEmitArray) {
424 return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
425 ArrayElements, Filler);
426 }
427
428 // Can't emit as an array, carry on to emit as a struct.
429 }
430
431 CharUnits DesiredSize = Utils.getSize(DesiredTy);
432 CharUnits Align = CharUnits::One();
433 for (llvm::Constant *C : Elems)
434 Align = std::max(Align, Utils.getAlignment(C));
435 CharUnits AlignedSize = Size.alignTo(Align);
436
437 bool Packed = false;
438 ArrayRef<llvm::Constant*> UnpackedElems = Elems;
439 llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
440 if ((DesiredSize < AlignedSize && !AllowOversized) ||
441 DesiredSize.alignTo(Align) != DesiredSize) {
442 // The natural layout would be the wrong size; force use of a packed layout.
443 NaturalLayout = false;
444 Packed = true;
445 } else if (DesiredSize > AlignedSize) {
446 // The constant would be too small. Add padding to fix it.
447 UnpackedElemStorage.assign(Elems.begin(), Elems.end());
448 UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
449 UnpackedElems = UnpackedElemStorage;
450 }
451
452 // If we don't have a natural layout, insert padding as necessary.
453 // As we go, double-check to see if we can actually just emit Elems
454 // as a non-packed struct and do so opportunistically if possible.
455 llvm::SmallVector<llvm::Constant*, 32> PackedElems;
456 if (!NaturalLayout) {
457 CharUnits SizeSoFar = CharUnits::Zero();
458 for (size_t I = 0; I != Elems.size(); ++I) {
459 CharUnits Align = Utils.getAlignment(Elems[I]);
460 CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
461 CharUnits DesiredOffset = Offset(I);
462 assert(DesiredOffset >= SizeSoFar && "elements out of order");
463
464 if (DesiredOffset != NaturalOffset)
465 Packed = true;
466 if (DesiredOffset != SizeSoFar)
467 PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
468 PackedElems.push_back(Elems[I]);
469 SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
470 }
471 // If we're using the packed layout, pad it out to the desired size if
472 // necessary.
473 if (Packed) {
474 assert((SizeSoFar <= DesiredSize || AllowOversized) &&
475 "requested size is too small for contents");
476 if (SizeSoFar < DesiredSize)
477 PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
478 }
479 }
480
481 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
482 CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
483
484 // Pick the type to use. If the type is layout identical to the desired
485 // type then use it, otherwise use whatever the builder produced for us.
486 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
487 if (DesiredSTy->isLayoutIdentical(STy))
488 STy = DesiredSTy;
489 }
490
491 return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
492}
493
494void ConstantAggregateBuilder::condense(CharUnits Offset,
495 llvm::Type *DesiredTy) {
496 CharUnits Size = getSize(DesiredTy);
497
498 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
499 if (!FirstElemToReplace)
500 return;
501 size_t First = *FirstElemToReplace;
502
503 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size);
504 if (!LastElemToReplace)
505 return;
506 size_t Last = *LastElemToReplace;
507
508 size_t Length = Last - First;
509 if (Length == 0)
510 return;
511
512 if (Length == 1 && Offsets[First] == Offset &&
513 getSize(Elems[First]) == Size) {
514 // Re-wrap single element structs if necessary. Otherwise, leave any single
515 // element constant of the right size alone even if it has the wrong type.
516 auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
517 if (STy && STy->getNumElements() == 1 &&
518 STy->getElementType(0) == Elems[First]->getType())
519 Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
520 return;
521 }
522
523 llvm::Constant *Replacement = buildFrom(
524 CGM, makeArrayRef(Elems).slice(First, Length),
525 makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
526 /*known to have natural layout=*/false, DesiredTy, false);
527 replace(Elems, First, Last, {Replacement});
528 replace(Offsets, First, Last, {Offset});
529}
530
531//===----------------------------------------------------------------------===//
532// ConstStructBuilder
533//===----------------------------------------------------------------------===//
534
535class ConstStructBuilder {
536 CodeGenModule &CGM;
537 ConstantEmitter &Emitter;
538 ConstantAggregateBuilder &Builder;
539 CharUnits StartOffset;
540
541public:
542 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
543 InitListExpr *ILE, QualType StructTy);
544 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
545 const APValue &Value, QualType ValTy);
546 static bool UpdateStruct(ConstantEmitter &Emitter,
547 ConstantAggregateBuilder &Const, CharUnits Offset,
548 InitListExpr *Updater);
549
550private:
551 ConstStructBuilder(ConstantEmitter &Emitter,
552 ConstantAggregateBuilder &Builder, CharUnits StartOffset)
553 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
554 StartOffset(StartOffset) {}
555
556 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
557 llvm::Constant *InitExpr, bool AllowOverwrite = false);
558
559 bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
560 bool AllowOverwrite = false);
561
562 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
563 llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
564
565 bool Build(InitListExpr *ILE, bool AllowOverwrite);
566 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
567 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
568 llvm::Constant *Finalize(QualType Ty);
569};
570
571bool ConstStructBuilder::AppendField(
572 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
573 bool AllowOverwrite) {
Ken Dyck1c80fd12011-03-15 01:09:02 +0000574 const ASTContext &Context = CGM.getContext();
575
576 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000577
Richard Smith5745feb2019-06-17 21:08:30 +0000578 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
Richard Smithc8998922012-02-23 08:33:23 +0000579}
580
Richard Smith5745feb2019-06-17 21:08:30 +0000581bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
582 llvm::Constant *InitCst,
583 bool AllowOverwrite) {
584 return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000585}
586
Richard Smith5745feb2019-06-17 21:08:30 +0000587bool ConstStructBuilder::AppendBitField(
588 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
589 bool AllowOverwrite) {
590 uint64_t FieldSize = Field->getBitWidthValue(CGM.getContext());
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000591 llvm::APInt FieldValue = CI->getValue();
592
593 // Promote the size of FieldValue if necessary
594 // FIXME: This should never occur, but currently it can because initializer
595 // constants are cast to bool, and because clang is not enforcing bitfield
596 // width limits.
597 if (FieldSize > FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000598 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000599
600 // Truncate the size of FieldValue to the bit field size.
601 if (FieldSize < FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000602 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000603
Richard Smith5745feb2019-06-17 21:08:30 +0000604 return Builder.addBits(FieldValue,
605 CGM.getContext().toBits(StartOffset) + FieldOffset,
606 AllowOverwrite);
607}
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000608
Richard Smith5745feb2019-06-17 21:08:30 +0000609static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
610 ConstantAggregateBuilder &Const,
611 CharUnits Offset, QualType Type,
612 InitListExpr *Updater) {
613 if (Type->isRecordType())
614 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000615
Richard Smith5745feb2019-06-17 21:08:30 +0000616 auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
617 if (!CAT)
618 return false;
619 QualType ElemType = CAT->getElementType();
620 CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
621 llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000622
Richard Smith5745feb2019-06-17 21:08:30 +0000623 llvm::Constant *FillC = nullptr;
624 if (Expr *Filler = Updater->getArrayFiller()) {
625 if (!isa<NoInitExpr>(Filler)) {
626 FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
627 if (!FillC)
628 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000629 }
Richard Smith5745feb2019-06-17 21:08:30 +0000630 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000631
Richard Smith5745feb2019-06-17 21:08:30 +0000632 unsigned NumElementsToUpdate =
633 FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits();
634 for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
635 Expr *Init = nullptr;
636 if (I < Updater->getNumInits())
637 Init = Updater->getInit(I);
638
639 if (!Init && FillC) {
640 if (!Const.add(FillC, Offset, true))
641 return false;
642 } else if (!Init || isa<NoInitExpr>(Init)) {
643 continue;
644 } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
645 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
646 ChildILE))
647 return false;
648 // Attempt to reduce the array element to a single constant if necessary.
649 Const.condense(Offset, ElemTy);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000650 } else {
Richard Smith5745feb2019-06-17 21:08:30 +0000651 llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
652 if (!Const.add(Val, Offset, true))
653 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000654 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000655 }
656
Richard Smith5745feb2019-06-17 21:08:30 +0000657 return true;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000658}
659
Richard Smith5745feb2019-06-17 21:08:30 +0000660bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000661 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
662 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
663
Richard Smith5745feb2019-06-17 21:08:30 +0000664 unsigned FieldNo = -1;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000665 unsigned ElementNo = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000666
667 // Bail out if we have base classes. We could support these, but they only
668 // arise in C++1z where we will have already constant folded most interesting
669 // cases. FIXME: There are still a few more cases we can handle this way.
670 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
671 if (CXXRD->getNumBases())
672 return false;
673
Richard Smith5745feb2019-06-17 21:08:30 +0000674 for (FieldDecl *Field : RD->fields()) {
675 ++FieldNo;
676
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000677 // If this is a union, skip all the fields that aren't being initialized.
Richard Smith5745feb2019-06-17 21:08:30 +0000678 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000679 continue;
680
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000681 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedman2782dac2013-06-26 20:50:34 +0000682 if (Field->isUnnamedBitfield())
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000683 continue;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000684
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000685 // Get the initializer. A struct can include fields without initializers,
686 // we just use explicit null values for them.
Richard Smith5745feb2019-06-17 21:08:30 +0000687 Expr *Init = nullptr;
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000688 if (ElementNo < ILE->getNumInits())
Richard Smith5745feb2019-06-17 21:08:30 +0000689 Init = ILE->getInit(ElementNo++);
690 if (Init && isa<NoInitExpr>(Init))
691 continue;
Eli Friedman3ee10222010-07-17 23:55:01 +0000692
Richard Smith5745feb2019-06-17 21:08:30 +0000693 // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
694 // represents additional overwriting of our current constant value, and not
695 // a new constant to emit independently.
696 if (AllowOverwrite &&
697 (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
698 if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
699 CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
700 Layout.getFieldOffset(FieldNo));
701 if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
702 Field->getType(), SubILE))
703 return false;
704 // If we split apart the field's value, try to collapse it down to a
705 // single value now.
706 Builder.condense(StartOffset + Offset,
707 CGM.getTypes().ConvertTypeForMem(Field->getType()));
708 continue;
709 }
710 }
711
712 llvm::Constant *EltInit =
713 Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
714 : Emitter.emitNullForMemory(Field->getType());
Eli Friedman3ee10222010-07-17 23:55:01 +0000715 if (!EltInit)
716 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000717
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000718 if (!Field->isBitField()) {
719 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000720 if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
721 AllowOverwrite))
722 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000723 } else {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000724 // Otherwise we have a bitfield.
David Majnemer8062eb62015-03-14 22:24:38 +0000725 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
Richard Smith5745feb2019-06-17 21:08:30 +0000726 if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
727 AllowOverwrite))
728 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000729 } else {
730 // We are trying to initialize a bitfield with a non-trivial constant,
731 // this must require run-time code.
732 return false;
733 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000734 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000735 }
736
Richard Smithdafff942012-01-14 04:30:29 +0000737 return true;
738}
739
Richard Smithc8998922012-02-23 08:33:23 +0000740namespace {
741struct BaseInfo {
742 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
743 : Decl(Decl), Offset(Offset), Index(Index) {
744 }
745
746 const CXXRecordDecl *Decl;
747 CharUnits Offset;
748 unsigned Index;
749
750 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
751};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000752}
Richard Smithc8998922012-02-23 08:33:23 +0000753
John McCallde0fe072017-08-15 21:42:52 +0000754bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000755 bool IsPrimaryBase,
Richard Smithc8998922012-02-23 08:33:23 +0000756 const CXXRecordDecl *VTableClass,
757 CharUnits Offset) {
Richard Smithdafff942012-01-14 04:30:29 +0000758 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
759
Richard Smithc8998922012-02-23 08:33:23 +0000760 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
761 // Add a vtable pointer, if we need one and it hasn't already been added.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000762 if (CD->isDynamicClass() && !IsPrimaryBase) {
763 llvm::Constant *VTableAddressPoint =
764 CGM.getCXXABI().getVTableAddressPointForConstExpr(
765 BaseSubobject(CD, Offset), VTableClass);
Richard Smith5745feb2019-06-17 21:08:30 +0000766 if (!AppendBytes(Offset, VTableAddressPoint))
767 return false;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000768 }
Richard Smithc8998922012-02-23 08:33:23 +0000769
770 // Accumulate and sort bases, in order to visit them in address order, which
771 // may not be the same as declaration order.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000772 SmallVector<BaseInfo, 8> Bases;
Richard Smithc8998922012-02-23 08:33:23 +0000773 Bases.reserve(CD->getNumBases());
Richard Smithdafff942012-01-14 04:30:29 +0000774 unsigned BaseNo = 0;
Richard Smithc8998922012-02-23 08:33:23 +0000775 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
Richard Smithdafff942012-01-14 04:30:29 +0000776 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
Richard Smithc8998922012-02-23 08:33:23 +0000777 assert(!Base->isVirtual() && "should not have virtual bases here");
Richard Smithdafff942012-01-14 04:30:29 +0000778 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
779 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Richard Smithc8998922012-02-23 08:33:23 +0000780 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
781 }
Fangrui Song899d1392019-04-24 14:43:05 +0000782 llvm::stable_sort(Bases);
Richard Smithdafff942012-01-14 04:30:29 +0000783
Richard Smithc8998922012-02-23 08:33:23 +0000784 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
785 BaseInfo &Base = Bases[I];
Richard Smithdafff942012-01-14 04:30:29 +0000786
Richard Smithc8998922012-02-23 08:33:23 +0000787 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
788 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000789 VTableClass, Offset + Base.Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000790 }
791 }
792
793 unsigned FieldNo = 0;
Eli Friedmana154dd52012-03-30 03:55:31 +0000794 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000795
796 for (RecordDecl::field_iterator Field = RD->field_begin(),
797 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Richard Smithdafff942012-01-14 04:30:29 +0000798 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie275a55c2019-05-22 20:36:06 +0000799 if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
Richard Smithdafff942012-01-14 04:30:29 +0000800 continue;
801
802 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedman2782dac2013-06-26 20:50:34 +0000803 if (Field->isUnnamedBitfield())
Richard Smithdafff942012-01-14 04:30:29 +0000804 continue;
Richard Smithdafff942012-01-14 04:30:29 +0000805
806 // Emit the value of the initializer.
807 const APValue &FieldValue =
808 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
809 llvm::Constant *EltInit =
John McCallde0fe072017-08-15 21:42:52 +0000810 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
811 if (!EltInit)
812 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000813
814 if (!Field->isBitField()) {
815 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000816 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
817 EltInit))
818 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000819 } else {
820 // Otherwise we have a bitfield.
Richard Smith5745feb2019-06-17 21:08:30 +0000821 if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
822 cast<llvm::ConstantInt>(EltInit)))
823 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000824 }
825 }
John McCallde0fe072017-08-15 21:42:52 +0000826
827 return true;
Richard Smithdafff942012-01-14 04:30:29 +0000828}
829
Richard Smith5745feb2019-06-17 21:08:30 +0000830llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
831 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
832 llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
833 return Builder.build(ValTy, RD->hasFlexibleArrayMember());
Yunzhong Gaocb779302015-06-10 00:27:52 +0000834}
835
John McCallde0fe072017-08-15 21:42:52 +0000836llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
837 InitListExpr *ILE,
838 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000839 ConstantAggregateBuilder Const(Emitter.CGM);
840 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithdafff942012-01-14 04:30:29 +0000841
Richard Smith5745feb2019-06-17 21:08:30 +0000842 if (!Builder.Build(ILE, /*AllowOverwrite*/false))
Craig Topper8a13c412014-05-21 05:09:00 +0000843 return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +0000844
John McCallde0fe072017-08-15 21:42:52 +0000845 return Builder.Finalize(ValTy);
Richard Smithdafff942012-01-14 04:30:29 +0000846}
847
John McCallde0fe072017-08-15 21:42:52 +0000848llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +0000849 const APValue &Val,
850 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000851 ConstantAggregateBuilder Const(Emitter.CGM);
852 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithc8998922012-02-23 08:33:23 +0000853
854 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
855 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
John McCallde0fe072017-08-15 21:42:52 +0000856 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
857 return nullptr;
Richard Smithc8998922012-02-23 08:33:23 +0000858
Richard Smithdafff942012-01-14 04:30:29 +0000859 return Builder.Finalize(ValTy);
860}
861
Richard Smith5745feb2019-06-17 21:08:30 +0000862bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
863 ConstantAggregateBuilder &Const,
864 CharUnits Offset, InitListExpr *Updater) {
865 return ConstStructBuilder(Emitter, Const, Offset)
866 .Build(Updater, /*AllowOverwrite*/ true);
867}
Richard Smithdafff942012-01-14 04:30:29 +0000868
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000869//===----------------------------------------------------------------------===//
870// ConstExprEmitter
871//===----------------------------------------------------------------------===//
Richard Smithdd5bdd82012-01-17 21:42:19 +0000872
John McCallde0fe072017-08-15 21:42:52 +0000873static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
874 CodeGenFunction *CGF,
875 const CompoundLiteralExpr *E) {
876 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
877 if (llvm::GlobalVariable *Addr =
878 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
879 return ConstantAddress(Addr, Align);
880
Alexander Richardson6d989432017-10-15 18:48:14 +0000881 LangAS addressSpace = E->getType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000882
883 ConstantEmitter emitter(CGM, CGF);
884 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
885 addressSpace, E->getType());
886 if (!C) {
887 assert(!E->isFileScope() &&
888 "file-scope compound literal did not have constant initializer!");
889 return ConstantAddress::invalid();
890 }
891
892 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
893 CGM.isTypeConstant(E->getType(), true),
894 llvm::GlobalValue::InternalLinkage,
895 C, ".compoundliteral", nullptr,
896 llvm::GlobalVariable::NotThreadLocal,
897 CGM.getContext().getTargetAddressSpace(addressSpace));
898 emitter.finalize(GV);
899 GV->setAlignment(Align.getQuantity());
900 CGM.setAddrOfConstantCompoundLiteral(E, GV);
901 return ConstantAddress(GV, Align);
902}
903
Richard Smith3e268632018-05-23 23:41:38 +0000904static llvm::Constant *
Richard Smith5745feb2019-06-17 21:08:30 +0000905EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
Richard Smith3e268632018-05-23 23:41:38 +0000906 llvm::Type *CommonElementType, unsigned ArrayBound,
907 SmallVectorImpl<llvm::Constant *> &Elements,
908 llvm::Constant *Filler) {
909 // Figure out how long the initial prefix of non-zero elements is.
910 unsigned NonzeroLength = ArrayBound;
911 if (Elements.size() < NonzeroLength && Filler->isNullValue())
912 NonzeroLength = Elements.size();
913 if (NonzeroLength == Elements.size()) {
914 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
915 --NonzeroLength;
916 }
917
Richard Smith5745feb2019-06-17 21:08:30 +0000918 if (NonzeroLength == 0)
919 return llvm::ConstantAggregateZero::get(DesiredType);
Richard Smith3e268632018-05-23 23:41:38 +0000920
921 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
922 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
923 if (TrailingZeroes >= 8) {
924 assert(Elements.size() >= NonzeroLength &&
925 "missing initializer for non-zero element");
Richard Smith83497d92018-07-19 21:38:56 +0000926
927 // If all the elements had the same type up to the trailing zeroes, emit a
928 // struct of two arrays (the nonzero data and the zeroinitializer).
929 if (CommonElementType && NonzeroLength >= 8) {
930 llvm::Constant *Initial = llvm::ConstantArray::get(
Richard Smith4c656882018-07-19 23:24:41 +0000931 llvm::ArrayType::get(CommonElementType, NonzeroLength),
Richard Smith83497d92018-07-19 21:38:56 +0000932 makeArrayRef(Elements).take_front(NonzeroLength));
933 Elements.resize(2);
934 Elements[0] = Initial;
935 } else {
936 Elements.resize(NonzeroLength + 1);
937 }
938
Richard Smith3e268632018-05-23 23:41:38 +0000939 auto *FillerType =
Richard Smith5745feb2019-06-17 21:08:30 +0000940 CommonElementType ? CommonElementType : DesiredType->getElementType();
Richard Smith3e268632018-05-23 23:41:38 +0000941 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
942 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
943 CommonElementType = nullptr;
944 } else if (Elements.size() != ArrayBound) {
945 // Otherwise pad to the right size with the filler if necessary.
946 Elements.resize(ArrayBound, Filler);
947 if (Filler->getType() != CommonElementType)
948 CommonElementType = nullptr;
949 }
950
951 // If all elements have the same type, just emit an array constant.
952 if (CommonElementType)
953 return llvm::ConstantArray::get(
954 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
955
956 // We have mixed types. Use a packed struct.
957 llvm::SmallVector<llvm::Type *, 16> Types;
958 Types.reserve(Elements.size());
959 for (llvm::Constant *Elt : Elements)
960 Types.push_back(Elt->getType());
961 llvm::StructType *SType =
962 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
963 return llvm::ConstantStruct::get(SType, Elements);
964}
965
Eli Friedman7f98e3c2019-02-08 21:36:04 +0000966// This class only needs to handle arrays, structs and unions. Outside C++11
967// mode, we don't currently constant fold those types. All other types are
968// handled by constant folding.
969//
970// Constant folding is currently missing support for a few features supported
971// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000972class ConstExprEmitter :
John McCallde0fe072017-08-15 21:42:52 +0000973 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
Anders Carlsson610ee712008-01-26 01:36:00 +0000974 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +0000975 ConstantEmitter &Emitter;
Owen Anderson170229f2009-07-14 23:10:40 +0000976 llvm::LLVMContext &VMContext;
Anders Carlsson610ee712008-01-26 01:36:00 +0000977public:
John McCallde0fe072017-08-15 21:42:52 +0000978 ConstExprEmitter(ConstantEmitter &emitter)
979 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
Anders Carlsson610ee712008-01-26 01:36:00 +0000980 }
Mike Stump11289f42009-09-09 15:08:12 +0000981
Anders Carlsson610ee712008-01-26 01:36:00 +0000982 //===--------------------------------------------------------------------===//
983 // Visitor Methods
984 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000985
John McCallde0fe072017-08-15 21:42:52 +0000986 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
Craig Topper8a13c412014-05-21 05:09:00 +0000987 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +0000988 }
Mike Stump11289f42009-09-09 15:08:12 +0000989
Bill Wendling8003edc2018-11-09 00:41:36 +0000990 llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
991 return Visit(CE->getSubExpr(), T);
992 }
993
John McCallde0fe072017-08-15 21:42:52 +0000994 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
995 return Visit(PE->getSubExpr(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +0000996 }
Mike Stump11289f42009-09-09 15:08:12 +0000997
John McCall7c454bb2011-07-15 05:09:51 +0000998 llvm::Constant *
John McCallde0fe072017-08-15 21:42:52 +0000999 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
1000 QualType T) {
1001 return Visit(PE->getReplacement(), T);
John McCall7c454bb2011-07-15 05:09:51 +00001002 }
1003
John McCallde0fe072017-08-15 21:42:52 +00001004 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
1005 QualType T) {
1006 return Visit(GE->getResultExpr(), T);
Peter Collingbourne91147592011-04-15 00:35:48 +00001007 }
1008
John McCallde0fe072017-08-15 21:42:52 +00001009 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
1010 return Visit(CE->getChosenSubExpr(), T);
Eli Friedman4c27ac22013-07-16 22:40:53 +00001011 }
1012
John McCallde0fe072017-08-15 21:42:52 +00001013 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
1014 return Visit(E->getInitializer(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +00001015 }
John McCallf3a88602011-02-03 08:15:49 +00001016
John McCallde0fe072017-08-15 21:42:52 +00001017 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001018 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
John McCallde0fe072017-08-15 21:42:52 +00001019 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
John McCall2de87f62011-03-15 21:17:48 +00001020 Expr *subExpr = E->getSubExpr();
John McCall2de87f62011-03-15 21:17:48 +00001021
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001022 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00001023 case CK_ToUnion: {
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001024 // GCC cast to union extension
1025 assert(E->getType()->isUnionType() &&
1026 "Destination type is not union type!");
Mike Stump11289f42009-09-09 15:08:12 +00001027
John McCallde0fe072017-08-15 21:42:52 +00001028 auto field = E->getTargetUnionField();
1029
1030 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1031 if (!C) return nullptr;
1032
1033 auto destTy = ConvertType(destType);
1034 if (C->getType() == destTy) return C;
1035
Anders Carlssond65ab042009-07-31 21:38:39 +00001036 // Build a struct with the union sub-element as the first member,
John McCallde0fe072017-08-15 21:42:52 +00001037 // and padded to the appropriate size.
Bill Wendling99729582012-02-07 00:13:27 +00001038 SmallVector<llvm::Constant*, 2> Elts;
1039 SmallVector<llvm::Type*, 2> Types;
Anders Carlssond65ab042009-07-31 21:38:39 +00001040 Elts.push_back(C);
1041 Types.push_back(C->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00001042 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
John McCallde0fe072017-08-15 21:42:52 +00001043 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
Mike Stump11289f42009-09-09 15:08:12 +00001044
Anders Carlssond65ab042009-07-31 21:38:39 +00001045 assert(CurSize <= TotalSize && "Union size mismatch!");
1046 if (unsigned NumPadBytes = TotalSize - CurSize) {
Chris Lattnerece04092012-02-07 00:39:47 +00001047 llvm::Type *Ty = CGM.Int8Ty;
Anders Carlssond65ab042009-07-31 21:38:39 +00001048 if (NumPadBytes > 1)
1049 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001050
Nuno Lopes5863c992010-04-16 20:56:35 +00001051 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssond65ab042009-07-31 21:38:39 +00001052 Types.push_back(Ty);
1053 }
Mike Stump11289f42009-09-09 15:08:12 +00001054
John McCallde0fe072017-08-15 21:42:52 +00001055 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
Anders Carlssond65ab042009-07-31 21:38:39 +00001056 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes4d78cf02009-01-17 00:48:48 +00001057 }
Anders Carlsson9500ad12009-10-18 20:31:03 +00001058
John McCallde0fe072017-08-15 21:42:52 +00001059 case CK_AddressSpaceConversion: {
1060 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1061 if (!C) return nullptr;
Alexander Richardson6d989432017-10-15 18:48:14 +00001062 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1063 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +00001064 llvm::Type *destTy = ConvertType(E->getType());
1065 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1066 destAS, destTy);
1067 }
David Tweede1468322013-12-11 13:39:46 +00001068
John McCall2de87f62011-03-15 21:17:48 +00001069 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00001070 case CK_AtomicToNonAtomic:
1071 case CK_NonAtomicToAtomic:
John McCall2de87f62011-03-15 21:17:48 +00001072 case CK_NoOp:
Eli Friedman4c27ac22013-07-16 22:40:53 +00001073 case CK_ConstructorConversion:
John McCallde0fe072017-08-15 21:42:52 +00001074 return Visit(subExpr, destType);
Anders Carlsson9500ad12009-10-18 20:31:03 +00001075
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001076 case CK_IntToOCLSampler:
1077 llvm_unreachable("global sampler variables are not generated");
1078
John McCall2de87f62011-03-15 21:17:48 +00001079 case CK_Dependent: llvm_unreachable("saw dependent cast!");
1080
Eli Friedman34866c72012-08-31 00:14:07 +00001081 case CK_BuiltinFnToFnPtr:
1082 llvm_unreachable("builtin functions are handled elsewhere");
1083
John McCallc62bb392012-02-15 01:22:51 +00001084 case CK_ReinterpretMemberPointer:
1085 case CK_DerivedToBaseMemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00001086 case CK_BaseToDerivedMemberPointer: {
1087 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1088 if (!C) return nullptr;
John McCallc62bb392012-02-15 01:22:51 +00001089 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
John McCallde0fe072017-08-15 21:42:52 +00001090 }
John McCallc62bb392012-02-15 01:22:51 +00001091
John McCall2de87f62011-03-15 21:17:48 +00001092 // These will never be supported.
1093 case CK_ObjCObjectLValueCast:
John McCall2d637d22011-09-10 06:18:15 +00001094 case CK_ARCProduceObject:
1095 case CK_ARCConsumeObject:
1096 case CK_ARCReclaimReturnedObject:
1097 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00001098 case CK_CopyAndAutoreleaseBlockObject:
Craig Topper8a13c412014-05-21 05:09:00 +00001099 return nullptr;
John McCall2de87f62011-03-15 21:17:48 +00001100
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001101 // These don't need to be handled here because Evaluate knows how to
Richard Smithdd5bdd82012-01-17 21:42:19 +00001102 // evaluate them in the cases where they can be folded.
John McCallc62bb392012-02-15 01:22:51 +00001103 case CK_BitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001104 case CK_ToVoid:
1105 case CK_Dynamic:
1106 case CK_LValueBitCast:
1107 case CK_NullToMemberPointer:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001108 case CK_UserDefinedConversion:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001109 case CK_CPointerToObjCPointerCast:
1110 case CK_BlockPointerToObjCPointerCast:
1111 case CK_AnyPointerToBlockPointerCast:
John McCall2de87f62011-03-15 21:17:48 +00001112 case CK_ArrayToPointerDecay:
1113 case CK_FunctionToPointerDecay:
1114 case CK_BaseToDerived:
1115 case CK_DerivedToBase:
1116 case CK_UncheckedDerivedToBase:
1117 case CK_MemberPointerToBoolean:
1118 case CK_VectorSplat:
1119 case CK_FloatingRealToComplex:
1120 case CK_FloatingComplexToReal:
1121 case CK_FloatingComplexToBoolean:
1122 case CK_FloatingComplexCast:
1123 case CK_FloatingComplexToIntegralComplex:
1124 case CK_IntegralRealToComplex:
1125 case CK_IntegralComplexToReal:
1126 case CK_IntegralComplexToBoolean:
1127 case CK_IntegralComplexCast:
1128 case CK_IntegralComplexToFloatingComplex:
John McCall2de87f62011-03-15 21:17:48 +00001129 case CK_PointerToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001130 case CK_PointerToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001131 case CK_NullToPointer:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001132 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001133 case CK_BooleanToSignedIntegral:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001134 case CK_IntegralToPointer:
John McCall2de87f62011-03-15 21:17:48 +00001135 case CK_IntegralToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001136 case CK_IntegralToFloating:
John McCall2de87f62011-03-15 21:17:48 +00001137 case CK_FloatingToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001138 case CK_FloatingToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001139 case CK_FloatingCast:
Leonard Chan99bda372018-10-15 16:07:02 +00001140 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001141 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001142 case CK_FixedPointToIntegral:
1143 case CK_IntegralToFixedPoint:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001144 case CK_ZeroToOCLOpaqueType:
Craig Topper8a13c412014-05-21 05:09:00 +00001145 return nullptr;
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001146 }
Matt Beaumont-Gay145e2eb2011-03-17 00:46:34 +00001147 llvm_unreachable("Invalid CastKind");
Anders Carlsson610ee712008-01-26 01:36:00 +00001148 }
Devang Patela703a672008-02-05 02:39:50 +00001149
John McCallde0fe072017-08-15 21:42:52 +00001150 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
Richard Smith852c9db2013-04-20 22:23:05 +00001151 // No need for a DefaultInitExprScope: we don't handle 'this' in a
1152 // constant expression.
John McCallde0fe072017-08-15 21:42:52 +00001153 return Visit(DIE->getExpr(), T);
Richard Smith852c9db2013-04-20 22:23:05 +00001154 }
1155
John McCallde0fe072017-08-15 21:42:52 +00001156 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
Tim Shen4a05bb82016-06-21 20:29:17 +00001157 if (!E->cleanupsHaveSideEffects())
John McCallde0fe072017-08-15 21:42:52 +00001158 return Visit(E->getSubExpr(), T);
Tim Shen4a05bb82016-06-21 20:29:17 +00001159 return nullptr;
1160 }
1161
John McCallde0fe072017-08-15 21:42:52 +00001162 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
1163 QualType T) {
1164 return Visit(E->GetTemporaryExpr(), T);
Douglas Gregorfe314812011-06-21 17:03:29 +00001165 }
1166
John McCallde0fe072017-08-15 21:42:52 +00001167 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
Richard Smith3e268632018-05-23 23:41:38 +00001168 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
1169 assert(CAT && "can't emit array init for non-constant-bound array");
Richard Smith9ec1e482012-04-15 02:50:59 +00001170 unsigned NumInitElements = ILE->getNumInits();
Richard Smith3e268632018-05-23 23:41:38 +00001171 unsigned NumElements = CAT->getSize().getZExtValue();
Devang Patela703a672008-02-05 02:39:50 +00001172
Mike Stump11289f42009-09-09 15:08:12 +00001173 // Initialising an array requires us to automatically
Devang Patela703a672008-02-05 02:39:50 +00001174 // initialise any elements that have not been initialised explicitly
1175 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
1176
Richard Smith3e268632018-05-23 23:41:38 +00001177 QualType EltType = CAT->getElementType();
John McCallde0fe072017-08-15 21:42:52 +00001178
David Majnemer90d85442014-12-28 23:46:59 +00001179 // Initialize remaining array elements.
Richard Smith3e268632018-05-23 23:41:38 +00001180 llvm::Constant *fillC = nullptr;
1181 if (Expr *filler = ILE->getArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00001182 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
Richard Smith3e268632018-05-23 23:41:38 +00001183 if (!fillC)
1184 return nullptr;
1185 }
David Majnemer90d85442014-12-28 23:46:59 +00001186
Devang Patela703a672008-02-05 02:39:50 +00001187 // Copy initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00001188 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00001189 if (fillC && fillC->isNullValue())
1190 Elts.reserve(NumInitableElts + 1);
1191 else
1192 Elts.reserve(NumElements);
Benjamin Kramer8001f742012-02-14 12:06:21 +00001193
Richard Smith3e268632018-05-23 23:41:38 +00001194 llvm::Type *CommonElementType = nullptr;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001195 for (unsigned i = 0; i < NumInitableElts; ++i) {
Anders Carlsson80f97ab2009-04-08 04:48:15 +00001196 Expr *Init = ILE->getInit(i);
John McCallde0fe072017-08-15 21:42:52 +00001197 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
Daniel Dunbar38ad1e62009-02-17 18:43:32 +00001198 if (!C)
Craig Topper8a13c412014-05-21 05:09:00 +00001199 return nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00001200 if (i == 0)
1201 CommonElementType = C->getType();
1202 else if (C->getType() != CommonElementType)
1203 CommonElementType = nullptr;
Devang Patela703a672008-02-05 02:39:50 +00001204 Elts.push_back(C);
1205 }
Eli Friedman34994cb2008-05-30 19:58:50 +00001206
Richard Smith5745feb2019-06-17 21:08:30 +00001207 llvm::ArrayType *Desired =
1208 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
1209 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00001210 fillC);
Devang Patela703a672008-02-05 02:39:50 +00001211 }
1212
John McCallde0fe072017-08-15 21:42:52 +00001213 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
1214 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001215 }
1216
John McCallde0fe072017-08-15 21:42:52 +00001217 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
1218 QualType T) {
1219 return CGM.EmitNullConstant(T);
Anders Carlsson02714ed2009-01-30 06:13:25 +00001220 }
Mike Stump11289f42009-09-09 15:08:12 +00001221
John McCallde0fe072017-08-15 21:42:52 +00001222 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
Richard Smith122f88d2016-12-06 23:52:28 +00001223 if (ILE->isTransparent())
John McCallde0fe072017-08-15 21:42:52 +00001224 return Visit(ILE->getInit(0), T);
Richard Smith122f88d2016-12-06 23:52:28 +00001225
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001226 if (ILE->getType()->isArrayType())
John McCallde0fe072017-08-15 21:42:52 +00001227 return EmitArrayInitialization(ILE, T);
Devang Patel45a65d22008-01-29 23:23:18 +00001228
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001229 if (ILE->getType()->isRecordType())
John McCallde0fe072017-08-15 21:42:52 +00001230 return EmitRecordInitialization(ILE, T);
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001231
Craig Topper8a13c412014-05-21 05:09:00 +00001232 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +00001233 }
Eli Friedmana2433112008-02-21 17:57:49 +00001234
John McCallde0fe072017-08-15 21:42:52 +00001235 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1236 QualType destType) {
1237 auto C = Visit(E->getBase(), destType);
Richard Smith5745feb2019-06-17 21:08:30 +00001238 if (!C)
1239 return nullptr;
1240
1241 ConstantAggregateBuilder Const(CGM);
1242 Const.add(C, CharUnits::Zero(), false);
1243
1244 if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
1245 E->getUpdater()))
1246 return nullptr;
1247
1248 llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
1249 bool HasFlexibleArray = false;
1250 if (auto *RT = destType->getAs<RecordType>())
1251 HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1252 return Const.build(ValTy, HasFlexibleArray);
Fangrui Song6907ce22018-07-30 19:24:48 +00001253 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00001254
John McCallde0fe072017-08-15 21:42:52 +00001255 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
John McCall49786a62010-02-02 08:02:49 +00001256 if (!E->getConstructor()->isTrivial())
Craig Topper8a13c412014-05-21 05:09:00 +00001257 return nullptr;
John McCall49786a62010-02-02 08:02:49 +00001258
Anders Carlssoncb86e102010-02-05 18:38:45 +00001259 // FIXME: We should not have to call getBaseElementType here.
Fangrui Song6907ce22018-07-30 19:24:48 +00001260 const RecordType *RT =
Anders Carlssoncb86e102010-02-05 18:38:45 +00001261 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1262 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00001263
Anders Carlssoncb86e102010-02-05 18:38:45 +00001264 // If the class doesn't have a trivial destructor, we can't emit it as a
1265 // constant expr.
1266 if (!RD->hasTrivialDestructor())
Craig Topper8a13c412014-05-21 05:09:00 +00001267 return nullptr;
1268
John McCall49786a62010-02-02 08:02:49 +00001269 // Only copy and default constructors can be trivial.
1270
John McCall49786a62010-02-02 08:02:49 +00001271
1272 if (E->getNumArgs()) {
1273 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001274 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1275 "trivial ctor has argument but isn't a copy/move ctor");
John McCall49786a62010-02-02 08:02:49 +00001276
1277 Expr *Arg = E->getArg(0);
1278 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1279 "argument to copy ctor is of wrong type");
1280
John McCallde0fe072017-08-15 21:42:52 +00001281 return Visit(Arg, Ty);
John McCall49786a62010-02-02 08:02:49 +00001282 }
1283
1284 return CGM.EmitNullConstant(Ty);
1285 }
1286
John McCallde0fe072017-08-15 21:42:52 +00001287 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001288 // This is a string literal initializing an array in an initializer.
Eli Friedmanfcec6302011-11-01 02:23:42 +00001289 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson610ee712008-01-26 01:36:00 +00001290 }
1291
John McCallde0fe072017-08-15 21:42:52 +00001292 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001293 // This must be an @encode initializing an array in a static initializer.
1294 // Don't emit it as the address of the string, emit the string data itself
1295 // as an inline array.
1296 std::string Str;
1297 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
John McCallde0fe072017-08-15 21:42:52 +00001298 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00001299
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001300 // Resize the string to the right size, adding zeros at the end, or
1301 // truncating as needed.
1302 Str.resize(CAT->getSize().getZExtValue(), '\0');
Chris Lattner9c818332012-02-05 02:30:40 +00001303 return llvm::ConstantDataArray::getString(VMContext, Str, false);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001304 }
Mike Stump11289f42009-09-09 15:08:12 +00001305
John McCallde0fe072017-08-15 21:42:52 +00001306 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1307 return Visit(E->getSubExpr(), T);
Eli Friedman045bf4f2008-05-29 11:22:45 +00001308 }
Mike Stumpa6703322009-02-19 22:01:56 +00001309
Anders Carlsson610ee712008-01-26 01:36:00 +00001310 // Utility methods
Chris Lattner2192fe52011-07-18 04:24:23 +00001311 llvm::Type *ConvertType(QualType T) {
Anders Carlsson610ee712008-01-26 01:36:00 +00001312 return CGM.getTypes().ConvertType(T);
1313 }
Anders Carlssona4139112008-01-26 02:08:50 +00001314};
Mike Stump11289f42009-09-09 15:08:12 +00001315
Anders Carlsson610ee712008-01-26 01:36:00 +00001316} // end anonymous namespace.
1317
John McCallde0fe072017-08-15 21:42:52 +00001318llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1319 AbstractState saved) {
1320 Abstract = saved.OldValue;
1321
1322 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1323 "created a placeholder while doing an abstract emission?");
1324
1325 // No validation necessary for now.
1326 // No cleanup to do for now.
1327 return C;
1328}
1329
1330llvm::Constant *
1331ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1332 auto state = pushAbstract();
1333 auto C = tryEmitPrivateForVarInit(D);
1334 return validateAndPopAbstract(C, state);
1335}
1336
1337llvm::Constant *
1338ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1339 auto state = pushAbstract();
1340 auto C = tryEmitPrivate(E, destType);
1341 return validateAndPopAbstract(C, state);
1342}
1343
1344llvm::Constant *
1345ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1346 auto state = pushAbstract();
1347 auto C = tryEmitPrivate(value, destType);
1348 return validateAndPopAbstract(C, state);
1349}
1350
1351llvm::Constant *
1352ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1353 auto state = pushAbstract();
1354 auto C = tryEmitPrivate(E, destType);
1355 C = validateAndPopAbstract(C, state);
1356 if (!C) {
1357 CGM.Error(E->getExprLoc(),
1358 "internal error: could not emit constant value \"abstractly\"");
1359 C = CGM.EmitNullConstant(destType);
1360 }
1361 return C;
1362}
1363
1364llvm::Constant *
1365ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1366 QualType destType) {
1367 auto state = pushAbstract();
1368 auto C = tryEmitPrivate(value, destType);
1369 C = validateAndPopAbstract(C, state);
1370 if (!C) {
1371 CGM.Error(loc,
1372 "internal error: could not emit constant value \"abstractly\"");
1373 C = CGM.EmitNullConstant(destType);
1374 }
1375 return C;
1376}
1377
1378llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1379 initializeNonAbstract(D.getType().getAddressSpace());
1380 return markIfFailed(tryEmitPrivateForVarInit(D));
1381}
1382
1383llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
Alexander Richardson6d989432017-10-15 18:48:14 +00001384 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001385 QualType destType) {
1386 initializeNonAbstract(destAddrSpace);
1387 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1388}
1389
1390llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
Alexander Richardson6d989432017-10-15 18:48:14 +00001391 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001392 QualType destType) {
1393 initializeNonAbstract(destAddrSpace);
1394 auto C = tryEmitPrivateForMemory(value, destType);
1395 assert(C && "couldn't emit constant value non-abstractly?");
1396 return C;
1397}
1398
1399llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1400 assert(!Abstract && "cannot get current address for abstract constant");
1401
1402
1403
1404 // Make an obviously ill-formed global that should blow up compilation
1405 // if it survives.
1406 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1407 llvm::GlobalValue::PrivateLinkage,
1408 /*init*/ nullptr,
1409 /*name*/ "",
1410 /*before*/ nullptr,
1411 llvm::GlobalVariable::NotThreadLocal,
1412 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1413
1414 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1415
1416 return global;
1417}
1418
1419void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1420 llvm::GlobalValue *placeholder) {
1421 assert(!PlaceholderAddresses.empty());
1422 assert(PlaceholderAddresses.back().first == nullptr);
1423 assert(PlaceholderAddresses.back().second == placeholder);
1424 PlaceholderAddresses.back().first = signal;
1425}
1426
1427namespace {
1428 struct ReplacePlaceholders {
1429 CodeGenModule &CGM;
1430
1431 /// The base address of the global.
1432 llvm::Constant *Base;
1433 llvm::Type *BaseValueTy = nullptr;
1434
1435 /// The placeholder addresses that were registered during emission.
1436 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1437
1438 /// The locations of the placeholder signals.
1439 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1440
1441 /// The current index stack. We use a simple unsigned stack because
1442 /// we assume that placeholders will be relatively sparse in the
1443 /// initializer, but we cache the index values we find just in case.
1444 llvm::SmallVector<unsigned, 8> Indices;
1445 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1446
1447 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1448 ArrayRef<std::pair<llvm::Constant*,
1449 llvm::GlobalVariable*>> addresses)
1450 : CGM(CGM), Base(base),
1451 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1452 }
1453
1454 void replaceInInitializer(llvm::Constant *init) {
1455 // Remember the type of the top-most initializer.
1456 BaseValueTy = init->getType();
1457
1458 // Initialize the stack.
1459 Indices.push_back(0);
1460 IndexValues.push_back(nullptr);
1461
1462 // Recurse into the initializer.
1463 findLocations(init);
1464
1465 // Check invariants.
1466 assert(IndexValues.size() == Indices.size() && "mismatch");
1467 assert(Indices.size() == 1 && "didn't pop all indices");
1468
1469 // Do the replacement; this basically invalidates 'init'.
1470 assert(Locations.size() == PlaceholderAddresses.size() &&
1471 "missed a placeholder?");
1472
1473 // We're iterating over a hashtable, so this would be a source of
1474 // non-determinism in compiler output *except* that we're just
1475 // messing around with llvm::Constant structures, which never itself
1476 // does anything that should be visible in compiler output.
1477 for (auto &entry : Locations) {
1478 assert(entry.first->getParent() == nullptr && "not a placeholder!");
1479 entry.first->replaceAllUsesWith(entry.second);
1480 entry.first->eraseFromParent();
1481 }
1482 }
1483
1484 private:
1485 void findLocations(llvm::Constant *init) {
1486 // Recurse into aggregates.
1487 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1488 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1489 Indices.push_back(i);
1490 IndexValues.push_back(nullptr);
1491
1492 findLocations(agg->getOperand(i));
1493
1494 IndexValues.pop_back();
1495 Indices.pop_back();
1496 }
1497 return;
1498 }
1499
1500 // Otherwise, check for registered constants.
1501 while (true) {
1502 auto it = PlaceholderAddresses.find(init);
1503 if (it != PlaceholderAddresses.end()) {
1504 setLocation(it->second);
1505 break;
1506 }
1507
1508 // Look through bitcasts or other expressions.
1509 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1510 init = expr->getOperand(0);
1511 } else {
1512 break;
1513 }
1514 }
1515 }
1516
1517 void setLocation(llvm::GlobalVariable *placeholder) {
1518 assert(Locations.find(placeholder) == Locations.end() &&
1519 "already found location for placeholder!");
1520
1521 // Lazily fill in IndexValues with the values from Indices.
1522 // We do this in reverse because we should always have a strict
1523 // prefix of indices from the start.
1524 assert(Indices.size() == IndexValues.size());
1525 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1526 if (IndexValues[i]) {
1527#ifndef NDEBUG
1528 for (size_t j = 0; j != i + 1; ++j) {
1529 assert(IndexValues[j] &&
1530 isa<llvm::ConstantInt>(IndexValues[j]) &&
1531 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1532 == Indices[j]);
1533 }
1534#endif
1535 break;
1536 }
1537
1538 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1539 }
1540
1541 // Form a GEP and then bitcast to the placeholder type so that the
1542 // replacement will succeed.
1543 llvm::Constant *location =
1544 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1545 Base, IndexValues);
1546 location = llvm::ConstantExpr::getBitCast(location,
1547 placeholder->getType());
1548
1549 Locations.insert({placeholder, location});
1550 }
1551 };
1552}
1553
1554void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1555 assert(InitializedNonAbstract &&
1556 "finalizing emitter that was used for abstract emission?");
1557 assert(!Finalized && "finalizing emitter multiple times");
1558 assert(global->getInitializer());
1559
1560 // Note that we might also be Failed.
1561 Finalized = true;
1562
1563 if (!PlaceholderAddresses.empty()) {
1564 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1565 .replaceInInitializer(global->getInitializer());
1566 PlaceholderAddresses.clear(); // satisfy
1567 }
1568}
1569
1570ConstantEmitter::~ConstantEmitter() {
1571 assert((!InitializedNonAbstract || Finalized || Failed) &&
1572 "not finalized after being initialized for non-abstract emission");
1573 assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1574}
1575
1576static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1577 if (auto AT = type->getAs<AtomicType>()) {
1578 return CGM.getContext().getQualifiedType(AT->getValueType(),
1579 type.getQualifiers());
1580 }
1581 return type;
1582}
1583
1584llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
Fariborz Jahaniancc7f0082013-01-10 23:28:43 +00001585 // Make a quick check if variable can be default NULL initialized
1586 // and avoid going through rest of code which may do, for c++11,
1587 // initialization of memory to all NULLs.
Richard Smith3f1d6de2018-05-21 20:36:58 +00001588 if (!D.hasLocalStorage()) {
1589 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1590 if (Ty->isRecordType())
1591 if (const CXXConstructExpr *E =
1592 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1593 const CXXConstructorDecl *CD = E->getConstructor();
1594 if (CD->isTrivial() && CD->isDefaultConstructor())
1595 return CGM.EmitNullConstant(D.getType());
1596 }
Bill Wendling958b94d2018-12-01 09:06:26 +00001597 InConstantContext = true;
Richard Smith3f1d6de2018-05-21 20:36:58 +00001598 }
John McCallde0fe072017-08-15 21:42:52 +00001599
1600 QualType destType = D.getType();
1601
1602 // Try to emit the initializer. Note that this can allow some things that
1603 // are not allowed by tryEmitPrivateForMemory alone.
1604 if (auto value = D.evaluateValue()) {
1605 return tryEmitPrivateForMemory(*value, destType);
1606 }
Richard Smithdafff942012-01-14 04:30:29 +00001607
Richard Smith6331c402012-02-13 22:16:19 +00001608 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1609 // reference is a constant expression, and the reference binds to a temporary,
1610 // then constant initialization is performed. ConstExprEmitter will
1611 // incorrectly emit a prvalue constant in this case, and the calling code
1612 // interprets that as the (pointer) value of the reference, rather than the
1613 // desired value of the referee.
John McCallde0fe072017-08-15 21:42:52 +00001614 if (destType->isReferenceType())
Craig Topper8a13c412014-05-21 05:09:00 +00001615 return nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00001616
Richard Smithdafff942012-01-14 04:30:29 +00001617 const Expr *E = D.getInit();
1618 assert(E && "No initializer to emit");
1619
John McCallde0fe072017-08-15 21:42:52 +00001620 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1621 auto C =
1622 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1623 return (C ? emitForMemory(C, destType) : nullptr);
1624}
1625
1626llvm::Constant *
1627ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1628 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1629 auto C = tryEmitAbstract(E, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001630 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001631}
1632
1633llvm::Constant *
1634ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1635 QualType destType) {
1636 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1637 auto C = tryEmitAbstract(value, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001638 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001639}
1640
1641llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1642 QualType destType) {
1643 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1644 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1645 return (C ? emitForMemory(C, destType) : nullptr);
1646}
1647
1648llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1649 QualType destType) {
1650 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1651 auto C = tryEmitPrivate(value, nonMemoryDestType);
1652 return (C ? emitForMemory(C, destType) : nullptr);
1653}
1654
1655llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1656 llvm::Constant *C,
1657 QualType destType) {
1658 // For an _Atomic-qualified constant, we may need to add tail padding.
1659 if (auto AT = destType->getAs<AtomicType>()) {
1660 QualType destValueType = AT->getValueType();
1661 C = emitForMemory(CGM, C, destValueType);
1662
1663 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1664 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1665 if (innerSize == outerSize)
1666 return C;
1667
1668 assert(innerSize < outerSize && "emitted over-large constant for atomic");
1669 llvm::Constant *elts[] = {
1670 C,
1671 llvm::ConstantAggregateZero::get(
1672 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1673 };
1674 return llvm::ConstantStruct::getAnon(elts);
Richard Smithdafff942012-01-14 04:30:29 +00001675 }
John McCallde0fe072017-08-15 21:42:52 +00001676
1677 // Zero-extend bool.
1678 if (C->getType()->isIntegerTy(1)) {
1679 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1680 return llvm::ConstantExpr::getZExt(C, boolTy);
1681 }
1682
Richard Smithdafff942012-01-14 04:30:29 +00001683 return C;
1684}
1685
John McCallde0fe072017-08-15 21:42:52 +00001686llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1687 QualType destType) {
Anders Carlsson38eef1d2008-12-01 02:42:14 +00001688 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +00001689
Anders Carlssond8e39bb2009-04-11 01:08:03 +00001690 bool Success = false;
Mike Stump11289f42009-09-09 15:08:12 +00001691
John McCallde0fe072017-08-15 21:42:52 +00001692 if (destType->isReferenceType())
1693 Success = E->EvaluateAsLValue(Result, CGM.getContext());
Mike Stump11289f42009-09-09 15:08:12 +00001694 else
Bill Wendling2a81f662018-12-01 08:29:36 +00001695 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
Mike Stump11289f42009-09-09 15:08:12 +00001696
John McCallde0fe072017-08-15 21:42:52 +00001697 llvm::Constant *C;
Richard Smithdafff942012-01-14 04:30:29 +00001698 if (Success && !Result.HasSideEffects)
John McCallde0fe072017-08-15 21:42:52 +00001699 C = tryEmitPrivate(Result.Val, destType);
Richard Smithbc6387672012-03-02 23:27:11 +00001700 else
John McCallde0fe072017-08-15 21:42:52 +00001701 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
Eli Friedman10c24172008-06-01 15:31:44 +00001702
Eli Friedman10c24172008-06-01 15:31:44 +00001703 return C;
Anders Carlsson610ee712008-01-26 01:36:00 +00001704}
Eli Friedman20bb5e02009-04-13 21:47:26 +00001705
Yaxun Liu402804b2016-12-15 08:09:08 +00001706llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1707 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1708}
1709
John McCall99e5e982017-08-17 05:03:55 +00001710namespace {
1711/// A struct which can be used to peephole certain kinds of finalization
1712/// that normally happen during l-value emission.
1713struct ConstantLValue {
1714 llvm::Constant *Value;
1715 bool HasOffsetApplied;
1716
1717 /*implicit*/ ConstantLValue(llvm::Constant *value,
1718 bool hasOffsetApplied = false)
1719 : Value(value), HasOffsetApplied(false) {}
1720
1721 /*implicit*/ ConstantLValue(ConstantAddress address)
1722 : ConstantLValue(address.getPointer()) {}
1723};
1724
1725/// A helper class for emitting constant l-values.
1726class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1727 ConstantLValue> {
1728 CodeGenModule &CGM;
1729 ConstantEmitter &Emitter;
1730 const APValue &Value;
1731 QualType DestType;
1732
1733 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1734 friend StmtVisitorBase;
1735
1736public:
1737 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1738 QualType destType)
1739 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1740
1741 llvm::Constant *tryEmit();
1742
1743private:
1744 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1745 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1746
1747 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
Bill Wendling8003edc2018-11-09 00:41:36 +00001748 ConstantLValue VisitConstantExpr(const ConstantExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001749 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1750 ConstantLValue VisitStringLiteral(const StringLiteral *E);
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001751 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001752 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1753 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1754 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1755 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1756 ConstantLValue VisitCallExpr(const CallExpr *E);
1757 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1758 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1759 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1760 ConstantLValue VisitMaterializeTemporaryExpr(
1761 const MaterializeTemporaryExpr *E);
1762
1763 bool hasNonZeroOffset() const {
1764 return !Value.getLValueOffset().isZero();
1765 }
1766
1767 /// Return the value offset.
1768 llvm::Constant *getOffset() {
1769 return llvm::ConstantInt::get(CGM.Int64Ty,
1770 Value.getLValueOffset().getQuantity());
1771 }
1772
1773 /// Apply the value offset to the given constant.
1774 llvm::Constant *applyOffset(llvm::Constant *C) {
1775 if (!hasNonZeroOffset())
1776 return C;
1777
1778 llvm::Type *origPtrTy = C->getType();
1779 unsigned AS = origPtrTy->getPointerAddressSpace();
1780 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1781 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1782 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1783 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1784 return C;
1785 }
1786};
1787
1788}
1789
1790llvm::Constant *ConstantLValueEmitter::tryEmit() {
1791 const APValue::LValueBase &base = Value.getLValueBase();
1792
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001793 // The destination type should be a pointer or reference
John McCall99e5e982017-08-17 05:03:55 +00001794 // type, but it might also be a cast thereof.
1795 //
1796 // FIXME: the chain of casts required should be reflected in the APValue.
1797 // We need this in order to correctly handle things like a ptrtoint of a
1798 // non-zero null pointer and addrspace casts that aren't trivially
1799 // represented in LLVM IR.
1800 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1801 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1802
1803 // If there's no base at all, this is a null or absolute pointer,
1804 // possibly cast back to an integer type.
1805 if (!base) {
1806 return tryEmitAbsolute(destTy);
1807 }
1808
1809 // Otherwise, try to emit the base.
1810 ConstantLValue result = tryEmitBase(base);
1811
1812 // If that failed, we're done.
1813 llvm::Constant *value = result.Value;
1814 if (!value) return nullptr;
1815
1816 // Apply the offset if necessary and not already done.
1817 if (!result.HasOffsetApplied) {
1818 value = applyOffset(value);
1819 }
1820
1821 // Convert to the appropriate type; this could be an lvalue for
1822 // an integer. FIXME: performAddrSpaceCast
1823 if (isa<llvm::PointerType>(destTy))
1824 return llvm::ConstantExpr::getPointerCast(value, destTy);
1825
1826 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1827}
1828
1829/// Try to emit an absolute l-value, such as a null pointer or an integer
1830/// bitcast to pointer type.
1831llvm::Constant *
1832ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
John McCall99e5e982017-08-17 05:03:55 +00001833 // If we're producing a pointer, this is easy.
Don Hintonf170dff2019-03-19 06:14:14 +00001834 auto destPtrTy = cast<llvm::PointerType>(destTy);
1835 if (Value.isNullPointer()) {
1836 // FIXME: integer offsets from non-zero null pointers.
1837 return CGM.getNullPointer(destPtrTy, DestType);
John McCall99e5e982017-08-17 05:03:55 +00001838 }
1839
Don Hintonf170dff2019-03-19 06:14:14 +00001840 // Convert the integer to a pointer-sized integer before converting it
1841 // to a pointer.
1842 // FIXME: signedness depends on the original integer type.
1843 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
Simon Pilgrim3ff9c512019-05-11 11:01:46 +00001844 llvm::Constant *C;
Don Hintonf170dff2019-03-19 06:14:14 +00001845 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1846 /*isSigned*/ false);
1847 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
John McCall99e5e982017-08-17 05:03:55 +00001848 return C;
1849}
1850
1851ConstantLValue
1852ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1853 // Handle values.
1854 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1855 if (D->hasAttr<WeakRefAttr>())
1856 return CGM.GetWeakRefReference(D).getPointer();
1857
1858 if (auto FD = dyn_cast<FunctionDecl>(D))
1859 return CGM.GetAddrOfFunction(FD);
1860
1861 if (auto VD = dyn_cast<VarDecl>(D)) {
1862 // We can never refer to a variable with local storage.
1863 if (!VD->hasLocalStorage()) {
1864 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1865 return CGM.GetAddrOfGlobalVar(VD);
1866
1867 if (VD->isLocalVarDecl()) {
1868 return CGM.getOrCreateStaticVarDecl(
1869 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1870 }
1871 }
1872 }
1873
1874 return nullptr;
1875 }
1876
Richard Smithee0ce3022019-05-17 07:06:46 +00001877 // Handle typeid(T).
1878 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1879 llvm::Type *StdTypeInfoPtrTy =
1880 CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1881 llvm::Constant *TypeInfo =
1882 CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1883 if (TypeInfo->getType() != StdTypeInfoPtrTy)
1884 TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1885 return TypeInfo;
1886 }
1887
John McCall99e5e982017-08-17 05:03:55 +00001888 // Otherwise, it must be an expression.
1889 return Visit(base.get<const Expr*>());
1890}
1891
1892ConstantLValue
Bill Wendling8003edc2018-11-09 00:41:36 +00001893ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1894 return Visit(E->getSubExpr());
1895}
1896
1897ConstantLValue
John McCall99e5e982017-08-17 05:03:55 +00001898ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1899 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1900}
1901
1902ConstantLValue
1903ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1904 return CGM.GetAddrOfConstantStringFromLiteral(E);
1905}
1906
1907ConstantLValue
1908ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1909 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1910}
1911
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001912static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1913 QualType T,
1914 CodeGenModule &CGM) {
1915 auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1916 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1917}
1918
John McCall99e5e982017-08-17 05:03:55 +00001919ConstantLValue
1920ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001921 return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1922}
1923
1924ConstantLValue
1925ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1926 assert(E->isExpressibleAsConstantInitializer() &&
1927 "this boxed expression can't be emitted as a compile-time constant");
1928 auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1929 return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
John McCall99e5e982017-08-17 05:03:55 +00001930}
1931
1932ConstantLValue
1933ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
Eli Friedman3f82f9e2019-01-22 00:11:17 +00001934 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
John McCall99e5e982017-08-17 05:03:55 +00001935}
1936
1937ConstantLValue
1938ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1939 assert(Emitter.CGF && "Invalid address of label expression outside function");
1940 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1941 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1942 CGM.getTypes().ConvertType(E->getType()));
1943 return Ptr;
1944}
1945
1946ConstantLValue
1947ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1948 unsigned builtin = E->getBuiltinCallee();
1949 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1950 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1951 return nullptr;
1952
1953 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1954 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1955 return CGM.getObjCRuntime().GenerateConstantString(literal);
1956 } else {
1957 // FIXME: need to deal with UCN conversion issues.
1958 return CGM.GetAddrOfConstantCFString(literal);
1959 }
1960}
1961
1962ConstantLValue
1963ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1964 StringRef functionName;
1965 if (auto CGF = Emitter.CGF)
1966 functionName = CGF->CurFn->getName();
1967 else
1968 functionName = "global";
1969
1970 return CGM.GetAddrOfGlobalBlock(E, functionName);
1971}
1972
1973ConstantLValue
1974ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1975 QualType T;
1976 if (E->isTypeOperand())
1977 T = E->getTypeOperand(CGM.getContext());
1978 else
1979 T = E->getExprOperand()->getType();
1980 return CGM.GetAddrOfRTTIDescriptor(T);
1981}
1982
1983ConstantLValue
1984ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1985 return CGM.GetAddrOfUuidDescriptor(E);
1986}
1987
1988ConstantLValue
1989ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1990 const MaterializeTemporaryExpr *E) {
1991 assert(E->getStorageDuration() == SD_Static);
1992 SmallVector<const Expr *, 2> CommaLHSs;
1993 SmallVector<SubobjectAdjustment, 2> Adjustments;
1994 const Expr *Inner = E->GetTemporaryExpr()
1995 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1996 return CGM.GetAddrOfGlobalTemporary(E, Inner);
1997}
1998
John McCallde0fe072017-08-15 21:42:52 +00001999llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
2000 QualType DestType) {
Richard Smithdafff942012-01-14 04:30:29 +00002001 switch (Value.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002002 case APValue::None:
2003 case APValue::Indeterminate:
2004 // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2005 return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
John McCall99e5e982017-08-17 05:03:55 +00002006 case APValue::LValue:
2007 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
Richard Smithbc6387672012-03-02 23:27:11 +00002008 case APValue::Int:
John McCallde0fe072017-08-15 21:42:52 +00002009 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
Leonard Chan86285d22019-01-16 18:53:05 +00002010 case APValue::FixedPoint:
2011 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2012 Value.getFixedPoint().getValue());
Richard Smithdafff942012-01-14 04:30:29 +00002013 case APValue::ComplexInt: {
2014 llvm::Constant *Complex[2];
2015
John McCallde0fe072017-08-15 21:42:52 +00002016 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002017 Value.getComplexIntReal());
John McCallde0fe072017-08-15 21:42:52 +00002018 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002019 Value.getComplexIntImag());
2020
2021 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002022 llvm::StructType *STy =
2023 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002024 return llvm::ConstantStruct::get(STy, Complex);
2025 }
2026 case APValue::Float: {
2027 const llvm::APFloat &Init = Value.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002028 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
John McCallde0fe072017-08-15 21:42:52 +00002029 !CGM.getContext().getLangOpts().NativeHalfType &&
Akira Hatanaka502775a2017-12-09 00:02:37 +00002030 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
John McCallde0fe072017-08-15 21:42:52 +00002031 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2032 Init.bitcastToAPInt());
Richard Smithdafff942012-01-14 04:30:29 +00002033 else
John McCallde0fe072017-08-15 21:42:52 +00002034 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
Richard Smithdafff942012-01-14 04:30:29 +00002035 }
2036 case APValue::ComplexFloat: {
2037 llvm::Constant *Complex[2];
2038
John McCallde0fe072017-08-15 21:42:52 +00002039 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002040 Value.getComplexFloatReal());
John McCallde0fe072017-08-15 21:42:52 +00002041 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002042 Value.getComplexFloatImag());
2043
2044 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002045 llvm::StructType *STy =
2046 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002047 return llvm::ConstantStruct::get(STy, Complex);
2048 }
2049 case APValue::Vector: {
Richard Smithdafff942012-01-14 04:30:29 +00002050 unsigned NumElts = Value.getVectorLength();
George Burgess IV533ff002015-12-11 00:23:35 +00002051 SmallVector<llvm::Constant *, 4> Inits(NumElts);
Richard Smithdafff942012-01-14 04:30:29 +00002052
George Burgess IV533ff002015-12-11 00:23:35 +00002053 for (unsigned I = 0; I != NumElts; ++I) {
2054 const APValue &Elt = Value.getVectorElt(I);
Richard Smithdafff942012-01-14 04:30:29 +00002055 if (Elt.isInt())
John McCallde0fe072017-08-15 21:42:52 +00002056 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
George Burgess IV533ff002015-12-11 00:23:35 +00002057 else if (Elt.isFloat())
John McCallde0fe072017-08-15 21:42:52 +00002058 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
Richard Smithdafff942012-01-14 04:30:29 +00002059 else
George Burgess IV533ff002015-12-11 00:23:35 +00002060 llvm_unreachable("unsupported vector element type");
Richard Smithdafff942012-01-14 04:30:29 +00002061 }
2062 return llvm::ConstantVector::get(Inits);
2063 }
2064 case APValue::AddrLabelDiff: {
2065 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2066 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
John McCallde0fe072017-08-15 21:42:52 +00002067 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2068 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2069 if (!LHS || !RHS) return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002070
2071 // Compute difference
John McCallde0fe072017-08-15 21:42:52 +00002072 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2073 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2074 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
Richard Smithdafff942012-01-14 04:30:29 +00002075 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2076
2077 // LLVM is a bit sensitive about the exact format of the
2078 // address-of-label difference; make sure to truncate after
2079 // the subtraction.
2080 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2081 }
2082 case APValue::Struct:
2083 case APValue::Union:
John McCallde0fe072017-08-15 21:42:52 +00002084 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002085 case APValue::Array: {
Richard Smith3e268632018-05-23 23:41:38 +00002086 const ConstantArrayType *CAT =
2087 CGM.getContext().getAsConstantArrayType(DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002088 unsigned NumElements = Value.getArraySize();
2089 unsigned NumInitElts = Value.getArrayInitializedElts();
2090
Richard Smithdafff942012-01-14 04:30:29 +00002091 // Emit array filler, if there is one.
Craig Topper8a13c412014-05-21 05:09:00 +00002092 llvm::Constant *Filler = nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00002093 if (Value.hasArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00002094 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2095 CAT->getElementType());
Richard Smith3e268632018-05-23 23:41:38 +00002096 if (!Filler)
2097 return nullptr;
Hans Wennborg156349f2018-05-23 08:24:01 +00002098 }
David Majnemer90d85442014-12-28 23:46:59 +00002099
Richard Smith3e268632018-05-23 23:41:38 +00002100 // Emit initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00002101 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00002102 if (Filler && Filler->isNullValue())
2103 Elts.reserve(NumInitElts + 1);
2104 else
2105 Elts.reserve(NumElements);
2106
2107 llvm::Type *CommonElementType = nullptr;
2108 for (unsigned I = 0; I < NumInitElts; ++I) {
2109 llvm::Constant *C = tryEmitPrivateForMemory(
2110 Value.getArrayInitializedElt(I), CAT->getElementType());
John McCallde0fe072017-08-15 21:42:52 +00002111 if (!C) return nullptr;
2112
Richard Smithdafff942012-01-14 04:30:29 +00002113 if (I == 0)
2114 CommonElementType = C->getType();
2115 else if (C->getType() != CommonElementType)
Craig Topper8a13c412014-05-21 05:09:00 +00002116 CommonElementType = nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002117 Elts.push_back(C);
2118 }
2119
Balaji V. Iyer749e8282018-08-08 00:01:21 +00002120 // This means that the array type is probably "IncompleteType" or some
2121 // type that is not ConstantArray.
2122 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
2123 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
2124 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
2125 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
2126 NumElements);
2127 return llvm::ConstantAggregateZero::get(AType);
2128 }
2129
Richard Smith5745feb2019-06-17 21:08:30 +00002130 llvm::ArrayType *Desired =
2131 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2132 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00002133 Filler);
Richard Smithdafff942012-01-14 04:30:29 +00002134 }
2135 case APValue::MemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00002136 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002137 }
2138 llvm_unreachable("Unknown APValue kind");
2139}
2140
George Burgess IV1a39b862016-12-28 07:27:40 +00002141llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2142 const CompoundLiteralExpr *E) {
2143 return EmittedCompoundLiterals.lookup(E);
2144}
2145
2146void CodeGenModule::setAddrOfConstantCompoundLiteral(
2147 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2148 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2149 (void)Ok;
2150 assert(Ok && "CLE has already been emitted!");
2151}
2152
John McCall7f416cc2015-09-08 08:05:57 +00002153ConstantAddress
Richard Smith2d988f02011-11-22 22:48:32 +00002154CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2155 assert(E->isFileScope() && "not a file-scope compound literal expr");
John McCallde0fe072017-08-15 21:42:52 +00002156 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
Richard Smith2d988f02011-11-22 22:48:32 +00002157}
2158
John McCallf3a88602011-02-03 08:15:49 +00002159llvm::Constant *
2160CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2161 // Member pointer constants always have a very particular form.
2162 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2163 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2164
2165 // A member function pointer.
2166 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
David Majnemere2be95b2015-06-23 07:31:01 +00002167 return getCXXABI().EmitMemberFunctionPointer(method);
John McCallf3a88602011-02-03 08:15:49 +00002168
2169 // Otherwise, a member data pointer.
Richard Smithdafff942012-01-14 04:30:29 +00002170 uint64_t fieldOffset = getContext().getFieldOffset(decl);
John McCallf3a88602011-02-03 08:15:49 +00002171 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2172 return getCXXABI().EmitMemberDataPointer(type, chars);
2173}
2174
John McCall0217dfc22011-02-15 06:40:56 +00002175static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002176 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002177 const CXXRecordDecl *base);
2178
Anders Carlsson849ea412010-11-22 18:42:14 +00002179static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
Yaxun Liu402804b2016-12-15 08:09:08 +00002180 const RecordDecl *record,
John McCall0217dfc22011-02-15 06:40:56 +00002181 bool asCompleteObject) {
2182 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2192fe52011-07-18 04:24:23 +00002183 llvm::StructType *structure =
John McCall0217dfc22011-02-15 06:40:56 +00002184 (asCompleteObject ? layout.getLLVMType()
2185 : layout.getBaseSubobjectLLVMType());
Anders Carlsson849ea412010-11-22 18:42:14 +00002186
John McCall0217dfc22011-02-15 06:40:56 +00002187 unsigned numElements = structure->getNumElements();
2188 std::vector<llvm::Constant *> elements(numElements);
Anders Carlsson849ea412010-11-22 18:42:14 +00002189
Yaxun Liu402804b2016-12-15 08:09:08 +00002190 auto CXXR = dyn_cast<CXXRecordDecl>(record);
John McCall0217dfc22011-02-15 06:40:56 +00002191 // Fill in all the bases.
Yaxun Liu402804b2016-12-15 08:09:08 +00002192 if (CXXR) {
2193 for (const auto &I : CXXR->bases()) {
2194 if (I.isVirtual()) {
2195 // Ignore virtual bases; if we're laying out for a complete
2196 // object, we'll lay these out later.
2197 continue;
2198 }
2199
2200 const CXXRecordDecl *base =
2201 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2202
2203 // Ignore empty bases.
2204 if (base->isEmpty() ||
2205 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2206 .isZero())
2207 continue;
2208
2209 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2210 llvm::Type *baseType = structure->getElementType(fieldIndex);
2211 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlsson849ea412010-11-22 18:42:14 +00002212 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002213 }
2214
John McCall0217dfc22011-02-15 06:40:56 +00002215 // Fill in all the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002216 for (const auto *Field : record->fields()) {
Eli Friedmandae858a2011-12-07 01:30:11 +00002217 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2218 // will fill in later.)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002219 if (!Field->isBitField()) {
2220 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2221 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
Eli Friedmandae858a2011-12-07 01:30:11 +00002222 }
2223
2224 // For unions, stop after the first named field.
David Majnemer4e51dfc2015-05-30 09:12:07 +00002225 if (record->isUnion()) {
2226 if (Field->getIdentifier())
2227 break;
George Karpenkov39e51372018-07-28 02:16:13 +00002228 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
David Majnemer4e51dfc2015-05-30 09:12:07 +00002229 if (FieldRD->findFirstNamedDataMember())
2230 break;
2231 }
John McCall0217dfc22011-02-15 06:40:56 +00002232 }
2233
2234 // Fill in the virtual bases, if we're working with the complete object.
Yaxun Liu402804b2016-12-15 08:09:08 +00002235 if (CXXR && asCompleteObject) {
2236 for (const auto &I : CXXR->vbases()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002237 const CXXRecordDecl *base =
Aaron Ballman445a9392014-03-13 16:15:17 +00002238 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
John McCall0217dfc22011-02-15 06:40:56 +00002239
2240 // Ignore empty bases.
2241 if (base->isEmpty())
2242 continue;
2243
2244 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2245
2246 // We might have already laid this field out.
2247 if (elements[fieldIndex]) continue;
2248
Chris Lattner2192fe52011-07-18 04:24:23 +00002249 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall0217dfc22011-02-15 06:40:56 +00002250 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2251 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002252 }
2253
2254 // Now go through all other fields and zero them out.
John McCall0217dfc22011-02-15 06:40:56 +00002255 for (unsigned i = 0; i != numElements; ++i) {
2256 if (!elements[i])
2257 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlsson849ea412010-11-22 18:42:14 +00002258 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002259
John McCall0217dfc22011-02-15 06:40:56 +00002260 return llvm::ConstantStruct::get(structure, elements);
2261}
2262
2263/// Emit the null constant for a base subobject.
2264static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002265 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002266 const CXXRecordDecl *base) {
2267 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2268
2269 // Just zero out bases that don't have any pointer to data members.
2270 if (baseLayout.isZeroInitializableAsBase())
2271 return llvm::Constant::getNullValue(baseType);
2272
David Majnemer2213bfe2014-10-17 01:00:43 +00002273 // Otherwise, we can just use its null constant.
2274 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
Anders Carlsson849ea412010-11-22 18:42:14 +00002275}
2276
John McCallde0fe072017-08-15 21:42:52 +00002277llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2278 QualType T) {
2279 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2280}
2281
Eli Friedman20bb5e02009-04-13 21:47:26 +00002282llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
Yaxun Liu402804b2016-12-15 08:09:08 +00002283 if (T->getAs<PointerType>())
2284 return getNullPointer(
2285 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2286
John McCall614dbdc2010-08-22 21:01:12 +00002287 if (getTypes().isZeroInitializable(T))
Anders Carlsson867b48f2009-08-24 17:16:23 +00002288 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Fangrui Song6907ce22018-07-30 19:24:48 +00002289
Anders Carlssonf48123b2009-08-09 18:26:27 +00002290 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Chris Lattner72977a12012-02-06 22:00:56 +00002291 llvm::ArrayType *ATy =
2292 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
Mike Stump11289f42009-09-09 15:08:12 +00002293
Anders Carlssonf48123b2009-08-09 18:26:27 +00002294 QualType ElementTy = CAT->getElementType();
2295
John McCallde0fe072017-08-15 21:42:52 +00002296 llvm::Constant *Element =
2297 ConstantEmitter::emitNullForMemory(*this, ElementTy);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002298 unsigned NumElements = CAT->getSize().getZExtValue();
Chris Lattner72977a12012-02-06 22:00:56 +00002299 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002300 return llvm::ConstantArray::get(ATy, Array);
Anders Carlssonf48123b2009-08-09 18:26:27 +00002301 }
Anders Carlssond606de72009-08-23 01:25:01 +00002302
Yaxun Liu402804b2016-12-15 08:09:08 +00002303 if (const RecordType *RT = T->getAs<RecordType>())
2304 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002305
David Majnemer5fd33e02015-04-24 01:25:08 +00002306 assert(T->isMemberDataPointerType() &&
Anders Carlssone8bfe412010-02-02 05:17:25 +00002307 "Should only see pointers to data members here!");
David Majnemer2213bfe2014-10-17 01:00:43 +00002308
John McCallf3a88602011-02-03 08:15:49 +00002309 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman20bb5e02009-04-13 21:47:26 +00002310}
Eli Friedmanfde961d2011-10-14 02:27:24 +00002311
2312llvm::Constant *
2313CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2314 return ::EmitNullConstant(*this, Record, false);
2315}