blob: e17c1c5f7ac4f6924e823ea4cf6b5f3423f8f806 [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
John McCall5d865c322010-08-31 07:33:07 +000013#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000014#include "CGObjCRuntime.h"
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000015#include "CGRecordLayout.h"
Reid Kleckner98031782019-12-09 16:11:56 -080016#include "CodeGenFunction.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"
Reid Kleckner98031782019-12-09 16:11:56 -080022#include "clang/AST/Attr.h"
Anders Carlssone1d5ca52009-07-24 15:20:52 +000023#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Richard Smith5745feb2019-06-17 21:08:30 +000026#include "llvm/ADT/STLExtras.h"
Reid Kleckner98031782019-12-09 16:11:56 -080027#include "llvm/ADT/Sequence.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalVariable.h"
Anders Carlsson610ee712008-01-26 01:36:00 +000032using namespace clang;
33using namespace CodeGen;
34
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000035//===----------------------------------------------------------------------===//
Richard Smith5745feb2019-06-17 21:08:30 +000036// ConstantAggregateBuilder
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000037//===----------------------------------------------------------------------===//
38
39namespace {
Yunzhong Gaocb779302015-06-10 00:27:52 +000040class ConstExprEmitter;
Richard Smith5745feb2019-06-17 21:08:30 +000041
42struct ConstantAggregateBuilderUtils {
Anders Carlssone1d5ca52009-07-24 15:20:52 +000043 CodeGenModule &CGM;
Anders Carlssone1d5ca52009-07-24 15:20:52 +000044
Richard Smith5745feb2019-06-17 21:08:30 +000045 ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
Mike Stump11289f42009-09-09 15:08:12 +000046
Ken Dycka1b35102011-03-18 01:26:17 +000047 CharUnits getAlignment(const llvm::Constant *C) const {
Ken Dycka1b35102011-03-18 01:26:17 +000048 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000049 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000050 }
Mike Stump11289f42009-09-09 15:08:12 +000051
Richard Smith5745feb2019-06-17 21:08:30 +000052 CharUnits getSize(llvm::Type *Ty) const {
53 return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
54 }
55
56 CharUnits getSize(const llvm::Constant *C) const {
57 return getSize(C->getType());
58 }
59
60 llvm::Constant *getPadding(CharUnits PadSize) const {
61 llvm::Type *Ty = CGM.Int8Ty;
62 if (PadSize > CharUnits::One())
63 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
64 return llvm::UndefValue::get(Ty);
65 }
66
67 llvm::Constant *getZeroes(CharUnits ZeroSize) const {
68 llvm::Type *Ty = llvm::ArrayType::get(CGM.Int8Ty, ZeroSize.getQuantity());
69 return llvm::ConstantAggregateZero::get(Ty);
Anders Carlssone1d5ca52009-07-24 15:20:52 +000070 }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000071};
Mike Stump11289f42009-09-09 15:08:12 +000072
Richard Smith5745feb2019-06-17 21:08:30 +000073/// Incremental builder for an llvm::Constant* holding a struct or array
74/// constant.
75class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
76 /// The elements of the constant. These two arrays must have the same size;
77 /// Offsets[i] describes the offset of Elems[i] within the constant. The
78 /// elements are kept in increasing offset order, and we ensure that there
79 /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
80 ///
81 /// This may contain explicit padding elements (in order to create a
82 /// natural layout), but need not. Gaps between elements are implicitly
83 /// considered to be filled with undef.
84 llvm::SmallVector<llvm::Constant*, 32> Elems;
85 llvm::SmallVector<CharUnits, 32> Offsets;
86
87 /// The size of the constant (the maximum end offset of any added element).
88 /// May be larger than the end of Elems.back() if we split the last element
89 /// and removed some trailing undefs.
90 CharUnits Size = CharUnits::Zero();
91
92 /// This is true only if laying out Elems in order as the elements of a
93 /// non-packed LLVM struct will give the correct layout.
94 bool NaturalLayout = true;
95
96 bool split(size_t Index, CharUnits Hint);
97 Optional<size_t> splitAt(CharUnits Pos);
98
99 static llvm::Constant *buildFrom(CodeGenModule &CGM,
100 ArrayRef<llvm::Constant *> Elems,
101 ArrayRef<CharUnits> Offsets,
102 CharUnits StartOffset, CharUnits Size,
103 bool NaturalLayout, llvm::Type *DesiredTy,
104 bool AllowOversized);
105
106public:
107 ConstantAggregateBuilder(CodeGenModule &CGM)
108 : ConstantAggregateBuilderUtils(CGM) {}
109
110 /// Update or overwrite the value starting at \p Offset with \c C.
111 ///
112 /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
113 /// a constant that has already been added. This flag is only used to
114 /// detect bugs.
115 bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
116
117 /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
118 bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
119
120 /// Attempt to condense the value starting at \p Offset to a constant of type
121 /// \p DesiredTy.
122 void condense(CharUnits Offset, llvm::Type *DesiredTy);
123
124 /// Produce a constant representing the entire accumulated value, ideally of
125 /// the specified type. If \p AllowOversized, the constant might be larger
126 /// than implied by \p DesiredTy (eg, if there is a flexible array member).
127 /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
128 /// even if we can't represent it as that type.
129 llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
130 return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
131 NaturalLayout, DesiredTy, AllowOversized);
132 }
133};
134
135template<typename Container, typename Range = std::initializer_list<
136 typename Container::value_type>>
137static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
138 assert(BeginOff <= EndOff && "invalid replacement range");
139 llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
140}
141
142bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
143 bool AllowOverwrite) {
144 // Common case: appending to a layout.
145 if (Offset >= Size) {
146 CharUnits Align = getAlignment(C);
147 CharUnits AlignedSize = Size.alignTo(Align);
148 if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
149 NaturalLayout = false;
150 else if (AlignedSize < Offset) {
151 Elems.push_back(getPadding(Offset - Size));
152 Offsets.push_back(Size);
153 }
154 Elems.push_back(C);
155 Offsets.push_back(Offset);
156 Size = Offset + getSize(C);
157 return true;
158 }
159
160 // Uncommon case: constant overlaps what we've already created.
161 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
162 if (!FirstElemToReplace)
163 return false;
164
165 CharUnits CSize = getSize(C);
166 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
167 if (!LastElemToReplace)
168 return false;
169
170 assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
171 "unexpectedly overwriting field");
172
173 replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
174 replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
175 Size = std::max(Size, Offset + CSize);
176 NaturalLayout = false;
177 return true;
178}
179
180bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
181 bool AllowOverwrite) {
182 const ASTContext &Context = CGM.getContext();
183 const uint64_t CharWidth = CGM.getContext().getCharWidth();
184
185 // Offset of where we want the first bit to go within the bits of the
186 // current char.
187 unsigned OffsetWithinChar = OffsetInBits % CharWidth;
188
189 // We split bit-fields up into individual bytes. Walk over the bytes and
190 // update them.
Richard Smith780c3742019-06-22 20:41:57 +0000191 for (CharUnits OffsetInChars =
192 Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
Richard Smith5745feb2019-06-17 21:08:30 +0000193 /**/; ++OffsetInChars) {
194 // Number of bits we want to fill in this char.
195 unsigned WantedBits =
196 std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
197
198 // Get a char containing the bits we want in the right places. The other
199 // bits have unspecified values.
200 llvm::APInt BitsThisChar = Bits;
201 if (BitsThisChar.getBitWidth() < CharWidth)
202 BitsThisChar = BitsThisChar.zext(CharWidth);
203 if (CGM.getDataLayout().isBigEndian()) {
204 // Figure out how much to shift by. We may need to left-shift if we have
205 // less than one byte of Bits left.
206 int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
207 if (Shift > 0)
208 BitsThisChar.lshrInPlace(Shift);
209 else if (Shift < 0)
210 BitsThisChar = BitsThisChar.shl(-Shift);
211 } else {
212 BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
213 }
214 if (BitsThisChar.getBitWidth() > CharWidth)
215 BitsThisChar = BitsThisChar.trunc(CharWidth);
216
217 if (WantedBits == CharWidth) {
218 // Got a full byte: just add it directly.
219 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
220 OffsetInChars, AllowOverwrite);
221 } else {
222 // Partial byte: update the existing integer if there is one. If we
223 // can't split out a 1-CharUnit range to update, then we can't add
224 // these bits and fail the entire constant emission.
225 llvm::Optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
226 if (!FirstElemToUpdate)
227 return false;
228 llvm::Optional<size_t> LastElemToUpdate =
229 splitAt(OffsetInChars + CharUnits::One());
230 if (!LastElemToUpdate)
231 return false;
232 assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
233 "should have at most one element covering one byte");
234
235 // Figure out which bits we want and discard the rest.
236 llvm::APInt UpdateMask(CharWidth, 0);
237 if (CGM.getDataLayout().isBigEndian())
238 UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
239 CharWidth - OffsetWithinChar);
240 else
241 UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
242 BitsThisChar &= UpdateMask;
243
244 if (*FirstElemToUpdate == *LastElemToUpdate ||
245 Elems[*FirstElemToUpdate]->isNullValue() ||
246 isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
247 // All existing bits are either zero or undef.
248 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
249 OffsetInChars, /*AllowOverwrite*/ true);
250 } else {
251 llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
252 // In order to perform a partial update, we need the existing bitwise
253 // value, which we can only extract for a constant int.
254 auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
255 if (!CI)
256 return false;
257 // Because this is a 1-CharUnit range, the constant occupying it must
258 // be exactly one CharUnit wide.
259 assert(CI->getBitWidth() == CharWidth && "splitAt failed");
260 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
261 "unexpectedly overwriting bitfield");
262 BitsThisChar |= (CI->getValue() & ~UpdateMask);
263 ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
264 }
265 }
266
267 // Stop if we've added all the bits.
268 if (WantedBits == Bits.getBitWidth())
269 break;
270
271 // Remove the consumed bits from Bits.
272 if (!CGM.getDataLayout().isBigEndian())
273 Bits.lshrInPlace(WantedBits);
274 Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
275
276 // The remanining bits go at the start of the following bytes.
277 OffsetWithinChar = 0;
278 }
279
280 return true;
281}
282
283/// Returns a position within Elems and Offsets such that all elements
284/// before the returned index end before Pos and all elements at or after
285/// the returned index begin at or after Pos. Splits elements as necessary
286/// to ensure this. Returns None if we find something we can't split.
287Optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
288 if (Pos >= Size)
289 return Offsets.size();
290
291 while (true) {
Fangrui Song7264a472019-07-03 08:13:17 +0000292 auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
Richard Smith5745feb2019-06-17 21:08:30 +0000293 if (FirstAfterPos == Offsets.begin())
294 return 0;
295
296 // If we already have an element starting at Pos, we're done.
297 size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
298 if (Offsets[LastAtOrBeforePosIndex] == Pos)
299 return LastAtOrBeforePosIndex;
300
301 // We found an element starting before Pos. Check for overlap.
302 if (Offsets[LastAtOrBeforePosIndex] +
303 getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
304 return LastAtOrBeforePosIndex + 1;
305
306 // Try to decompose it into smaller constants.
307 if (!split(LastAtOrBeforePosIndex, Pos))
308 return None;
309 }
310}
311
312/// Split the constant at index Index, if possible. Return true if we did.
313/// Hint indicates the location at which we'd like to split, but may be
314/// ignored.
315bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
316 NaturalLayout = false;
317 llvm::Constant *C = Elems[Index];
318 CharUnits Offset = Offsets[Index];
319
320 if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
321 replace(Elems, Index, Index + 1,
322 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
323 [&](unsigned Op) { return CA->getOperand(Op); }));
324 if (auto *Seq = dyn_cast<llvm::SequentialType>(CA->getType())) {
325 // Array or vector.
326 CharUnits ElemSize = getSize(Seq->getElementType());
327 replace(
328 Offsets, Index, Index + 1,
329 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
330 [&](unsigned Op) { return Offset + Op * ElemSize; }));
331 } else {
332 // Must be a struct.
333 auto *ST = cast<llvm::StructType>(CA->getType());
334 const llvm::StructLayout *Layout =
335 CGM.getDataLayout().getStructLayout(ST);
336 replace(Offsets, Index, Index + 1,
337 llvm::map_range(
338 llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
339 return Offset + CharUnits::fromQuantity(
340 Layout->getElementOffset(Op));
341 }));
342 }
343 return true;
344 }
345
346 if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
347 // FIXME: If possible, split into two ConstantDataSequentials at Hint.
348 CharUnits ElemSize = getSize(CDS->getElementType());
349 replace(Elems, Index, Index + 1,
350 llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
351 [&](unsigned Elem) {
352 return CDS->getElementAsConstant(Elem);
353 }));
354 replace(Offsets, Index, Index + 1,
355 llvm::map_range(
356 llvm::seq(0u, CDS->getNumElements()),
357 [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
358 return true;
359 }
360
Mikael Holmen5136ea42019-06-18 06:41:56 +0000361 if (isa<llvm::ConstantAggregateZero>(C)) {
Richard Smith5745feb2019-06-17 21:08:30 +0000362 CharUnits ElemSize = getSize(C);
363 assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
364 replace(Elems, Index, Index + 1,
365 {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
366 replace(Offsets, Index, Index + 1, {Offset, Hint});
367 return true;
368 }
369
370 if (isa<llvm::UndefValue>(C)) {
371 replace(Elems, Index, Index + 1, {});
372 replace(Offsets, Index, Index + 1, {});
373 return true;
374 }
375
376 // FIXME: We could split a ConstantInt if the need ever arose.
377 // We don't need to do this to handle bit-fields because we always eagerly
378 // split them into 1-byte chunks.
379
380 return false;
381}
382
383static llvm::Constant *
384EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
385 llvm::Type *CommonElementType, unsigned ArrayBound,
386 SmallVectorImpl<llvm::Constant *> &Elements,
387 llvm::Constant *Filler);
388
389llvm::Constant *ConstantAggregateBuilder::buildFrom(
390 CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
391 ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
392 bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
393 ConstantAggregateBuilderUtils Utils(CGM);
394
395 if (Elems.empty())
396 return llvm::UndefValue::get(DesiredTy);
397
398 auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
399
400 // If we want an array type, see if all the elements are the same type and
401 // appropriately spaced.
402 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
403 assert(!AllowOversized && "oversized array emission not supported");
404
405 bool CanEmitArray = true;
406 llvm::Type *CommonType = Elems[0]->getType();
407 llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
408 CharUnits ElemSize = Utils.getSize(ATy->getElementType());
409 SmallVector<llvm::Constant*, 32> ArrayElements;
410 for (size_t I = 0; I != Elems.size(); ++I) {
411 // Skip zeroes; we'll use a zero value as our array filler.
412 if (Elems[I]->isNullValue())
413 continue;
414
415 // All remaining elements must be the same type.
416 if (Elems[I]->getType() != CommonType ||
417 Offset(I) % ElemSize != 0) {
418 CanEmitArray = false;
419 break;
420 }
421 ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
422 ArrayElements.back() = Elems[I];
423 }
424
425 if (CanEmitArray) {
426 return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
427 ArrayElements, Filler);
428 }
429
430 // Can't emit as an array, carry on to emit as a struct.
431 }
432
433 CharUnits DesiredSize = Utils.getSize(DesiredTy);
434 CharUnits Align = CharUnits::One();
435 for (llvm::Constant *C : Elems)
436 Align = std::max(Align, Utils.getAlignment(C));
437 CharUnits AlignedSize = Size.alignTo(Align);
438
439 bool Packed = false;
440 ArrayRef<llvm::Constant*> UnpackedElems = Elems;
441 llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
442 if ((DesiredSize < AlignedSize && !AllowOversized) ||
443 DesiredSize.alignTo(Align) != DesiredSize) {
444 // The natural layout would be the wrong size; force use of a packed layout.
445 NaturalLayout = false;
446 Packed = true;
447 } else if (DesiredSize > AlignedSize) {
448 // The constant would be too small. Add padding to fix it.
449 UnpackedElemStorage.assign(Elems.begin(), Elems.end());
450 UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
451 UnpackedElems = UnpackedElemStorage;
452 }
453
454 // If we don't have a natural layout, insert padding as necessary.
455 // As we go, double-check to see if we can actually just emit Elems
456 // as a non-packed struct and do so opportunistically if possible.
457 llvm::SmallVector<llvm::Constant*, 32> PackedElems;
458 if (!NaturalLayout) {
459 CharUnits SizeSoFar = CharUnits::Zero();
460 for (size_t I = 0; I != Elems.size(); ++I) {
461 CharUnits Align = Utils.getAlignment(Elems[I]);
462 CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
463 CharUnits DesiredOffset = Offset(I);
464 assert(DesiredOffset >= SizeSoFar && "elements out of order");
465
466 if (DesiredOffset != NaturalOffset)
467 Packed = true;
468 if (DesiredOffset != SizeSoFar)
469 PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
470 PackedElems.push_back(Elems[I]);
471 SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
472 }
473 // If we're using the packed layout, pad it out to the desired size if
474 // necessary.
475 if (Packed) {
476 assert((SizeSoFar <= DesiredSize || AllowOversized) &&
477 "requested size is too small for contents");
478 if (SizeSoFar < DesiredSize)
479 PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
480 }
481 }
482
483 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
484 CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
485
486 // Pick the type to use. If the type is layout identical to the desired
487 // type then use it, otherwise use whatever the builder produced for us.
488 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
489 if (DesiredSTy->isLayoutIdentical(STy))
490 STy = DesiredSTy;
491 }
492
493 return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
494}
495
496void ConstantAggregateBuilder::condense(CharUnits Offset,
497 llvm::Type *DesiredTy) {
498 CharUnits Size = getSize(DesiredTy);
499
500 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
501 if (!FirstElemToReplace)
502 return;
503 size_t First = *FirstElemToReplace;
504
505 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size);
506 if (!LastElemToReplace)
507 return;
508 size_t Last = *LastElemToReplace;
509
510 size_t Length = Last - First;
511 if (Length == 0)
512 return;
513
514 if (Length == 1 && Offsets[First] == Offset &&
515 getSize(Elems[First]) == Size) {
516 // Re-wrap single element structs if necessary. Otherwise, leave any single
517 // element constant of the right size alone even if it has the wrong type.
518 auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
519 if (STy && STy->getNumElements() == 1 &&
520 STy->getElementType(0) == Elems[First]->getType())
521 Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
522 return;
523 }
524
525 llvm::Constant *Replacement = buildFrom(
526 CGM, makeArrayRef(Elems).slice(First, Length),
527 makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
528 /*known to have natural layout=*/false, DesiredTy, false);
529 replace(Elems, First, Last, {Replacement});
530 replace(Offsets, First, Last, {Offset});
531}
532
533//===----------------------------------------------------------------------===//
534// ConstStructBuilder
535//===----------------------------------------------------------------------===//
536
537class ConstStructBuilder {
538 CodeGenModule &CGM;
539 ConstantEmitter &Emitter;
540 ConstantAggregateBuilder &Builder;
541 CharUnits StartOffset;
542
543public:
544 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
545 InitListExpr *ILE, QualType StructTy);
546 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
547 const APValue &Value, QualType ValTy);
548 static bool UpdateStruct(ConstantEmitter &Emitter,
549 ConstantAggregateBuilder &Const, CharUnits Offset,
550 InitListExpr *Updater);
551
552private:
553 ConstStructBuilder(ConstantEmitter &Emitter,
554 ConstantAggregateBuilder &Builder, CharUnits StartOffset)
555 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
556 StartOffset(StartOffset) {}
557
558 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
559 llvm::Constant *InitExpr, bool AllowOverwrite = false);
560
561 bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
562 bool AllowOverwrite = false);
563
564 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
565 llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
566
567 bool Build(InitListExpr *ILE, bool AllowOverwrite);
568 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
569 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
570 llvm::Constant *Finalize(QualType Ty);
571};
572
573bool ConstStructBuilder::AppendField(
574 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
575 bool AllowOverwrite) {
Ken Dyck1c80fd12011-03-15 01:09:02 +0000576 const ASTContext &Context = CGM.getContext();
577
578 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000579
Richard Smith5745feb2019-06-17 21:08:30 +0000580 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
Richard Smithc8998922012-02-23 08:33:23 +0000581}
582
Richard Smith5745feb2019-06-17 21:08:30 +0000583bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
584 llvm::Constant *InitCst,
585 bool AllowOverwrite) {
586 return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000587}
588
Richard Smith5745feb2019-06-17 21:08:30 +0000589bool ConstStructBuilder::AppendBitField(
590 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
591 bool AllowOverwrite) {
592 uint64_t FieldSize = Field->getBitWidthValue(CGM.getContext());
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000593 llvm::APInt FieldValue = CI->getValue();
594
595 // Promote the size of FieldValue if necessary
596 // FIXME: This should never occur, but currently it can because initializer
597 // constants are cast to bool, and because clang is not enforcing bitfield
598 // width limits.
599 if (FieldSize > FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000600 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000601
602 // Truncate the size of FieldValue to the bit field size.
603 if (FieldSize < FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000604 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000605
Richard Smith5745feb2019-06-17 21:08:30 +0000606 return Builder.addBits(FieldValue,
607 CGM.getContext().toBits(StartOffset) + FieldOffset,
608 AllowOverwrite);
609}
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000610
Richard Smith5745feb2019-06-17 21:08:30 +0000611static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
612 ConstantAggregateBuilder &Const,
613 CharUnits Offset, QualType Type,
614 InitListExpr *Updater) {
615 if (Type->isRecordType())
616 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000617
Richard Smith5745feb2019-06-17 21:08:30 +0000618 auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
619 if (!CAT)
620 return false;
621 QualType ElemType = CAT->getElementType();
622 CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
623 llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000624
Richard Smith5745feb2019-06-17 21:08:30 +0000625 llvm::Constant *FillC = nullptr;
626 if (Expr *Filler = Updater->getArrayFiller()) {
627 if (!isa<NoInitExpr>(Filler)) {
628 FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
629 if (!FillC)
630 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000631 }
Richard Smith5745feb2019-06-17 21:08:30 +0000632 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000633
Richard Smith5745feb2019-06-17 21:08:30 +0000634 unsigned NumElementsToUpdate =
635 FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits();
636 for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
637 Expr *Init = nullptr;
638 if (I < Updater->getNumInits())
639 Init = Updater->getInit(I);
640
641 if (!Init && FillC) {
642 if (!Const.add(FillC, Offset, true))
643 return false;
644 } else if (!Init || isa<NoInitExpr>(Init)) {
645 continue;
646 } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
647 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
648 ChildILE))
649 return false;
650 // Attempt to reduce the array element to a single constant if necessary.
651 Const.condense(Offset, ElemTy);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000652 } else {
Richard Smith5745feb2019-06-17 21:08:30 +0000653 llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
654 if (!Const.add(Val, Offset, true))
655 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000656 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000657 }
658
Richard Smith5745feb2019-06-17 21:08:30 +0000659 return true;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000660}
661
Richard Smith5745feb2019-06-17 21:08:30 +0000662bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000663 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000664 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
665
Richard Smith5745feb2019-06-17 21:08:30 +0000666 unsigned FieldNo = -1;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000667 unsigned ElementNo = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000668
669 // Bail out if we have base classes. We could support these, but they only
670 // arise in C++1z where we will have already constant folded most interesting
671 // cases. FIXME: There are still a few more cases we can handle this way.
672 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
673 if (CXXRD->getNumBases())
674 return false;
675
Richard Smith5745feb2019-06-17 21:08:30 +0000676 for (FieldDecl *Field : RD->fields()) {
677 ++FieldNo;
678
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000679 // If this is a union, skip all the fields that aren't being initialized.
Richard Smith78b239e2019-06-20 20:44:45 +0000680 if (RD->isUnion() &&
681 !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000682 continue;
683
Richard Smith78b239e2019-06-20 20:44:45 +0000684 // Don't emit anonymous bitfields or zero-sized fields.
685 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000686 continue;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000687
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000688 // Get the initializer. A struct can include fields without initializers,
689 // we just use explicit null values for them.
Richard Smith5745feb2019-06-17 21:08:30 +0000690 Expr *Init = nullptr;
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000691 if (ElementNo < ILE->getNumInits())
Richard Smith5745feb2019-06-17 21:08:30 +0000692 Init = ILE->getInit(ElementNo++);
693 if (Init && isa<NoInitExpr>(Init))
694 continue;
Eli Friedman3ee10222010-07-17 23:55:01 +0000695
Richard Smith5745feb2019-06-17 21:08:30 +0000696 // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
697 // represents additional overwriting of our current constant value, and not
698 // a new constant to emit independently.
699 if (AllowOverwrite &&
700 (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
701 if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
702 CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
703 Layout.getFieldOffset(FieldNo));
704 if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
705 Field->getType(), SubILE))
706 return false;
707 // If we split apart the field's value, try to collapse it down to a
708 // single value now.
709 Builder.condense(StartOffset + Offset,
710 CGM.getTypes().ConvertTypeForMem(Field->getType()));
711 continue;
712 }
713 }
714
715 llvm::Constant *EltInit =
716 Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
717 : Emitter.emitNullForMemory(Field->getType());
Eli Friedman3ee10222010-07-17 23:55:01 +0000718 if (!EltInit)
719 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000720
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000721 if (!Field->isBitField()) {
722 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000723 if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
724 AllowOverwrite))
725 return false;
Richard Smith78b239e2019-06-20 20:44:45 +0000726 // After emitting a non-empty field with [[no_unique_address]], we may
727 // need to overwrite its tail padding.
728 if (Field->hasAttr<NoUniqueAddressAttr>())
729 AllowOverwrite = true;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000730 } else {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000731 // Otherwise we have a bitfield.
David Majnemer8062eb62015-03-14 22:24:38 +0000732 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
Richard Smith5745feb2019-06-17 21:08:30 +0000733 if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
734 AllowOverwrite))
735 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000736 } else {
737 // We are trying to initialize a bitfield with a non-trivial constant,
738 // this must require run-time code.
739 return false;
740 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000741 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000742 }
743
Richard Smithdafff942012-01-14 04:30:29 +0000744 return true;
745}
746
Richard Smithc8998922012-02-23 08:33:23 +0000747namespace {
748struct BaseInfo {
749 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
750 : Decl(Decl), Offset(Offset), Index(Index) {
751 }
752
753 const CXXRecordDecl *Decl;
754 CharUnits Offset;
755 unsigned Index;
756
757 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
758};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000759}
Richard Smithc8998922012-02-23 08:33:23 +0000760
John McCallde0fe072017-08-15 21:42:52 +0000761bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000762 bool IsPrimaryBase,
Richard Smithc8998922012-02-23 08:33:23 +0000763 const CXXRecordDecl *VTableClass,
764 CharUnits Offset) {
Richard Smithdafff942012-01-14 04:30:29 +0000765 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
766
Richard Smithc8998922012-02-23 08:33:23 +0000767 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
768 // Add a vtable pointer, if we need one and it hasn't already been added.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000769 if (CD->isDynamicClass() && !IsPrimaryBase) {
770 llvm::Constant *VTableAddressPoint =
771 CGM.getCXXABI().getVTableAddressPointForConstExpr(
772 BaseSubobject(CD, Offset), VTableClass);
Richard Smith5745feb2019-06-17 21:08:30 +0000773 if (!AppendBytes(Offset, VTableAddressPoint))
774 return false;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000775 }
Richard Smithc8998922012-02-23 08:33:23 +0000776
777 // Accumulate and sort bases, in order to visit them in address order, which
778 // may not be the same as declaration order.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000779 SmallVector<BaseInfo, 8> Bases;
Richard Smithc8998922012-02-23 08:33:23 +0000780 Bases.reserve(CD->getNumBases());
Richard Smithdafff942012-01-14 04:30:29 +0000781 unsigned BaseNo = 0;
Richard Smithc8998922012-02-23 08:33:23 +0000782 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
Richard Smithdafff942012-01-14 04:30:29 +0000783 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
Richard Smithc8998922012-02-23 08:33:23 +0000784 assert(!Base->isVirtual() && "should not have virtual bases here");
Richard Smithdafff942012-01-14 04:30:29 +0000785 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
786 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Richard Smithc8998922012-02-23 08:33:23 +0000787 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
788 }
Fangrui Song899d1392019-04-24 14:43:05 +0000789 llvm::stable_sort(Bases);
Richard Smithdafff942012-01-14 04:30:29 +0000790
Richard Smithc8998922012-02-23 08:33:23 +0000791 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
792 BaseInfo &Base = Bases[I];
Richard Smithdafff942012-01-14 04:30:29 +0000793
Richard Smithc8998922012-02-23 08:33:23 +0000794 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
795 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000796 VTableClass, Offset + Base.Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000797 }
798 }
799
800 unsigned FieldNo = 0;
Eli Friedmana154dd52012-03-30 03:55:31 +0000801 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000802
Richard Smith78b239e2019-06-20 20:44:45 +0000803 bool AllowOverwrite = false;
Richard Smithdafff942012-01-14 04:30:29 +0000804 for (RecordDecl::field_iterator Field = RD->field_begin(),
805 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Richard Smithdafff942012-01-14 04:30:29 +0000806 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie275a55c2019-05-22 20:36:06 +0000807 if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
Richard Smithdafff942012-01-14 04:30:29 +0000808 continue;
809
Richard Smith78b239e2019-06-20 20:44:45 +0000810 // Don't emit anonymous bitfields or zero-sized fields.
811 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
Richard Smithdafff942012-01-14 04:30:29 +0000812 continue;
Richard Smithdafff942012-01-14 04:30:29 +0000813
814 // Emit the value of the initializer.
815 const APValue &FieldValue =
816 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
817 llvm::Constant *EltInit =
John McCallde0fe072017-08-15 21:42:52 +0000818 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
819 if (!EltInit)
820 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000821
822 if (!Field->isBitField()) {
823 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000824 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smith78b239e2019-06-20 20:44:45 +0000825 EltInit, AllowOverwrite))
Richard Smith5745feb2019-06-17 21:08:30 +0000826 return false;
Richard Smith78b239e2019-06-20 20:44:45 +0000827 // After emitting a non-empty field with [[no_unique_address]], we may
828 // need to overwrite its tail padding.
829 if (Field->hasAttr<NoUniqueAddressAttr>())
830 AllowOverwrite = true;
Richard Smithdafff942012-01-14 04:30:29 +0000831 } else {
832 // Otherwise we have a bitfield.
Richard Smith5745feb2019-06-17 21:08:30 +0000833 if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smith78b239e2019-06-20 20:44:45 +0000834 cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
Richard Smith5745feb2019-06-17 21:08:30 +0000835 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000836 }
837 }
John McCallde0fe072017-08-15 21:42:52 +0000838
839 return true;
Richard Smithdafff942012-01-14 04:30:29 +0000840}
841
Richard Smith5745feb2019-06-17 21:08:30 +0000842llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000843 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
Richard Smith5745feb2019-06-17 21:08:30 +0000844 llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
845 return Builder.build(ValTy, RD->hasFlexibleArrayMember());
Yunzhong Gaocb779302015-06-10 00:27:52 +0000846}
847
John McCallde0fe072017-08-15 21:42:52 +0000848llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
849 InitListExpr *ILE,
850 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000851 ConstantAggregateBuilder Const(Emitter.CGM);
852 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithdafff942012-01-14 04:30:29 +0000853
Richard Smith5745feb2019-06-17 21:08:30 +0000854 if (!Builder.Build(ILE, /*AllowOverwrite*/false))
Craig Topper8a13c412014-05-21 05:09:00 +0000855 return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +0000856
John McCallde0fe072017-08-15 21:42:52 +0000857 return Builder.Finalize(ValTy);
Richard Smithdafff942012-01-14 04:30:29 +0000858}
859
John McCallde0fe072017-08-15 21:42:52 +0000860llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +0000861 const APValue &Val,
862 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000863 ConstantAggregateBuilder Const(Emitter.CGM);
864 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithc8998922012-02-23 08:33:23 +0000865
866 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
867 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
John McCallde0fe072017-08-15 21:42:52 +0000868 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
869 return nullptr;
Richard Smithc8998922012-02-23 08:33:23 +0000870
Richard Smithdafff942012-01-14 04:30:29 +0000871 return Builder.Finalize(ValTy);
872}
873
Richard Smith5745feb2019-06-17 21:08:30 +0000874bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
875 ConstantAggregateBuilder &Const,
876 CharUnits Offset, InitListExpr *Updater) {
877 return ConstStructBuilder(Emitter, Const, Offset)
878 .Build(Updater, /*AllowOverwrite*/ true);
879}
Richard Smithdafff942012-01-14 04:30:29 +0000880
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000881//===----------------------------------------------------------------------===//
882// ConstExprEmitter
883//===----------------------------------------------------------------------===//
Richard Smithdd5bdd82012-01-17 21:42:19 +0000884
John McCallde0fe072017-08-15 21:42:52 +0000885static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
886 CodeGenFunction *CGF,
887 const CompoundLiteralExpr *E) {
888 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
889 if (llvm::GlobalVariable *Addr =
890 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
891 return ConstantAddress(Addr, Align);
892
Alexander Richardson6d989432017-10-15 18:48:14 +0000893 LangAS addressSpace = E->getType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000894
895 ConstantEmitter emitter(CGM, CGF);
896 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
897 addressSpace, E->getType());
898 if (!C) {
899 assert(!E->isFileScope() &&
900 "file-scope compound literal did not have constant initializer!");
901 return ConstantAddress::invalid();
902 }
903
904 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
905 CGM.isTypeConstant(E->getType(), true),
906 llvm::GlobalValue::InternalLinkage,
907 C, ".compoundliteral", nullptr,
908 llvm::GlobalVariable::NotThreadLocal,
909 CGM.getContext().getTargetAddressSpace(addressSpace));
910 emitter.finalize(GV);
Guillaume Chateletc79099e2019-10-03 13:00:29 +0000911 GV->setAlignment(Align.getAsAlign());
John McCallde0fe072017-08-15 21:42:52 +0000912 CGM.setAddrOfConstantCompoundLiteral(E, GV);
913 return ConstantAddress(GV, Align);
914}
915
Richard Smith3e268632018-05-23 23:41:38 +0000916static llvm::Constant *
Richard Smith5745feb2019-06-17 21:08:30 +0000917EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
Richard Smith3e268632018-05-23 23:41:38 +0000918 llvm::Type *CommonElementType, unsigned ArrayBound,
919 SmallVectorImpl<llvm::Constant *> &Elements,
920 llvm::Constant *Filler) {
921 // Figure out how long the initial prefix of non-zero elements is.
922 unsigned NonzeroLength = ArrayBound;
923 if (Elements.size() < NonzeroLength && Filler->isNullValue())
924 NonzeroLength = Elements.size();
925 if (NonzeroLength == Elements.size()) {
926 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
927 --NonzeroLength;
928 }
929
Richard Smith5745feb2019-06-17 21:08:30 +0000930 if (NonzeroLength == 0)
931 return llvm::ConstantAggregateZero::get(DesiredType);
Richard Smith3e268632018-05-23 23:41:38 +0000932
933 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
934 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
935 if (TrailingZeroes >= 8) {
936 assert(Elements.size() >= NonzeroLength &&
937 "missing initializer for non-zero element");
Richard Smith83497d92018-07-19 21:38:56 +0000938
939 // If all the elements had the same type up to the trailing zeroes, emit a
940 // struct of two arrays (the nonzero data and the zeroinitializer).
941 if (CommonElementType && NonzeroLength >= 8) {
942 llvm::Constant *Initial = llvm::ConstantArray::get(
Richard Smith4c656882018-07-19 23:24:41 +0000943 llvm::ArrayType::get(CommonElementType, NonzeroLength),
Richard Smith83497d92018-07-19 21:38:56 +0000944 makeArrayRef(Elements).take_front(NonzeroLength));
945 Elements.resize(2);
946 Elements[0] = Initial;
947 } else {
948 Elements.resize(NonzeroLength + 1);
949 }
950
Richard Smith3e268632018-05-23 23:41:38 +0000951 auto *FillerType =
Richard Smith5745feb2019-06-17 21:08:30 +0000952 CommonElementType ? CommonElementType : DesiredType->getElementType();
Richard Smith3e268632018-05-23 23:41:38 +0000953 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
954 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
955 CommonElementType = nullptr;
956 } else if (Elements.size() != ArrayBound) {
957 // Otherwise pad to the right size with the filler if necessary.
958 Elements.resize(ArrayBound, Filler);
959 if (Filler->getType() != CommonElementType)
960 CommonElementType = nullptr;
961 }
962
963 // If all elements have the same type, just emit an array constant.
964 if (CommonElementType)
965 return llvm::ConstantArray::get(
966 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
967
968 // We have mixed types. Use a packed struct.
969 llvm::SmallVector<llvm::Type *, 16> Types;
970 Types.reserve(Elements.size());
971 for (llvm::Constant *Elt : Elements)
972 Types.push_back(Elt->getType());
973 llvm::StructType *SType =
974 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
975 return llvm::ConstantStruct::get(SType, Elements);
976}
977
Eli Friedman7f98e3c2019-02-08 21:36:04 +0000978// This class only needs to handle arrays, structs and unions. Outside C++11
979// mode, we don't currently constant fold those types. All other types are
980// handled by constant folding.
981//
982// Constant folding is currently missing support for a few features supported
983// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000984class ConstExprEmitter :
John McCallde0fe072017-08-15 21:42:52 +0000985 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
Anders Carlsson610ee712008-01-26 01:36:00 +0000986 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +0000987 ConstantEmitter &Emitter;
Owen Anderson170229f2009-07-14 23:10:40 +0000988 llvm::LLVMContext &VMContext;
Anders Carlsson610ee712008-01-26 01:36:00 +0000989public:
John McCallde0fe072017-08-15 21:42:52 +0000990 ConstExprEmitter(ConstantEmitter &emitter)
991 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
Anders Carlsson610ee712008-01-26 01:36:00 +0000992 }
Mike Stump11289f42009-09-09 15:08:12 +0000993
Anders Carlsson610ee712008-01-26 01:36:00 +0000994 //===--------------------------------------------------------------------===//
995 // Visitor Methods
996 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000997
John McCallde0fe072017-08-15 21:42:52 +0000998 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
Craig Topper8a13c412014-05-21 05:09:00 +0000999 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +00001000 }
Mike Stump11289f42009-09-09 15:08:12 +00001001
Bill Wendling8003edc2018-11-09 00:41:36 +00001002 llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
1003 return Visit(CE->getSubExpr(), T);
1004 }
1005
John McCallde0fe072017-08-15 21:42:52 +00001006 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
1007 return Visit(PE->getSubExpr(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +00001008 }
Mike Stump11289f42009-09-09 15:08:12 +00001009
John McCall7c454bb2011-07-15 05:09:51 +00001010 llvm::Constant *
John McCallde0fe072017-08-15 21:42:52 +00001011 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
1012 QualType T) {
1013 return Visit(PE->getReplacement(), T);
John McCall7c454bb2011-07-15 05:09:51 +00001014 }
1015
John McCallde0fe072017-08-15 21:42:52 +00001016 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
1017 QualType T) {
1018 return Visit(GE->getResultExpr(), T);
Peter Collingbourne91147592011-04-15 00:35:48 +00001019 }
1020
John McCallde0fe072017-08-15 21:42:52 +00001021 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
1022 return Visit(CE->getChosenSubExpr(), T);
Eli Friedman4c27ac22013-07-16 22:40:53 +00001023 }
1024
John McCallde0fe072017-08-15 21:42:52 +00001025 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
1026 return Visit(E->getInitializer(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +00001027 }
John McCallf3a88602011-02-03 08:15:49 +00001028
John McCallde0fe072017-08-15 21:42:52 +00001029 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001030 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
John McCallde0fe072017-08-15 21:42:52 +00001031 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
John McCall2de87f62011-03-15 21:17:48 +00001032 Expr *subExpr = E->getSubExpr();
John McCall2de87f62011-03-15 21:17:48 +00001033
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001034 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00001035 case CK_ToUnion: {
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001036 // GCC cast to union extension
1037 assert(E->getType()->isUnionType() &&
1038 "Destination type is not union type!");
Mike Stump11289f42009-09-09 15:08:12 +00001039
John McCallde0fe072017-08-15 21:42:52 +00001040 auto field = E->getTargetUnionField();
1041
1042 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1043 if (!C) return nullptr;
1044
1045 auto destTy = ConvertType(destType);
1046 if (C->getType() == destTy) return C;
1047
Anders Carlssond65ab042009-07-31 21:38:39 +00001048 // Build a struct with the union sub-element as the first member,
John McCallde0fe072017-08-15 21:42:52 +00001049 // and padded to the appropriate size.
Bill Wendling99729582012-02-07 00:13:27 +00001050 SmallVector<llvm::Constant*, 2> Elts;
1051 SmallVector<llvm::Type*, 2> Types;
Anders Carlssond65ab042009-07-31 21:38:39 +00001052 Elts.push_back(C);
1053 Types.push_back(C->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00001054 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
John McCallde0fe072017-08-15 21:42:52 +00001055 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
Mike Stump11289f42009-09-09 15:08:12 +00001056
Anders Carlssond65ab042009-07-31 21:38:39 +00001057 assert(CurSize <= TotalSize && "Union size mismatch!");
1058 if (unsigned NumPadBytes = TotalSize - CurSize) {
Chris Lattnerece04092012-02-07 00:39:47 +00001059 llvm::Type *Ty = CGM.Int8Ty;
Anders Carlssond65ab042009-07-31 21:38:39 +00001060 if (NumPadBytes > 1)
1061 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001062
Nuno Lopes5863c992010-04-16 20:56:35 +00001063 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssond65ab042009-07-31 21:38:39 +00001064 Types.push_back(Ty);
1065 }
Mike Stump11289f42009-09-09 15:08:12 +00001066
John McCallde0fe072017-08-15 21:42:52 +00001067 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
Anders Carlssond65ab042009-07-31 21:38:39 +00001068 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes4d78cf02009-01-17 00:48:48 +00001069 }
Anders Carlsson9500ad12009-10-18 20:31:03 +00001070
John McCallde0fe072017-08-15 21:42:52 +00001071 case CK_AddressSpaceConversion: {
1072 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1073 if (!C) return nullptr;
Alexander Richardson6d989432017-10-15 18:48:14 +00001074 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1075 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +00001076 llvm::Type *destTy = ConvertType(E->getType());
1077 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1078 destAS, destTy);
1079 }
David Tweede1468322013-12-11 13:39:46 +00001080
John McCall2de87f62011-03-15 21:17:48 +00001081 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00001082 case CK_AtomicToNonAtomic:
1083 case CK_NonAtomicToAtomic:
John McCall2de87f62011-03-15 21:17:48 +00001084 case CK_NoOp:
Eli Friedman4c27ac22013-07-16 22:40:53 +00001085 case CK_ConstructorConversion:
John McCallde0fe072017-08-15 21:42:52 +00001086 return Visit(subExpr, destType);
Anders Carlsson9500ad12009-10-18 20:31:03 +00001087
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001088 case CK_IntToOCLSampler:
1089 llvm_unreachable("global sampler variables are not generated");
1090
John McCall2de87f62011-03-15 21:17:48 +00001091 case CK_Dependent: llvm_unreachable("saw dependent cast!");
1092
Eli Friedman34866c72012-08-31 00:14:07 +00001093 case CK_BuiltinFnToFnPtr:
1094 llvm_unreachable("builtin functions are handled elsewhere");
1095
John McCallc62bb392012-02-15 01:22:51 +00001096 case CK_ReinterpretMemberPointer:
1097 case CK_DerivedToBaseMemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00001098 case CK_BaseToDerivedMemberPointer: {
1099 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1100 if (!C) return nullptr;
John McCallc62bb392012-02-15 01:22:51 +00001101 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
John McCallde0fe072017-08-15 21:42:52 +00001102 }
John McCallc62bb392012-02-15 01:22:51 +00001103
John McCall2de87f62011-03-15 21:17:48 +00001104 // These will never be supported.
1105 case CK_ObjCObjectLValueCast:
John McCall2d637d22011-09-10 06:18:15 +00001106 case CK_ARCProduceObject:
1107 case CK_ARCConsumeObject:
1108 case CK_ARCReclaimReturnedObject:
1109 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00001110 case CK_CopyAndAutoreleaseBlockObject:
Craig Topper8a13c412014-05-21 05:09:00 +00001111 return nullptr;
John McCall2de87f62011-03-15 21:17:48 +00001112
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001113 // These don't need to be handled here because Evaluate knows how to
Richard Smithdd5bdd82012-01-17 21:42:19 +00001114 // evaluate them in the cases where they can be folded.
John McCallc62bb392012-02-15 01:22:51 +00001115 case CK_BitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001116 case CK_ToVoid:
1117 case CK_Dynamic:
1118 case CK_LValueBitCast:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00001119 case CK_LValueToRValueBitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001120 case CK_NullToMemberPointer:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001121 case CK_UserDefinedConversion:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001122 case CK_CPointerToObjCPointerCast:
1123 case CK_BlockPointerToObjCPointerCast:
1124 case CK_AnyPointerToBlockPointerCast:
John McCall2de87f62011-03-15 21:17:48 +00001125 case CK_ArrayToPointerDecay:
1126 case CK_FunctionToPointerDecay:
1127 case CK_BaseToDerived:
1128 case CK_DerivedToBase:
1129 case CK_UncheckedDerivedToBase:
1130 case CK_MemberPointerToBoolean:
1131 case CK_VectorSplat:
1132 case CK_FloatingRealToComplex:
1133 case CK_FloatingComplexToReal:
1134 case CK_FloatingComplexToBoolean:
1135 case CK_FloatingComplexCast:
1136 case CK_FloatingComplexToIntegralComplex:
1137 case CK_IntegralRealToComplex:
1138 case CK_IntegralComplexToReal:
1139 case CK_IntegralComplexToBoolean:
1140 case CK_IntegralComplexCast:
1141 case CK_IntegralComplexToFloatingComplex:
John McCall2de87f62011-03-15 21:17:48 +00001142 case CK_PointerToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001143 case CK_PointerToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001144 case CK_NullToPointer:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001145 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001146 case CK_BooleanToSignedIntegral:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001147 case CK_IntegralToPointer:
John McCall2de87f62011-03-15 21:17:48 +00001148 case CK_IntegralToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001149 case CK_IntegralToFloating:
John McCall2de87f62011-03-15 21:17:48 +00001150 case CK_FloatingToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001151 case CK_FloatingToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001152 case CK_FloatingCast:
Leonard Chan99bda372018-10-15 16:07:02 +00001153 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001154 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001155 case CK_FixedPointToIntegral:
1156 case CK_IntegralToFixedPoint:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001157 case CK_ZeroToOCLOpaqueType:
Craig Topper8a13c412014-05-21 05:09:00 +00001158 return nullptr;
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001159 }
Matt Beaumont-Gay145e2eb2011-03-17 00:46:34 +00001160 llvm_unreachable("Invalid CastKind");
Anders Carlsson610ee712008-01-26 01:36:00 +00001161 }
Devang Patela703a672008-02-05 02:39:50 +00001162
John McCallde0fe072017-08-15 21:42:52 +00001163 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
Richard Smith852c9db2013-04-20 22:23:05 +00001164 // No need for a DefaultInitExprScope: we don't handle 'this' in a
1165 // constant expression.
John McCallde0fe072017-08-15 21:42:52 +00001166 return Visit(DIE->getExpr(), T);
Richard Smith852c9db2013-04-20 22:23:05 +00001167 }
1168
John McCallde0fe072017-08-15 21:42:52 +00001169 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
Akira Hatanakad35a4542019-11-20 18:13:44 -08001170 return Visit(E->getSubExpr(), T);
Tim Shen4a05bb82016-06-21 20:29:17 +00001171 }
1172
John McCallde0fe072017-08-15 21:42:52 +00001173 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
1174 QualType T) {
Tykerb0561b32019-11-17 11:41:55 +01001175 return Visit(E->getSubExpr(), T);
Douglas Gregorfe314812011-06-21 17:03:29 +00001176 }
1177
John McCallde0fe072017-08-15 21:42:52 +00001178 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
Richard Smith3e268632018-05-23 23:41:38 +00001179 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
1180 assert(CAT && "can't emit array init for non-constant-bound array");
Richard Smith9ec1e482012-04-15 02:50:59 +00001181 unsigned NumInitElements = ILE->getNumInits();
Richard Smith3e268632018-05-23 23:41:38 +00001182 unsigned NumElements = CAT->getSize().getZExtValue();
Devang Patela703a672008-02-05 02:39:50 +00001183
Mike Stump11289f42009-09-09 15:08:12 +00001184 // Initialising an array requires us to automatically
Devang Patela703a672008-02-05 02:39:50 +00001185 // initialise any elements that have not been initialised explicitly
1186 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
1187
Richard Smith3e268632018-05-23 23:41:38 +00001188 QualType EltType = CAT->getElementType();
John McCallde0fe072017-08-15 21:42:52 +00001189
David Majnemer90d85442014-12-28 23:46:59 +00001190 // Initialize remaining array elements.
Richard Smith3e268632018-05-23 23:41:38 +00001191 llvm::Constant *fillC = nullptr;
1192 if (Expr *filler = ILE->getArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00001193 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
Richard Smith3e268632018-05-23 23:41:38 +00001194 if (!fillC)
1195 return nullptr;
1196 }
David Majnemer90d85442014-12-28 23:46:59 +00001197
Devang Patela703a672008-02-05 02:39:50 +00001198 // Copy initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00001199 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00001200 if (fillC && fillC->isNullValue())
1201 Elts.reserve(NumInitableElts + 1);
1202 else
1203 Elts.reserve(NumElements);
Benjamin Kramer8001f742012-02-14 12:06:21 +00001204
Richard Smith3e268632018-05-23 23:41:38 +00001205 llvm::Type *CommonElementType = nullptr;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001206 for (unsigned i = 0; i < NumInitableElts; ++i) {
Anders Carlsson80f97ab2009-04-08 04:48:15 +00001207 Expr *Init = ILE->getInit(i);
John McCallde0fe072017-08-15 21:42:52 +00001208 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
Daniel Dunbar38ad1e62009-02-17 18:43:32 +00001209 if (!C)
Craig Topper8a13c412014-05-21 05:09:00 +00001210 return nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00001211 if (i == 0)
1212 CommonElementType = C->getType();
1213 else if (C->getType() != CommonElementType)
1214 CommonElementType = nullptr;
Devang Patela703a672008-02-05 02:39:50 +00001215 Elts.push_back(C);
1216 }
Eli Friedman34994cb2008-05-30 19:58:50 +00001217
Richard Smith5745feb2019-06-17 21:08:30 +00001218 llvm::ArrayType *Desired =
1219 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
1220 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00001221 fillC);
Devang Patela703a672008-02-05 02:39:50 +00001222 }
1223
John McCallde0fe072017-08-15 21:42:52 +00001224 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
1225 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001226 }
1227
John McCallde0fe072017-08-15 21:42:52 +00001228 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
1229 QualType T) {
1230 return CGM.EmitNullConstant(T);
Anders Carlsson02714ed2009-01-30 06:13:25 +00001231 }
Mike Stump11289f42009-09-09 15:08:12 +00001232
John McCallde0fe072017-08-15 21:42:52 +00001233 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
Richard Smith122f88d2016-12-06 23:52:28 +00001234 if (ILE->isTransparent())
John McCallde0fe072017-08-15 21:42:52 +00001235 return Visit(ILE->getInit(0), T);
Richard Smith122f88d2016-12-06 23:52:28 +00001236
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001237 if (ILE->getType()->isArrayType())
John McCallde0fe072017-08-15 21:42:52 +00001238 return EmitArrayInitialization(ILE, T);
Devang Patel45a65d22008-01-29 23:23:18 +00001239
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001240 if (ILE->getType()->isRecordType())
John McCallde0fe072017-08-15 21:42:52 +00001241 return EmitRecordInitialization(ILE, T);
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001242
Craig Topper8a13c412014-05-21 05:09:00 +00001243 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +00001244 }
Eli Friedmana2433112008-02-21 17:57:49 +00001245
John McCallde0fe072017-08-15 21:42:52 +00001246 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1247 QualType destType) {
1248 auto C = Visit(E->getBase(), destType);
Richard Smith5745feb2019-06-17 21:08:30 +00001249 if (!C)
1250 return nullptr;
1251
1252 ConstantAggregateBuilder Const(CGM);
1253 Const.add(C, CharUnits::Zero(), false);
1254
1255 if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
1256 E->getUpdater()))
1257 return nullptr;
1258
1259 llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
1260 bool HasFlexibleArray = false;
1261 if (auto *RT = destType->getAs<RecordType>())
1262 HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1263 return Const.build(ValTy, HasFlexibleArray);
Fangrui Song6907ce22018-07-30 19:24:48 +00001264 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00001265
John McCallde0fe072017-08-15 21:42:52 +00001266 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
John McCall49786a62010-02-02 08:02:49 +00001267 if (!E->getConstructor()->isTrivial())
Craig Topper8a13c412014-05-21 05:09:00 +00001268 return nullptr;
John McCall49786a62010-02-02 08:02:49 +00001269
Richard Smith96c89942020-02-06 16:19:37 -08001270 // Only default and copy/move constructors can be trivial.
John McCall49786a62010-02-02 08:02:49 +00001271 if (E->getNumArgs()) {
1272 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001273 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1274 "trivial ctor has argument but isn't a copy/move ctor");
John McCall49786a62010-02-02 08:02:49 +00001275
1276 Expr *Arg = E->getArg(0);
1277 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1278 "argument to copy ctor is of wrong type");
1279
John McCallde0fe072017-08-15 21:42:52 +00001280 return Visit(Arg, Ty);
John McCall49786a62010-02-02 08:02:49 +00001281 }
1282
1283 return CGM.EmitNullConstant(Ty);
1284 }
1285
John McCallde0fe072017-08-15 21:42:52 +00001286 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001287 // This is a string literal initializing an array in an initializer.
Eli Friedmanfcec6302011-11-01 02:23:42 +00001288 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson610ee712008-01-26 01:36:00 +00001289 }
1290
John McCallde0fe072017-08-15 21:42:52 +00001291 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001292 // This must be an @encode initializing an array in a static initializer.
1293 // Don't emit it as the address of the string, emit the string data itself
1294 // as an inline array.
1295 std::string Str;
1296 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
John McCallde0fe072017-08-15 21:42:52 +00001297 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00001298
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001299 // Resize the string to the right size, adding zeros at the end, or
1300 // truncating as needed.
1301 Str.resize(CAT->getSize().getZExtValue(), '\0');
Chris Lattner9c818332012-02-05 02:30:40 +00001302 return llvm::ConstantDataArray::getString(VMContext, Str, false);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001303 }
Mike Stump11289f42009-09-09 15:08:12 +00001304
John McCallde0fe072017-08-15 21:42:52 +00001305 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1306 return Visit(E->getSubExpr(), T);
Eli Friedman045bf4f2008-05-29 11:22:45 +00001307 }
Mike Stumpa6703322009-02-19 22:01:56 +00001308
Anders Carlsson610ee712008-01-26 01:36:00 +00001309 // Utility methods
Chris Lattner2192fe52011-07-18 04:24:23 +00001310 llvm::Type *ConvertType(QualType T) {
Anders Carlsson610ee712008-01-26 01:36:00 +00001311 return CGM.getTypes().ConvertType(T);
1312 }
Anders Carlssona4139112008-01-26 02:08:50 +00001313};
Mike Stump11289f42009-09-09 15:08:12 +00001314
Anders Carlsson610ee712008-01-26 01:36:00 +00001315} // end anonymous namespace.
1316
John McCallde0fe072017-08-15 21:42:52 +00001317llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1318 AbstractState saved) {
1319 Abstract = saved.OldValue;
1320
1321 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1322 "created a placeholder while doing an abstract emission?");
1323
1324 // No validation necessary for now.
1325 // No cleanup to do for now.
1326 return C;
1327}
1328
1329llvm::Constant *
1330ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1331 auto state = pushAbstract();
1332 auto C = tryEmitPrivateForVarInit(D);
1333 return validateAndPopAbstract(C, state);
1334}
1335
1336llvm::Constant *
1337ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1338 auto state = pushAbstract();
1339 auto C = tryEmitPrivate(E, destType);
1340 return validateAndPopAbstract(C, state);
1341}
1342
1343llvm::Constant *
1344ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1345 auto state = pushAbstract();
1346 auto C = tryEmitPrivate(value, destType);
1347 return validateAndPopAbstract(C, state);
1348}
1349
1350llvm::Constant *
1351ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1352 auto state = pushAbstract();
1353 auto C = tryEmitPrivate(E, destType);
1354 C = validateAndPopAbstract(C, state);
1355 if (!C) {
1356 CGM.Error(E->getExprLoc(),
1357 "internal error: could not emit constant value \"abstractly\"");
1358 C = CGM.EmitNullConstant(destType);
1359 }
1360 return C;
1361}
1362
1363llvm::Constant *
1364ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1365 QualType destType) {
1366 auto state = pushAbstract();
1367 auto C = tryEmitPrivate(value, destType);
1368 C = validateAndPopAbstract(C, state);
1369 if (!C) {
1370 CGM.Error(loc,
1371 "internal error: could not emit constant value \"abstractly\"");
1372 C = CGM.EmitNullConstant(destType);
1373 }
1374 return C;
1375}
1376
1377llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1378 initializeNonAbstract(D.getType().getAddressSpace());
1379 return markIfFailed(tryEmitPrivateForVarInit(D));
1380}
1381
1382llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
Alexander Richardson6d989432017-10-15 18:48:14 +00001383 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001384 QualType destType) {
1385 initializeNonAbstract(destAddrSpace);
1386 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1387}
1388
1389llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
Alexander Richardson6d989432017-10-15 18:48:14 +00001390 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001391 QualType destType) {
1392 initializeNonAbstract(destAddrSpace);
1393 auto C = tryEmitPrivateForMemory(value, destType);
1394 assert(C && "couldn't emit constant value non-abstractly?");
1395 return C;
1396}
1397
1398llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1399 assert(!Abstract && "cannot get current address for abstract constant");
1400
1401
1402
1403 // Make an obviously ill-formed global that should blow up compilation
1404 // if it survives.
1405 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1406 llvm::GlobalValue::PrivateLinkage,
1407 /*init*/ nullptr,
1408 /*name*/ "",
1409 /*before*/ nullptr,
1410 llvm::GlobalVariable::NotThreadLocal,
1411 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1412
1413 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1414
1415 return global;
1416}
1417
1418void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1419 llvm::GlobalValue *placeholder) {
1420 assert(!PlaceholderAddresses.empty());
1421 assert(PlaceholderAddresses.back().first == nullptr);
1422 assert(PlaceholderAddresses.back().second == placeholder);
1423 PlaceholderAddresses.back().first = signal;
1424}
1425
1426namespace {
1427 struct ReplacePlaceholders {
1428 CodeGenModule &CGM;
1429
1430 /// The base address of the global.
1431 llvm::Constant *Base;
1432 llvm::Type *BaseValueTy = nullptr;
1433
1434 /// The placeholder addresses that were registered during emission.
1435 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1436
1437 /// The locations of the placeholder signals.
1438 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1439
1440 /// The current index stack. We use a simple unsigned stack because
1441 /// we assume that placeholders will be relatively sparse in the
1442 /// initializer, but we cache the index values we find just in case.
1443 llvm::SmallVector<unsigned, 8> Indices;
1444 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1445
1446 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1447 ArrayRef<std::pair<llvm::Constant*,
1448 llvm::GlobalVariable*>> addresses)
1449 : CGM(CGM), Base(base),
1450 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1451 }
1452
1453 void replaceInInitializer(llvm::Constant *init) {
1454 // Remember the type of the top-most initializer.
1455 BaseValueTy = init->getType();
1456
1457 // Initialize the stack.
1458 Indices.push_back(0);
1459 IndexValues.push_back(nullptr);
1460
1461 // Recurse into the initializer.
1462 findLocations(init);
1463
1464 // Check invariants.
1465 assert(IndexValues.size() == Indices.size() && "mismatch");
1466 assert(Indices.size() == 1 && "didn't pop all indices");
1467
1468 // Do the replacement; this basically invalidates 'init'.
1469 assert(Locations.size() == PlaceholderAddresses.size() &&
1470 "missed a placeholder?");
1471
1472 // We're iterating over a hashtable, so this would be a source of
1473 // non-determinism in compiler output *except* that we're just
1474 // messing around with llvm::Constant structures, which never itself
1475 // does anything that should be visible in compiler output.
1476 for (auto &entry : Locations) {
1477 assert(entry.first->getParent() == nullptr && "not a placeholder!");
1478 entry.first->replaceAllUsesWith(entry.second);
1479 entry.first->eraseFromParent();
1480 }
1481 }
1482
1483 private:
1484 void findLocations(llvm::Constant *init) {
1485 // Recurse into aggregates.
1486 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1487 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1488 Indices.push_back(i);
1489 IndexValues.push_back(nullptr);
1490
1491 findLocations(agg->getOperand(i));
1492
1493 IndexValues.pop_back();
1494 Indices.pop_back();
1495 }
1496 return;
1497 }
1498
1499 // Otherwise, check for registered constants.
1500 while (true) {
1501 auto it = PlaceholderAddresses.find(init);
1502 if (it != PlaceholderAddresses.end()) {
1503 setLocation(it->second);
1504 break;
1505 }
1506
1507 // Look through bitcasts or other expressions.
1508 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1509 init = expr->getOperand(0);
1510 } else {
1511 break;
1512 }
1513 }
1514 }
1515
1516 void setLocation(llvm::GlobalVariable *placeholder) {
1517 assert(Locations.find(placeholder) == Locations.end() &&
1518 "already found location for placeholder!");
1519
1520 // Lazily fill in IndexValues with the values from Indices.
1521 // We do this in reverse because we should always have a strict
1522 // prefix of indices from the start.
1523 assert(Indices.size() == IndexValues.size());
1524 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1525 if (IndexValues[i]) {
1526#ifndef NDEBUG
1527 for (size_t j = 0; j != i + 1; ++j) {
1528 assert(IndexValues[j] &&
1529 isa<llvm::ConstantInt>(IndexValues[j]) &&
1530 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1531 == Indices[j]);
1532 }
1533#endif
1534 break;
1535 }
1536
1537 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1538 }
1539
1540 // Form a GEP and then bitcast to the placeholder type so that the
1541 // replacement will succeed.
1542 llvm::Constant *location =
1543 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1544 Base, IndexValues);
1545 location = llvm::ConstantExpr::getBitCast(location,
1546 placeholder->getType());
1547
1548 Locations.insert({placeholder, location});
1549 }
1550 };
1551}
1552
1553void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1554 assert(InitializedNonAbstract &&
1555 "finalizing emitter that was used for abstract emission?");
1556 assert(!Finalized && "finalizing emitter multiple times");
1557 assert(global->getInitializer());
1558
1559 // Note that we might also be Failed.
1560 Finalized = true;
1561
1562 if (!PlaceholderAddresses.empty()) {
1563 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1564 .replaceInInitializer(global->getInitializer());
1565 PlaceholderAddresses.clear(); // satisfy
1566 }
1567}
1568
1569ConstantEmitter::~ConstantEmitter() {
1570 assert((!InitializedNonAbstract || Finalized || Failed) &&
1571 "not finalized after being initialized for non-abstract emission");
1572 assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1573}
1574
1575static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1576 if (auto AT = type->getAs<AtomicType>()) {
1577 return CGM.getContext().getQualifiedType(AT->getValueType(),
1578 type.getQualifiers());
1579 }
1580 return type;
1581}
1582
1583llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
Fariborz Jahaniancc7f0082013-01-10 23:28:43 +00001584 // Make a quick check if variable can be default NULL initialized
1585 // and avoid going through rest of code which may do, for c++11,
1586 // initialization of memory to all NULLs.
Richard Smith3f1d6de2018-05-21 20:36:58 +00001587 if (!D.hasLocalStorage()) {
1588 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1589 if (Ty->isRecordType())
1590 if (const CXXConstructExpr *E =
1591 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1592 const CXXConstructorDecl *CD = E->getConstructor();
1593 if (CD->isTrivial() && CD->isDefaultConstructor())
1594 return CGM.EmitNullConstant(D.getType());
1595 }
Bill Wendling958b94d2018-12-01 09:06:26 +00001596 InConstantContext = true;
Richard Smith3f1d6de2018-05-21 20:36:58 +00001597 }
John McCallde0fe072017-08-15 21:42:52 +00001598
1599 QualType destType = D.getType();
1600
1601 // Try to emit the initializer. Note that this can allow some things that
1602 // are not allowed by tryEmitPrivateForMemory alone.
1603 if (auto value = D.evaluateValue()) {
1604 return tryEmitPrivateForMemory(*value, destType);
1605 }
Richard Smithdafff942012-01-14 04:30:29 +00001606
Richard Smith6331c402012-02-13 22:16:19 +00001607 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1608 // reference is a constant expression, and the reference binds to a temporary,
1609 // then constant initialization is performed. ConstExprEmitter will
1610 // incorrectly emit a prvalue constant in this case, and the calling code
1611 // interprets that as the (pointer) value of the reference, rather than the
1612 // desired value of the referee.
John McCallde0fe072017-08-15 21:42:52 +00001613 if (destType->isReferenceType())
Craig Topper8a13c412014-05-21 05:09:00 +00001614 return nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00001615
Richard Smithdafff942012-01-14 04:30:29 +00001616 const Expr *E = D.getInit();
1617 assert(E && "No initializer to emit");
1618
John McCallde0fe072017-08-15 21:42:52 +00001619 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1620 auto C =
1621 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1622 return (C ? emitForMemory(C, destType) : nullptr);
1623}
1624
1625llvm::Constant *
1626ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1627 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1628 auto C = tryEmitAbstract(E, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001629 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001630}
1631
1632llvm::Constant *
1633ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1634 QualType destType) {
1635 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1636 auto C = tryEmitAbstract(value, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001637 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001638}
1639
1640llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1641 QualType destType) {
1642 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1643 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1644 return (C ? emitForMemory(C, destType) : nullptr);
1645}
1646
1647llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1648 QualType destType) {
1649 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1650 auto C = tryEmitPrivate(value, nonMemoryDestType);
1651 return (C ? emitForMemory(C, destType) : nullptr);
1652}
1653
1654llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1655 llvm::Constant *C,
1656 QualType destType) {
1657 // For an _Atomic-qualified constant, we may need to add tail padding.
1658 if (auto AT = destType->getAs<AtomicType>()) {
1659 QualType destValueType = AT->getValueType();
1660 C = emitForMemory(CGM, C, destValueType);
1661
1662 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1663 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1664 if (innerSize == outerSize)
1665 return C;
1666
1667 assert(innerSize < outerSize && "emitted over-large constant for atomic");
1668 llvm::Constant *elts[] = {
1669 C,
1670 llvm::ConstantAggregateZero::get(
1671 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1672 };
1673 return llvm::ConstantStruct::getAnon(elts);
Richard Smithdafff942012-01-14 04:30:29 +00001674 }
John McCallde0fe072017-08-15 21:42:52 +00001675
1676 // Zero-extend bool.
1677 if (C->getType()->isIntegerTy(1)) {
1678 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1679 return llvm::ConstantExpr::getZExt(C, boolTy);
1680 }
1681
Richard Smithdafff942012-01-14 04:30:29 +00001682 return C;
1683}
1684
John McCallde0fe072017-08-15 21:42:52 +00001685llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1686 QualType destType) {
Anders Carlsson38eef1d2008-12-01 02:42:14 +00001687 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +00001688
Anders Carlssond8e39bb2009-04-11 01:08:03 +00001689 bool Success = false;
Mike Stump11289f42009-09-09 15:08:12 +00001690
John McCallde0fe072017-08-15 21:42:52 +00001691 if (destType->isReferenceType())
1692 Success = E->EvaluateAsLValue(Result, CGM.getContext());
Mike Stump11289f42009-09-09 15:08:12 +00001693 else
Bill Wendling2a81f662018-12-01 08:29:36 +00001694 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
Mike Stump11289f42009-09-09 15:08:12 +00001695
John McCallde0fe072017-08-15 21:42:52 +00001696 llvm::Constant *C;
Richard Smithdafff942012-01-14 04:30:29 +00001697 if (Success && !Result.HasSideEffects)
John McCallde0fe072017-08-15 21:42:52 +00001698 C = tryEmitPrivate(Result.Val, destType);
Richard Smithbc6387672012-03-02 23:27:11 +00001699 else
John McCallde0fe072017-08-15 21:42:52 +00001700 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
Eli Friedman10c24172008-06-01 15:31:44 +00001701
Eli Friedman10c24172008-06-01 15:31:44 +00001702 return C;
Anders Carlsson610ee712008-01-26 01:36:00 +00001703}
Eli Friedman20bb5e02009-04-13 21:47:26 +00001704
Yaxun Liu402804b2016-12-15 08:09:08 +00001705llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1706 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1707}
1708
John McCall99e5e982017-08-17 05:03:55 +00001709namespace {
1710/// A struct which can be used to peephole certain kinds of finalization
1711/// that normally happen during l-value emission.
1712struct ConstantLValue {
1713 llvm::Constant *Value;
1714 bool HasOffsetApplied;
1715
1716 /*implicit*/ ConstantLValue(llvm::Constant *value,
1717 bool hasOffsetApplied = false)
Akira Hatanakaa6d57a82019-12-18 13:54:30 -08001718 : Value(value), HasOffsetApplied(hasOffsetApplied) {}
John McCall99e5e982017-08-17 05:03:55 +00001719
1720 /*implicit*/ ConstantLValue(ConstantAddress address)
1721 : ConstantLValue(address.getPointer()) {}
1722};
1723
1724/// A helper class for emitting constant l-values.
1725class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1726 ConstantLValue> {
1727 CodeGenModule &CGM;
1728 ConstantEmitter &Emitter;
1729 const APValue &Value;
1730 QualType DestType;
1731
1732 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1733 friend StmtVisitorBase;
1734
1735public:
1736 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1737 QualType destType)
1738 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1739
1740 llvm::Constant *tryEmit();
1741
1742private:
1743 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1744 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1745
1746 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
Bill Wendling8003edc2018-11-09 00:41:36 +00001747 ConstantLValue VisitConstantExpr(const ConstantExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001748 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1749 ConstantLValue VisitStringLiteral(const StringLiteral *E);
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001750 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001751 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1752 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1753 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1754 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1755 ConstantLValue VisitCallExpr(const CallExpr *E);
1756 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1757 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1758 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1759 ConstantLValue VisitMaterializeTemporaryExpr(
1760 const MaterializeTemporaryExpr *E);
1761
1762 bool hasNonZeroOffset() const {
1763 return !Value.getLValueOffset().isZero();
1764 }
1765
1766 /// Return the value offset.
1767 llvm::Constant *getOffset() {
1768 return llvm::ConstantInt::get(CGM.Int64Ty,
1769 Value.getLValueOffset().getQuantity());
1770 }
1771
1772 /// Apply the value offset to the given constant.
1773 llvm::Constant *applyOffset(llvm::Constant *C) {
1774 if (!hasNonZeroOffset())
1775 return C;
1776
1777 llvm::Type *origPtrTy = C->getType();
1778 unsigned AS = origPtrTy->getPointerAddressSpace();
1779 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1780 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1781 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1782 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1783 return C;
1784 }
1785};
1786
1787}
1788
1789llvm::Constant *ConstantLValueEmitter::tryEmit() {
1790 const APValue::LValueBase &base = Value.getLValueBase();
1791
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001792 // The destination type should be a pointer or reference
John McCall99e5e982017-08-17 05:03:55 +00001793 // type, but it might also be a cast thereof.
1794 //
1795 // FIXME: the chain of casts required should be reflected in the APValue.
1796 // We need this in order to correctly handle things like a ptrtoint of a
1797 // non-zero null pointer and addrspace casts that aren't trivially
1798 // represented in LLVM IR.
1799 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1800 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1801
1802 // If there's no base at all, this is a null or absolute pointer,
1803 // possibly cast back to an integer type.
1804 if (!base) {
1805 return tryEmitAbsolute(destTy);
1806 }
1807
1808 // Otherwise, try to emit the base.
1809 ConstantLValue result = tryEmitBase(base);
1810
1811 // If that failed, we're done.
1812 llvm::Constant *value = result.Value;
1813 if (!value) return nullptr;
1814
1815 // Apply the offset if necessary and not already done.
1816 if (!result.HasOffsetApplied) {
1817 value = applyOffset(value);
1818 }
1819
1820 // Convert to the appropriate type; this could be an lvalue for
1821 // an integer. FIXME: performAddrSpaceCast
1822 if (isa<llvm::PointerType>(destTy))
1823 return llvm::ConstantExpr::getPointerCast(value, destTy);
1824
1825 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1826}
1827
1828/// Try to emit an absolute l-value, such as a null pointer or an integer
1829/// bitcast to pointer type.
1830llvm::Constant *
1831ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
John McCall99e5e982017-08-17 05:03:55 +00001832 // If we're producing a pointer, this is easy.
Don Hintonf170dff2019-03-19 06:14:14 +00001833 auto destPtrTy = cast<llvm::PointerType>(destTy);
1834 if (Value.isNullPointer()) {
1835 // FIXME: integer offsets from non-zero null pointers.
1836 return CGM.getNullPointer(destPtrTy, DestType);
John McCall99e5e982017-08-17 05:03:55 +00001837 }
1838
Don Hintonf170dff2019-03-19 06:14:14 +00001839 // Convert the integer to a pointer-sized integer before converting it
1840 // to a pointer.
1841 // FIXME: signedness depends on the original integer type.
1842 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
Simon Pilgrim3ff9c512019-05-11 11:01:46 +00001843 llvm::Constant *C;
Don Hintonf170dff2019-03-19 06:14:14 +00001844 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1845 /*isSigned*/ false);
1846 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
John McCall99e5e982017-08-17 05:03:55 +00001847 return C;
1848}
1849
1850ConstantLValue
1851ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1852 // Handle values.
1853 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1854 if (D->hasAttr<WeakRefAttr>())
1855 return CGM.GetWeakRefReference(D).getPointer();
1856
1857 if (auto FD = dyn_cast<FunctionDecl>(D))
1858 return CGM.GetAddrOfFunction(FD);
1859
1860 if (auto VD = dyn_cast<VarDecl>(D)) {
1861 // We can never refer to a variable with local storage.
1862 if (!VD->hasLocalStorage()) {
1863 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1864 return CGM.GetAddrOfGlobalVar(VD);
1865
1866 if (VD->isLocalVarDecl()) {
1867 return CGM.getOrCreateStaticVarDecl(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001868 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
John McCall99e5e982017-08-17 05:03:55 +00001869 }
1870 }
1871 }
1872
1873 return nullptr;
1874 }
1875
Richard Smithee0ce3022019-05-17 07:06:46 +00001876 // Handle typeid(T).
1877 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1878 llvm::Type *StdTypeInfoPtrTy =
1879 CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1880 llvm::Constant *TypeInfo =
1881 CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1882 if (TypeInfo->getType() != StdTypeInfoPtrTy)
1883 TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1884 return TypeInfo;
1885 }
1886
John McCall99e5e982017-08-17 05:03:55 +00001887 // Otherwise, it must be an expression.
1888 return Visit(base.get<const Expr*>());
1889}
1890
1891ConstantLValue
Bill Wendling8003edc2018-11-09 00:41:36 +00001892ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1893 return Visit(E->getSubExpr());
1894}
1895
1896ConstantLValue
John McCall99e5e982017-08-17 05:03:55 +00001897ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1898 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1899}
1900
1901ConstantLValue
1902ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1903 return CGM.GetAddrOfConstantStringFromLiteral(E);
1904}
1905
1906ConstantLValue
1907ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1908 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1909}
1910
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001911static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1912 QualType T,
1913 CodeGenModule &CGM) {
1914 auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1915 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1916}
1917
John McCall99e5e982017-08-17 05:03:55 +00001918ConstantLValue
1919ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001920 return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1921}
1922
1923ConstantLValue
1924ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1925 assert(E->isExpressibleAsConstantInitializer() &&
1926 "this boxed expression can't be emitted as a compile-time constant");
1927 auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1928 return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
John McCall99e5e982017-08-17 05:03:55 +00001929}
1930
1931ConstantLValue
1932ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
Eli Friedman3f82f9e2019-01-22 00:11:17 +00001933 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
John McCall99e5e982017-08-17 05:03:55 +00001934}
1935
1936ConstantLValue
1937ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1938 assert(Emitter.CGF && "Invalid address of label expression outside function");
1939 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1940 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1941 CGM.getTypes().ConvertType(E->getType()));
1942 return Ptr;
1943}
1944
1945ConstantLValue
1946ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1947 unsigned builtin = E->getBuiltinCallee();
1948 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1949 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1950 return nullptr;
1951
1952 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1953 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1954 return CGM.getObjCRuntime().GenerateConstantString(literal);
1955 } else {
1956 // FIXME: need to deal with UCN conversion issues.
1957 return CGM.GetAddrOfConstantCFString(literal);
1958 }
1959}
1960
1961ConstantLValue
1962ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1963 StringRef functionName;
1964 if (auto CGF = Emitter.CGF)
1965 functionName = CGF->CurFn->getName();
1966 else
1967 functionName = "global";
1968
1969 return CGM.GetAddrOfGlobalBlock(E, functionName);
1970}
1971
1972ConstantLValue
1973ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1974 QualType T;
1975 if (E->isTypeOperand())
1976 T = E->getTypeOperand(CGM.getContext());
1977 else
1978 T = E->getExprOperand()->getType();
1979 return CGM.GetAddrOfRTTIDescriptor(T);
1980}
1981
1982ConstantLValue
1983ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1984 return CGM.GetAddrOfUuidDescriptor(E);
1985}
1986
1987ConstantLValue
1988ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1989 const MaterializeTemporaryExpr *E) {
1990 assert(E->getStorageDuration() == SD_Static);
1991 SmallVector<const Expr *, 2> CommaLHSs;
1992 SmallVector<SubobjectAdjustment, 2> Adjustments;
Tykerb0561b32019-11-17 11:41:55 +01001993 const Expr *Inner =
1994 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
John McCall99e5e982017-08-17 05:03:55 +00001995 return CGM.GetAddrOfGlobalTemporary(E, Inner);
1996}
1997
John McCallde0fe072017-08-15 21:42:52 +00001998llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
1999 QualType DestType) {
Richard Smithdafff942012-01-14 04:30:29 +00002000 switch (Value.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002001 case APValue::None:
2002 case APValue::Indeterminate:
2003 // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2004 return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
John McCall99e5e982017-08-17 05:03:55 +00002005 case APValue::LValue:
2006 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
Richard Smithbc6387672012-03-02 23:27:11 +00002007 case APValue::Int:
John McCallde0fe072017-08-15 21:42:52 +00002008 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
Leonard Chan86285d22019-01-16 18:53:05 +00002009 case APValue::FixedPoint:
2010 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2011 Value.getFixedPoint().getValue());
Richard Smithdafff942012-01-14 04:30:29 +00002012 case APValue::ComplexInt: {
2013 llvm::Constant *Complex[2];
2014
John McCallde0fe072017-08-15 21:42:52 +00002015 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002016 Value.getComplexIntReal());
John McCallde0fe072017-08-15 21:42:52 +00002017 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002018 Value.getComplexIntImag());
2019
2020 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002021 llvm::StructType *STy =
2022 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002023 return llvm::ConstantStruct::get(STy, Complex);
2024 }
2025 case APValue::Float: {
2026 const llvm::APFloat &Init = Value.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002027 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
John McCallde0fe072017-08-15 21:42:52 +00002028 !CGM.getContext().getLangOpts().NativeHalfType &&
Akira Hatanaka502775a2017-12-09 00:02:37 +00002029 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
John McCallde0fe072017-08-15 21:42:52 +00002030 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2031 Init.bitcastToAPInt());
Richard Smithdafff942012-01-14 04:30:29 +00002032 else
John McCallde0fe072017-08-15 21:42:52 +00002033 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
Richard Smithdafff942012-01-14 04:30:29 +00002034 }
2035 case APValue::ComplexFloat: {
2036 llvm::Constant *Complex[2];
2037
John McCallde0fe072017-08-15 21:42:52 +00002038 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002039 Value.getComplexFloatReal());
John McCallde0fe072017-08-15 21:42:52 +00002040 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002041 Value.getComplexFloatImag());
2042
2043 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002044 llvm::StructType *STy =
2045 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002046 return llvm::ConstantStruct::get(STy, Complex);
2047 }
2048 case APValue::Vector: {
Richard Smithdafff942012-01-14 04:30:29 +00002049 unsigned NumElts = Value.getVectorLength();
George Burgess IV533ff002015-12-11 00:23:35 +00002050 SmallVector<llvm::Constant *, 4> Inits(NumElts);
Richard Smithdafff942012-01-14 04:30:29 +00002051
George Burgess IV533ff002015-12-11 00:23:35 +00002052 for (unsigned I = 0; I != NumElts; ++I) {
2053 const APValue &Elt = Value.getVectorElt(I);
Richard Smithdafff942012-01-14 04:30:29 +00002054 if (Elt.isInt())
John McCallde0fe072017-08-15 21:42:52 +00002055 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
George Burgess IV533ff002015-12-11 00:23:35 +00002056 else if (Elt.isFloat())
John McCallde0fe072017-08-15 21:42:52 +00002057 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
Richard Smithdafff942012-01-14 04:30:29 +00002058 else
George Burgess IV533ff002015-12-11 00:23:35 +00002059 llvm_unreachable("unsupported vector element type");
Richard Smithdafff942012-01-14 04:30:29 +00002060 }
2061 return llvm::ConstantVector::get(Inits);
2062 }
2063 case APValue::AddrLabelDiff: {
2064 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2065 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
John McCallde0fe072017-08-15 21:42:52 +00002066 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2067 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2068 if (!LHS || !RHS) return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002069
2070 // Compute difference
John McCallde0fe072017-08-15 21:42:52 +00002071 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2072 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2073 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
Richard Smithdafff942012-01-14 04:30:29 +00002074 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2075
2076 // LLVM is a bit sensitive about the exact format of the
2077 // address-of-label difference; make sure to truncate after
2078 // the subtraction.
2079 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2080 }
2081 case APValue::Struct:
2082 case APValue::Union:
John McCallde0fe072017-08-15 21:42:52 +00002083 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002084 case APValue::Array: {
Richard Smith3e268632018-05-23 23:41:38 +00002085 const ConstantArrayType *CAT =
2086 CGM.getContext().getAsConstantArrayType(DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002087 unsigned NumElements = Value.getArraySize();
2088 unsigned NumInitElts = Value.getArrayInitializedElts();
2089
Richard Smithdafff942012-01-14 04:30:29 +00002090 // Emit array filler, if there is one.
Craig Topper8a13c412014-05-21 05:09:00 +00002091 llvm::Constant *Filler = nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00002092 if (Value.hasArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00002093 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2094 CAT->getElementType());
Richard Smith3e268632018-05-23 23:41:38 +00002095 if (!Filler)
2096 return nullptr;
Hans Wennborg156349f2018-05-23 08:24:01 +00002097 }
David Majnemer90d85442014-12-28 23:46:59 +00002098
Richard Smith3e268632018-05-23 23:41:38 +00002099 // Emit initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00002100 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00002101 if (Filler && Filler->isNullValue())
2102 Elts.reserve(NumInitElts + 1);
2103 else
2104 Elts.reserve(NumElements);
2105
2106 llvm::Type *CommonElementType = nullptr;
2107 for (unsigned I = 0; I < NumInitElts; ++I) {
2108 llvm::Constant *C = tryEmitPrivateForMemory(
2109 Value.getArrayInitializedElt(I), CAT->getElementType());
John McCallde0fe072017-08-15 21:42:52 +00002110 if (!C) return nullptr;
2111
Richard Smithdafff942012-01-14 04:30:29 +00002112 if (I == 0)
2113 CommonElementType = C->getType();
2114 else if (C->getType() != CommonElementType)
Craig Topper8a13c412014-05-21 05:09:00 +00002115 CommonElementType = nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002116 Elts.push_back(C);
2117 }
2118
Balaji V. Iyer749e8282018-08-08 00:01:21 +00002119 // This means that the array type is probably "IncompleteType" or some
2120 // type that is not ConstantArray.
2121 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
2122 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
2123 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
2124 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
2125 NumElements);
2126 return llvm::ConstantAggregateZero::get(AType);
2127 }
2128
Richard Smith5745feb2019-06-17 21:08:30 +00002129 llvm::ArrayType *Desired =
2130 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2131 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00002132 Filler);
Richard Smithdafff942012-01-14 04:30:29 +00002133 }
2134 case APValue::MemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00002135 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002136 }
2137 llvm_unreachable("Unknown APValue kind");
2138}
2139
George Burgess IV1a39b862016-12-28 07:27:40 +00002140llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2141 const CompoundLiteralExpr *E) {
2142 return EmittedCompoundLiterals.lookup(E);
2143}
2144
2145void CodeGenModule::setAddrOfConstantCompoundLiteral(
2146 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2147 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2148 (void)Ok;
2149 assert(Ok && "CLE has already been emitted!");
2150}
2151
John McCall7f416cc2015-09-08 08:05:57 +00002152ConstantAddress
Richard Smith2d988f02011-11-22 22:48:32 +00002153CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2154 assert(E->isFileScope() && "not a file-scope compound literal expr");
John McCallde0fe072017-08-15 21:42:52 +00002155 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
Richard Smith2d988f02011-11-22 22:48:32 +00002156}
2157
John McCallf3a88602011-02-03 08:15:49 +00002158llvm::Constant *
2159CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2160 // Member pointer constants always have a very particular form.
2161 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2162 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2163
2164 // A member function pointer.
2165 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
David Majnemere2be95b2015-06-23 07:31:01 +00002166 return getCXXABI().EmitMemberFunctionPointer(method);
John McCallf3a88602011-02-03 08:15:49 +00002167
2168 // Otherwise, a member data pointer.
Richard Smithdafff942012-01-14 04:30:29 +00002169 uint64_t fieldOffset = getContext().getFieldOffset(decl);
John McCallf3a88602011-02-03 08:15:49 +00002170 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2171 return getCXXABI().EmitMemberDataPointer(type, chars);
2172}
2173
John McCall0217dfc22011-02-15 06:40:56 +00002174static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002175 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002176 const CXXRecordDecl *base);
2177
Anders Carlsson849ea412010-11-22 18:42:14 +00002178static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
Yaxun Liu402804b2016-12-15 08:09:08 +00002179 const RecordDecl *record,
John McCall0217dfc22011-02-15 06:40:56 +00002180 bool asCompleteObject) {
2181 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2192fe52011-07-18 04:24:23 +00002182 llvm::StructType *structure =
John McCall0217dfc22011-02-15 06:40:56 +00002183 (asCompleteObject ? layout.getLLVMType()
2184 : layout.getBaseSubobjectLLVMType());
Anders Carlsson849ea412010-11-22 18:42:14 +00002185
John McCall0217dfc22011-02-15 06:40:56 +00002186 unsigned numElements = structure->getNumElements();
2187 std::vector<llvm::Constant *> elements(numElements);
Anders Carlsson849ea412010-11-22 18:42:14 +00002188
Yaxun Liu402804b2016-12-15 08:09:08 +00002189 auto CXXR = dyn_cast<CXXRecordDecl>(record);
John McCall0217dfc22011-02-15 06:40:56 +00002190 // Fill in all the bases.
Yaxun Liu402804b2016-12-15 08:09:08 +00002191 if (CXXR) {
2192 for (const auto &I : CXXR->bases()) {
2193 if (I.isVirtual()) {
2194 // Ignore virtual bases; if we're laying out for a complete
2195 // object, we'll lay these out later.
2196 continue;
2197 }
2198
2199 const CXXRecordDecl *base =
2200 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2201
2202 // Ignore empty bases.
2203 if (base->isEmpty() ||
2204 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2205 .isZero())
2206 continue;
2207
2208 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2209 llvm::Type *baseType = structure->getElementType(fieldIndex);
2210 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlsson849ea412010-11-22 18:42:14 +00002211 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002212 }
2213
John McCall0217dfc22011-02-15 06:40:56 +00002214 // Fill in all the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002215 for (const auto *Field : record->fields()) {
Eli Friedmandae858a2011-12-07 01:30:11 +00002216 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2217 // will fill in later.)
Richard Smith78b239e2019-06-20 20:44:45 +00002218 if (!Field->isBitField() && !Field->isZeroSize(CGM.getContext())) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002219 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2220 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
Eli Friedmandae858a2011-12-07 01:30:11 +00002221 }
2222
2223 // For unions, stop after the first named field.
David Majnemer4e51dfc2015-05-30 09:12:07 +00002224 if (record->isUnion()) {
2225 if (Field->getIdentifier())
2226 break;
George Karpenkov39e51372018-07-28 02:16:13 +00002227 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
David Majnemer4e51dfc2015-05-30 09:12:07 +00002228 if (FieldRD->findFirstNamedDataMember())
2229 break;
2230 }
John McCall0217dfc22011-02-15 06:40:56 +00002231 }
2232
2233 // Fill in the virtual bases, if we're working with the complete object.
Yaxun Liu402804b2016-12-15 08:09:08 +00002234 if (CXXR && asCompleteObject) {
2235 for (const auto &I : CXXR->vbases()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002236 const CXXRecordDecl *base =
Aaron Ballman445a9392014-03-13 16:15:17 +00002237 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
John McCall0217dfc22011-02-15 06:40:56 +00002238
2239 // Ignore empty bases.
2240 if (base->isEmpty())
2241 continue;
2242
2243 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2244
2245 // We might have already laid this field out.
2246 if (elements[fieldIndex]) continue;
2247
Chris Lattner2192fe52011-07-18 04:24:23 +00002248 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall0217dfc22011-02-15 06:40:56 +00002249 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2250 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002251 }
2252
2253 // Now go through all other fields and zero them out.
John McCall0217dfc22011-02-15 06:40:56 +00002254 for (unsigned i = 0; i != numElements; ++i) {
2255 if (!elements[i])
2256 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlsson849ea412010-11-22 18:42:14 +00002257 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002258
John McCall0217dfc22011-02-15 06:40:56 +00002259 return llvm::ConstantStruct::get(structure, elements);
2260}
2261
2262/// Emit the null constant for a base subobject.
2263static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002264 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002265 const CXXRecordDecl *base) {
2266 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2267
2268 // Just zero out bases that don't have any pointer to data members.
2269 if (baseLayout.isZeroInitializableAsBase())
2270 return llvm::Constant::getNullValue(baseType);
2271
David Majnemer2213bfe2014-10-17 01:00:43 +00002272 // Otherwise, we can just use its null constant.
2273 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
Anders Carlsson849ea412010-11-22 18:42:14 +00002274}
2275
John McCallde0fe072017-08-15 21:42:52 +00002276llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2277 QualType T) {
2278 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2279}
2280
Eli Friedman20bb5e02009-04-13 21:47:26 +00002281llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
Yaxun Liu402804b2016-12-15 08:09:08 +00002282 if (T->getAs<PointerType>())
2283 return getNullPointer(
2284 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2285
John McCall614dbdc2010-08-22 21:01:12 +00002286 if (getTypes().isZeroInitializable(T))
Anders Carlsson867b48f2009-08-24 17:16:23 +00002287 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Fangrui Song6907ce22018-07-30 19:24:48 +00002288
Anders Carlssonf48123b2009-08-09 18:26:27 +00002289 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Chris Lattner72977a12012-02-06 22:00:56 +00002290 llvm::ArrayType *ATy =
2291 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
Mike Stump11289f42009-09-09 15:08:12 +00002292
Anders Carlssonf48123b2009-08-09 18:26:27 +00002293 QualType ElementTy = CAT->getElementType();
2294
John McCallde0fe072017-08-15 21:42:52 +00002295 llvm::Constant *Element =
2296 ConstantEmitter::emitNullForMemory(*this, ElementTy);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002297 unsigned NumElements = CAT->getSize().getZExtValue();
Chris Lattner72977a12012-02-06 22:00:56 +00002298 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002299 return llvm::ConstantArray::get(ATy, Array);
Anders Carlssonf48123b2009-08-09 18:26:27 +00002300 }
Anders Carlssond606de72009-08-23 01:25:01 +00002301
Yaxun Liu402804b2016-12-15 08:09:08 +00002302 if (const RecordType *RT = T->getAs<RecordType>())
2303 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002304
David Majnemer5fd33e02015-04-24 01:25:08 +00002305 assert(T->isMemberDataPointerType() &&
Anders Carlssone8bfe412010-02-02 05:17:25 +00002306 "Should only see pointers to data members here!");
David Majnemer2213bfe2014-10-17 01:00:43 +00002307
John McCallf3a88602011-02-03 08:15:49 +00002308 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman20bb5e02009-04-13 21:47:26 +00002309}
Eli Friedmanfde961d2011-10-14 02:27:24 +00002310
2311llvm::Constant *
2312CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2313 return ::EmitNullConstant(*this, Record, false);
2314}