1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Constant Expr nodes as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
16 #include "CGObjCRuntime.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/APValue.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/Builtins.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalVariable.h"
28 using namespace clang;
29 using namespace CodeGen;
31 //===----------------------------------------------------------------------===//
33 //===----------------------------------------------------------------------===//
36 class ConstStructBuilder {
41 CharUnits NextFieldOffsetInChars;
42 CharUnits LLVMStructAlignment;
43 SmallVector<llvm::Constant *, 32> Elements;
45 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
47 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
48 const APValue &Value, QualType ValTy);
51 ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
52 : CGM(CGM), CGF(CGF), Packed(false),
53 NextFieldOffsetInChars(CharUnits::Zero()),
54 LLVMStructAlignment(CharUnits::One()) { }
56 void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
57 llvm::Constant *InitExpr);
59 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
61 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
62 llvm::ConstantInt *InitExpr);
64 void AppendPadding(CharUnits PadSize);
66 void AppendTailPadding(CharUnits RecordSize);
68 void ConvertStructToPacked();
70 bool Build(InitListExpr *ILE);
71 void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
72 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
73 llvm::Constant *Finalize(QualType Ty);
75 CharUnits getAlignment(const llvm::Constant *C) const {
76 if (Packed) return CharUnits::One();
77 return CharUnits::fromQuantity(
78 CGM.getDataLayout().getABITypeAlignment(C->getType()));
81 CharUnits getSizeInChars(const llvm::Constant *C) const {
82 return CharUnits::fromQuantity(
83 CGM.getDataLayout().getTypeAllocSize(C->getType()));
87 void ConstStructBuilder::
88 AppendField(const FieldDecl *Field, uint64_t FieldOffset,
89 llvm::Constant *InitCst) {
90 const ASTContext &Context = CGM.getContext();
92 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
94 AppendBytes(FieldOffsetInChars, InitCst);
97 void ConstStructBuilder::
98 AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
100 assert(NextFieldOffsetInChars <= FieldOffsetInChars
101 && "Field offset mismatch!");
103 CharUnits FieldAlignment = getAlignment(InitCst);
105 // Round up the field offset to the alignment of the field type.
106 CharUnits AlignedNextFieldOffsetInChars =
107 NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
109 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
110 assert(!Packed && "Alignment is wrong even with a packed struct!");
112 // Convert the struct to a packed struct.
113 ConvertStructToPacked();
115 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
118 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
119 // We need to append padding.
120 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
122 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
123 "Did not add enough padding!");
125 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
129 Elements.push_back(InitCst);
130 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
131 getSizeInChars(InitCst);
134 assert(LLVMStructAlignment == CharUnits::One() &&
135 "Packed struct not byte-aligned!");
137 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
140 void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
141 uint64_t FieldOffset,
142 llvm::ConstantInt *CI) {
143 const ASTContext &Context = CGM.getContext();
144 const uint64_t CharWidth = Context.getCharWidth();
145 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
146 if (FieldOffset > NextFieldOffsetInBits) {
147 // We need to add padding.
148 CharUnits PadSize = Context.toCharUnitsFromBits(
149 llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
150 Context.getTargetInfo().getCharAlign()));
152 AppendPadding(PadSize);
155 uint64_t FieldSize = Field->getBitWidthValue(Context);
157 llvm::APInt FieldValue = CI->getValue();
159 // Promote the size of FieldValue if necessary
160 // FIXME: This should never occur, but currently it can because initializer
161 // constants are cast to bool, and because clang is not enforcing bitfield
163 if (FieldSize > FieldValue.getBitWidth())
164 FieldValue = FieldValue.zext(FieldSize);
166 // Truncate the size of FieldValue to the bit field size.
167 if (FieldSize < FieldValue.getBitWidth())
168 FieldValue = FieldValue.trunc(FieldSize);
170 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
171 if (FieldOffset < NextFieldOffsetInBits) {
172 // Either part of the field or the entire field can go into the previous
174 assert(!Elements.empty() && "Elements can't be empty!");
176 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
178 bool FitsCompletelyInPreviousByte =
179 BitsInPreviousByte >= FieldValue.getBitWidth();
181 llvm::APInt Tmp = FieldValue;
183 if (!FitsCompletelyInPreviousByte) {
184 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
186 if (CGM.getDataLayout().isBigEndian()) {
187 Tmp = Tmp.lshr(NewFieldWidth);
188 Tmp = Tmp.trunc(BitsInPreviousByte);
190 // We want the remaining high bits.
191 FieldValue = FieldValue.trunc(NewFieldWidth);
193 Tmp = Tmp.trunc(BitsInPreviousByte);
195 // We want the remaining low bits.
196 FieldValue = FieldValue.lshr(BitsInPreviousByte);
197 FieldValue = FieldValue.trunc(NewFieldWidth);
201 Tmp = Tmp.zext(CharWidth);
202 if (CGM.getDataLayout().isBigEndian()) {
203 if (FitsCompletelyInPreviousByte)
204 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
206 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
209 // 'or' in the bits that go into the previous byte.
210 llvm::Value *LastElt = Elements.back();
211 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
212 Tmp |= Val->getValue();
214 assert(isa<llvm::UndefValue>(LastElt));
215 // If there is an undef field that we're adding to, it can either be a
216 // scalar undef (in which case, we just replace it with our field) or it
217 // is an array. If it is an array, we have to pull one byte off the
218 // array so that the other undef bytes stay around.
219 if (!isa<llvm::IntegerType>(LastElt->getType())) {
220 // The undef padding will be a multibyte array, create a new smaller
221 // padding and then an hole for our i8 to get plopped into.
222 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
223 "Expected array padding of undefs");
224 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
225 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
226 AT->getNumElements() != 0 &&
227 "Expected non-empty array padding of undefs");
229 // Remove the padding array.
230 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
233 // Add the padding back in two chunks.
234 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
235 AppendPadding(CharUnits::One());
236 assert(isa<llvm::UndefValue>(Elements.back()) &&
237 Elements.back()->getType()->isIntegerTy(CharWidth) &&
238 "Padding addition didn't work right");
242 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
244 if (FitsCompletelyInPreviousByte)
248 while (FieldValue.getBitWidth() > CharWidth) {
251 if (CGM.getDataLayout().isBigEndian()) {
252 // We want the high bits.
254 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
256 // We want the low bits.
257 Tmp = FieldValue.trunc(CharWidth);
259 FieldValue = FieldValue.lshr(CharWidth);
262 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
263 ++NextFieldOffsetInChars;
265 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
268 assert(FieldValue.getBitWidth() > 0 &&
269 "Should have at least one bit left!");
270 assert(FieldValue.getBitWidth() <= CharWidth &&
271 "Should not have more than a byte left!");
273 if (FieldValue.getBitWidth() < CharWidth) {
274 if (CGM.getDataLayout().isBigEndian()) {
275 unsigned BitWidth = FieldValue.getBitWidth();
277 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
279 FieldValue = FieldValue.zext(CharWidth);
282 // Append the last element.
283 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
285 ++NextFieldOffsetInChars;
288 void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
289 if (PadSize.isZero())
292 llvm::Type *Ty = CGM.Int8Ty;
293 if (PadSize > CharUnits::One())
294 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
296 llvm::Constant *C = llvm::UndefValue::get(Ty);
297 Elements.push_back(C);
298 assert(getAlignment(C) == CharUnits::One() &&
299 "Padding must have 1 byte alignment!");
301 NextFieldOffsetInChars += getSizeInChars(C);
304 void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
305 assert(NextFieldOffsetInChars <= RecordSize &&
308 AppendPadding(RecordSize - NextFieldOffsetInChars);
311 void ConstStructBuilder::ConvertStructToPacked() {
312 SmallVector<llvm::Constant *, 16> PackedElements;
313 CharUnits ElementOffsetInChars = CharUnits::Zero();
315 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
316 llvm::Constant *C = Elements[i];
318 CharUnits ElementAlign = CharUnits::fromQuantity(
319 CGM.getDataLayout().getABITypeAlignment(C->getType()));
320 CharUnits AlignedElementOffsetInChars =
321 ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
323 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
324 // We need some padding.
326 AlignedElementOffsetInChars - ElementOffsetInChars;
328 llvm::Type *Ty = CGM.Int8Ty;
329 if (NumChars > CharUnits::One())
330 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
332 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
333 PackedElements.push_back(Padding);
334 ElementOffsetInChars += getSizeInChars(Padding);
337 PackedElements.push_back(C);
338 ElementOffsetInChars += getSizeInChars(C);
341 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
342 "Packing the struct changed its size!");
344 Elements.swap(PackedElements);
345 LLVMStructAlignment = CharUnits::One();
349 bool ConstStructBuilder::Build(InitListExpr *ILE) {
350 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
351 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
353 unsigned FieldNo = 0;
354 unsigned ElementNo = 0;
356 for (RecordDecl::field_iterator Field = RD->field_begin(),
357 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
358 // If this is a union, skip all the fields that aren't being initialized.
359 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
362 // Don't emit anonymous bitfields, they just affect layout.
363 if (Field->isUnnamedBitfield())
366 // Get the initializer. A struct can include fields without initializers,
367 // we just use explicit null values for them.
368 llvm::Constant *EltInit;
369 if (ElementNo < ILE->getNumInits())
370 EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
371 Field->getType(), CGF);
373 EltInit = CGM.EmitNullConstant(Field->getType());
378 if (!Field->isBitField()) {
379 // Handle non-bitfield members.
380 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
382 // Otherwise we have a bitfield.
383 AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
384 cast<llvm::ConstantInt>(EltInit));
393 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
394 : Decl(Decl), Offset(Offset), Index(Index) {
397 const CXXRecordDecl *Decl;
401 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
405 void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
407 const CXXRecordDecl *VTableClass,
409 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
411 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
412 // Add a vtable pointer, if we need one and it hasn't already been added.
413 if (CD->isDynamicClass() && !IsPrimaryBase) {
414 llvm::Constant *VTableAddressPoint =
415 CGM.getCXXABI().getVTableAddressPointForConstExpr(
416 BaseSubobject(CD, Offset), VTableClass);
417 AppendBytes(Offset, VTableAddressPoint);
420 // Accumulate and sort bases, in order to visit them in address order, which
421 // may not be the same as declaration order.
422 SmallVector<BaseInfo, 8> Bases;
423 Bases.reserve(CD->getNumBases());
425 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
426 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
427 assert(!Base->isVirtual() && "should not have virtual bases here");
428 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
429 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
430 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
432 std::stable_sort(Bases.begin(), Bases.end());
434 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
435 BaseInfo &Base = Bases[I];
437 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
438 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
439 VTableClass, Offset + Base.Offset);
443 unsigned FieldNo = 0;
444 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
446 for (RecordDecl::field_iterator Field = RD->field_begin(),
447 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
448 // If this is a union, skip all the fields that aren't being initialized.
449 if (RD->isUnion() && Val.getUnionField() != *Field)
452 // Don't emit anonymous bitfields, they just affect layout.
453 if (Field->isUnnamedBitfield())
456 // Emit the value of the initializer.
457 const APValue &FieldValue =
458 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
459 llvm::Constant *EltInit =
460 CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
461 assert(EltInit && "EmitConstantValue can't fail");
463 if (!Field->isBitField()) {
464 // Handle non-bitfield members.
465 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
467 // Otherwise we have a bitfield.
468 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
469 cast<llvm::ConstantInt>(EltInit));
474 llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
475 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
476 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
478 CharUnits LayoutSizeInChars = Layout.getSize();
480 if (NextFieldOffsetInChars > LayoutSizeInChars) {
481 // If the struct is bigger than the size of the record type,
482 // we must have a flexible array member at the end.
483 assert(RD->hasFlexibleArrayMember() &&
484 "Must have flexible array member if struct is bigger than type!");
486 // No tail padding is necessary.
488 // Append tail padding if necessary.
489 AppendTailPadding(LayoutSizeInChars);
491 CharUnits LLVMSizeInChars =
492 NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
494 // Check if we need to convert the struct to a packed struct.
495 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
496 LLVMSizeInChars > LayoutSizeInChars) {
497 assert(!Packed && "Size mismatch!");
499 ConvertStructToPacked();
500 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
501 "Converting to packed did not help!");
504 assert(LayoutSizeInChars == NextFieldOffsetInChars &&
505 "Tail padding mismatch!");
508 // Pick the type to use. If the type is layout identical to the ConvertType
509 // type then use it, otherwise use whatever the builder produced for us.
510 llvm::StructType *STy =
511 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
513 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
514 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
515 if (ValSTy->isLayoutIdentical(STy))
519 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
521 assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) ==
522 getSizeInChars(Result) && "Size mismatch!");
527 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
528 CodeGenFunction *CGF,
530 ConstStructBuilder Builder(CGM, CGF);
532 if (!Builder.Build(ILE))
535 return Builder.Finalize(ILE->getType());
538 llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
539 CodeGenFunction *CGF,
542 ConstStructBuilder Builder(CGM, CGF);
544 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
545 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
546 Builder.Build(Val, RD, false, CD, CharUnits::Zero());
548 return Builder.Finalize(ValTy);
552 //===----------------------------------------------------------------------===//
554 //===----------------------------------------------------------------------===//
556 /// This class only needs to handle two cases:
557 /// 1) Literals (this is used by APValue emission to emit literals).
558 /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
559 /// constant fold these types).
560 class ConstExprEmitter :
561 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
563 CodeGenFunction *CGF;
564 llvm::LLVMContext &VMContext;
566 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
567 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
570 //===--------------------------------------------------------------------===//
572 //===--------------------------------------------------------------------===//
574 llvm::Constant *VisitStmt(Stmt *S) {
578 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
579 return Visit(PE->getSubExpr());
583 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
584 return Visit(PE->getReplacement());
587 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
588 return Visit(GE->getResultExpr());
591 llvm::Constant *VisitChooseExpr(ChooseExpr *CE) {
592 return Visit(CE->getChosenSubExpr());
595 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
596 return Visit(E->getInitializer());
599 llvm::Constant *VisitCastExpr(CastExpr* E) {
600 Expr *subExpr = E->getSubExpr();
601 llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
602 if (!C) return nullptr;
604 llvm::Type *destType = ConvertType(E->getType());
606 switch (E->getCastKind()) {
608 // GCC cast to union extension
609 assert(E->getType()->isUnionType() &&
610 "Destination type is not union type!");
612 // Build a struct with the union sub-element as the first member,
613 // and padded to the appropriate size
614 SmallVector<llvm::Constant*, 2> Elts;
615 SmallVector<llvm::Type*, 2> Types;
617 Types.push_back(C->getType());
618 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
619 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType);
621 assert(CurSize <= TotalSize && "Union size mismatch!");
622 if (unsigned NumPadBytes = TotalSize - CurSize) {
623 llvm::Type *Ty = CGM.Int8Ty;
625 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
627 Elts.push_back(llvm::UndefValue::get(Ty));
631 llvm::StructType* STy =
632 llvm::StructType::get(C->getType()->getContext(), Types, false);
633 return llvm::ConstantStruct::get(STy, Elts);
636 case CK_AddressSpaceConversion:
637 return llvm::ConstantExpr::getAddrSpaceCast(C, destType);
639 case CK_LValueToRValue:
640 case CK_AtomicToNonAtomic:
641 case CK_NonAtomicToAtomic:
643 case CK_ConstructorConversion:
646 case CK_Dependent: llvm_unreachable("saw dependent cast!");
648 case CK_BuiltinFnToFnPtr:
649 llvm_unreachable("builtin functions are handled elsewhere");
651 case CK_ReinterpretMemberPointer:
652 case CK_DerivedToBaseMemberPointer:
653 case CK_BaseToDerivedMemberPointer:
654 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
656 // These will never be supported.
657 case CK_ObjCObjectLValueCast:
658 case CK_ARCProduceObject:
659 case CK_ARCConsumeObject:
660 case CK_ARCReclaimReturnedObject:
661 case CK_ARCExtendBlockObject:
662 case CK_CopyAndAutoreleaseBlockObject:
665 // These don't need to be handled here because Evaluate knows how to
666 // evaluate them in the cases where they can be folded.
670 case CK_LValueBitCast:
671 case CK_NullToMemberPointer:
672 case CK_UserDefinedConversion:
673 case CK_CPointerToObjCPointerCast:
674 case CK_BlockPointerToObjCPointerCast:
675 case CK_AnyPointerToBlockPointerCast:
676 case CK_ArrayToPointerDecay:
677 case CK_FunctionToPointerDecay:
678 case CK_BaseToDerived:
679 case CK_DerivedToBase:
680 case CK_UncheckedDerivedToBase:
681 case CK_MemberPointerToBoolean:
683 case CK_FloatingRealToComplex:
684 case CK_FloatingComplexToReal:
685 case CK_FloatingComplexToBoolean:
686 case CK_FloatingComplexCast:
687 case CK_FloatingComplexToIntegralComplex:
688 case CK_IntegralRealToComplex:
689 case CK_IntegralComplexToReal:
690 case CK_IntegralComplexToBoolean:
691 case CK_IntegralComplexCast:
692 case CK_IntegralComplexToFloatingComplex:
693 case CK_PointerToIntegral:
694 case CK_PointerToBoolean:
695 case CK_NullToPointer:
696 case CK_IntegralCast:
697 case CK_IntegralToPointer:
698 case CK_IntegralToBoolean:
699 case CK_IntegralToFloating:
700 case CK_FloatingToIntegral:
701 case CK_FloatingToBoolean:
702 case CK_FloatingCast:
703 case CK_ZeroToOCLEvent:
706 llvm_unreachable("Invalid CastKind");
709 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
710 return Visit(DAE->getExpr());
713 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
714 // No need for a DefaultInitExprScope: we don't handle 'this' in a
715 // constant expression.
716 return Visit(DIE->getExpr());
719 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
720 return Visit(E->GetTemporaryExpr());
723 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
724 if (ILE->isStringLiteralInit())
725 return Visit(ILE->getInit(0));
727 llvm::ArrayType *AType =
728 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
729 llvm::Type *ElemTy = AType->getElementType();
730 unsigned NumInitElements = ILE->getNumInits();
731 unsigned NumElements = AType->getNumElements();
733 // Initialising an array requires us to automatically
734 // initialise any elements that have not been initialised explicitly
735 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
737 // Copy initializer elements.
738 std::vector<llvm::Constant*> Elts;
739 Elts.reserve(NumInitableElts + NumElements);
741 bool RewriteType = false;
742 for (unsigned i = 0; i < NumInitableElts; ++i) {
743 Expr *Init = ILE->getInit(i);
744 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
747 RewriteType |= (C->getType() != ElemTy);
751 // Initialize remaining array elements.
752 // FIXME: This doesn't handle member pointers correctly!
753 llvm::Constant *fillC;
754 if (Expr *filler = ILE->getArrayFiller())
755 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
757 fillC = llvm::Constant::getNullValue(ElemTy);
760 RewriteType |= (fillC->getType() != ElemTy);
761 Elts.resize(NumElements, fillC);
764 // FIXME: Try to avoid packing the array
765 std::vector<llvm::Type*> Types;
766 Types.reserve(NumInitableElts + NumElements);
767 for (unsigned i = 0, e = Elts.size(); i < e; ++i)
768 Types.push_back(Elts[i]->getType());
769 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
771 return llvm::ConstantStruct::get(SType, Elts);
774 return llvm::ConstantArray::get(AType, Elts);
777 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) {
778 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
781 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
782 return CGM.EmitNullConstant(E->getType());
785 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
786 if (ILE->getType()->isArrayType())
787 return EmitArrayInitialization(ILE);
789 if (ILE->getType()->isRecordType())
790 return EmitRecordInitialization(ILE);
795 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
796 if (!E->getConstructor()->isTrivial())
799 QualType Ty = E->getType();
801 // FIXME: We should not have to call getBaseElementType here.
802 const RecordType *RT =
803 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
804 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
806 // If the class doesn't have a trivial destructor, we can't emit it as a
808 if (!RD->hasTrivialDestructor())
811 // Only copy and default constructors can be trivial.
814 if (E->getNumArgs()) {
815 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
816 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
817 "trivial ctor has argument but isn't a copy/move ctor");
819 Expr *Arg = E->getArg(0);
820 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
821 "argument to copy ctor is of wrong type");
826 return CGM.EmitNullConstant(Ty);
829 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
830 return CGM.GetConstantArrayFromStringLiteral(E);
833 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
834 // This must be an @encode initializing an array in a static initializer.
835 // Don't emit it as the address of the string, emit the string data itself
836 // as an inline array.
838 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
839 QualType T = E->getType();
840 if (T->getTypeClass() == Type::TypeOfExpr)
841 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
842 const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
844 // Resize the string to the right size, adding zeros at the end, or
845 // truncating as needed.
846 Str.resize(CAT->getSize().getZExtValue(), '\0');
847 return llvm::ConstantDataArray::getString(VMContext, Str, false);
850 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
851 return Visit(E->getSubExpr());
855 llvm::Type *ConvertType(QualType T) {
856 return CGM.getTypes().ConvertType(T);
860 llvm::Constant *EmitLValue(APValue::LValueBase LVBase) {
861 if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) {
862 if (Decl->hasAttr<WeakRefAttr>())
863 return CGM.GetWeakRefReference(Decl);
864 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
865 return CGM.GetAddrOfFunction(FD);
866 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
867 // We can never refer to a variable with local storage.
868 if (!VD->hasLocalStorage()) {
869 if (VD->isFileVarDecl() || VD->hasExternalStorage())
870 return CGM.GetAddrOfGlobalVar(VD);
871 else if (VD->isLocalVarDecl())
872 return CGM.getStaticLocalDeclAddress(VD);
878 Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>());
879 switch (E->getStmtClass()) {
881 case Expr::CompoundLiteralExprClass: {
882 // Note that due to the nature of compound literals, this is guaranteed
883 // to be the only use of the variable, so we just generate it here.
884 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
885 llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(),
886 CLE->getType(), CGF);
887 // FIXME: "Leaked" on failure.
889 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
890 E->getType().isConstant(CGM.getContext()),
891 llvm::GlobalValue::InternalLinkage,
892 C, ".compoundliteral", nullptr,
893 llvm::GlobalVariable::NotThreadLocal,
894 CGM.getContext().getTargetAddressSpace(E->getType()));
897 case Expr::StringLiteralClass:
898 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
899 case Expr::ObjCEncodeExprClass:
900 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
901 case Expr::ObjCStringLiteralClass: {
902 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
904 CGM.getObjCRuntime().GenerateConstantString(SL->getString());
905 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
907 case Expr::PredefinedExprClass: {
908 unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
910 LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
911 return cast<llvm::Constant>(Res.getAddress());
912 } else if (Type == PredefinedExpr::PrettyFunction) {
913 return CGM.GetAddrOfConstantCString("top level", ".tmp");
916 return CGM.GetAddrOfConstantCString("", ".tmp");
918 case Expr::AddrLabelExprClass: {
919 assert(CGF && "Invalid address of label expression outside function.");
920 llvm::Constant *Ptr =
921 CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
922 return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
924 case Expr::CallExprClass: {
925 CallExpr* CE = cast<CallExpr>(E);
926 unsigned builtin = CE->getBuiltinCallee();
928 Builtin::BI__builtin___CFStringMakeConstantString &&
930 Builtin::BI__builtin___NSStringMakeConstantString)
932 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
933 const StringLiteral *Literal = cast<StringLiteral>(Arg);
935 Builtin::BI__builtin___NSStringMakeConstantString) {
936 return CGM.getObjCRuntime().GenerateConstantString(Literal);
938 // FIXME: need to deal with UCN conversion issues.
939 return CGM.GetAddrOfConstantCFString(Literal);
941 case Expr::BlockExprClass: {
942 std::string FunctionName;
944 FunctionName = CGF->CurFn->getName();
946 FunctionName = "global";
948 return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
950 case Expr::CXXTypeidExprClass: {
951 CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E);
953 if (Typeid->isTypeOperand())
954 T = Typeid->getTypeOperand(CGM.getContext());
956 T = Typeid->getExprOperand()->getType();
957 return CGM.GetAddrOfRTTIDescriptor(T);
959 case Expr::CXXUuidofExprClass: {
960 return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E));
962 case Expr::MaterializeTemporaryExprClass: {
963 MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
964 assert(MTE->getStorageDuration() == SD_Static);
965 SmallVector<const Expr *, 2> CommaLHSs;
966 SmallVector<SubobjectAdjustment, 2> Adjustments;
967 const Expr *Inner = MTE->GetTemporaryExpr()
968 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
969 return CGM.GetAddrOfGlobalTemporary(MTE, Inner);
977 } // end anonymous namespace.
979 llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
980 CodeGenFunction *CGF) {
981 // Make a quick check if variable can be default NULL initialized
982 // and avoid going through rest of code which may do, for c++11,
983 // initialization of memory to all NULLs.
984 if (!D.hasLocalStorage()) {
985 QualType Ty = D.getType();
986 if (Ty->isArrayType())
987 Ty = Context.getBaseElementType(Ty);
988 if (Ty->isRecordType())
989 if (const CXXConstructExpr *E =
990 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
991 const CXXConstructorDecl *CD = E->getConstructor();
992 if (CD->isTrivial() && CD->isDefaultConstructor())
993 return EmitNullConstant(D.getType());
997 if (const APValue *Value = D.evaluateValue())
998 return EmitConstantValueForMemory(*Value, D.getType(), CGF);
1000 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1001 // reference is a constant expression, and the reference binds to a temporary,
1002 // then constant initialization is performed. ConstExprEmitter will
1003 // incorrectly emit a prvalue constant in this case, and the calling code
1004 // interprets that as the (pointer) value of the reference, rather than the
1005 // desired value of the referee.
1006 if (D.getType()->isReferenceType())
1009 const Expr *E = D.getInit();
1010 assert(E && "No initializer to emit");
1012 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1013 if (C && C->getType()->isIntegerTy(1)) {
1014 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1015 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1020 llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
1022 CodeGenFunction *CGF) {
1023 Expr::EvalResult Result;
1025 bool Success = false;
1027 if (DestType->isReferenceType())
1028 Success = E->EvaluateAsLValue(Result, Context);
1030 Success = E->EvaluateAsRValue(Result, Context);
1032 llvm::Constant *C = nullptr;
1033 if (Success && !Result.HasSideEffects)
1034 C = EmitConstantValue(Result.Val, DestType, CGF);
1036 C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1038 if (C && C->getType()->isIntegerTy(1)) {
1039 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1040 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1045 llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value,
1047 CodeGenFunction *CGF) {
1048 // For an _Atomic-qualified constant, we may need to add tail padding.
1049 if (auto *AT = DestType->getAs<AtomicType>()) {
1050 QualType InnerType = AT->getValueType();
1051 auto *Inner = EmitConstantValue(Value, InnerType, CGF);
1053 uint64_t InnerSize = Context.getTypeSize(InnerType);
1054 uint64_t OuterSize = Context.getTypeSize(DestType);
1055 if (InnerSize == OuterSize)
1058 assert(InnerSize < OuterSize && "emitted over-large constant for atomic");
1059 llvm::Constant *Elts[] = {
1061 llvm::ConstantAggregateZero::get(
1062 llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8))
1064 return llvm::ConstantStruct::getAnon(Elts);
1067 switch (Value.getKind()) {
1068 case APValue::Uninitialized:
1069 llvm_unreachable("Constant expressions should be initialized.");
1070 case APValue::LValue: {
1071 llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
1072 llvm::Constant *Offset =
1073 llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity());
1076 if (APValue::LValueBase LVBase = Value.getLValueBase()) {
1077 // An array can be represented as an lvalue referring to the base.
1078 if (isa<llvm::ArrayType>(DestTy)) {
1079 assert(Offset->isNullValue() && "offset on array initializer");
1080 return ConstExprEmitter(*this, CGF).Visit(
1081 const_cast<Expr*>(LVBase.get<const Expr*>()));
1084 C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase);
1086 // Apply offset if necessary.
1087 if (!Offset->isNullValue()) {
1088 unsigned AS = C->getType()->getPointerAddressSpace();
1089 llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS);
1090 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy);
1091 Casted = llvm::ConstantExpr::getGetElementPtr(Casted, Offset);
1092 C = llvm::ConstantExpr::getPointerCast(Casted, C->getType());
1095 // Convert to the appropriate type; this could be an lvalue for
1097 if (isa<llvm::PointerType>(DestTy))
1098 return llvm::ConstantExpr::getPointerCast(C, DestTy);
1100 return llvm::ConstantExpr::getPtrToInt(C, DestTy);
1104 // Convert to the appropriate type; this could be an lvalue for
1106 if (isa<llvm::PointerType>(DestTy))
1107 return llvm::ConstantExpr::getIntToPtr(C, DestTy);
1109 // If the types don't match this should only be a truncate.
1110 if (C->getType() != DestTy)
1111 return llvm::ConstantExpr::getTrunc(C, DestTy);
1117 return llvm::ConstantInt::get(VMContext, Value.getInt());
1118 case APValue::ComplexInt: {
1119 llvm::Constant *Complex[2];
1121 Complex[0] = llvm::ConstantInt::get(VMContext,
1122 Value.getComplexIntReal());
1123 Complex[1] = llvm::ConstantInt::get(VMContext,
1124 Value.getComplexIntImag());
1126 // FIXME: the target may want to specify that this is packed.
1127 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1128 Complex[1]->getType(),
1130 return llvm::ConstantStruct::get(STy, Complex);
1132 case APValue::Float: {
1133 const llvm::APFloat &Init = Value.getFloat();
1134 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf &&
1135 !Context.getLangOpts().NativeHalfType)
1136 return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
1138 return llvm::ConstantFP::get(VMContext, Init);
1140 case APValue::ComplexFloat: {
1141 llvm::Constant *Complex[2];
1143 Complex[0] = llvm::ConstantFP::get(VMContext,
1144 Value.getComplexFloatReal());
1145 Complex[1] = llvm::ConstantFP::get(VMContext,
1146 Value.getComplexFloatImag());
1148 // FIXME: the target may want to specify that this is packed.
1149 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1150 Complex[1]->getType(),
1152 return llvm::ConstantStruct::get(STy, Complex);
1154 case APValue::Vector: {
1155 SmallVector<llvm::Constant *, 4> Inits;
1156 unsigned NumElts = Value.getVectorLength();
1158 for (unsigned i = 0; i != NumElts; ++i) {
1159 const APValue &Elt = Value.getVectorElt(i);
1161 Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
1163 Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
1165 return llvm::ConstantVector::get(Inits);
1167 case APValue::AddrLabelDiff: {
1168 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1169 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1170 llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF);
1171 llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF);
1173 // Compute difference
1174 llvm::Type *ResultType = getTypes().ConvertType(DestType);
1175 LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
1176 RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
1177 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1179 // LLVM is a bit sensitive about the exact format of the
1180 // address-of-label difference; make sure to truncate after
1182 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1184 case APValue::Struct:
1185 case APValue::Union:
1186 return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
1187 case APValue::Array: {
1188 const ArrayType *CAT = Context.getAsArrayType(DestType);
1189 unsigned NumElements = Value.getArraySize();
1190 unsigned NumInitElts = Value.getArrayInitializedElts();
1192 std::vector<llvm::Constant*> Elts;
1193 Elts.reserve(NumElements);
1195 // Emit array filler, if there is one.
1196 llvm::Constant *Filler = nullptr;
1197 if (Value.hasArrayFiller())
1198 Filler = EmitConstantValueForMemory(Value.getArrayFiller(),
1199 CAT->getElementType(), CGF);
1201 // Emit initializer elements.
1202 llvm::Type *CommonElementType = nullptr;
1203 for (unsigned I = 0; I < NumElements; ++I) {
1204 llvm::Constant *C = Filler;
1205 if (I < NumInitElts)
1206 C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I),
1207 CAT->getElementType(), CGF);
1209 assert(Filler && "Missing filler for implicit elements of initializer");
1211 CommonElementType = C->getType();
1212 else if (C->getType() != CommonElementType)
1213 CommonElementType = nullptr;
1217 if (!CommonElementType) {
1218 // FIXME: Try to avoid packing the array
1219 std::vector<llvm::Type*> Types;
1220 Types.reserve(NumElements);
1221 for (unsigned i = 0, e = Elts.size(); i < e; ++i)
1222 Types.push_back(Elts[i]->getType());
1223 llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true);
1224 return llvm::ConstantStruct::get(SType, Elts);
1227 llvm::ArrayType *AType =
1228 llvm::ArrayType::get(CommonElementType, NumElements);
1229 return llvm::ConstantArray::get(AType, Elts);
1231 case APValue::MemberPointer:
1232 return getCXXABI().EmitMemberPointer(Value, DestType);
1234 llvm_unreachable("Unknown APValue kind");
1238 CodeGenModule::EmitConstantValueForMemory(const APValue &Value,
1240 CodeGenFunction *CGF) {
1241 llvm::Constant *C = EmitConstantValue(Value, DestType, CGF);
1242 if (C->getType()->isIntegerTy(1)) {
1243 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType);
1244 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1250 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
1251 assert(E->isFileScope() && "not a file-scope compound literal expr");
1252 return ConstExprEmitter(*this, nullptr).EmitLValue(E);
1256 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
1257 // Member pointer constants always have a very particular form.
1258 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1259 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1261 // A member function pointer.
1262 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1263 return getCXXABI().EmitMemberPointer(method);
1265 // Otherwise, a member data pointer.
1266 uint64_t fieldOffset = getContext().getFieldOffset(decl);
1267 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1268 return getCXXABI().EmitMemberDataPointer(type, chars);
1272 FillInNullDataMemberPointers(CodeGenModule &CGM, QualType T,
1273 SmallVectorImpl<llvm::Constant *> &Elements,
1274 uint64_t StartOffset) {
1275 assert(StartOffset % CGM.getContext().getCharWidth() == 0 &&
1276 "StartOffset not byte aligned!");
1278 if (CGM.getTypes().isZeroInitializable(T))
1281 if (const ConstantArrayType *CAT =
1282 CGM.getContext().getAsConstantArrayType(T)) {
1283 QualType ElementTy = CAT->getElementType();
1284 uint64_t ElementSize = CGM.getContext().getTypeSize(ElementTy);
1286 for (uint64_t I = 0, E = CAT->getSize().getZExtValue(); I != E; ++I) {
1287 FillInNullDataMemberPointers(CGM, ElementTy, Elements,
1288 StartOffset + I * ElementSize);
1290 } else if (const RecordType *RT = T->getAs<RecordType>()) {
1291 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1292 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1294 // Go through all bases and fill in any null pointer to data members.
1295 for (const auto &I : RD->bases()) {
1296 if (I.isVirtual()) {
1297 // Ignore virtual bases.
1301 const CXXRecordDecl *BaseDecl =
1302 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
1304 // Ignore empty bases.
1305 if (BaseDecl->isEmpty())
1308 // Ignore bases that don't have any pointer to data members.
1309 if (CGM.getTypes().isZeroInitializable(BaseDecl))
1312 uint64_t BaseOffset =
1313 CGM.getContext().toBits(Layout.getBaseClassOffset(BaseDecl));
1314 FillInNullDataMemberPointers(CGM, I.getType(),
1315 Elements, StartOffset + BaseOffset);
1318 // Visit all fields.
1319 unsigned FieldNo = 0;
1320 for (RecordDecl::field_iterator I = RD->field_begin(),
1321 E = RD->field_end(); I != E; ++I, ++FieldNo) {
1322 QualType FieldType = I->getType();
1324 if (CGM.getTypes().isZeroInitializable(FieldType))
1327 uint64_t FieldOffset = StartOffset + Layout.getFieldOffset(FieldNo);
1328 FillInNullDataMemberPointers(CGM, FieldType, Elements, FieldOffset);
1331 assert(T->isMemberPointerType() && "Should only see member pointers here!");
1332 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1333 "Should only see pointers to data members here!");
1335 CharUnits StartIndex = CGM.getContext().toCharUnitsFromBits(StartOffset);
1336 CharUnits EndIndex = StartIndex + CGM.getContext().getTypeSizeInChars(T);
1338 // FIXME: hardcodes Itanium member pointer representation!
1339 llvm::Constant *NegativeOne =
1340 llvm::ConstantInt::get(CGM.Int8Ty, -1ULL, /*isSigned*/true);
1342 // Fill in the null data member pointer.
1343 for (CharUnits I = StartIndex; I != EndIndex; ++I)
1344 Elements[I.getQuantity()] = NegativeOne;
1348 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1349 llvm::Type *baseType,
1350 const CXXRecordDecl *base);
1352 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
1353 const CXXRecordDecl *record,
1354 bool asCompleteObject) {
1355 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
1356 llvm::StructType *structure =
1357 (asCompleteObject ? layout.getLLVMType()
1358 : layout.getBaseSubobjectLLVMType());
1360 unsigned numElements = structure->getNumElements();
1361 std::vector<llvm::Constant *> elements(numElements);
1363 // Fill in all the bases.
1364 for (const auto &I : record->bases()) {
1365 if (I.isVirtual()) {
1366 // Ignore virtual bases; if we're laying out for a complete
1367 // object, we'll lay these out later.
1371 const CXXRecordDecl *base =
1372 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1374 // Ignore empty bases.
1375 if (base->isEmpty())
1378 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
1379 llvm::Type *baseType = structure->getElementType(fieldIndex);
1380 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1383 // Fill in all the fields.
1384 for (const auto *Field : record->fields()) {
1385 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
1386 // will fill in later.)
1387 if (!Field->isBitField()) {
1388 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
1389 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
1392 // For unions, stop after the first named field.
1393 if (record->isUnion() && Field->getDeclName())
1397 // Fill in the virtual bases, if we're working with the complete object.
1398 if (asCompleteObject) {
1399 for (const auto &I : record->vbases()) {
1400 const CXXRecordDecl *base =
1401 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1403 // Ignore empty bases.
1404 if (base->isEmpty())
1407 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
1409 // We might have already laid this field out.
1410 if (elements[fieldIndex]) continue;
1412 llvm::Type *baseType = structure->getElementType(fieldIndex);
1413 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1417 // Now go through all other fields and zero them out.
1418 for (unsigned i = 0; i != numElements; ++i) {
1420 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
1423 return llvm::ConstantStruct::get(structure, elements);
1426 /// Emit the null constant for a base subobject.
1427 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1428 llvm::Type *baseType,
1429 const CXXRecordDecl *base) {
1430 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
1432 // Just zero out bases that don't have any pointer to data members.
1433 if (baseLayout.isZeroInitializableAsBase())
1434 return llvm::Constant::getNullValue(baseType);
1436 // If the base type is a struct, we can just use its null constant.
1437 if (isa<llvm::StructType>(baseType)) {
1438 return EmitNullConstant(CGM, base, /*complete*/ false);
1441 // Otherwise, some bases are represented as arrays of i8 if the size
1442 // of the base is smaller than its corresponding LLVM type. Figure
1443 // out how many elements this base array has.
1444 llvm::ArrayType *baseArrayType = cast<llvm::ArrayType>(baseType);
1445 unsigned numBaseElements = baseArrayType->getNumElements();
1447 // Fill in null data member pointers.
1448 SmallVector<llvm::Constant *, 16> baseElements(numBaseElements);
1449 FillInNullDataMemberPointers(CGM, CGM.getContext().getTypeDeclType(base),
1452 // Now go through all other elements and zero them out.
1453 if (numBaseElements) {
1454 llvm::Constant *i8_zero = llvm::Constant::getNullValue(CGM.Int8Ty);
1455 for (unsigned i = 0; i != numBaseElements; ++i) {
1456 if (!baseElements[i])
1457 baseElements[i] = i8_zero;
1461 return llvm::ConstantArray::get(baseArrayType, baseElements);
1464 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
1465 if (getTypes().isZeroInitializable(T))
1466 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
1468 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
1469 llvm::ArrayType *ATy =
1470 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
1472 QualType ElementTy = CAT->getElementType();
1474 llvm::Constant *Element = EmitNullConstant(ElementTy);
1475 unsigned NumElements = CAT->getSize().getZExtValue();
1477 if (Element->isNullValue())
1478 return llvm::ConstantAggregateZero::get(ATy);
1480 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
1481 return llvm::ConstantArray::get(ATy, Array);
1484 if (const RecordType *RT = T->getAs<RecordType>()) {
1485 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1486 return ::EmitNullConstant(*this, RD, /*complete object*/ true);
1489 assert(T->isMemberPointerType() && "Should only see member pointers here!");
1490 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1491 "Should only see pointers to data members here!");
1493 // Itanium C++ ABI 2.3:
1494 // A NULL pointer is represented as -1.
1495 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
1499 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
1500 return ::EmitNullConstant(*this, Record, false);