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