clang  9.0.0svn
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 "CodeGenFunction.h"
14 #include "CGCXXABI.h"
15 #include "CGObjCRuntime.h"
16 #include "CGRecordLayout.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/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/Builtins.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalVariable.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
32 //===----------------------------------------------------------------------===//
33 // ConstStructBuilder
34 //===----------------------------------------------------------------------===//
35 
36 namespace {
37 class ConstExprEmitter;
38 class ConstStructBuilder {
39  CodeGenModule &CGM;
40  ConstantEmitter &Emitter;
41 
42  bool Packed;
43  CharUnits NextFieldOffsetInChars;
44  CharUnits LLVMStructAlignment;
46 public:
47  static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
48  ConstExprEmitter *ExprEmitter,
49  llvm::Constant *Base,
50  InitListExpr *Updater,
51  QualType ValTy);
52  static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
53  InitListExpr *ILE, QualType StructTy);
54  static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
55  const APValue &Value, QualType ValTy);
56 
57 private:
58  ConstStructBuilder(ConstantEmitter &emitter)
59  : CGM(emitter.CGM), Emitter(emitter), Packed(false),
60  NextFieldOffsetInChars(CharUnits::Zero()),
61  LLVMStructAlignment(CharUnits::One()) { }
62 
63  void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
64  llvm::Constant *InitExpr);
65 
66  void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
67 
68  void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
69  llvm::ConstantInt *InitExpr);
70 
71  void AppendPadding(CharUnits PadSize);
72 
73  void AppendTailPadding(CharUnits RecordSize);
74 
75  void ConvertStructToPacked();
76 
77  bool Build(InitListExpr *ILE);
78  bool Build(ConstExprEmitter *Emitter, llvm::Constant *Base,
79  InitListExpr *Updater);
80  bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
81  const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
82  llvm::Constant *Finalize(QualType Ty);
83 
84  CharUnits getAlignment(const llvm::Constant *C) const {
85  if (Packed) return CharUnits::One();
87  CGM.getDataLayout().getABITypeAlignment(C->getType()));
88  }
89 
90  CharUnits getSizeInChars(const llvm::Constant *C) const {
92  CGM.getDataLayout().getTypeAllocSize(C->getType()));
93  }
94 };
95 
96 void ConstStructBuilder::
97 AppendField(const FieldDecl *Field, uint64_t FieldOffset,
98  llvm::Constant *InitCst) {
99  const ASTContext &Context = CGM.getContext();
100 
101  CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
102 
103  AppendBytes(FieldOffsetInChars, InitCst);
104 }
105 
106 void ConstStructBuilder::
107 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
108 
109  assert(NextFieldOffsetInChars <= FieldOffsetInChars
110  && "Field offset mismatch!");
111 
112  CharUnits FieldAlignment = getAlignment(InitCst);
113 
114  // Round up the field offset to the alignment of the field type.
115  CharUnits AlignedNextFieldOffsetInChars =
116  NextFieldOffsetInChars.alignTo(FieldAlignment);
117 
118  if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
119  // We need to append padding.
120  AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
121 
122  assert(NextFieldOffsetInChars == FieldOffsetInChars &&
123  "Did not add enough padding!");
124 
125  AlignedNextFieldOffsetInChars =
126  NextFieldOffsetInChars.alignTo(FieldAlignment);
127  }
128 
129  if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
130  assert(!Packed && "Alignment is wrong even with a packed struct!");
131 
132  // Convert the struct to a packed struct.
133  ConvertStructToPacked();
134 
135  // After we pack the struct, we may need to insert padding.
136  if (NextFieldOffsetInChars < FieldOffsetInChars) {
137  // We need to append padding.
138  AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
139 
140  assert(NextFieldOffsetInChars == FieldOffsetInChars &&
141  "Did not add enough padding!");
142  }
143  AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
144  }
145 
146  // Add the field.
147  Elements.push_back(InitCst);
148  NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
149  getSizeInChars(InitCst);
150 
151  if (Packed)
152  assert(LLVMStructAlignment == CharUnits::One() &&
153  "Packed struct not byte-aligned!");
154  else
155  LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
156 }
157 
158 void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
159  uint64_t FieldOffset,
160  llvm::ConstantInt *CI) {
161  const ASTContext &Context = CGM.getContext();
162  const uint64_t CharWidth = Context.getCharWidth();
163  uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
164  if (FieldOffset > NextFieldOffsetInBits) {
165  // We need to add padding.
166  CharUnits PadSize = Context.toCharUnitsFromBits(
167  llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
168  Context.getTargetInfo().getCharAlign()));
169 
170  AppendPadding(PadSize);
171  }
172 
173  uint64_t FieldSize = Field->getBitWidthValue(Context);
174 
175  llvm::APInt FieldValue = CI->getValue();
176 
177  // Promote the size of FieldValue if necessary
178  // FIXME: This should never occur, but currently it can because initializer
179  // constants are cast to bool, and because clang is not enforcing bitfield
180  // width limits.
181  if (FieldSize > FieldValue.getBitWidth())
182  FieldValue = FieldValue.zext(FieldSize);
183 
184  // Truncate the size of FieldValue to the bit field size.
185  if (FieldSize < FieldValue.getBitWidth())
186  FieldValue = FieldValue.trunc(FieldSize);
187 
188  NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
189  if (FieldOffset < NextFieldOffsetInBits) {
190  // Either part of the field or the entire field can go into the previous
191  // byte.
192  assert(!Elements.empty() && "Elements can't be empty!");
193 
194  unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
195 
196  bool FitsCompletelyInPreviousByte =
197  BitsInPreviousByte >= FieldValue.getBitWidth();
198 
199  llvm::APInt Tmp = FieldValue;
200 
201  if (!FitsCompletelyInPreviousByte) {
202  unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
203 
204  if (CGM.getDataLayout().isBigEndian()) {
205  Tmp.lshrInPlace(NewFieldWidth);
206  Tmp = Tmp.trunc(BitsInPreviousByte);
207 
208  // We want the remaining high bits.
209  FieldValue = FieldValue.trunc(NewFieldWidth);
210  } else {
211  Tmp = Tmp.trunc(BitsInPreviousByte);
212 
213  // We want the remaining low bits.
214  FieldValue.lshrInPlace(BitsInPreviousByte);
215  FieldValue = FieldValue.trunc(NewFieldWidth);
216  }
217  }
218 
219  Tmp = Tmp.zext(CharWidth);
220  if (CGM.getDataLayout().isBigEndian()) {
221  if (FitsCompletelyInPreviousByte)
222  Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
223  } else {
224  Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
225  }
226 
227  // 'or' in the bits that go into the previous byte.
228  llvm::Value *LastElt = Elements.back();
229  if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
230  Tmp |= Val->getValue();
231  else {
232  assert(isa<llvm::UndefValue>(LastElt));
233  // If there is an undef field that we're adding to, it can either be a
234  // scalar undef (in which case, we just replace it with our field) or it
235  // is an array. If it is an array, we have to pull one byte off the
236  // array so that the other undef bytes stay around.
237  if (!isa<llvm::IntegerType>(LastElt->getType())) {
238  // The undef padding will be a multibyte array, create a new smaller
239  // padding and then an hole for our i8 to get plopped into.
240  assert(isa<llvm::ArrayType>(LastElt->getType()) &&
241  "Expected array padding of undefs");
242  llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
243  assert(AT->getElementType()->isIntegerTy(CharWidth) &&
244  AT->getNumElements() != 0 &&
245  "Expected non-empty array padding of undefs");
246 
247  // Remove the padding array.
248  NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
249  Elements.pop_back();
250 
251  // Add the padding back in two chunks.
252  AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
253  AppendPadding(CharUnits::One());
254  assert(isa<llvm::UndefValue>(Elements.back()) &&
255  Elements.back()->getType()->isIntegerTy(CharWidth) &&
256  "Padding addition didn't work right");
257  }
258  }
259 
260  Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
261 
262  if (FitsCompletelyInPreviousByte)
263  return;
264  }
265 
266  while (FieldValue.getBitWidth() > CharWidth) {
267  llvm::APInt Tmp;
268 
269  if (CGM.getDataLayout().isBigEndian()) {
270  // We want the high bits.
271  Tmp =
272  FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
273  } else {
274  // We want the low bits.
275  Tmp = FieldValue.trunc(CharWidth);
276 
277  FieldValue.lshrInPlace(CharWidth);
278  }
279 
280  Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
281  ++NextFieldOffsetInChars;
282 
283  FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
284  }
285 
286  assert(FieldValue.getBitWidth() > 0 &&
287  "Should have at least one bit left!");
288  assert(FieldValue.getBitWidth() <= CharWidth &&
289  "Should not have more than a byte left!");
290 
291  if (FieldValue.getBitWidth() < CharWidth) {
292  if (CGM.getDataLayout().isBigEndian()) {
293  unsigned BitWidth = FieldValue.getBitWidth();
294 
295  FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
296  } else
297  FieldValue = FieldValue.zext(CharWidth);
298  }
299 
300  // Append the last element.
301  Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
302  FieldValue));
303  ++NextFieldOffsetInChars;
304 }
305 
306 void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
307  if (PadSize.isZero())
308  return;
309 
310  llvm::Type *Ty = CGM.Int8Ty;
311  if (PadSize > CharUnits::One())
312  Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
313 
314  llvm::Constant *C = llvm::UndefValue::get(Ty);
315  Elements.push_back(C);
316  assert(getAlignment(C) == CharUnits::One() &&
317  "Padding must have 1 byte alignment!");
318 
319  NextFieldOffsetInChars += getSizeInChars(C);
320 }
321 
322 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
323  assert(NextFieldOffsetInChars <= RecordSize &&
324  "Size mismatch!");
325 
326  AppendPadding(RecordSize - NextFieldOffsetInChars);
327 }
328 
329 void ConstStructBuilder::ConvertStructToPacked() {
330  SmallVector<llvm::Constant *, 16> PackedElements;
331  CharUnits ElementOffsetInChars = CharUnits::Zero();
332 
333  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
334  llvm::Constant *C = Elements[i];
335 
336  CharUnits ElementAlign = CharUnits::fromQuantity(
337  CGM.getDataLayout().getABITypeAlignment(C->getType()));
338  CharUnits AlignedElementOffsetInChars =
339  ElementOffsetInChars.alignTo(ElementAlign);
340 
341  if (AlignedElementOffsetInChars > ElementOffsetInChars) {
342  // We need some padding.
343  CharUnits NumChars =
344  AlignedElementOffsetInChars - ElementOffsetInChars;
345 
346  llvm::Type *Ty = CGM.Int8Ty;
347  if (NumChars > CharUnits::One())
348  Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
349 
350  llvm::Constant *Padding = llvm::UndefValue::get(Ty);
351  PackedElements.push_back(Padding);
352  ElementOffsetInChars += getSizeInChars(Padding);
353  }
354 
355  PackedElements.push_back(C);
356  ElementOffsetInChars += getSizeInChars(C);
357  }
358 
359  assert(ElementOffsetInChars == NextFieldOffsetInChars &&
360  "Packing the struct changed its size!");
361 
362  Elements.swap(PackedElements);
363  LLVMStructAlignment = CharUnits::One();
364  Packed = true;
365 }
366 
367 bool ConstStructBuilder::Build(InitListExpr *ILE) {
368  RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
369  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
370 
371  unsigned FieldNo = 0;
372  unsigned ElementNo = 0;
373 
374  // Bail out if we have base classes. We could support these, but they only
375  // arise in C++1z where we will have already constant folded most interesting
376  // cases. FIXME: There are still a few more cases we can handle this way.
377  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
378  if (CXXRD->getNumBases())
379  return false;
380 
381  for (RecordDecl::field_iterator Field = RD->field_begin(),
382  FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
383  // If this is a union, skip all the fields that aren't being initialized.
384  if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
385  continue;
386 
387  // Don't emit anonymous bitfields, they just affect layout.
388  if (Field->isUnnamedBitfield())
389  continue;
390 
391  // Get the initializer. A struct can include fields without initializers,
392  // we just use explicit null values for them.
393  llvm::Constant *EltInit;
394  if (ElementNo < ILE->getNumInits())
395  EltInit = Emitter.tryEmitPrivateForMemory(ILE->getInit(ElementNo++),
396  Field->getType());
397  else
398  EltInit = Emitter.emitNullForMemory(Field->getType());
399 
400  if (!EltInit)
401  return false;
402 
403  if (!Field->isBitField()) {
404  // Handle non-bitfield members.
405  AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
406  } else {
407  // Otherwise we have a bitfield.
408  if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
409  AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
410  } else {
411  // We are trying to initialize a bitfield with a non-trivial constant,
412  // this must require run-time code.
413  return false;
414  }
415  }
416  }
417 
418  return true;
419 }
420 
421 namespace {
422 struct BaseInfo {
423  BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
424  : Decl(Decl), Offset(Offset), Index(Index) {
425  }
426 
427  const CXXRecordDecl *Decl;
429  unsigned Index;
430 
431  bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
432 };
433 }
434 
435 bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
436  bool IsPrimaryBase,
437  const CXXRecordDecl *VTableClass,
438  CharUnits Offset) {
439  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
440 
441  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
442  // Add a vtable pointer, if we need one and it hasn't already been added.
443  if (CD->isDynamicClass() && !IsPrimaryBase) {
444  llvm::Constant *VTableAddressPoint =
446  BaseSubobject(CD, Offset), VTableClass);
447  AppendBytes(Offset, VTableAddressPoint);
448  }
449 
450  // Accumulate and sort bases, in order to visit them in address order, which
451  // may not be the same as declaration order.
453  Bases.reserve(CD->getNumBases());
454  unsigned BaseNo = 0;
455  for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
456  BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
457  assert(!Base->isVirtual() && "should not have virtual bases here");
458  const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
459  CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
460  Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
461  }
462  std::stable_sort(Bases.begin(), Bases.end());
463 
464  for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
465  BaseInfo &Base = Bases[I];
466 
467  bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
468  Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
469  VTableClass, Offset + Base.Offset);
470  }
471  }
472 
473  unsigned FieldNo = 0;
474  uint64_t OffsetBits = CGM.getContext().toBits(Offset);
475 
476  for (RecordDecl::field_iterator Field = RD->field_begin(),
477  FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
478  // If this is a union, skip all the fields that aren't being initialized.
479  if (RD->isUnion() && Val.getUnionField() != *Field)
480  continue;
481 
482  // Don't emit anonymous bitfields, they just affect layout.
483  if (Field->isUnnamedBitfield())
484  continue;
485 
486  // Emit the value of the initializer.
487  const APValue &FieldValue =
488  RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
489  llvm::Constant *EltInit =
490  Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
491  if (!EltInit)
492  return false;
493 
494  if (!Field->isBitField()) {
495  // Handle non-bitfield members.
496  AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
497  } else {
498  // Otherwise we have a bitfield.
499  AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
500  cast<llvm::ConstantInt>(EltInit));
501  }
502  }
503 
504  return true;
505 }
506 
507 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
508  RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
509  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
510 
511  CharUnits LayoutSizeInChars = Layout.getSize();
512 
513  if (NextFieldOffsetInChars > LayoutSizeInChars) {
514  // If the struct is bigger than the size of the record type,
515  // we must have a flexible array member at the end.
516  assert(RD->hasFlexibleArrayMember() &&
517  "Must have flexible array member if struct is bigger than type!");
518 
519  // No tail padding is necessary.
520  } else {
521  // Append tail padding if necessary.
522  CharUnits LLVMSizeInChars =
523  NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
524 
525  if (LLVMSizeInChars != LayoutSizeInChars)
526  AppendTailPadding(LayoutSizeInChars);
527 
528  LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
529 
530  // Check if we need to convert the struct to a packed struct.
531  if (NextFieldOffsetInChars <= LayoutSizeInChars &&
532  LLVMSizeInChars > LayoutSizeInChars) {
533  assert(!Packed && "Size mismatch!");
534 
535  ConvertStructToPacked();
536  assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
537  "Converting to packed did not help!");
538  }
539 
540  LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
541 
542  assert(LayoutSizeInChars == LLVMSizeInChars &&
543  "Tail padding mismatch!");
544  }
545 
546  // Pick the type to use. If the type is layout identical to the ConvertType
547  // type then use it, otherwise use whatever the builder produced for us.
548  llvm::StructType *STy =
549  llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
550  Elements, Packed);
551  llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
552  if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
553  if (ValSTy->isLayoutIdentical(STy))
554  STy = ValSTy;
555  }
556 
557  llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
558 
559  assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==
560  getSizeInChars(Result) &&
561  "Size mismatch!");
562 
563  return Result;
564 }
565 
566 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
567  ConstExprEmitter *ExprEmitter,
568  llvm::Constant *Base,
569  InitListExpr *Updater,
570  QualType ValTy) {
571  ConstStructBuilder Builder(Emitter);
572  if (!Builder.Build(ExprEmitter, Base, Updater))
573  return nullptr;
574  return Builder.Finalize(ValTy);
575 }
576 
577 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
578  InitListExpr *ILE,
579  QualType ValTy) {
580  ConstStructBuilder Builder(Emitter);
581 
582  if (!Builder.Build(ILE))
583  return nullptr;
584 
585  return Builder.Finalize(ValTy);
586 }
587 
588 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
589  const APValue &Val,
590  QualType ValTy) {
591  ConstStructBuilder Builder(Emitter);
592 
593  const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
594  const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
595  if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
596  return nullptr;
597 
598  return Builder.Finalize(ValTy);
599 }
600 
601 
602 //===----------------------------------------------------------------------===//
603 // ConstExprEmitter
604 //===----------------------------------------------------------------------===//
605 
606 static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
607  CodeGenFunction *CGF,
608  const CompoundLiteralExpr *E) {
609  CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
610  if (llvm::GlobalVariable *Addr =
612  return ConstantAddress(Addr, Align);
613 
614  LangAS addressSpace = E->getType().getAddressSpace();
615 
616  ConstantEmitter emitter(CGM, CGF);
617  llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
618  addressSpace, E->getType());
619  if (!C) {
620  assert(!E->isFileScope() &&
621  "file-scope compound literal did not have constant initializer!");
622  return ConstantAddress::invalid();
623  }
624 
625  auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
626  CGM.isTypeConstant(E->getType(), true),
628  C, ".compoundliteral", nullptr,
629  llvm::GlobalVariable::NotThreadLocal,
630  CGM.getContext().getTargetAddressSpace(addressSpace));
631  emitter.finalize(GV);
632  GV->setAlignment(Align.getQuantity());
634  return ConstantAddress(GV, Align);
635 }
636 
637 static llvm::Constant *
638 EmitArrayConstant(CodeGenModule &CGM, const ConstantArrayType *DestType,
639  llvm::Type *CommonElementType, unsigned ArrayBound,
641  llvm::Constant *Filler) {
642  // Figure out how long the initial prefix of non-zero elements is.
643  unsigned NonzeroLength = ArrayBound;
644  if (Elements.size() < NonzeroLength && Filler->isNullValue())
645  NonzeroLength = Elements.size();
646  if (NonzeroLength == Elements.size()) {
647  while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
648  --NonzeroLength;
649  }
650 
651  if (NonzeroLength == 0) {
652  return llvm::ConstantAggregateZero::get(
653  CGM.getTypes().ConvertType(QualType(DestType, 0)));
654  }
655 
656  // Add a zeroinitializer array filler if we have lots of trailing zeroes.
657  unsigned TrailingZeroes = ArrayBound - NonzeroLength;
658  if (TrailingZeroes >= 8) {
659  assert(Elements.size() >= NonzeroLength &&
660  "missing initializer for non-zero element");
661 
662  // If all the elements had the same type up to the trailing zeroes, emit a
663  // struct of two arrays (the nonzero data and the zeroinitializer).
664  if (CommonElementType && NonzeroLength >= 8) {
665  llvm::Constant *Initial = llvm::ConstantArray::get(
666  llvm::ArrayType::get(CommonElementType, NonzeroLength),
667  makeArrayRef(Elements).take_front(NonzeroLength));
668  Elements.resize(2);
669  Elements[0] = Initial;
670  } else {
671  Elements.resize(NonzeroLength + 1);
672  }
673 
674  auto *FillerType =
675  CommonElementType
676  ? CommonElementType
677  : CGM.getTypes().ConvertType(DestType->getElementType());
678  FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
679  Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
680  CommonElementType = nullptr;
681  } else if (Elements.size() != ArrayBound) {
682  // Otherwise pad to the right size with the filler if necessary.
683  Elements.resize(ArrayBound, Filler);
684  if (Filler->getType() != CommonElementType)
685  CommonElementType = nullptr;
686  }
687 
688  // If all elements have the same type, just emit an array constant.
689  if (CommonElementType)
690  return llvm::ConstantArray::get(
691  llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
692 
693  // We have mixed types. Use a packed struct.
695  Types.reserve(Elements.size());
696  for (llvm::Constant *Elt : Elements)
697  Types.push_back(Elt->getType());
698  llvm::StructType *SType =
699  llvm::StructType::get(CGM.getLLVMContext(), Types, true);
700  return llvm::ConstantStruct::get(SType, Elements);
701 }
702 
703 /// This class only needs to handle two cases:
704 /// 1) Literals (this is used by APValue emission to emit literals).
705 /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
706 /// constant fold these types).
707 class ConstExprEmitter :
708  public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
709  CodeGenModule &CGM;
710  ConstantEmitter &Emitter;
711  llvm::LLVMContext &VMContext;
712 public:
713  ConstExprEmitter(ConstantEmitter &emitter)
714  : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
715  }
716 
717  //===--------------------------------------------------------------------===//
718  // Visitor Methods
719  //===--------------------------------------------------------------------===//
720 
721  llvm::Constant *VisitStmt(Stmt *S, QualType T) {
722  return nullptr;
723  }
724 
725  llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
726  return Visit(CE->getSubExpr(), T);
727  }
728 
729  llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
730  return Visit(PE->getSubExpr(), T);
731  }
732 
733  llvm::Constant *
734  VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
735  QualType T) {
736  return Visit(PE->getReplacement(), T);
737  }
738 
739  llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
740  QualType T) {
741  return Visit(GE->getResultExpr(), T);
742  }
743 
744  llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
745  return Visit(CE->getChosenSubExpr(), T);
746  }
747 
748  llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
749  return Visit(E->getInitializer(), T);
750  }
751 
752  llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
753  if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
754  CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
755  Expr *subExpr = E->getSubExpr();
756 
757  switch (E->getCastKind()) {
758  case CK_ToUnion: {
759  // GCC cast to union extension
760  assert(E->getType()->isUnionType() &&
761  "Destination type is not union type!");
762 
763  auto field = E->getTargetUnionField();
764 
765  auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
766  if (!C) return nullptr;
767 
768  auto destTy = ConvertType(destType);
769  if (C->getType() == destTy) return C;
770 
771  // Build a struct with the union sub-element as the first member,
772  // and padded to the appropriate size.
775  Elts.push_back(C);
776  Types.push_back(C->getType());
777  unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
778  unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
779 
780  assert(CurSize <= TotalSize && "Union size mismatch!");
781  if (unsigned NumPadBytes = TotalSize - CurSize) {
782  llvm::Type *Ty = CGM.Int8Ty;
783  if (NumPadBytes > 1)
784  Ty = llvm::ArrayType::get(Ty, NumPadBytes);
785 
786  Elts.push_back(llvm::UndefValue::get(Ty));
787  Types.push_back(Ty);
788  }
789 
790  llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
791  return llvm::ConstantStruct::get(STy, Elts);
792  }
793 
794  case CK_AddressSpaceConversion: {
795  auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
796  if (!C) return nullptr;
797  LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
798  LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
799  llvm::Type *destTy = ConvertType(E->getType());
800  return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
801  destAS, destTy);
802  }
803 
804  case CK_LValueToRValue:
805  case CK_AtomicToNonAtomic:
806  case CK_NonAtomicToAtomic:
807  case CK_NoOp:
808  case CK_ConstructorConversion:
809  return Visit(subExpr, destType);
810 
811  case CK_IntToOCLSampler:
812  llvm_unreachable("global sampler variables are not generated");
813 
814  case CK_Dependent: llvm_unreachable("saw dependent cast!");
815 
816  case CK_BuiltinFnToFnPtr:
817  llvm_unreachable("builtin functions are handled elsewhere");
818 
819  case CK_ReinterpretMemberPointer:
820  case CK_DerivedToBaseMemberPointer:
821  case CK_BaseToDerivedMemberPointer: {
822  auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
823  if (!C) return nullptr;
824  return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
825  }
826 
827  // These will never be supported.
828  case CK_ObjCObjectLValueCast:
829  case CK_ARCProduceObject:
830  case CK_ARCConsumeObject:
831  case CK_ARCReclaimReturnedObject:
832  case CK_ARCExtendBlockObject:
833  case CK_CopyAndAutoreleaseBlockObject:
834  return nullptr;
835 
836  // These don't need to be handled here because Evaluate knows how to
837  // evaluate them in the cases where they can be folded.
838  case CK_BitCast:
839  case CK_ToVoid:
840  case CK_Dynamic:
841  case CK_LValueBitCast:
842  case CK_NullToMemberPointer:
843  case CK_UserDefinedConversion:
844  case CK_CPointerToObjCPointerCast:
845  case CK_BlockPointerToObjCPointerCast:
846  case CK_AnyPointerToBlockPointerCast:
847  case CK_ArrayToPointerDecay:
848  case CK_FunctionToPointerDecay:
849  case CK_BaseToDerived:
850  case CK_DerivedToBase:
851  case CK_UncheckedDerivedToBase:
852  case CK_MemberPointerToBoolean:
853  case CK_VectorSplat:
854  case CK_FloatingRealToComplex:
855  case CK_FloatingComplexToReal:
856  case CK_FloatingComplexToBoolean:
857  case CK_FloatingComplexCast:
858  case CK_FloatingComplexToIntegralComplex:
859  case CK_IntegralRealToComplex:
860  case CK_IntegralComplexToReal:
861  case CK_IntegralComplexToBoolean:
862  case CK_IntegralComplexCast:
863  case CK_IntegralComplexToFloatingComplex:
864  case CK_PointerToIntegral:
865  case CK_PointerToBoolean:
866  case CK_NullToPointer:
867  case CK_IntegralCast:
868  case CK_BooleanToSignedIntegral:
869  case CK_IntegralToPointer:
870  case CK_IntegralToBoolean:
871  case CK_IntegralToFloating:
872  case CK_FloatingToIntegral:
873  case CK_FloatingToBoolean:
874  case CK_FloatingCast:
875  case CK_FixedPointCast:
876  case CK_FixedPointToBoolean:
877  case CK_ZeroToOCLOpaqueType:
878  return nullptr;
879  }
880  llvm_unreachable("Invalid CastKind");
881  }
882 
883  llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE, QualType T) {
884  return Visit(DAE->getExpr(), T);
885  }
886 
887  llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
888  // No need for a DefaultInitExprScope: we don't handle 'this' in a
889  // constant expression.
890  return Visit(DIE->getExpr(), T);
891  }
892 
893  llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
894  if (!E->cleanupsHaveSideEffects())
895  return Visit(E->getSubExpr(), T);
896  return nullptr;
897  }
898 
899  llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
900  QualType T) {
901  return Visit(E->GetTemporaryExpr(), T);
902  }
903 
904  llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
905  auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
906  assert(CAT && "can't emit array init for non-constant-bound array");
907  unsigned NumInitElements = ILE->getNumInits();
908  unsigned NumElements = CAT->getSize().getZExtValue();
909 
910  // Initialising an array requires us to automatically
911  // initialise any elements that have not been initialised explicitly
912  unsigned NumInitableElts = std::min(NumInitElements, NumElements);
913 
914  QualType EltType = CAT->getElementType();
915 
916  // Initialize remaining array elements.
917  llvm::Constant *fillC = nullptr;
918  if (Expr *filler = ILE->getArrayFiller()) {
919  fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
920  if (!fillC)
921  return nullptr;
922  }
923 
924  // Copy initializer elements.
926  if (fillC && fillC->isNullValue())
927  Elts.reserve(NumInitableElts + 1);
928  else
929  Elts.reserve(NumElements);
930 
931  llvm::Type *CommonElementType = nullptr;
932  for (unsigned i = 0; i < NumInitableElts; ++i) {
933  Expr *Init = ILE->getInit(i);
934  llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
935  if (!C)
936  return nullptr;
937  if (i == 0)
938  CommonElementType = C->getType();
939  else if (C->getType() != CommonElementType)
940  CommonElementType = nullptr;
941  Elts.push_back(C);
942  }
943 
944  return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
945  fillC);
946  }
947 
948  llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
949  return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
950  }
951 
952  llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
953  QualType T) {
954  return CGM.EmitNullConstant(T);
955  }
956 
957  llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
958  if (ILE->isTransparent())
959  return Visit(ILE->getInit(0), T);
960 
961  if (ILE->getType()->isArrayType())
962  return EmitArrayInitialization(ILE, T);
963 
964  if (ILE->getType()->isRecordType())
965  return EmitRecordInitialization(ILE, T);
966 
967  return nullptr;
968  }
969 
970  llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
971  InitListExpr *Updater,
972  QualType destType) {
973  if (auto destAT = CGM.getContext().getAsArrayType(destType)) {
974  llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
975  llvm::Type *ElemType = AType->getElementType();
976 
977  unsigned NumInitElements = Updater->getNumInits();
978  unsigned NumElements = AType->getNumElements();
979 
980  std::vector<llvm::Constant *> Elts;
981  Elts.reserve(NumElements);
982 
983  QualType destElemType = destAT->getElementType();
984 
985  if (auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
986  for (unsigned i = 0; i != NumElements; ++i)
987  Elts.push_back(DataArray->getElementAsConstant(i));
988  else if (auto Array = dyn_cast<llvm::ConstantArray>(Base))
989  for (unsigned i = 0; i != NumElements; ++i)
990  Elts.push_back(Array->getOperand(i));
991  else
992  return nullptr; // FIXME: other array types not implemented
993 
994  llvm::Constant *fillC = nullptr;
995  if (Expr *filler = Updater->getArrayFiller())
996  if (!isa<NoInitExpr>(filler))
997  fillC = Emitter.tryEmitAbstractForMemory(filler, destElemType);
998  bool RewriteType = (fillC && fillC->getType() != ElemType);
999 
1000  for (unsigned i = 0; i != NumElements; ++i) {
1001  Expr *Init = nullptr;
1002  if (i < NumInitElements)
1003  Init = Updater->getInit(i);
1004 
1005  if (!Init && fillC)
1006  Elts[i] = fillC;
1007  else if (!Init || isa<NoInitExpr>(Init))
1008  ; // Do nothing.
1009  else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1010  Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
1011  else
1012  Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType);
1013 
1014  if (!Elts[i])
1015  return nullptr;
1016  RewriteType |= (Elts[i]->getType() != ElemType);
1017  }
1018 
1019  if (RewriteType) {
1020  std::vector<llvm::Type *> Types;
1021  Types.reserve(NumElements);
1022  for (unsigned i = 0; i != NumElements; ++i)
1023  Types.push_back(Elts[i]->getType());
1024  llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
1025  Types, true);
1026  return llvm::ConstantStruct::get(SType, Elts);
1027  }
1028 
1029  return llvm::ConstantArray::get(AType, Elts);
1030  }
1031 
1032  if (destType->isRecordType())
1033  return ConstStructBuilder::BuildStruct(Emitter, this, Base, Updater,
1034  destType);
1035 
1036  return nullptr;
1037  }
1038 
1039  llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1040  QualType destType) {
1041  auto C = Visit(E->getBase(), destType);
1042  if (!C) return nullptr;
1043  return EmitDesignatedInitUpdater(C, E->getUpdater(), destType);
1044  }
1045 
1046  llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
1047  if (!E->getConstructor()->isTrivial())
1048  return nullptr;
1049 
1050  // FIXME: We should not have to call getBaseElementType here.
1051  const RecordType *RT =
1053  const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1054 
1055  // If the class doesn't have a trivial destructor, we can't emit it as a
1056  // constant expr.
1057  if (!RD->hasTrivialDestructor())
1058  return nullptr;
1059 
1060  // Only copy and default constructors can be trivial.
1061 
1062 
1063  if (E->getNumArgs()) {
1064  assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
1065  assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1066  "trivial ctor has argument but isn't a copy/move ctor");
1067 
1068  Expr *Arg = E->getArg(0);
1069  assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1070  "argument to copy ctor is of wrong type");
1071 
1072  return Visit(Arg, Ty);
1073  }
1074 
1075  return CGM.EmitNullConstant(Ty);
1076  }
1077 
1078  llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
1079  return CGM.GetConstantArrayFromStringLiteral(E);
1080  }
1081 
1082  llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
1083  // This must be an @encode initializing an array in a static initializer.
1084  // Don't emit it as the address of the string, emit the string data itself
1085  // as an inline array.
1086  std::string Str;
1088  const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1089 
1090  // Resize the string to the right size, adding zeros at the end, or
1091  // truncating as needed.
1092  Str.resize(CAT->getSize().getZExtValue(), '\0');
1093  return llvm::ConstantDataArray::getString(VMContext, Str, false);
1094  }
1095 
1096  llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1097  return Visit(E->getSubExpr(), T);
1098  }
1099 
1100  // Utility methods
1101  llvm::Type *ConvertType(QualType T) {
1102  return CGM.getTypes().ConvertType(T);
1103  }
1104 };
1105 
1106 } // end anonymous namespace.
1107 
1108 bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
1109  llvm::Constant *Base,
1110  InitListExpr *Updater) {
1111  assert(Base && "base expression should not be empty");
1112 
1113  QualType ExprType = Updater->getType();
1114  RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1115  const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1116  const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
1117  cast<llvm::StructType>(Base->getType()));
1118  unsigned FieldNo = -1;
1119  unsigned ElementNo = 0;
1120 
1121  // Bail out if we have base classes. We could support these, but they only
1122  // arise in C++1z where we will have already constant folded most interesting
1123  // cases. FIXME: There are still a few more cases we can handle this way.
1124  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1125  if (CXXRD->getNumBases())
1126  return false;
1127 
1128  for (FieldDecl *Field : RD->fields()) {
1129  ++FieldNo;
1130 
1131  if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1132  continue;
1133 
1134  // Skip anonymous bitfields.
1135  if (Field->isUnnamedBitfield())
1136  continue;
1137 
1138  llvm::Constant *EltInit = Base->getAggregateElement(ElementNo);
1139 
1140  // Bail out if the type of the ConstantStruct does not have the same layout
1141  // as the type of the InitListExpr.
1142  if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1143  Layout.getFieldOffset(ElementNo) !=
1144  BaseLayout->getElementOffsetInBits(ElementNo))
1145  return false;
1146 
1147  // Get the initializer. If we encounter an empty field or a NoInitExpr,
1148  // we use values from the base expression.
1149  Expr *Init = nullptr;
1150  if (ElementNo < Updater->getNumInits())
1151  Init = Updater->getInit(ElementNo);
1152 
1153  if (!Init || isa<NoInitExpr>(Init))
1154  ; // Do nothing.
1155  else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1156  EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1157  Field->getType());
1158  else
1159  EltInit = Emitter.tryEmitPrivateForMemory(Init, Field->getType());
1160 
1161  ++ElementNo;
1162 
1163  if (!EltInit)
1164  return false;
1165 
1166  if (!Field->isBitField())
1167  AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1168  else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1169  AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1170  else
1171  // Initializing a bitfield with a non-trivial constant?
1172  return false;
1173  }
1174 
1175  return true;
1176 }
1177 
1178 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1179  AbstractState saved) {
1180  Abstract = saved.OldValue;
1181 
1182  assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1183  "created a placeholder while doing an abstract emission?");
1184 
1185  // No validation necessary for now.
1186  // No cleanup to do for now.
1187  return C;
1188 }
1189 
1190 llvm::Constant *
1192  auto state = pushAbstract();
1193  auto C = tryEmitPrivateForVarInit(D);
1194  return validateAndPopAbstract(C, state);
1195 }
1196 
1197 llvm::Constant *
1199  auto state = pushAbstract();
1200  auto C = tryEmitPrivate(E, destType);
1201  return validateAndPopAbstract(C, state);
1202 }
1203 
1204 llvm::Constant *
1206  auto state = pushAbstract();
1207  auto C = tryEmitPrivate(value, destType);
1208  return validateAndPopAbstract(C, state);
1209 }
1210 
1211 llvm::Constant *
1213  auto state = pushAbstract();
1214  auto C = tryEmitPrivate(E, destType);
1215  C = validateAndPopAbstract(C, state);
1216  if (!C) {
1217  CGM.Error(E->getExprLoc(),
1218  "internal error: could not emit constant value \"abstractly\"");
1219  C = CGM.EmitNullConstant(destType);
1220  }
1221  return C;
1222 }
1223 
1224 llvm::Constant *
1226  QualType destType) {
1227  auto state = pushAbstract();
1228  auto C = tryEmitPrivate(value, destType);
1229  C = validateAndPopAbstract(C, state);
1230  if (!C) {
1231  CGM.Error(loc,
1232  "internal error: could not emit constant value \"abstractly\"");
1233  C = CGM.EmitNullConstant(destType);
1234  }
1235  return C;
1236 }
1237 
1239  initializeNonAbstract(D.getType().getAddressSpace());
1240  return markIfFailed(tryEmitPrivateForVarInit(D));
1241 }
1242 
1244  LangAS destAddrSpace,
1245  QualType destType) {
1246  initializeNonAbstract(destAddrSpace);
1247  return markIfFailed(tryEmitPrivateForMemory(E, destType));
1248 }
1249 
1250 llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1251  LangAS destAddrSpace,
1252  QualType destType) {
1253  initializeNonAbstract(destAddrSpace);
1254  auto C = tryEmitPrivateForMemory(value, destType);
1255  assert(C && "couldn't emit constant value non-abstractly?");
1256  return C;
1257 }
1258 
1260  assert(!Abstract && "cannot get current address for abstract constant");
1261 
1262 
1263 
1264  // Make an obviously ill-formed global that should blow up compilation
1265  // if it survives.
1266  auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1267  llvm::GlobalValue::PrivateLinkage,
1268  /*init*/ nullptr,
1269  /*name*/ "",
1270  /*before*/ nullptr,
1271  llvm::GlobalVariable::NotThreadLocal,
1272  CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1273 
1274  PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1275 
1276  return global;
1277 }
1278 
1280  llvm::GlobalValue *placeholder) {
1281  assert(!PlaceholderAddresses.empty());
1282  assert(PlaceholderAddresses.back().first == nullptr);
1283  assert(PlaceholderAddresses.back().second == placeholder);
1284  PlaceholderAddresses.back().first = signal;
1285 }
1286 
1287 namespace {
1288  struct ReplacePlaceholders {
1289  CodeGenModule &CGM;
1290 
1291  /// The base address of the global.
1292  llvm::Constant *Base;
1293  llvm::Type *BaseValueTy = nullptr;
1294 
1295  /// The placeholder addresses that were registered during emission.
1296  llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1297 
1298  /// The locations of the placeholder signals.
1299  llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1300 
1301  /// The current index stack. We use a simple unsigned stack because
1302  /// we assume that placeholders will be relatively sparse in the
1303  /// initializer, but we cache the index values we find just in case.
1306 
1307  ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1308  ArrayRef<std::pair<llvm::Constant*,
1309  llvm::GlobalVariable*>> addresses)
1310  : CGM(CGM), Base(base),
1311  PlaceholderAddresses(addresses.begin(), addresses.end()) {
1312  }
1313 
1314  void replaceInInitializer(llvm::Constant *init) {
1315  // Remember the type of the top-most initializer.
1316  BaseValueTy = init->getType();
1317 
1318  // Initialize the stack.
1319  Indices.push_back(0);
1320  IndexValues.push_back(nullptr);
1321 
1322  // Recurse into the initializer.
1323  findLocations(init);
1324 
1325  // Check invariants.
1326  assert(IndexValues.size() == Indices.size() && "mismatch");
1327  assert(Indices.size() == 1 && "didn't pop all indices");
1328 
1329  // Do the replacement; this basically invalidates 'init'.
1330  assert(Locations.size() == PlaceholderAddresses.size() &&
1331  "missed a placeholder?");
1332 
1333  // We're iterating over a hashtable, so this would be a source of
1334  // non-determinism in compiler output *except* that we're just
1335  // messing around with llvm::Constant structures, which never itself
1336  // does anything that should be visible in compiler output.
1337  for (auto &entry : Locations) {
1338  assert(entry.first->getParent() == nullptr && "not a placeholder!");
1339  entry.first->replaceAllUsesWith(entry.second);
1340  entry.first->eraseFromParent();
1341  }
1342  }
1343 
1344  private:
1345  void findLocations(llvm::Constant *init) {
1346  // Recurse into aggregates.
1347  if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1348  for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1349  Indices.push_back(i);
1350  IndexValues.push_back(nullptr);
1351 
1352  findLocations(agg->getOperand(i));
1353 
1354  IndexValues.pop_back();
1355  Indices.pop_back();
1356  }
1357  return;
1358  }
1359 
1360  // Otherwise, check for registered constants.
1361  while (true) {
1362  auto it = PlaceholderAddresses.find(init);
1363  if (it != PlaceholderAddresses.end()) {
1364  setLocation(it->second);
1365  break;
1366  }
1367 
1368  // Look through bitcasts or other expressions.
1369  if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1370  init = expr->getOperand(0);
1371  } else {
1372  break;
1373  }
1374  }
1375  }
1376 
1377  void setLocation(llvm::GlobalVariable *placeholder) {
1378  assert(Locations.find(placeholder) == Locations.end() &&
1379  "already found location for placeholder!");
1380 
1381  // Lazily fill in IndexValues with the values from Indices.
1382  // We do this in reverse because we should always have a strict
1383  // prefix of indices from the start.
1384  assert(Indices.size() == IndexValues.size());
1385  for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1386  if (IndexValues[i]) {
1387 #ifndef NDEBUG
1388  for (size_t j = 0; j != i + 1; ++j) {
1389  assert(IndexValues[j] &&
1390  isa<llvm::ConstantInt>(IndexValues[j]) &&
1391  cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1392  == Indices[j]);
1393  }
1394 #endif
1395  break;
1396  }
1397 
1398  IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1399  }
1400 
1401  // Form a GEP and then bitcast to the placeholder type so that the
1402  // replacement will succeed.
1403  llvm::Constant *location =
1404  llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1405  Base, IndexValues);
1406  location = llvm::ConstantExpr::getBitCast(location,
1407  placeholder->getType());
1408 
1409  Locations.insert({placeholder, location});
1410  }
1411  };
1412 }
1413 
1414 void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1415  assert(InitializedNonAbstract &&
1416  "finalizing emitter that was used for abstract emission?");
1417  assert(!Finalized && "finalizing emitter multiple times");
1418  assert(global->getInitializer());
1419 
1420  // Note that we might also be Failed.
1421  Finalized = true;
1422 
1423  if (!PlaceholderAddresses.empty()) {
1424  ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1425  .replaceInInitializer(global->getInitializer());
1426  PlaceholderAddresses.clear(); // satisfy
1427  }
1428 }
1429 
1431  assert((!InitializedNonAbstract || Finalized || Failed) &&
1432  "not finalized after being initialized for non-abstract emission");
1433  assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1434 }
1435 
1437  if (auto AT = type->getAs<AtomicType>()) {
1438  return CGM.getContext().getQualifiedType(AT->getValueType(),
1439  type.getQualifiers());
1440  }
1441  return type;
1442 }
1443 
1445  // Make a quick check if variable can be default NULL initialized
1446  // and avoid going through rest of code which may do, for c++11,
1447  // initialization of memory to all NULLs.
1448  if (!D.hasLocalStorage()) {
1450  if (Ty->isRecordType())
1451  if (const CXXConstructExpr *E =
1452  dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1453  const CXXConstructorDecl *CD = E->getConstructor();
1454  if (CD->isTrivial() && CD->isDefaultConstructor())
1455  return CGM.EmitNullConstant(D.getType());
1456  }
1457  InConstantContext = true;
1458  }
1459 
1460  QualType destType = D.getType();
1461 
1462  // Try to emit the initializer. Note that this can allow some things that
1463  // are not allowed by tryEmitPrivateForMemory alone.
1464  if (auto value = D.evaluateValue()) {
1465  return tryEmitPrivateForMemory(*value, destType);
1466  }
1467 
1468  // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1469  // reference is a constant expression, and the reference binds to a temporary,
1470  // then constant initialization is performed. ConstExprEmitter will
1471  // incorrectly emit a prvalue constant in this case, and the calling code
1472  // interprets that as the (pointer) value of the reference, rather than the
1473  // desired value of the referee.
1474  if (destType->isReferenceType())
1475  return nullptr;
1476 
1477  const Expr *E = D.getInit();
1478  assert(E && "No initializer to emit");
1479 
1480  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1481  auto C =
1482  ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1483  return (C ? emitForMemory(C, destType) : nullptr);
1484 }
1485 
1486 llvm::Constant *
1488  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1489  auto C = tryEmitAbstract(E, nonMemoryDestType);
1490  return (C ? emitForMemory(C, destType) : nullptr);
1491 }
1492 
1493 llvm::Constant *
1495  QualType destType) {
1496  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1497  auto C = tryEmitAbstract(value, nonMemoryDestType);
1498  return (C ? emitForMemory(C, destType) : nullptr);
1499 }
1500 
1502  QualType destType) {
1503  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1504  llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1505  return (C ? emitForMemory(C, destType) : nullptr);
1506 }
1507 
1509  QualType destType) {
1510  auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1511  auto C = tryEmitPrivate(value, nonMemoryDestType);
1512  return (C ? emitForMemory(C, destType) : nullptr);
1513 }
1514 
1516  llvm::Constant *C,
1517  QualType destType) {
1518  // For an _Atomic-qualified constant, we may need to add tail padding.
1519  if (auto AT = destType->getAs<AtomicType>()) {
1520  QualType destValueType = AT->getValueType();
1521  C = emitForMemory(CGM, C, destValueType);
1522 
1523  uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1524  uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1525  if (innerSize == outerSize)
1526  return C;
1527 
1528  assert(innerSize < outerSize && "emitted over-large constant for atomic");
1529  llvm::Constant *elts[] = {
1530  C,
1531  llvm::ConstantAggregateZero::get(
1532  llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1533  };
1534  return llvm::ConstantStruct::getAnon(elts);
1535  }
1536 
1537  // Zero-extend bool.
1538  if (C->getType()->isIntegerTy(1)) {
1539  llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1540  return llvm::ConstantExpr::getZExt(C, boolTy);
1541  }
1542 
1543  return C;
1544 }
1545 
1546 llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1547  QualType destType) {
1548  Expr::EvalResult Result;
1549 
1550  bool Success = false;
1551 
1552  if (destType->isReferenceType())
1553  Success = E->EvaluateAsLValue(Result, CGM.getContext());
1554  else
1555  Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
1556 
1557  llvm::Constant *C;
1558  if (Success && !Result.HasSideEffects)
1559  C = tryEmitPrivate(Result.Val, destType);
1560  else
1561  C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
1562 
1563  return C;
1564 }
1565 
1566 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1567  return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1568 }
1569 
1570 namespace {
1571 /// A struct which can be used to peephole certain kinds of finalization
1572 /// that normally happen during l-value emission.
1573 struct ConstantLValue {
1574  llvm::Constant *Value;
1575  bool HasOffsetApplied;
1576 
1577  /*implicit*/ ConstantLValue(llvm::Constant *value,
1578  bool hasOffsetApplied = false)
1579  : Value(value), HasOffsetApplied(false) {}
1580 
1581  /*implicit*/ ConstantLValue(ConstantAddress address)
1582  : ConstantLValue(address.getPointer()) {}
1583 };
1584 
1585 /// A helper class for emitting constant l-values.
1586 class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1587  ConstantLValue> {
1588  CodeGenModule &CGM;
1589  ConstantEmitter &Emitter;
1590  const APValue &Value;
1591  QualType DestType;
1592 
1593  // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1594  friend StmtVisitorBase;
1595 
1596 public:
1597  ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1598  QualType destType)
1599  : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1600 
1601  llvm::Constant *tryEmit();
1602 
1603 private:
1604  llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1605  ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1606 
1607  ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1608  ConstantLValue VisitConstantExpr(const ConstantExpr *E);
1609  ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1610  ConstantLValue VisitStringLiteral(const StringLiteral *E);
1611  ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1612  ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1613  ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1614  ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1615  ConstantLValue VisitCallExpr(const CallExpr *E);
1616  ConstantLValue VisitBlockExpr(const BlockExpr *E);
1617  ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1618  ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1619  ConstantLValue VisitMaterializeTemporaryExpr(
1620  const MaterializeTemporaryExpr *E);
1621 
1622  bool hasNonZeroOffset() const {
1623  return !Value.getLValueOffset().isZero();
1624  }
1625 
1626  /// Return the value offset.
1627  llvm::Constant *getOffset() {
1628  return llvm::ConstantInt::get(CGM.Int64Ty,
1629  Value.getLValueOffset().getQuantity());
1630  }
1631 
1632  /// Apply the value offset to the given constant.
1633  llvm::Constant *applyOffset(llvm::Constant *C) {
1634  if (!hasNonZeroOffset())
1635  return C;
1636 
1637  llvm::Type *origPtrTy = C->getType();
1638  unsigned AS = origPtrTy->getPointerAddressSpace();
1639  llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1640  C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1641  C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1642  C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1643  return C;
1644  }
1645 };
1646 
1647 }
1648 
1649 llvm::Constant *ConstantLValueEmitter::tryEmit() {
1650  const APValue::LValueBase &base = Value.getLValueBase();
1651 
1652  // Certain special array initializers are represented in APValue
1653  // as l-values referring to the base expression which generates the
1654  // array. This happens with e.g. string literals. These should
1655  // probably just get their own representation kind in APValue.
1656  if (DestType->isArrayType()) {
1657  assert(!hasNonZeroOffset() && "offset on array initializer");
1658  auto expr = const_cast<Expr*>(base.get<const Expr*>());
1659  return ConstExprEmitter(Emitter).Visit(expr, DestType);
1660  }
1661 
1662  // Otherwise, the destination type should be a pointer or reference
1663  // type, but it might also be a cast thereof.
1664  //
1665  // FIXME: the chain of casts required should be reflected in the APValue.
1666  // We need this in order to correctly handle things like a ptrtoint of a
1667  // non-zero null pointer and addrspace casts that aren't trivially
1668  // represented in LLVM IR.
1669  auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1670  assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1671 
1672  // If there's no base at all, this is a null or absolute pointer,
1673  // possibly cast back to an integer type.
1674  if (!base) {
1675  return tryEmitAbsolute(destTy);
1676  }
1677 
1678  // Otherwise, try to emit the base.
1679  ConstantLValue result = tryEmitBase(base);
1680 
1681  // If that failed, we're done.
1682  llvm::Constant *value = result.Value;
1683  if (!value) return nullptr;
1684 
1685  // Apply the offset if necessary and not already done.
1686  if (!result.HasOffsetApplied) {
1687  value = applyOffset(value);
1688  }
1689 
1690  // Convert to the appropriate type; this could be an lvalue for
1691  // an integer. FIXME: performAddrSpaceCast
1692  if (isa<llvm::PointerType>(destTy))
1693  return llvm::ConstantExpr::getPointerCast(value, destTy);
1694 
1695  return llvm::ConstantExpr::getPtrToInt(value, destTy);
1696 }
1697 
1698 /// Try to emit an absolute l-value, such as a null pointer or an integer
1699 /// bitcast to pointer type.
1700 llvm::Constant *
1701 ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1702  auto offset = getOffset();
1703 
1704  // If we're producing a pointer, this is easy.
1705  if (auto destPtrTy = cast<llvm::PointerType>(destTy)) {
1706  if (Value.isNullPointer()) {
1707  // FIXME: integer offsets from non-zero null pointers.
1708  return CGM.getNullPointer(destPtrTy, DestType);
1709  }
1710 
1711  // Convert the integer to a pointer-sized integer before converting it
1712  // to a pointer.
1713  // FIXME: signedness depends on the original integer type.
1714  auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1715  llvm::Constant *C = offset;
1716  C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1717  /*isSigned*/ false);
1718  C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1719  return C;
1720  }
1721 
1722  // Otherwise, we're basically returning an integer constant.
1723 
1724  // FIXME: this does the wrong thing with ptrtoint of a null pointer,
1725  // but since we don't know the original pointer type, there's not much
1726  // we can do about it.
1727 
1728  auto C = getOffset();
1729  C = llvm::ConstantExpr::getIntegerCast(C, destTy, /*isSigned*/ false);
1730  return C;
1731 }
1732 
1733 ConstantLValue
1734 ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1735  // Handle values.
1736  if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1737  if (D->hasAttr<WeakRefAttr>())
1738  return CGM.GetWeakRefReference(D).getPointer();
1739 
1740  if (auto FD = dyn_cast<FunctionDecl>(D))
1741  return CGM.GetAddrOfFunction(FD);
1742 
1743  if (auto VD = dyn_cast<VarDecl>(D)) {
1744  // We can never refer to a variable with local storage.
1745  if (!VD->hasLocalStorage()) {
1746  if (VD->isFileVarDecl() || VD->hasExternalStorage())
1747  return CGM.GetAddrOfGlobalVar(VD);
1748 
1749  if (VD->isLocalVarDecl()) {
1750  return CGM.getOrCreateStaticVarDecl(
1751  *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1752  }
1753  }
1754  }
1755 
1756  return nullptr;
1757  }
1758 
1759  // Otherwise, it must be an expression.
1760  return Visit(base.get<const Expr*>());
1761 }
1762 
1763 ConstantLValue
1764 ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1765  return Visit(E->getSubExpr());
1766 }
1767 
1768 ConstantLValue
1769 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1770  return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1771 }
1772 
1773 ConstantLValue
1774 ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1775  return CGM.GetAddrOfConstantStringFromLiteral(E);
1776 }
1777 
1778 ConstantLValue
1779 ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1781 }
1782 
1783 ConstantLValue
1784 ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1785  auto C = CGM.getObjCRuntime().GenerateConstantString(E->getString());
1786  return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(E->getType()));
1787 }
1788 
1789 ConstantLValue
1790 ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1792 }
1793 
1794 ConstantLValue
1795 ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1796  assert(Emitter.CGF && "Invalid address of label expression outside function");
1797  llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1798  Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1799  CGM.getTypes().ConvertType(E->getType()));
1800  return Ptr;
1801 }
1802 
1803 ConstantLValue
1804 ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1805  unsigned builtin = E->getBuiltinCallee();
1806  if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1807  builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1808  return nullptr;
1809 
1810  auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1811  if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1812  return CGM.getObjCRuntime().GenerateConstantString(literal);
1813  } else {
1814  // FIXME: need to deal with UCN conversion issues.
1815  return CGM.GetAddrOfConstantCFString(literal);
1816  }
1817 }
1818 
1819 ConstantLValue
1820 ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1821  StringRef functionName;
1822  if (auto CGF = Emitter.CGF)
1823  functionName = CGF->CurFn->getName();
1824  else
1825  functionName = "global";
1826 
1827  return CGM.GetAddrOfGlobalBlock(E, functionName);
1828 }
1829 
1830 ConstantLValue
1831 ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1832  QualType T;
1833  if (E->isTypeOperand())
1834  T = E->getTypeOperand(CGM.getContext());
1835  else
1836  T = E->getExprOperand()->getType();
1837  return CGM.GetAddrOfRTTIDescriptor(T);
1838 }
1839 
1840 ConstantLValue
1841 ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1842  return CGM.GetAddrOfUuidDescriptor(E);
1843 }
1844 
1845 ConstantLValue
1846 ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1847  const MaterializeTemporaryExpr *E) {
1848  assert(E->getStorageDuration() == SD_Static);
1849  SmallVector<const Expr *, 2> CommaLHSs;
1851  const Expr *Inner = E->GetTemporaryExpr()
1852  ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1853  return CGM.GetAddrOfGlobalTemporary(E, Inner);
1854 }
1855 
1857  QualType DestType) {
1858  switch (Value.getKind()) {
1860  llvm_unreachable("Constant expressions should be initialized.");
1861  case APValue::LValue:
1862  return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
1863  case APValue::Int:
1864  return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
1865  case APValue::FixedPoint:
1866  return llvm::ConstantInt::get(CGM.getLLVMContext(),
1867  Value.getFixedPoint().getValue());
1868  case APValue::ComplexInt: {
1869  llvm::Constant *Complex[2];
1870 
1871  Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1872  Value.getComplexIntReal());
1873  Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
1874  Value.getComplexIntImag());
1875 
1876  // FIXME: the target may want to specify that this is packed.
1877  llvm::StructType *STy =
1878  llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1879  return llvm::ConstantStruct::get(STy, Complex);
1880  }
1881  case APValue::Float: {
1882  const llvm::APFloat &Init = Value.getFloat();
1883  if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
1884  !CGM.getContext().getLangOpts().NativeHalfType &&
1886  return llvm::ConstantInt::get(CGM.getLLVMContext(),
1887  Init.bitcastToAPInt());
1888  else
1889  return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
1890  }
1891  case APValue::ComplexFloat: {
1892  llvm::Constant *Complex[2];
1893 
1894  Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1895  Value.getComplexFloatReal());
1896  Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
1897  Value.getComplexFloatImag());
1898 
1899  // FIXME: the target may want to specify that this is packed.
1900  llvm::StructType *STy =
1901  llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
1902  return llvm::ConstantStruct::get(STy, Complex);
1903  }
1904  case APValue::Vector: {
1905  unsigned NumElts = Value.getVectorLength();
1907 
1908  for (unsigned I = 0; I != NumElts; ++I) {
1909  const APValue &Elt = Value.getVectorElt(I);
1910  if (Elt.isInt())
1911  Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
1912  else if (Elt.isFloat())
1913  Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
1914  else
1915  llvm_unreachable("unsupported vector element type");
1916  }
1917  return llvm::ConstantVector::get(Inits);
1918  }
1919  case APValue::AddrLabelDiff: {
1920  const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1921  const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1922  llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
1923  llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
1924  if (!LHS || !RHS) return nullptr;
1925 
1926  // Compute difference
1927  llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
1928  LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
1929  RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
1930  llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1931 
1932  // LLVM is a bit sensitive about the exact format of the
1933  // address-of-label difference; make sure to truncate after
1934  // the subtraction.
1935  return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1936  }
1937  case APValue::Struct:
1938  case APValue::Union:
1939  return ConstStructBuilder::BuildStruct(*this, Value, DestType);
1940  case APValue::Array: {
1941  const ConstantArrayType *CAT =
1942  CGM.getContext().getAsConstantArrayType(DestType);
1943  unsigned NumElements = Value.getArraySize();
1944  unsigned NumInitElts = Value.getArrayInitializedElts();
1945 
1946  // Emit array filler, if there is one.
1947  llvm::Constant *Filler = nullptr;
1948  if (Value.hasArrayFiller()) {
1949  Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
1950  CAT->getElementType());
1951  if (!Filler)
1952  return nullptr;
1953  }
1954 
1955  // Emit initializer elements.
1957  if (Filler && Filler->isNullValue())
1958  Elts.reserve(NumInitElts + 1);
1959  else
1960  Elts.reserve(NumElements);
1961 
1962  llvm::Type *CommonElementType = nullptr;
1963  for (unsigned I = 0; I < NumInitElts; ++I) {
1964  llvm::Constant *C = tryEmitPrivateForMemory(
1965  Value.getArrayInitializedElt(I), CAT->getElementType());
1966  if (!C) return nullptr;
1967 
1968  if (I == 0)
1969  CommonElementType = C->getType();
1970  else if (C->getType() != CommonElementType)
1971  CommonElementType = nullptr;
1972  Elts.push_back(C);
1973  }
1974 
1975  // This means that the array type is probably "IncompleteType" or some
1976  // type that is not ConstantArray.
1977  if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
1978  const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
1979  CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
1980  llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
1981  NumElements);
1982  return llvm::ConstantAggregateZero::get(AType);
1983  }
1984 
1985  return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1986  Filler);
1987  }
1989  return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
1990  }
1991  llvm_unreachable("Unknown APValue kind");
1992 }
1993 
1995  const CompoundLiteralExpr *E) {
1996  return EmittedCompoundLiterals.lookup(E);
1997 }
1998 
2000  const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2001  bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2002  (void)Ok;
2003  assert(Ok && "CLE has already been emitted!");
2004 }
2005 
2008  assert(E->isFileScope() && "not a file-scope compound literal expr");
2009  return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
2010 }
2011 
2012 llvm::Constant *
2014  // Member pointer constants always have a very particular form.
2015  const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2016  const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2017 
2018  // A member function pointer.
2019  if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
2020  return getCXXABI().EmitMemberFunctionPointer(method);
2021 
2022  // Otherwise, a member data pointer.
2023  uint64_t fieldOffset = getContext().getFieldOffset(decl);
2024  CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2025  return getCXXABI().EmitMemberDataPointer(type, chars);
2026 }
2027 
2028 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2029  llvm::Type *baseType,
2030  const CXXRecordDecl *base);
2031 
2032 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2033  const RecordDecl *record,
2034  bool asCompleteObject) {
2035  const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2036  llvm::StructType *structure =
2037  (asCompleteObject ? layout.getLLVMType()
2038  : layout.getBaseSubobjectLLVMType());
2039 
2040  unsigned numElements = structure->getNumElements();
2041  std::vector<llvm::Constant *> elements(numElements);
2042 
2043  auto CXXR = dyn_cast<CXXRecordDecl>(record);
2044  // Fill in all the bases.
2045  if (CXXR) {
2046  for (const auto &I : CXXR->bases()) {
2047  if (I.isVirtual()) {
2048  // Ignore virtual bases; if we're laying out for a complete
2049  // object, we'll lay these out later.
2050  continue;
2051  }
2052 
2053  const CXXRecordDecl *base =
2054  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2055 
2056  // Ignore empty bases.
2057  if (base->isEmpty() ||
2059  .isZero())
2060  continue;
2061 
2062  unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2063  llvm::Type *baseType = structure->getElementType(fieldIndex);
2064  elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2065  }
2066  }
2067 
2068  // Fill in all the fields.
2069  for (const auto *Field : record->fields()) {
2070  // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2071  // will fill in later.)
2072  if (!Field->isBitField()) {
2073  unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2074  elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
2075  }
2076 
2077  // For unions, stop after the first named field.
2078  if (record->isUnion()) {
2079  if (Field->getIdentifier())
2080  break;
2081  if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2082  if (FieldRD->findFirstNamedDataMember())
2083  break;
2084  }
2085  }
2086 
2087  // Fill in the virtual bases, if we're working with the complete object.
2088  if (CXXR && asCompleteObject) {
2089  for (const auto &I : CXXR->vbases()) {
2090  const CXXRecordDecl *base =
2091  cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2092 
2093  // Ignore empty bases.
2094  if (base->isEmpty())
2095  continue;
2096 
2097  unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2098 
2099  // We might have already laid this field out.
2100  if (elements[fieldIndex]) continue;
2101 
2102  llvm::Type *baseType = structure->getElementType(fieldIndex);
2103  elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2104  }
2105  }
2106 
2107  // Now go through all other fields and zero them out.
2108  for (unsigned i = 0; i != numElements; ++i) {
2109  if (!elements[i])
2110  elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
2111  }
2112 
2113  return llvm::ConstantStruct::get(structure, elements);
2114 }
2115 
2116 /// Emit the null constant for a base subobject.
2117 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2118  llvm::Type *baseType,
2119  const CXXRecordDecl *base) {
2120  const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2121 
2122  // Just zero out bases that don't have any pointer to data members.
2123  if (baseLayout.isZeroInitializableAsBase())
2124  return llvm::Constant::getNullValue(baseType);
2125 
2126  // Otherwise, we can just use its null constant.
2127  return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
2128 }
2129 
2131  QualType T) {
2132  return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2133 }
2134 
2136  if (T->getAs<PointerType>())
2137  return getNullPointer(
2138  cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2139 
2140  if (getTypes().isZeroInitializable(T))
2141  return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
2142 
2143  if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2144  llvm::ArrayType *ATy =
2145  cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
2146 
2147  QualType ElementTy = CAT->getElementType();
2148 
2149  llvm::Constant *Element =
2150  ConstantEmitter::emitNullForMemory(*this, ElementTy);
2151  unsigned NumElements = CAT->getSize().getZExtValue();
2152  SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2153  return llvm::ConstantArray::get(ATy, Array);
2154  }
2155 
2156  if (const RecordType *RT = T->getAs<RecordType>())
2157  return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
2158 
2159  assert(T->isMemberDataPointerType() &&
2160  "Should only see pointers to data members here!");
2161 
2162  return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
2163 }
2164 
2165 llvm::Constant *
2167  return ::EmitNullConstant(*this, Record, false);
2168 }
const llvm::DataLayout & getDataLayout() const
const Expr * getSubExpr() const
Definition: Expr.h:896
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
Defines the clang::ASTContext interface.
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:183
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition: Expr.h:4024
virtual llvm::Constant * EmitMemberPointer(const APValue &MP, QualType MPT)
Create a member pointer for the given member pointer constant.
Definition: CGCXXABI.cpp:118
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2536
A (possibly-)qualified type.
Definition: Type.h:634
Static storage duration.
Definition: Specifiers.h:280
bool isArrayType() const
Definition: Type.h:6344
llvm::Constant * emitForInitializer(const APValue &value, LangAS destAddrSpace, QualType destType)
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:2559
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:75
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:192
__SIZE_TYPE__ size_t
The unsigned integer type of the result of the sizeof operator.
Definition: opencl-c.h:67
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
bool isMemberDataPointerType() const
Definition: Type.h:6337
llvm::APSInt getValue() const
Definition: FixedPoint.h:110
llvm::Constant * getMemberPointerConstant(const UnaryOperator *e)
llvm::LLVMContext & getLLVMContext()
const Expr * getInit(unsigned Init) const
Definition: Expr.h:4239
ConstantAddress GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
Stmt - This represents one statement.
Definition: Stmt.h:65
llvm::Constant * tryEmitForInitializer(const VarDecl &D)
Try to emit the initiaizer of the given declaration as an abstract constant.
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
Definition: Type.cpp:504
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:232
#define trunc(__x)
Definition: tgmath.h:1232
bool isRecordType() const
Definition: Type.h:6368
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:1932
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
llvm::Constant * emitForMemory(llvm::Constant *C, QualType T)
bool isTransparent() const
Is this a transparent initializer list (that is, an InitListExpr that is purely syntactic, and whose semantics are that of the sole contained initializer)?
Definition: Expr.cpp:2058
ParenExpr - This represents a parethesized expression, e.g.
Definition: Expr.h:1850
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2811
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1261
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:115
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:689
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2483
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
Definition: ExprCXX.h:4155
const Expr * getResultExpr() const
The generic selection&#39;s result expression.
Definition: Expr.h:5092
const AddrLabelExpr * getAddrLabelDiffLHS() const
Definition: APValue.h:405
QualType getElementType() const
Definition: Type.h:2846
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition: DeclCXX.cpp:2355
llvm::Constant * tryEmitPrivateForVarInit(const VarDecl &D)
Represents a variable declaration or definition.
Definition: Decl.h:812
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:2931
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
APFloat & getComplexFloatReal()
Definition: APValue.h:297
const T * getAs() const
Member-template getAs<specific type>&#39;.
Definition: Type.h:6755
unsigned getCharAlign() const
Definition: TargetInfo.h:370
LangAS
Defines the address space values used by the address space qualifier of QualType. ...
Definition: AddressSpaces.h:25
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
Expr * getExprOperand() const
Definition: ExprCXX.h:725
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Definition: ExprCXX.h:3088
bool isZeroInitializableAsBase() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer when considered as a bas...
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:269
Represents a struct/union/class.
Definition: Decl.h:3592
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
Definition: DeclCXX.h:1326
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
Definition: ExprCXX.h:4196
bool cleanupsHaveSideEffects() const
Definition: ExprCXX.h:3126
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
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...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:154
llvm::Constant * tryEmitAbstractForInitializer(const VarDecl &D)
Try to emit the initializer of the given declaration as an abstract constant.
bool isFileScope() const
Definition: Expr.h:2961
field_range fields() const
Definition: Decl.h:3783
Represents a member of a struct/union/class.
Definition: Decl.h:2578
StringLiteral * getString()
Definition: ExprObjC.h:62
unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const
bool isReferenceType() const
Definition: Type.h:6307
unsigned getArraySize() const
Definition: APValue.h:361
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:52
Expr * getSubExpr()
Definition: Expr.h:3056
i32 captured_struct **param SharedsTy A type which contains references the shared variables *param Shareds Context with the list of shared variables from the p *TaskFunction *param Data Additional data for task generation like final * state
bool isFloat() const
Definition: APValue.h:239
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
Describes an C or C++ initializer list.
Definition: Expr.h:4191
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:668
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2656
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:37
APValue Val
Val - This is the value the expression can be folded to.
Definition: Expr.h:573
llvm::Constant * tryEmitPrivate(const Expr *E, QualType T)
llvm::StructType * getBaseSubobjectLLVMType() const
Return the "base subobject" LLVM type associated with this record.
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
Definition: Expr.cpp:2594
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:50
field_iterator field_begin() const
Definition: Decl.cpp:4144
unsigned getBitWidthValue(const ASTContext &Ctx) const
Definition: Decl.cpp:3786
bool isInt() const
Definition: APValue.h:238
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3004
APSInt & getComplexIntReal()
Definition: APValue.h:281
llvm::GlobalValue * getCurrentAddrPrivate()
Get the address of the current location.
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1072
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:446
bool isTypeConstant(QualType QTy, bool ExcludeCtorDtor)
isTypeConstant - Determine whether an object of this type can be emitted as a constant.
const Expr * getExpr() const
Get the initialization expression that will be used.
Definition: ExprCXX.h:1161
APValue & getVectorElt(unsigned I)
Definition: APValue.h:325
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1616
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:57
ConstantAddress getElementBitCast(llvm::Type *ty) const
Definition: Address.h:92
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
const TargetCodeGenInfo & getTargetCodeGenInfo()
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1333
APValue & getArrayFiller()
Definition: APValue.h:349
llvm::Constant * getNullPointer(llvm::PointerType *T, QualType QT)
Get target specific null pointer.
InitListExpr * getUpdater() const
Definition: Expr.h:4777
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:178
ConstantExpr - An expression that occurs in a constant context.
Definition: Expr.h:910
unsigned Offset
Definition: Format.cpp:1630
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
bool hasArrayFiller() const
Definition: APValue.h:346
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:636
This represents one expression.
Definition: Expr.h:106
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2375
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1035
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.
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:6818
Inits[]
Definition: OpenMPClause.h:150
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:5183
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
unsigned getNumInits() const
Definition: Expr.h:4221
field_iterator field_end() const
Definition: Decl.h:3786
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
Definition: RecordLayout.h:217
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:62
QualType getType() const
Definition: Expr.h:128
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
APValue & getStructField(unsigned i)
Definition: APValue.h:378
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition: ExprCXX.h:4199
QualType getEncodedType() const
Definition: ExprObjC.h:400
ConstantAddress GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
UnaryOperator - This represents the unary-expression&#39;s (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
Definition: Expr.h:1902
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition: ExprCXX.cpp:76
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:3957
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition: Decl.cpp:2257
APSInt & getComplexIntImag()
Definition: APValue.h:289
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2025
const Expr * getSubExpr() const
Definition: Expr.h:1866
bool isUnionType() const
Definition: Type.cpp:474
ASTContext & getContext() const
const FieldDecl * getUnionField() const
Definition: APValue.h:389
ConstantAddress GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
Definition: Expr.cpp:1367
The l-value was considered opaque, so the alignment was determined from a type.
RecordDecl * getDecl() const
Definition: Type.h:4379
APValue & getStructBase(unsigned i)
Definition: APValue.h:374
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:718
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Definition: RecordLayout.h:190
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
Definition: CGDecl.cpp:210
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...
Expr * getBase() const
Definition: Expr.h:4774
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:338
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:73
#define false
Definition: stdbool.h:33
static QualType getNonMemoryType(CodeGenModule &CGM, QualType type)
StringLiteral * getFunctionName()
Definition: Expr.h:1819
Encodes a location in the source.
const AddrLabelExpr * getAddrLabelDiffRHS() const
Definition: APValue.h:409
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6187
virtual ConstantAddress GenerateConstantString(const StringLiteral *)=0
Generate a constant string object.
Expr * getSubExpr() const
Definition: Expr.h:1932
ConstantAddress GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
CastKind getCastKind() const
Definition: Expr.h:3050
APValue & getUnionValue()
Definition: APValue.h:393
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:2659
APFloat & getFloat()
Definition: APValue.h:265
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2040
const ConstantArrayType * getAsConstantArrayType(QualType T) const
Definition: ASTContext.h:2415
ConstantAddress GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:182
llvm::Constant * EmitNullConstantForBase(const CXXRecordDecl *Record)
Return a null constant appropriate for zero-initializing a base class with the given type...
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
llvm::Constant * emitAbstract(const Expr *E, QualType T)
Emit the result of the given expression as an abstract constant, asserting that it succeeded...
ConstantAddress GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
void registerCurrentAddrPrivate(llvm::Constant *signal, llvm::GlobalValue *placeholder)
Register a &#39;signal&#39; value with the emitter to inform it where to resolve a placeholder.
llvm::GlobalVariable * getAddrOfConstantCompoundLiteralIfEmitted(const CompoundLiteralExpr *E)
If it&#39;s been emitted already, returns the GlobalVariable corresponding to a compound literal...
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can&#39;t be done.
llvm::Constant * emitNullForMemory(QualType T)
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition: Expr.h:4285
bool hasFlexibleArrayMember() const
Definition: Decl.h:3646
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2295
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:214
const Expr * getInitializer() const
Definition: Expr.h:2957
Represents a C11 generic selection.
Definition: Expr.h:5016
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:3763
const FieldDecl * getTargetUnionField() const
Definition: Expr.h:3081
This class organizes the cross-function state that is used while generating LLVM code.
bool isTypeOperand() const
Definition: ExprCXX.h:708
Dataflow Directional Tag Classes.
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:183
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1764
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:571
const Expr * getInit() const
Definition: Decl.h:1219
static llvm::Constant * EmitNullConstantForBase(CodeGenModule &CGM, llvm::Type *baseType, const CXXRecordDecl *base)
Emit the null constant for a base subobject.
llvm::Constant * getPointer() const
Definition: Address.h:83
const Expr * getExpr() const
Definition: ExprCXX.h:1105
unsigned getArrayInitializedElts() const
Definition: APValue.h:357
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2755
llvm::Module & getModule() const
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
Definition: DeclBase.h:2016
LabelDecl * getLabel() const
Definition: Expr.h:3785
llvm::Constant * tryEmitPrivateForMemory(const Expr *E, QualType T)
void EmitExplicitCastExprType(const ExplicitCastExpr *E, CodeGenFunction *CGF=nullptr)
Emit type info if type of an expression is a variably modified type.
Definition: CGExpr.cpp:1019
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition: Expr.h:544
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4369
StmtVisitorBase - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:35
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:379
const llvm::APInt & getSize() const
Definition: Type.h:2889
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2076
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.
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1412
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
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.
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
ConstantAddress GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E)
Returns a pointer to a constant global variable for the given file-scope compound literal expression...
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Definition: APValue.h:38
Represents a base class of a C++ class.
Definition: DeclCXX.h:191
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2072
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1136
void setAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV)
Notes that CLE&#39;s GlobalVariable is GV.
static llvm::Constant * EmitNullConstant(CodeGenModule &CGM, const RecordDecl *record, bool asCompleteObject)
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
ValueKind getKind() const
Definition: APValue.h:236
APFloat & getComplexFloatImag()
Definition: APValue.h:305
Represents a C++ struct/union/class.
Definition: DeclCXX.h:299
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:3983
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6098
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:74
CharUnits getNonVirtualSize() const
getNonVirtualSize - Get the non-virtual size (in chars) of an object, which is the size of the object...
Definition: RecordLayout.h:202
unsigned getVirtualBaseIndex(const CXXRecordDecl *base) const
Return the LLVM field index corresponding to the given virtual base.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1572
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2402
void finalize(llvm::GlobalVariable *global)
llvm::Constant * tryEmitAbstract(const Expr *E, QualType T)
Try to emit the result of the given expression as an abstract constant.
static ConstantAddress invalid()
Definition: Address.h:79
CGCXXABI & getCXXABI() const
__DEVICE__ int max(int __a, int __b)
bool isUnion() const
Definition: Decl.h:3251
llvm::Constant * tryEmitAbstractForMemory(const Expr *E, QualType T)
__DEVICE__ int min(int __a, int __b)
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
Definition: Expr.h:4303
llvm::Constant * GetAddrOfGlobalBlock(const BlockExpr *BE, StringRef Name)
Gets the address of a block which requires no captures.
Definition: CGBlocks.cpp:1370
QualType getType() const
Definition: Decl.h:647
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition: ExprCXX.h:1409
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:886
APSInt & getInt()
Definition: APValue.h:257
unsigned getTargetAddressSpace(QualType T) const
Definition: ASTContext.h:2501
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:706
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:2871
Defines enum values for all the target-independent builtin functions.
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:4899
APFixedPoint & getFixedPoint()
Definition: APValue.h:273
CharUnits & getLValueOffset()
Definition: APValue.cpp:627
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
unsigned getVectorLength() const
Definition: APValue.h:333