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;
36 class ConstExprEmitter;
37 class ConstStructBuilder {
47 ConstExprEmitter *Emitter,
48 llvm::ConstantStruct *
Base,
57 : CGM(CGM), CGF(CGF), Packed(
false),
58 NextFieldOffsetInChars(
CharUnits::Zero()),
61 void AppendField(
const FieldDecl *Field, uint64_t FieldOffset,
62 llvm::Constant *InitExpr);
64 void AppendBytes(
CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
66 void AppendBitField(
const FieldDecl *Field, uint64_t FieldOffset,
67 llvm::ConstantInt *InitExpr);
71 void AppendTailPadding(
CharUnits RecordSize);
73 void ConvertStructToPacked();
76 bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *
Base,
80 llvm::Constant *Finalize(
QualType Ty);
82 CharUnits getAlignment(
const llvm::Constant *
C)
const {
85 CGM.getDataLayout().getABITypeAlignment(C->getType()));
88 CharUnits getSizeInChars(
const llvm::Constant *C)
const {
90 CGM.getDataLayout().getTypeAllocSize(C->getType()));
94 void ConstStructBuilder::
95 AppendField(
const FieldDecl *Field, uint64_t FieldOffset,
96 llvm::Constant *InitCst) {
101 AppendBytes(FieldOffsetInChars, InitCst);
104 void ConstStructBuilder::
105 AppendBytes(
CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
107 assert(NextFieldOffsetInChars <= FieldOffsetInChars
108 &&
"Field offset mismatch!");
110 CharUnits FieldAlignment = getAlignment(InitCst);
113 CharUnits AlignedNextFieldOffsetInChars =
116 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
118 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
120 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
121 "Did not add enough padding!");
123 AlignedNextFieldOffsetInChars =
127 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
128 assert(!Packed &&
"Alignment is wrong even with a packed struct!");
131 ConvertStructToPacked();
134 if (NextFieldOffsetInChars < FieldOffsetInChars) {
136 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
138 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
139 "Did not add enough padding!");
141 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
145 Elements.push_back(InitCst);
146 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
147 getSizeInChars(InitCst);
151 "Packed struct not byte-aligned!");
153 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
156 void ConstStructBuilder::AppendBitField(
const FieldDecl *Field,
157 uint64_t FieldOffset,
158 llvm::ConstantInt *CI) {
161 uint64_t NextFieldOffsetInBits = Context.
toBits(NextFieldOffsetInChars);
162 if (FieldOffset > NextFieldOffsetInBits) {
165 llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
168 AppendPadding(PadSize);
173 llvm::APInt FieldValue = CI->getValue();
179 if (FieldSize > FieldValue.getBitWidth())
180 FieldValue = FieldValue.zext(FieldSize);
183 if (FieldSize < FieldValue.getBitWidth())
184 FieldValue = FieldValue.trunc(FieldSize);
186 NextFieldOffsetInBits = Context.
toBits(NextFieldOffsetInChars);
187 if (FieldOffset < NextFieldOffsetInBits) {
190 assert(!Elements.empty() &&
"Elements can't be empty!");
192 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
194 bool FitsCompletelyInPreviousByte =
195 BitsInPreviousByte >= FieldValue.getBitWidth();
197 llvm::APInt Tmp = FieldValue;
199 if (!FitsCompletelyInPreviousByte) {
200 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
202 if (CGM.getDataLayout().isBigEndian()) {
203 Tmp = Tmp.lshr(NewFieldWidth);
204 Tmp = Tmp.trunc(BitsInPreviousByte);
207 FieldValue = FieldValue.trunc(NewFieldWidth);
209 Tmp = Tmp.trunc(BitsInPreviousByte);
212 FieldValue = FieldValue.lshr(BitsInPreviousByte);
213 FieldValue = FieldValue.trunc(NewFieldWidth);
217 Tmp = Tmp.zext(CharWidth);
218 if (CGM.getDataLayout().isBigEndian()) {
219 if (FitsCompletelyInPreviousByte)
220 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
222 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
227 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
228 Tmp |= Val->getValue();
230 assert(isa<llvm::UndefValue>(LastElt));
235 if (!isa<llvm::IntegerType>(LastElt->getType())) {
238 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
239 "Expected array padding of undefs");
240 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
241 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
242 AT->getNumElements() != 0 &&
243 "Expected non-empty array padding of undefs");
252 assert(isa<llvm::UndefValue>(Elements.back()) &&
253 Elements.back()->getType()->isIntegerTy(CharWidth) &&
254 "Padding addition didn't work right");
258 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
260 if (FitsCompletelyInPreviousByte)
264 while (FieldValue.getBitWidth() > CharWidth) {
267 if (CGM.getDataLayout().isBigEndian()) {
270 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).
trunc(CharWidth);
273 Tmp = FieldValue.trunc(CharWidth);
275 FieldValue = FieldValue.lshr(CharWidth);
278 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
279 ++NextFieldOffsetInChars;
281 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
284 assert(FieldValue.getBitWidth() > 0 &&
285 "Should have at least one bit left!");
286 assert(FieldValue.getBitWidth() <= CharWidth &&
287 "Should not have more than a byte left!");
289 if (FieldValue.getBitWidth() < CharWidth) {
290 if (CGM.getDataLayout().isBigEndian()) {
291 unsigned BitWidth = FieldValue.getBitWidth();
293 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
295 FieldValue = FieldValue.zext(CharWidth);
299 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
301 ++NextFieldOffsetInChars;
304 void ConstStructBuilder::AppendPadding(
CharUnits PadSize) {
308 llvm::Type *Ty = CGM.Int8Ty;
310 Ty = llvm::ArrayType::get(Ty, PadSize.
getQuantity());
312 llvm::Constant *C = llvm::UndefValue::get(Ty);
313 Elements.push_back(C);
315 "Padding must have 1 byte alignment!");
317 NextFieldOffsetInChars += getSizeInChars(C);
320 void ConstStructBuilder::AppendTailPadding(
CharUnits RecordSize) {
321 assert(NextFieldOffsetInChars <= RecordSize &&
324 AppendPadding(RecordSize - NextFieldOffsetInChars);
327 void ConstStructBuilder::ConvertStructToPacked() {
331 for (
unsigned i = 0, e = Elements.size(); i != e; ++i) {
332 llvm::Constant *C = Elements[i];
335 CGM.getDataLayout().getABITypeAlignment(C->getType()));
339 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
342 AlignedElementOffsetInChars - ElementOffsetInChars;
344 llvm::Type *Ty = CGM.Int8Ty;
346 Ty = llvm::ArrayType::get(Ty, NumChars.
getQuantity());
348 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
349 PackedElements.push_back(Padding);
350 ElementOffsetInChars += getSizeInChars(Padding);
353 PackedElements.push_back(C);
354 ElementOffsetInChars += getSizeInChars(C);
357 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
358 "Packing the struct changed its size!");
360 Elements.swap(PackedElements);
367 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
369 unsigned FieldNo = 0;
370 unsigned ElementNo = 0;
373 FieldEnd = RD->
field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
384 llvm::Constant *EltInit;
385 if (ElementNo < ILE->getNumInits())
386 EltInit = CGM.EmitConstantExpr(ILE->
getInit(ElementNo++),
389 EltInit = CGM.EmitNullConstant(Field->
getType());
399 if (
auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
415 : Decl(Decl), Offset(Offset), Index(Index) {
430 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
434 if (CD->isDynamicClass() && !IsPrimaryBase) {
435 llvm::Constant *VTableAddressPoint =
436 CGM.getCXXABI().getVTableAddressPointForConstExpr(
438 AppendBytes(Offset, VTableAddressPoint);
444 Bases.reserve(CD->getNumBases());
447 BaseEnd = CD->bases_end();
Base != BaseEnd; ++
Base, ++BaseNo) {
448 assert(!
Base->isVirtual() &&
"should not have virtual bases here");
451 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
453 std::stable_sort(Bases.begin(), Bases.end());
455 for (
unsigned I = 0, N = Bases.size(); I != N; ++I) {
456 BaseInfo &
Base = Bases[I];
459 Build(Val.
getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
460 VTableClass, Offset + Base.Offset);
464 unsigned FieldNo = 0;
465 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
468 FieldEnd = RD->
field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
480 llvm::Constant *EltInit =
481 CGM.EmitConstantValueForMemory(FieldValue, Field->
getType(), CGF);
482 assert(EltInit &&
"EmitConstantValue can't fail");
486 AppendField(*Field, Layout.
getFieldOffset(FieldNo) + OffsetBits, EltInit);
489 AppendBitField(*Field, Layout.
getFieldOffset(FieldNo) + OffsetBits,
490 cast<llvm::ConstantInt>(EltInit));
495 llvm::Constant *ConstStructBuilder::Finalize(
QualType Ty) {
497 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
501 if (NextFieldOffsetInChars > LayoutSizeInChars) {
505 "Must have flexible array member if struct is bigger than type!");
513 if (LLVMSizeInChars != LayoutSizeInChars)
514 AppendTailPadding(LayoutSizeInChars);
520 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
521 LLVMSizeInChars > LayoutSizeInChars) {
522 assert(!Packed &&
"Size mismatch!");
524 ConvertStructToPacked();
525 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
526 "Converting to packed did not help!");
532 assert(LayoutSizeInChars == LLVMSizeInChars &&
533 "Tail padding mismatch!");
538 llvm::StructType *STy =
539 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
541 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
542 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
543 if (ValSTy->isLayoutIdentical(STy))
547 llvm::Constant *
Result = llvm::ConstantStruct::get(STy, Elements);
549 assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) ==
550 getSizeInChars(Result) &&
"Size mismatch!");
555 llvm::Constant *ConstStructBuilder::BuildStruct(
CodeGenModule &CGM,
557 ConstExprEmitter *Emitter,
558 llvm::ConstantStruct *Base,
560 ConstStructBuilder
Builder(CGM, CGF);
561 if (!
Builder.Build(Emitter, Base, Updater))
566 llvm::Constant *ConstStructBuilder::BuildStruct(
CodeGenModule &CGM,
569 ConstStructBuilder
Builder(CGM, CGF);
577 llvm::Constant *ConstStructBuilder::BuildStruct(
CodeGenModule &CGM,
581 ConstStructBuilder
Builder(CGM, CGF);
587 return Builder.Finalize(ValTy);
599 class ConstExprEmitter :
600 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
603 llvm::LLVMContext &VMContext;
606 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
613 llvm::Constant *VisitStmt(
Stmt *
S) {
617 llvm::Constant *VisitParenExpr(
ParenExpr *PE) {
630 llvm::Constant *VisitChooseExpr(
ChooseExpr *CE) {
638 llvm::Constant *VisitCastExpr(
CastExpr* E) {
641 if (!C)
return nullptr;
643 llvm::Type *destType = ConvertType(E->
getType());
649 "Destination type is not union type!");
656 Types.push_back(C->getType());
657 unsigned CurSize = CGM.
getDataLayout().getTypeAllocSize(C->getType());
658 unsigned TotalSize = CGM.
getDataLayout().getTypeAllocSize(destType);
660 assert(CurSize <= TotalSize &&
"Union size mismatch!");
661 if (
unsigned NumPadBytes = TotalSize - CurSize) {
662 llvm::Type *Ty = CGM.
Int8Ty;
664 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
666 Elts.push_back(llvm::UndefValue::get(Ty));
670 llvm::StructType* STy =
671 llvm::StructType::get(C->getType()->getContext(), Types,
false);
672 return llvm::ConstantStruct::get(STy, Elts);
676 return llvm::ConstantExpr::getAddrSpaceCast(C, destType);
685 case CK_Dependent: llvm_unreachable(
"saw dependent cast!");
688 llvm_unreachable(
"builtin functions are handled elsewhere");
745 llvm_unreachable(
"Invalid CastKind");
762 llvm::Constant *EmitArrayInitialization(
InitListExpr *ILE) {
766 llvm::ArrayType *AType =
767 cast<llvm::ArrayType>(ConvertType(ILE->
getType()));
768 llvm::Type *ElemTy = AType->getElementType();
770 unsigned NumElements = AType->getNumElements();
774 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
778 llvm::Constant *fillC;
782 fillC = llvm::Constant::getNullValue(ElemTy);
787 if (fillC->isNullValue() && !NumInitableElts)
788 return llvm::ConstantAggregateZero::get(AType);
791 std::vector<llvm::Constant*> Elts;
792 Elts.reserve(NumInitableElts + NumElements);
794 bool RewriteType =
false;
795 for (
unsigned i = 0; i < NumInitableElts; ++i) {
800 RewriteType |= (C->getType() != ElemTy);
804 RewriteType |= (fillC->getType() != ElemTy);
805 Elts.resize(NumElements, fillC);
809 std::vector<llvm::Type*> Types;
810 Types.reserve(NumInitableElts + NumElements);
811 for (
unsigned i = 0, e = Elts.size(); i < e; ++i)
812 Types.push_back(Elts[i]->getType());
813 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
815 return llvm::ConstantStruct::get(SType, Elts);
818 return llvm::ConstantArray::get(AType, Elts);
821 llvm::Constant *EmitRecordInitialization(
InitListExpr *ILE) {
822 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
831 return EmitArrayInitialization(ILE);
834 return EmitRecordInitialization(ILE);
839 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
844 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(ExprType));
845 llvm::Type *ElemType = AType->getElementType();
848 unsigned NumElements = AType->getNumElements();
850 std::vector<llvm::Constant *> Elts;
851 Elts.reserve(NumElements);
853 if (llvm::ConstantDataArray *DataArray =
854 dyn_cast<llvm::ConstantDataArray>(Base))
855 for (
unsigned i = 0; i != NumElements; ++i)
856 Elts.push_back(DataArray->getElementAsConstant(i));
857 else if (llvm::ConstantArray *Array =
858 dyn_cast<llvm::ConstantArray>(Base))
859 for (
unsigned i = 0; i != NumElements; ++i)
860 Elts.push_back(Array->getOperand(i));
864 llvm::Constant *fillC =
nullptr;
866 if (!isa<NoInitExpr>(filler))
868 bool RewriteType = (fillC && fillC->getType() != ElemType);
870 for (
unsigned i = 0; i != NumElements; ++i) {
871 Expr *Init =
nullptr;
872 if (i < NumInitElements)
877 else if (!Init || isa<NoInitExpr>(Init))
879 else if (
InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
880 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE);
886 RewriteType |= (Elts[i]->getType() != ElemType);
890 std::vector<llvm::Type *> Types;
891 Types.reserve(NumElements);
892 for (
unsigned i = 0; i != NumElements; ++i)
893 Types.push_back(Elts[i]->getType());
894 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
896 return llvm::ConstantStruct::get(SType, Elts);
899 return llvm::ConstantArray::get(AType, Elts);
903 return ConstStructBuilder::BuildStruct(CGM, CGF,
this,
904 dyn_cast<llvm::ConstantStruct>(Base), Updater);
910 return EmitDesignatedInitUpdater(
928 if (!RD->hasTrivialDestructor())
935 assert(E->
getNumArgs() == 1 &&
"trivial ctor with > 1 argument");
937 "trivial ctor has argument but isn't a copy/move ctor");
941 "argument to copy ctor is of wrong type");
961 T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
966 Str.resize(CAT->
getSize().getZExtValue(),
'\0');
967 return llvm::ConstantDataArray::getString(VMContext, Str,
false);
970 llvm::Constant *VisitUnaryExtension(
const UnaryOperator *E) {
975 llvm::Type *ConvertType(
QualType T) {
988 if (!VD->hasLocalStorage()) {
989 if (VD->isFileVarDecl() || VD->hasExternalStorage())
991 else if (VD->isLocalVarDecl())
1000 switch (E->getStmtClass()) {
1002 case Expr::CompoundLiteralExprClass: {
1010 C =
new llvm::GlobalVariable(CGM.
getModule(), C->getType(),
1013 C,
".compoundliteral",
nullptr,
1014 llvm::GlobalVariable::NotThreadLocal,
1018 case Expr::StringLiteralClass:
1020 case Expr::ObjCEncodeExprClass:
1022 case Expr::ObjCStringLiteralClass: {
1026 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->
getType()));
1028 case Expr::PredefinedExprClass: {
1029 unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
1032 return cast<llvm::Constant>(Res.
getAddress());
1039 case Expr::AddrLabelExprClass: {
1040 assert(CGF &&
"Invalid address of label expression outside function.");
1041 llvm::Constant *Ptr =
1043 return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->
getType()));
1045 case Expr::CallExprClass: {
1049 Builtin::BI__builtin___CFStringMakeConstantString &&
1051 Builtin::BI__builtin___NSStringMakeConstantString)
1056 Builtin::BI__builtin___NSStringMakeConstantString) {
1062 case Expr::BlockExprClass: {
1063 std::string FunctionName;
1065 FunctionName = CGF->
CurFn->getName();
1067 FunctionName =
"global";
1071 case Expr::CXXTypeidExprClass: {
1080 case Expr::CXXUuidofExprClass: {
1083 case Expr::MaterializeTemporaryExprClass: {
1100 bool ConstStructBuilder::Build(ConstExprEmitter *Emitter,
1101 llvm::ConstantStruct *Base,
1103 assert(Base &&
"base expression should not be empty");
1108 const llvm::StructLayout *BaseLayout = CGM.
getDataLayout().getStructLayout(
1110 unsigned FieldNo = -1;
1111 unsigned ElementNo = 0;
1123 llvm::Constant *EltInit = Base->getOperand(ElementNo);
1129 BaseLayout->getElementOffsetInBits(ElementNo))
1134 Expr *Init =
nullptr;
1135 if (ElementNo < Updater->getNumInits())
1136 Init = Updater->
getInit(ElementNo);
1138 if (!Init || isa<NoInitExpr>(Init))
1140 else if (
InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
1141 EltInit = Emitter->EmitDesignatedInitUpdater(EltInit, ChildILE);
1152 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1173 dyn_cast_or_null<CXXConstructExpr>(D.
getInit())) {
1193 assert(E &&
"No initializer to emit");
1195 llvm::Constant* C = ConstExprEmitter(*
this, CGF).Visit(const_cast<Expr*>(E));
1196 if (C && C->getType()->isIntegerTy(1)) {
1198 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1208 bool Success =
false;
1215 llvm::Constant *C =
nullptr;
1219 C = ConstExprEmitter(*
this, CGF).Visit(const_cast<Expr*>(E));
1221 if (C && C->getType()->isIntegerTy(1)) {
1223 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1233 QualType InnerType = AT->getValueType();
1236 uint64_t InnerSize = Context.
getTypeSize(InnerType);
1237 uint64_t OuterSize = Context.
getTypeSize(DestType);
1238 if (InnerSize == OuterSize)
1241 assert(InnerSize < OuterSize &&
"emitted over-large constant for atomic");
1242 llvm::Constant *Elts[] = {
1244 llvm::ConstantAggregateZero::get(
1245 llvm::ArrayType::get(
Int8Ty, (OuterSize - InnerSize) / 8))
1247 return llvm::ConstantStruct::getAnon(Elts);
1252 llvm_unreachable(
"Constant expressions should be initialized.");
1255 llvm::Constant *Offset =
1261 if (isa<llvm::ArrayType>(DestTy)) {
1262 assert(Offset->isNullValue() &&
"offset on array initializer");
1263 return ConstExprEmitter(*
this, CGF).Visit(
1264 const_cast<Expr*>(LVBase.get<
const Expr*>()));
1267 C = ConstExprEmitter(*
this, CGF).EmitLValue(LVBase);
1270 if (!Offset->isNullValue()) {
1271 unsigned AS = C->getType()->getPointerAddressSpace();
1272 llvm::Type *CharPtrTy =
Int8Ty->getPointerTo(AS);
1273 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy);
1274 Casted = llvm::ConstantExpr::getGetElementPtr(
Int8Ty, Casted, Offset);
1275 C = llvm::ConstantExpr::getPointerCast(Casted, C->getType());
1280 if (isa<llvm::PointerType>(DestTy))
1281 return llvm::ConstantExpr::getPointerCast(C, DestTy);
1283 return llvm::ConstantExpr::getPtrToInt(C, DestTy);
1289 if (isa<llvm::PointerType>(DestTy))
1290 return llvm::ConstantExpr::getIntToPtr(C, DestTy);
1293 if (C->getType() != DestTy)
1294 return llvm::ConstantExpr::getTrunc(C, DestTy);
1300 return llvm::ConstantInt::get(VMContext, Value.
getInt());
1302 llvm::Constant *Complex[2];
1304 Complex[0] = llvm::ConstantInt::get(VMContext,
1306 Complex[1] = llvm::ConstantInt::get(VMContext,
1310 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1311 Complex[1]->getType(),
1313 return llvm::ConstantStruct::get(STy, Complex);
1316 const llvm::APFloat &Init = Value.
getFloat();
1317 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf &&
1320 return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
1322 return llvm::ConstantFP::get(VMContext, Init);
1325 llvm::Constant *Complex[2];
1327 Complex[0] = llvm::ConstantFP::get(VMContext,
1329 Complex[1] = llvm::ConstantFP::get(VMContext,
1333 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1334 Complex[1]->getType(),
1336 return llvm::ConstantStruct::get(STy, Complex);
1342 for (
unsigned i = 0; i != NumElts; ++i) {
1345 Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.
getInt()));
1347 Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.
getFloat()));
1349 return llvm::ConstantVector::get(Inits);
1359 LHS = llvm::ConstantExpr::getPtrToInt(LHS,
IntPtrTy);
1360 RHS = llvm::ConstantExpr::getPtrToInt(RHS,
IntPtrTy);
1361 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1366 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1370 return ConstStructBuilder::BuildStruct(*
this, CGF, Value, DestType);
1377 llvm::Constant *Filler =
nullptr;
1383 llvm::Type *CommonElementType =
1387 if (Filler && Filler->isNullValue() && !NumInitElts) {
1388 llvm::ArrayType *AType =
1389 llvm::ArrayType::get(CommonElementType, NumElements);
1390 return llvm::ConstantAggregateZero::get(AType);
1393 std::vector<llvm::Constant*> Elts;
1394 Elts.reserve(NumElements);
1395 for (
unsigned I = 0; I < NumElements; ++I) {
1396 llvm::Constant *C = Filler;
1397 if (I < NumInitElts)
1401 assert(Filler &&
"Missing filler for implicit elements of initializer");
1403 CommonElementType = C->getType();
1404 else if (C->getType() != CommonElementType)
1405 CommonElementType =
nullptr;
1409 if (!CommonElementType) {
1411 std::vector<llvm::Type*> Types;
1412 Types.reserve(NumElements);
1413 for (
unsigned i = 0, e = Elts.size(); i < e; ++i)
1414 Types.push_back(Elts[i]->getType());
1415 llvm::StructType *SType = llvm::StructType::get(VMContext, Types,
true);
1416 return llvm::ConstantStruct::get(SType, Elts);
1419 llvm::ArrayType *AType =
1420 llvm::ArrayType::get(CommonElementType, NumElements);
1421 return llvm::ConstantArray::get(AType, Elts);
1426 llvm_unreachable(
"Unknown APValue kind");
1434 if (C->getType()->isIntegerTy(1)) {
1436 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1443 assert(E->
isFileScope() &&
"not a file-scope compound literal expr");
1444 return ConstExprEmitter(*
this,
nullptr).EmitLValue(E);
1454 if (
const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1464 llvm::Type *baseType,
1469 bool asCompleteObject) {
1471 llvm::StructType *structure =
1475 unsigned numElements = structure->getNumElements();
1476 std::vector<llvm::Constant *> elements(numElements);
1479 for (
const auto &I : record->
bases()) {
1480 if (I.isVirtual()) {
1487 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
1494 llvm::Type *baseType = structure->getElementType(fieldIndex);
1499 for (
const auto *Field : record->
fields()) {
1511 if (
const auto *FieldRD =
1513 if (FieldRD->findFirstNamedDataMember())
1519 if (asCompleteObject) {
1520 for (
const auto &I : record->
vbases()) {
1522 cast<CXXRecordDecl>(I.getType()->castAs<
RecordType>()->getDecl());
1531 if (elements[fieldIndex])
continue;
1533 llvm::Type *baseType = structure->getElementType(fieldIndex);
1539 for (
unsigned i = 0; i != numElements; ++i) {
1541 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
1544 return llvm::ConstantStruct::get(structure, elements);
1549 llvm::Type *baseType,
1555 return llvm::Constant::getNullValue(baseType);
1562 if (
getTypes().isZeroInitializable(T))
1563 return llvm::Constant::getNullValue(
getTypes().ConvertTypeForMem(T));
1566 llvm::ArrayType *ATy =
1572 unsigned NumElements = CAT->
getSize().getZExtValue();
1574 return llvm::ConstantArray::get(ATy, Array);
1583 "Should only see pointers to data members here!");
llvm::Constant * GetAddrOfConstantCFString(const StringLiteral *Literal)
Return a pointer to a constant CFString object for the given string.
Defines the clang::ASTContext interface.
unsigned getNumInits() const
CastKind getCastKind() const
virtual llvm::Constant * EmitMemberPointer(const APValue &MP, QualType MPT)
Create a member pointer for the given member pointer constant.
const FieldDecl * getUnionField() const
APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
CodeGenTypes & getTypes()
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
bool isBitField() const
Determines whether this field is a bitfield.
llvm::Module & getModule() const
llvm::Constant * getMemberPointerConstant(const UnaryOperator *e)
IdentifierInfo * getIdentifier() const
Expr * GetTemporaryExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
bool isRecordType() const
bool hasFlexibleArrayMember() const
const llvm::DataLayout & getDataLayout() const
const Expr * getResultExpr() const
const Expr * getInit() const
Represents a call to a C++ constructor.
[ARC] Consumes a retainable object pointer that has just been produced, e.g. as the return value of a...
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
Represents a C++ constructor within a class.
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
llvm::Constant * EmitConstantValue(const APValue &Value, QualType DestType, CodeGenFunction *CGF=nullptr)
llvm::Value * getAddress() const
const llvm::APInt & getSize() const
unsigned getLLVMFieldNo(const FieldDecl *FD) const
Return llvm::StructType element number that corresponds to the field FD.
llvm::StructType * getLLVMType() const
Return the "complete object" LLVM type associated with this record.
APFloat & getComplexFloatReal()
field_iterator field_begin() const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
llvm::Constant * GetAddrOfGlobalVar(const VarDecl *D, llvm::Type *Ty=nullptr)
CK_Dynamic - A C++ dynamic_cast.
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
bool isMemberDataPointerType() const
llvm::Type * ConvertTypeForMem(QualType T)
llvm::GlobalVariable * GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *)
Return a pointer to a constant array for the given ObjCEncodeExpr node.
llvm::GlobalVariable * GetAddrOfConstantStringFromLiteral(const StringLiteral *S, StringRef Name=".str")
Return a pointer to a constant array for the given string literal.
llvm::Constant * EmitConstantValueForMemory(const APValue &Value, QualType DestType, CodeGenFunction *CGF=nullptr)
bool isEmpty() const
Determine whether this is an empty class in the sense of (C++11 [meta.unary.prop]).
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
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 ...
Converts between different integral complex types. _Complex char -> _Complex long long _Complex unsig...
llvm::IntegerType * Int64Ty
bool isReferenceType() const
StringLiteral * getString()
Converting between two Objective-C object types, which can occur when performing reference binding to...
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
[ARC] Causes a value of block type to be copied to the heap, if it is not already there...
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
llvm::Constant * GetConstantArrayFromStringLiteral(const StringLiteral *E)
Return a constant array for the given string.
Converts a floating point complex to bool by comparing against 0+0i.
unsigned getVirtualBaseIndex(const CXXRecordDecl *base) const
Return the LLVM field index corresponding to the given virtual base. Only valid when operating on the...
Describes an C or C++ initializer list.
Expr * getChosenSubExpr() const
const TargetInfo & getTargetInfo() const
const LangOptions & getLangOpts() const
APValue Val
Val - This is the value the expression can be folded to.
bool isZeroInitializableAsBase() const
Check whether this struct can be C++ zero-initialized with a zeroinitializer when considered as a bas...
llvm::GlobalVariable * GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr, unsigned Alignment=0)
Expr * getExprOperand() const
field_range fields() const
const ArrayType * getAsArrayType(QualType T) const
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
RecordDecl * getDecl() const
Expr * IgnoreParenCasts() LLVM_READONLY
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D...
uint64_t getFieldOffset(unsigned FieldNo) const
TypeClass getTypeClass() const
unsigned getBuiltinCallee() const
APSInt & getComplexIntReal()
A default argument (C++ [dcl.fct.default]).
bool isUnnamedBitfield() const
Determines whether this is an unnamed bitfield.
field_iterator field_end() const
APValue & getVectorElt(unsigned I)
static CharUnits One()
One - Construct a CharUnits quantity of one.
Causes a block literal to by copied to the heap and then autoreleased.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
APValue & getArrayFiller()
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
const Expr * getExpr() const
Get the initialization expression that will be used.
unsigned getCharAlign() const
Converts between different floating point complex types. _Complex float -> _Complex double...
unsigned getArrayInitializedElts() const
CGObjCRuntime & getObjCRuntime()
Return a reference to the configured Objective-C runtime.
Converts an integral complex to an integral real of the source's element type by discarding the imagi...
CGCXXABI & getCXXABI() const
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Inits[]
Gets the list of initial values for linear variables.
ASTContext & getContext() const
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
llvm::GlobalValue::LinkageTypes getLLVMLinkageVarDefinition(const VarDecl *VD, bool IsConstant)
Returns LLVM linkage for a declarator.
Expr * getSubExpr() const
APValue & getStructField(unsigned i)
virtual llvm::Constant * EmitMemberFunctionPointer(const CXXMethodDecl *MD)
Create a member pointer for the given method.
Converts from an integral complex to a floating complex. _Complex unsigned -> _Complex float...
Represents a reference to a non-type template parameter that has been substituted with a template arg...
llvm::Constant * GetAddrOfUuidDescriptor(const CXXUuidofExpr *E)
Get the address of a uuid descriptor .
APSInt & getComplexIntImag()
The result type of a method or function.
InitListExpr * getUpdater() const
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
APValue & getStructBase(unsigned i)
llvm::Constant * GetWeakRefReference(const ValueDecl *VD)
Get a reference to the target of VD.
llvm::Constant * getOrCreateStaticVarDecl(const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage)
APValue & getArrayInitializedElt(unsigned I)
virtual llvm::Value * EmitMemberPointerConversion(CodeGenFunction &CGF, const CastExpr *E, llvm::Value *Src)
llvm::Constant * GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E)
llvm::Constant * EmitConstantExpr(const Expr *E, QualType DestType, CodeGenFunction *CGF=nullptr)
CharUnits getSize() const
getSize - Get the record size in characters.
unsigned getBitWidthValue(const ASTContext &Ctx) const
const CXXRecordDecl * getPrimaryBase() const
getPrimaryBase - Get the primary base for this record.
const AddrLabelExpr * getAddrLabelDiffLHS() const
APValue & getUnionValue()
bool isConstant(ASTContext &Ctx) const
ValueKind getKind() const
Represents a static or instance method of a struct/union/class.
llvm::Constant * EmitNullConstantForBase(const CXXRecordDecl *Record)
const ConstantArrayType * getAsConstantArrayType(QualType T) const
llvm::Constant * GetAddrOfRTTIDescriptor(QualType Ty, bool ForEH=false)
Get the address of the RTTI descriptor for the given type.
Converts from an integral real to an integral complex whose element type matches the source...
const AddrLabelExpr * getAddrLabelDiffRHS() const
bool operator<(DeclarationName LHS, DeclarationName RHS)
llvm::Constant * GetAddrOfGlobalTemporary(const MaterializeTemporaryExpr *E, const Expr *Inner)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
virtual llvm::Constant * EmitNullMemberPointer(const MemberPointerType *MPT)
Create a null member pointer of the given type.
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Represents a C11 generic selection.
AddrLabelExpr - The GNU address of label extension, representing &&label.
Converts a floating point complex to floating point real of the source's element type. Just discards the imaginary component. _Complex long double -> long double.
Expr * getReplacement() const
const Expr * getExpr() const
QualType getTypeOperand(ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
EvalResult is a struct with detailed info about an evaluated expression.
llvm::Constant * GetAddrOfFunction(GlobalDecl GD, llvm::Type *Ty=0, bool ForVTable=false, bool DontDefer=false)
Converts an integral complex to bool by comparing against 0+0i.
bool isZero() const
isZero - Test whether the quantity equals zero.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
unsigned getNonVirtualBaseLLVMFieldNo(const CXXRecordDecl *RD) const
static llvm::Constant * EmitNullConstantForBase(CodeGenModule &CGM, llvm::Type *baseType, const CXXRecordDecl *base)
Emit the null constant for a base subobject.
llvm::IntegerType * IntPtrTy
llvm::Constant * EmitNullConstant(QualType T)
A conversion of a floating point real to a floating point complex of the original type...
unsigned getNumArgs() const
[ARC] Reclaim a retainable object pointer object that may have been produced and autoreleased as part...
llvm::PointerUnion< const ValueDecl *, const Expr * > LValueBase
[ARC] Produces a retainable object pointer so that it may be consumed, e.g. by being passed to a cons...
virtual llvm::Constant * EmitMemberDataPointer(const MemberPointerType *MPT, CharUnits offset)
Create a member pointer for the given field.
Converts from T to _Atomic(T).
Expr * getArg(unsigned Arg)
Return the specified argument.
CXXConstructorDecl * getConstructor() const
llvm::Constant * GetAddrOfGlobalBlock(const BlockExpr *BE, const char *)
Gets the address of a block which requires no captures.
Converts from a floating complex to an integral complex. _Complex float -> _Complex int...
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Represents a base class of a C++ class.
const Expr * getInitializer() const
llvm::Constant * EmitConstantInit(const VarDecl &D, CodeGenFunction *CGF=nullptr)
virtual llvm::Constant * GenerateConstantString(const StringLiteral *)=0
Generate a constant string object.
bool isDefaultConstructor() const
A use of a default initializer in a constructor or in aggregate initialization.
const Expr * getSubExpr() const
APFloat & getComplexFloatImag()
const LValueBase getLValueBase() const
Represents a C++ struct/union/class.
BoundNodesTreeBuilder *const Builder
QualType getEncodedType() const
Converts from _Atomic(T) to T.
LValue EmitPredefinedLValue(const PredefinedExpr *E)
bool isStringLiteralInit() const
unsigned getTargetAddressSpace(QualType T) const
QualType getElementType() const
const Expr * getInit(unsigned Init) const
FieldDecl * getInitializedFieldInUnion()
If this initializes a union, specifies which field in the union to initialize.
int64_t toBits(CharUnits CharSize) const
Convert a size in characters to a size in bits.
static llvm::Constant * EmitNullConstant(CodeGenModule &CGM, const CXXRecordDecl *record, bool asCompleteObject)
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
unsigned getArraySize() const
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const
bool isTypeOperand() const
llvm::StructType * getBaseSubobjectLLVMType() const
Return the "base subobject" LLVM type associated with this record.
CharUnits RoundUpToAlignment(const CharUnits &Align) const
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
base_class_range vbases()
unsigned getVectorLength() const
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Defines enum values for all the target-independent builtin functions.
Represents an implicitly-generated value initialization of an object of a given type.
bool hasLocalStorage() const
bool hasArrayFiller() const
CharUnits & getLValueOffset()