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