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