blob: e3e5d66605107c4bac2b145940e27200724c51d6 [file] [log] [blame]
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Constant Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000016#include "CGObjCRuntime.h"
Daniel Dunbar2924ade2010-03-30 22:26:10 +000017#include "CGRecordLayout.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "CodeGenModule.h"
Chris Lattnerf6b24ea2008-10-06 05:59:01 +000019#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Anders Carlsson4c98efd2009-07-24 15:20:52 +000021#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000022#include "clang/AST/StmtVisitor.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000023#include "clang/Basic/Builtins.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/GlobalVariable.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000028using namespace clang;
29using namespace CodeGen;
30
Chris Lattnereba3e5a2010-04-13 17:45:57 +000031//===----------------------------------------------------------------------===//
32// ConstStructBuilder
33//===----------------------------------------------------------------------===//
34
35namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000036class ConstStructBuilder {
Anders Carlsson4c98efd2009-07-24 15:20:52 +000037 CodeGenModule &CGM;
38 CodeGenFunction *CGF;
39
Mike Stump1eb44332009-09-09 15:08:12 +000040 bool Packed;
Ken Dyckdc496392011-03-17 01:33:18 +000041 CharUnits NextFieldOffsetInChars;
Ken Dyck7d2f9d52011-03-18 01:26:17 +000042 CharUnits LLVMStructAlignment;
Bill Wendlingcf6511b2012-02-07 00:54:58 +000043 SmallVector<llvm::Constant *, 32> Elements;
Chris Lattnereba3e5a2010-04-13 17:45:57 +000044public:
45 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
46 InitListExpr *ILE);
Richard Smith2d6a5672012-01-14 04:30:29 +000047 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
48 const APValue &Value, QualType ValTy);
49
50private:
Anders Carlsson4c98efd2009-07-24 15:20:52 +000051 ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
Ken Dyckdc496392011-03-17 01:33:18 +000052 : CGM(CGM), CGF(CGF), Packed(false),
53 NextFieldOffsetInChars(CharUnits::Zero()),
Ken Dyck7d2f9d52011-03-18 01:26:17 +000054 LLVMStructAlignment(CharUnits::One()) { }
Anders Carlsson4c98efd2009-07-24 15:20:52 +000055
Richard Smithc22adbd2012-02-23 08:33:23 +000056 void AppendVTablePointer(BaseSubobject Base, llvm::Constant *VTable,
57 const CXXRecordDecl *VTableClass);
58
Richard Smith2d6a5672012-01-14 04:30:29 +000059 void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
Chris Lattner8ce9e452010-04-13 18:16:19 +000060 llvm::Constant *InitExpr);
Mike Stump1eb44332009-09-09 15:08:12 +000061
Richard Smithc22adbd2012-02-23 08:33:23 +000062 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
63
Chris Lattner18806662010-07-05 17:04:23 +000064 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
65 llvm::ConstantInt *InitExpr);
Mike Stump1eb44332009-09-09 15:08:12 +000066
Ken Dyckc29ea8f2011-03-11 23:42:54 +000067 void AppendPadding(CharUnits PadSize);
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ken Dyck106ca042011-03-11 02:17:05 +000069 void AppendTailPadding(CharUnits RecordSize);
Anders Carlssond24393b2009-07-27 01:23:51 +000070
Chris Lattnereba3e5a2010-04-13 17:45:57 +000071 void ConvertStructToPacked();
Richard Smith2d6a5672012-01-14 04:30:29 +000072
Chris Lattnereba3e5a2010-04-13 17:45:57 +000073 bool Build(InitListExpr *ILE);
Richard Smithc22adbd2012-02-23 08:33:23 +000074 void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
75 llvm::Constant *VTable, const CXXRecordDecl *VTableClass,
76 CharUnits BaseOffset);
Richard Smith2d6a5672012-01-14 04:30:29 +000077 llvm::Constant *Finalize(QualType Ty);
Mike Stump1eb44332009-09-09 15:08:12 +000078
Ken Dyck7d2f9d52011-03-18 01:26:17 +000079 CharUnits getAlignment(const llvm::Constant *C) const {
80 if (Packed) return CharUnits::One();
81 return CharUnits::fromQuantity(
Micah Villmow25a6a842012-10-08 16:25:52 +000082 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Anders Carlsson4c98efd2009-07-24 15:20:52 +000083 }
Mike Stump1eb44332009-09-09 15:08:12 +000084
Ken Dyck15c152e2011-03-18 01:12:13 +000085 CharUnits getSizeInChars(const llvm::Constant *C) const {
86 return CharUnits::fromQuantity(
Micah Villmow25a6a842012-10-08 16:25:52 +000087 CGM.getDataLayout().getTypeAllocSize(C->getType()));
Anders Carlsson4c98efd2009-07-24 15:20:52 +000088 }
Anders Carlsson4c98efd2009-07-24 15:20:52 +000089};
Mike Stump1eb44332009-09-09 15:08:12 +000090
Richard Smithc22adbd2012-02-23 08:33:23 +000091void ConstStructBuilder::AppendVTablePointer(BaseSubobject Base,
92 llvm::Constant *VTable,
93 const CXXRecordDecl *VTableClass) {
94 // Find the appropriate vtable within the vtable group.
95 uint64_t AddressPoint =
96 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
97 llvm::Value *Indices[] = {
98 llvm::ConstantInt::get(CGM.Int64Ty, 0),
99 llvm::ConstantInt::get(CGM.Int64Ty, AddressPoint)
100 };
101 llvm::Constant *VTableAddressPoint =
102 llvm::ConstantExpr::getInBoundsGetElementPtr(VTable, Indices);
103
104 // Add the vtable at the start of the object.
Eli Friedman3754f962012-03-30 04:16:06 +0000105 AppendBytes(Base.getBaseOffset(), VTableAddressPoint);
Richard Smithc22adbd2012-02-23 08:33:23 +0000106}
107
Richard Smith2d6a5672012-01-14 04:30:29 +0000108void ConstStructBuilder::
Chris Lattner8ce9e452010-04-13 18:16:19 +0000109AppendField(const FieldDecl *Field, uint64_t FieldOffset,
110 llvm::Constant *InitCst) {
Ken Dyck6925cc42011-03-15 01:09:02 +0000111 const ASTContext &Context = CGM.getContext();
112
113 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000114
Richard Smithc22adbd2012-02-23 08:33:23 +0000115 AppendBytes(FieldOffsetInChars, InitCst);
116}
117
118void ConstStructBuilder::
119AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
120
Ken Dyckdc496392011-03-17 01:33:18 +0000121 assert(NextFieldOffsetInChars <= FieldOffsetInChars
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000122 && "Field offset mismatch!");
123
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000124 CharUnits FieldAlignment = getAlignment(InitCst);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000125
126 // Round up the field offset to the alignment of the field type.
Ken Dyckdc496392011-03-17 01:33:18 +0000127 CharUnits AlignedNextFieldOffsetInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000128 NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000129
Ken Dyckdc496392011-03-17 01:33:18 +0000130 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000131 assert(!Packed && "Alignment is wrong even with a packed struct!");
132
133 // Convert the struct to a packed struct.
134 ConvertStructToPacked();
Richard Smith2d6a5672012-01-14 04:30:29 +0000135
Ken Dyckdc496392011-03-17 01:33:18 +0000136 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000137 }
138
Ken Dyckdc496392011-03-17 01:33:18 +0000139 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000140 // We need to append padding.
Richard Smith2d6a5672012-01-14 04:30:29 +0000141 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000142
Ken Dyckdc496392011-03-17 01:33:18 +0000143 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000144 "Did not add enough padding!");
145
Ken Dyckdc496392011-03-17 01:33:18 +0000146 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000147 }
148
149 // Add the field.
Chris Lattner8ce9e452010-04-13 18:16:19 +0000150 Elements.push_back(InitCst);
Ken Dyckdc496392011-03-17 01:33:18 +0000151 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
Ken Dyck15c152e2011-03-18 01:12:13 +0000152 getSizeInChars(InitCst);
Richard Smith2d6a5672012-01-14 04:30:29 +0000153
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000154 if (Packed)
Richard Smith2d6a5672012-01-14 04:30:29 +0000155 assert(LLVMStructAlignment == CharUnits::One() &&
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000156 "Packed struct not byte-aligned!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000157 else
158 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000159}
160
Chris Lattner18806662010-07-05 17:04:23 +0000161void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
162 uint64_t FieldOffset,
163 llvm::ConstantInt *CI) {
Ken Dyckf004da42011-03-12 12:03:11 +0000164 const ASTContext &Context = CGM.getContext();
Ken Dyck4f318c02011-03-19 00:57:28 +0000165 const uint64_t CharWidth = Context.getCharWidth();
Ken Dyckdc496392011-03-17 01:33:18 +0000166 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
167 if (FieldOffset > NextFieldOffsetInBits) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000168 // We need to add padding.
Ken Dyckf004da42011-03-12 12:03:11 +0000169 CharUnits PadSize = Context.toCharUnitsFromBits(
Ken Dyckdc496392011-03-17 01:33:18 +0000170 llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000171 Context.getTargetInfo().getCharAlign()));
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000172
Ken Dyckf004da42011-03-12 12:03:11 +0000173 AppendPadding(PadSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000174 }
175
Richard Smitha6b8b2c2011-10-10 18:28:20 +0000176 uint64_t FieldSize = Field->getBitWidthValue(Context);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000177
178 llvm::APInt FieldValue = CI->getValue();
179
180 // Promote the size of FieldValue if necessary
181 // FIXME: This should never occur, but currently it can because initializer
182 // constants are cast to bool, and because clang is not enforcing bitfield
183 // width limits.
184 if (FieldSize > FieldValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +0000185 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000186
187 // Truncate the size of FieldValue to the bit field size.
188 if (FieldSize < FieldValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +0000189 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000190
Ken Dyckdc496392011-03-17 01:33:18 +0000191 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
192 if (FieldOffset < NextFieldOffsetInBits) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000193 // Either part of the field or the entire field can go into the previous
194 // byte.
195 assert(!Elements.empty() && "Elements can't be empty!");
196
Ken Dyckdc496392011-03-17 01:33:18 +0000197 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000198
199 bool FitsCompletelyInPreviousByte =
200 BitsInPreviousByte >= FieldValue.getBitWidth();
201
202 llvm::APInt Tmp = FieldValue;
203
204 if (!FitsCompletelyInPreviousByte) {
205 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
206
Micah Villmow25a6a842012-10-08 16:25:52 +0000207 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000208 Tmp = Tmp.lshr(NewFieldWidth);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000209 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000210
211 // We want the remaining high bits.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000212 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000213 } else {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000214 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000215
216 // We want the remaining low bits.
217 FieldValue = FieldValue.lshr(BitsInPreviousByte);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000218 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000219 }
220 }
221
Ken Dyck4f318c02011-03-19 00:57:28 +0000222 Tmp = Tmp.zext(CharWidth);
Micah Villmow25a6a842012-10-08 16:25:52 +0000223 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000224 if (FitsCompletelyInPreviousByte)
225 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
226 } else {
Ken Dyck4f318c02011-03-19 00:57:28 +0000227 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000228 }
229
Chris Lattner2bc00252010-07-05 18:03:30 +0000230 // 'or' in the bits that go into the previous byte.
231 llvm::Value *LastElt = Elements.back();
232 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000233 Tmp |= Val->getValue();
Chris Lattner2bc00252010-07-05 18:03:30 +0000234 else {
235 assert(isa<llvm::UndefValue>(LastElt));
236 // If there is an undef field that we're adding to, it can either be a
237 // scalar undef (in which case, we just replace it with our field) or it
238 // is an array. If it is an array, we have to pull one byte off the
239 // array so that the other undef bytes stay around.
240 if (!isa<llvm::IntegerType>(LastElt->getType())) {
241 // The undef padding will be a multibyte array, create a new smaller
242 // padding and then an hole for our i8 to get plopped into.
243 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
244 "Expected array padding of undefs");
Chris Lattner2acc6e32011-07-18 04:24:23 +0000245 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
Ken Dyck4f318c02011-03-19 00:57:28 +0000246 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
Chris Lattner2bc00252010-07-05 18:03:30 +0000247 AT->getNumElements() != 0 &&
248 "Expected non-empty array padding of undefs");
249
250 // Remove the padding array.
Ken Dyckdc496392011-03-17 01:33:18 +0000251 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
Chris Lattner2bc00252010-07-05 18:03:30 +0000252 Elements.pop_back();
253
254 // Add the padding back in two chunks.
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000255 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
256 AppendPadding(CharUnits::One());
Chris Lattner2bc00252010-07-05 18:03:30 +0000257 assert(isa<llvm::UndefValue>(Elements.back()) &&
Ken Dyck4f318c02011-03-19 00:57:28 +0000258 Elements.back()->getType()->isIntegerTy(CharWidth) &&
Chris Lattner2bc00252010-07-05 18:03:30 +0000259 "Padding addition didn't work right");
260 }
261 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000262
263 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
264
265 if (FitsCompletelyInPreviousByte)
Chris Lattner18806662010-07-05 17:04:23 +0000266 return;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000267 }
268
Ken Dyck4f318c02011-03-19 00:57:28 +0000269 while (FieldValue.getBitWidth() > CharWidth) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000270 llvm::APInt Tmp;
271
Micah Villmow25a6a842012-10-08 16:25:52 +0000272 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000273 // We want the high bits.
Ken Dyck4f318c02011-03-19 00:57:28 +0000274 Tmp =
275 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000276 } else {
277 // We want the low bits.
Ken Dyck4f318c02011-03-19 00:57:28 +0000278 Tmp = FieldValue.trunc(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000279
Ken Dyck4f318c02011-03-19 00:57:28 +0000280 FieldValue = FieldValue.lshr(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000281 }
282
283 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
Ken Dyck199c1892011-03-19 01:28:06 +0000284 ++NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000285
Ken Dyck4f318c02011-03-19 00:57:28 +0000286 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000287 }
288
289 assert(FieldValue.getBitWidth() > 0 &&
290 "Should have at least one bit left!");
Ken Dyck4f318c02011-03-19 00:57:28 +0000291 assert(FieldValue.getBitWidth() <= CharWidth &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000292 "Should not have more than a byte left!");
293
Ken Dyck4f318c02011-03-19 00:57:28 +0000294 if (FieldValue.getBitWidth() < CharWidth) {
Micah Villmow25a6a842012-10-08 16:25:52 +0000295 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000296 unsigned BitWidth = FieldValue.getBitWidth();
297
Ken Dyck4f318c02011-03-19 00:57:28 +0000298 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000299 } else
Ken Dyck4f318c02011-03-19 00:57:28 +0000300 FieldValue = FieldValue.zext(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000301 }
302
303 // Append the last element.
304 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
305 FieldValue));
Ken Dyck199c1892011-03-19 01:28:06 +0000306 ++NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000307}
308
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000309void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
310 if (PadSize.isZero())
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000311 return;
312
Chris Lattner8b418682012-02-07 00:39:47 +0000313 llvm::Type *Ty = CGM.Int8Ty;
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000314 if (PadSize > CharUnits::One())
315 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000316
Nuno Lopescdb30b42010-04-16 20:56:35 +0000317 llvm::Constant *C = llvm::UndefValue::get(Ty);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000318 Elements.push_back(C);
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000319 assert(getAlignment(C) == CharUnits::One() &&
320 "Padding must have 1 byte alignment!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000321
Ken Dyck15c152e2011-03-18 01:12:13 +0000322 NextFieldOffsetInChars += getSizeInChars(C);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000323}
324
Ken Dyck106ca042011-03-11 02:17:05 +0000325void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
Ken Dyckdc496392011-03-17 01:33:18 +0000326 assert(NextFieldOffsetInChars <= RecordSize &&
Ken Dyck106ca042011-03-11 02:17:05 +0000327 "Size mismatch!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000328
Ken Dyckdc496392011-03-17 01:33:18 +0000329 AppendPadding(RecordSize - NextFieldOffsetInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000330}
331
332void ConstStructBuilder::ConvertStructToPacked() {
Bill Wendling35f18a52012-02-07 00:04:27 +0000333 SmallVector<llvm::Constant *, 16> PackedElements;
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000334 CharUnits ElementOffsetInChars = CharUnits::Zero();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000335
336 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
337 llvm::Constant *C = Elements[i];
338
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000339 CharUnits ElementAlign = CharUnits::fromQuantity(
Micah Villmow25a6a842012-10-08 16:25:52 +0000340 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000341 CharUnits AlignedElementOffsetInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000342 ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000343
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000344 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000345 // We need some padding.
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000346 CharUnits NumChars =
347 AlignedElementOffsetInChars - ElementOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000348
Chris Lattner8b418682012-02-07 00:39:47 +0000349 llvm::Type *Ty = CGM.Int8Ty;
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000350 if (NumChars > CharUnits::One())
351 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000352
Nuno Lopescdb30b42010-04-16 20:56:35 +0000353 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000354 PackedElements.push_back(Padding);
Ken Dyck15c152e2011-03-18 01:12:13 +0000355 ElementOffsetInChars += getSizeInChars(Padding);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000356 }
357
358 PackedElements.push_back(C);
Ken Dyck15c152e2011-03-18 01:12:13 +0000359 ElementOffsetInChars += getSizeInChars(C);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000360 }
361
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000362 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000363 "Packing the struct changed its size!");
364
Bill Wendling35f18a52012-02-07 00:04:27 +0000365 Elements.swap(PackedElements);
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000366 LLVMStructAlignment = CharUnits::One();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000367 Packed = true;
368}
369
370bool ConstStructBuilder::Build(InitListExpr *ILE) {
Sebastian Redl24fe7982012-02-19 14:53:49 +0000371 if (ILE->initializesStdInitializerList()) {
Sebastian Redl19b1a6e2012-02-25 20:51:20 +0000372 //CGM.ErrorUnsupported(ILE, "global std::initializer_list");
Sebastian Redl24fe7982012-02-19 14:53:49 +0000373 return false;
374 }
375
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000376 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
377 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
378
379 unsigned FieldNo = 0;
380 unsigned ElementNo = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000381 const FieldDecl *LastFD = 0;
Eli Friedman5f608ae2012-10-12 23:29:20 +0000382 bool IsMsStruct = RD->isMsStruct(CGM.getContext());
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000383
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000384 for (RecordDecl::field_iterator Field = RD->field_begin(),
Chris Lattner8ce9e452010-04-13 18:16:19 +0000385 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000386 if (IsMsStruct) {
387 // Zero-length bitfields following non-bitfield members are
388 // ignored:
David Blaikie581deb32012-06-06 20:45:41 +0000389 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield(*Field, LastFD)) {
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000390 --FieldNo;
391 continue;
392 }
David Blaikie581deb32012-06-06 20:45:41 +0000393 LastFD = *Field;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000394 }
Chris Lattner8ce9e452010-04-13 18:16:19 +0000395
396 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000397 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000398 continue;
399
Chris Lattner8ce9e452010-04-13 18:16:19 +0000400 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedmandbff1a02011-08-23 20:22:34 +0000401 if (Field->isUnnamedBitfield()) {
David Blaikie581deb32012-06-06 20:45:41 +0000402 LastFD = *Field;
Chris Lattner8ce9e452010-04-13 18:16:19 +0000403 continue;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000404 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000405
Chris Lattner8ce9e452010-04-13 18:16:19 +0000406 // Get the initializer. A struct can include fields without initializers,
407 // we just use explicit null values for them.
408 llvm::Constant *EltInit;
409 if (ElementNo < ILE->getNumInits())
410 EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
411 Field->getType(), CGF);
412 else
413 EltInit = CGM.EmitNullConstant(Field->getType());
Eli Friedmanf0ca0ee2010-07-17 23:55:01 +0000414
415 if (!EltInit)
416 return false;
Chris Lattner8ce9e452010-04-13 18:16:19 +0000417
418 if (!Field->isBitField()) {
419 // Handle non-bitfield members.
David Blaikie581deb32012-06-06 20:45:41 +0000420 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000421 } else {
Chris Lattner8ce9e452010-04-13 18:16:19 +0000422 // Otherwise we have a bitfield.
David Blaikie581deb32012-06-06 20:45:41 +0000423 AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
Chris Lattner18806662010-07-05 17:04:23 +0000424 cast<llvm::ConstantInt>(EltInit));
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000425 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000426 }
427
Richard Smith2d6a5672012-01-14 04:30:29 +0000428 return true;
429}
430
Richard Smithc22adbd2012-02-23 08:33:23 +0000431namespace {
432struct BaseInfo {
433 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
434 : Decl(Decl), Offset(Offset), Index(Index) {
435 }
436
437 const CXXRecordDecl *Decl;
438 CharUnits Offset;
439 unsigned Index;
440
441 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
442};
443}
444
445void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
446 bool IsPrimaryBase, llvm::Constant *VTable,
447 const CXXRecordDecl *VTableClass,
448 CharUnits Offset) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000449 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
450
Richard Smithc22adbd2012-02-23 08:33:23 +0000451 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
452 // Add a vtable pointer, if we need one and it hasn't already been added.
453 if (CD->isDynamicClass() && !IsPrimaryBase)
454 AppendVTablePointer(BaseSubobject(CD, Offset), VTable, VTableClass);
455
456 // Accumulate and sort bases, in order to visit them in address order, which
457 // may not be the same as declaration order.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000458 SmallVector<BaseInfo, 8> Bases;
Richard Smithc22adbd2012-02-23 08:33:23 +0000459 Bases.reserve(CD->getNumBases());
Richard Smith2d6a5672012-01-14 04:30:29 +0000460 unsigned BaseNo = 0;
Richard Smithc22adbd2012-02-23 08:33:23 +0000461 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
Richard Smith2d6a5672012-01-14 04:30:29 +0000462 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
Richard Smithc22adbd2012-02-23 08:33:23 +0000463 assert(!Base->isVirtual() && "should not have virtual bases here");
Richard Smith2d6a5672012-01-14 04:30:29 +0000464 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
465 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Richard Smithc22adbd2012-02-23 08:33:23 +0000466 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
467 }
468 std::stable_sort(Bases.begin(), Bases.end());
Richard Smith2d6a5672012-01-14 04:30:29 +0000469
Richard Smithc22adbd2012-02-23 08:33:23 +0000470 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
471 BaseInfo &Base = Bases[I];
Richard Smith2d6a5672012-01-14 04:30:29 +0000472
Richard Smithc22adbd2012-02-23 08:33:23 +0000473 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
474 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
475 VTable, VTableClass, Offset + Base.Offset);
Richard Smith2d6a5672012-01-14 04:30:29 +0000476 }
477 }
478
479 unsigned FieldNo = 0;
480 const FieldDecl *LastFD = 0;
Eli Friedman5f608ae2012-10-12 23:29:20 +0000481 bool IsMsStruct = RD->isMsStruct(CGM.getContext());
Eli Friedman5fe61c62012-03-30 03:55:31 +0000482 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
Richard Smith2d6a5672012-01-14 04:30:29 +0000483
484 for (RecordDecl::field_iterator Field = RD->field_begin(),
485 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
486 if (IsMsStruct) {
487 // Zero-length bitfields following non-bitfield members are
488 // ignored:
David Blaikie581deb32012-06-06 20:45:41 +0000489 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield(*Field, LastFD)) {
Richard Smith2d6a5672012-01-14 04:30:29 +0000490 --FieldNo;
491 continue;
492 }
David Blaikie581deb32012-06-06 20:45:41 +0000493 LastFD = *Field;
Richard Smith2d6a5672012-01-14 04:30:29 +0000494 }
495
496 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie581deb32012-06-06 20:45:41 +0000497 if (RD->isUnion() && Val.getUnionField() != *Field)
Richard Smith2d6a5672012-01-14 04:30:29 +0000498 continue;
499
500 // Don't emit anonymous bitfields, they just affect layout.
501 if (Field->isUnnamedBitfield()) {
David Blaikie581deb32012-06-06 20:45:41 +0000502 LastFD = *Field;
Richard Smith2d6a5672012-01-14 04:30:29 +0000503 continue;
504 }
505
506 // Emit the value of the initializer.
507 const APValue &FieldValue =
508 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
509 llvm::Constant *EltInit =
Richard Smitha3ca41f2012-03-02 23:27:11 +0000510 CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
Richard Smith2d6a5672012-01-14 04:30:29 +0000511 assert(EltInit && "EmitConstantValue can't fail");
512
513 if (!Field->isBitField()) {
514 // Handle non-bitfield members.
David Blaikie581deb32012-06-06 20:45:41 +0000515 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
Richard Smith2d6a5672012-01-14 04:30:29 +0000516 } else {
517 // Otherwise we have a bitfield.
David Blaikie581deb32012-06-06 20:45:41 +0000518 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smith2d6a5672012-01-14 04:30:29 +0000519 cast<llvm::ConstantInt>(EltInit));
520 }
521 }
522}
523
524llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
525 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
526 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
527
Ken Dyckdc496392011-03-17 01:33:18 +0000528 CharUnits LayoutSizeInChars = Layout.getSize();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000529
Ken Dyckdc496392011-03-17 01:33:18 +0000530 if (NextFieldOffsetInChars > LayoutSizeInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000531 // If the struct is bigger than the size of the record type,
532 // we must have a flexible array member at the end.
533 assert(RD->hasFlexibleArrayMember() &&
534 "Must have flexible array member if struct is bigger than type!");
Richard Smith2d6a5672012-01-14 04:30:29 +0000535
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000536 // No tail padding is necessary.
Richard Smith2d6a5672012-01-14 04:30:29 +0000537 } else {
538 // Append tail padding if necessary.
539 AppendTailPadding(LayoutSizeInChars);
540
541 CharUnits LLVMSizeInChars =
542 NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
543
544 // Check if we need to convert the struct to a packed struct.
545 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
546 LLVMSizeInChars > LayoutSizeInChars) {
547 assert(!Packed && "Size mismatch!");
548
549 ConvertStructToPacked();
550 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
551 "Converting to packed did not help!");
552 }
553
554 assert(LayoutSizeInChars == NextFieldOffsetInChars &&
555 "Tail padding mismatch!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000556 }
557
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000558 // Pick the type to use. If the type is layout identical to the ConvertType
559 // type then use it, otherwise use whatever the builder produced for us.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000560 llvm::StructType *STy =
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000561 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
Richard Smith2d6a5672012-01-14 04:30:29 +0000562 Elements, Packed);
563 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
564 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
565 if (ValSTy->isLayoutIdentical(STy))
566 STy = ValSTy;
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000567 }
Richard Smith2d6a5672012-01-14 04:30:29 +0000568
569 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
570
571 assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) ==
572 getSizeInChars(Result) && "Size mismatch!");
573
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000574 return Result;
575}
576
Richard Smith2d6a5672012-01-14 04:30:29 +0000577llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
578 CodeGenFunction *CGF,
579 InitListExpr *ILE) {
580 ConstStructBuilder Builder(CGM, CGF);
581
582 if (!Builder.Build(ILE))
583 return 0;
584
585 return Builder.Finalize(ILE->getType());
586}
587
588llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
589 CodeGenFunction *CGF,
590 const APValue &Val,
591 QualType ValTy) {
592 ConstStructBuilder Builder(CGM, CGF);
Richard Smithc22adbd2012-02-23 08:33:23 +0000593
594 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
595 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
596 llvm::Constant *VTable = 0;
597 if (CD && CD->isDynamicClass())
598 VTable = CGM.getVTables().GetAddrOfVTable(CD);
599
600 Builder.Build(Val, RD, false, VTable, CD, CharUnits::Zero());
601
Richard Smith2d6a5672012-01-14 04:30:29 +0000602 return Builder.Finalize(ValTy);
603}
604
605
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000606//===----------------------------------------------------------------------===//
607// ConstExprEmitter
608//===----------------------------------------------------------------------===//
Richard Smithe7aa62d2012-01-17 21:42:19 +0000609
610/// This class only needs to handle two cases:
611/// 1) Literals (this is used by APValue emission to emit literals).
612/// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
613/// constant fold these types).
Benjamin Kramer85b45212009-11-28 19:45:26 +0000614class ConstExprEmitter :
Anders Carlsson84005b42008-01-26 04:30:23 +0000615 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000616 CodeGenModule &CGM;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000617 CodeGenFunction *CGF;
Owen Andersona1cf15f2009-07-14 23:10:40 +0000618 llvm::LLVMContext &VMContext;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000619public:
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000620 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
Owen Andersona1cf15f2009-07-14 23:10:40 +0000621 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000622 }
Mike Stump1eb44332009-09-09 15:08:12 +0000623
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000624 //===--------------------------------------------------------------------===//
625 // Visitor Methods
626 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000627
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000628 llvm::Constant *VisitStmt(Stmt *S) {
Anders Carlsson069880e2009-03-03 16:43:34 +0000629 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000630 }
Mike Stump1eb44332009-09-09 15:08:12 +0000631
632 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
633 return Visit(PE->getSubExpr());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000634 }
Mike Stump1eb44332009-09-09 15:08:12 +0000635
John McCall91a57552011-07-15 05:09:51 +0000636 llvm::Constant *
637 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
638 return Visit(PE->getReplacement());
639 }
640
Peter Collingbournef111d932011-04-15 00:35:48 +0000641 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
642 return Visit(GE->getResultExpr());
643 }
644
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000645 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
646 return Visit(E->getInitializer());
647 }
John McCall5808ce42011-02-03 08:15:49 +0000648
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000649 llvm::Constant *VisitCastExpr(CastExpr* E) {
John McCall8bba1f42011-03-15 21:17:48 +0000650 Expr *subExpr = E->getSubExpr();
651 llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
652 if (!C) return 0;
653
Chris Lattner2acc6e32011-07-18 04:24:23 +0000654 llvm::Type *destType = ConvertType(E->getType());
John McCall8bba1f42011-03-15 21:17:48 +0000655
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000656 switch (E->getCastKind()) {
John McCall2de56d12010-08-25 11:45:40 +0000657 case CK_ToUnion: {
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000658 // GCC cast to union extension
659 assert(E->getType()->isUnionType() &&
660 "Destination type is not union type!");
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000662 // Build a struct with the union sub-element as the first member,
663 // and padded to the appropriate size
Bill Wendlingf9ea9532012-02-07 00:13:27 +0000664 SmallVector<llvm::Constant*, 2> Elts;
665 SmallVector<llvm::Type*, 2> Types;
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000666 Elts.push_back(C);
667 Types.push_back(C->getType());
Micah Villmow25a6a842012-10-08 16:25:52 +0000668 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
669 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType);
Mike Stump1eb44332009-09-09 15:08:12 +0000670
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000671 assert(CurSize <= TotalSize && "Union size mismatch!");
672 if (unsigned NumPadBytes = TotalSize - CurSize) {
Chris Lattner8b418682012-02-07 00:39:47 +0000673 llvm::Type *Ty = CGM.Int8Ty;
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000674 if (NumPadBytes > 1)
675 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000676
Nuno Lopescdb30b42010-04-16 20:56:35 +0000677 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000678 Types.push_back(Ty);
679 }
Mike Stump1eb44332009-09-09 15:08:12 +0000680
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000681 llvm::StructType* STy =
682 llvm::StructType::get(C->getType()->getContext(), Types, false);
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000683 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes81e51e22009-01-17 00:48:48 +0000684 }
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000685
John McCall8bba1f42011-03-15 21:17:48 +0000686 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +0000687 case CK_AtomicToNonAtomic:
688 case CK_NonAtomicToAtomic:
John McCall8bba1f42011-03-15 21:17:48 +0000689 case CK_NoOp:
690 return C;
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000691
John McCall8bba1f42011-03-15 21:17:48 +0000692 case CK_Dependent: llvm_unreachable("saw dependent cast!");
693
Eli Friedmana6c66ce2012-08-31 00:14:07 +0000694 case CK_BuiltinFnToFnPtr:
695 llvm_unreachable("builtin functions are handled elsewhere");
696
John McCall4d4e5c12012-02-15 01:22:51 +0000697 case CK_ReinterpretMemberPointer:
698 case CK_DerivedToBaseMemberPointer:
699 case CK_BaseToDerivedMemberPointer:
700 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
701
John McCall8bba1f42011-03-15 21:17:48 +0000702 // These will never be supported.
703 case CK_ObjCObjectLValueCast:
John McCall33e56f32011-09-10 06:18:15 +0000704 case CK_ARCProduceObject:
705 case CK_ARCConsumeObject:
706 case CK_ARCReclaimReturnedObject:
707 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +0000708 case CK_CopyAndAutoreleaseBlockObject:
John McCall8bba1f42011-03-15 21:17:48 +0000709 return 0;
710
Eli Friedman65639282012-01-04 23:13:47 +0000711 // These don't need to be handled here because Evaluate knows how to
Richard Smithe7aa62d2012-01-17 21:42:19 +0000712 // evaluate them in the cases where they can be folded.
John McCall4d4e5c12012-02-15 01:22:51 +0000713 case CK_BitCast:
Richard Smithe7aa62d2012-01-17 21:42:19 +0000714 case CK_ToVoid:
715 case CK_Dynamic:
716 case CK_LValueBitCast:
717 case CK_NullToMemberPointer:
Richard Smithe7aa62d2012-01-17 21:42:19 +0000718 case CK_UserDefinedConversion:
719 case CK_ConstructorConversion:
Eli Friedman65639282012-01-04 23:13:47 +0000720 case CK_CPointerToObjCPointerCast:
721 case CK_BlockPointerToObjCPointerCast:
722 case CK_AnyPointerToBlockPointerCast:
John McCall8bba1f42011-03-15 21:17:48 +0000723 case CK_ArrayToPointerDecay:
724 case CK_FunctionToPointerDecay:
725 case CK_BaseToDerived:
726 case CK_DerivedToBase:
727 case CK_UncheckedDerivedToBase:
728 case CK_MemberPointerToBoolean:
729 case CK_VectorSplat:
730 case CK_FloatingRealToComplex:
731 case CK_FloatingComplexToReal:
732 case CK_FloatingComplexToBoolean:
733 case CK_FloatingComplexCast:
734 case CK_FloatingComplexToIntegralComplex:
735 case CK_IntegralRealToComplex:
736 case CK_IntegralComplexToReal:
737 case CK_IntegralComplexToBoolean:
738 case CK_IntegralComplexCast:
739 case CK_IntegralComplexToFloatingComplex:
John McCall8bba1f42011-03-15 21:17:48 +0000740 case CK_PointerToIntegral:
John McCall8bba1f42011-03-15 21:17:48 +0000741 case CK_PointerToBoolean:
John McCall8bba1f42011-03-15 21:17:48 +0000742 case CK_NullToPointer:
Eli Friedman65639282012-01-04 23:13:47 +0000743 case CK_IntegralCast:
744 case CK_IntegralToPointer:
John McCall8bba1f42011-03-15 21:17:48 +0000745 case CK_IntegralToBoolean:
John McCall8bba1f42011-03-15 21:17:48 +0000746 case CK_IntegralToFloating:
John McCall8bba1f42011-03-15 21:17:48 +0000747 case CK_FloatingToIntegral:
John McCall8bba1f42011-03-15 21:17:48 +0000748 case CK_FloatingToBoolean:
John McCall8bba1f42011-03-15 21:17:48 +0000749 case CK_FloatingCast:
Guy Benyeie6b9d802013-01-20 12:31:11 +0000750 case CK_ZeroToOCLEvent:
Eli Friedman65639282012-01-04 23:13:47 +0000751 return 0;
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000752 }
Matt Beaumont-Gay17d12fe2011-03-17 00:46:34 +0000753 llvm_unreachable("Invalid CastKind");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000754 }
Devang Pateleae15602008-02-05 02:39:50 +0000755
Chris Lattner04421082008-04-08 04:40:51 +0000756 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
757 return Visit(DAE->getExpr());
758 }
759
Douglas Gregor03e80032011-06-21 17:03:29 +0000760 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
761 return Visit(E->GetTemporaryExpr());
762 }
763
Eli Friedmana8234002008-05-30 10:24:46 +0000764 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
Richard Smithfe587202012-04-15 02:50:59 +0000765 if (ILE->isStringLiteralInit())
Nuno Lopesa75b71f2010-04-18 19:06:43 +0000766 return Visit(ILE->getInit(0));
767
Chris Lattner2acc6e32011-07-18 04:24:23 +0000768 llvm::ArrayType *AType =
Nuno Lopes67847042010-04-16 23:19:41 +0000769 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000770 llvm::Type *ElemTy = AType->getElementType();
Richard Smithfe587202012-04-15 02:50:59 +0000771 unsigned NumInitElements = ILE->getNumInits();
Devang Pateleae15602008-02-05 02:39:50 +0000772 unsigned NumElements = AType->getNumElements();
773
Mike Stump1eb44332009-09-09 15:08:12 +0000774 // Initialising an array requires us to automatically
Devang Pateleae15602008-02-05 02:39:50 +0000775 // initialise any elements that have not been initialised explicitly
776 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
777
778 // Copy initializer elements.
Bill Wendlingf9ea9532012-02-07 00:13:27 +0000779 std::vector<llvm::Constant*> Elts;
780 Elts.reserve(NumInitableElts + NumElements);
Benjamin Kramer14c59822012-02-14 12:06:21 +0000781
Eli Friedmana04a1532008-05-30 19:58:50 +0000782 bool RewriteType = false;
Benjamin Kramer14c59822012-02-14 12:06:21 +0000783 for (unsigned i = 0; i < NumInitableElts; ++i) {
Anders Carlssone9352cc2009-04-08 04:48:15 +0000784 Expr *Init = ILE->getInit(i);
785 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000786 if (!C)
787 return 0;
Eli Friedmana04a1532008-05-30 19:58:50 +0000788 RewriteType |= (C->getType() != ElemTy);
Devang Pateleae15602008-02-05 02:39:50 +0000789 Elts.push_back(C);
790 }
Eli Friedmana04a1532008-05-30 19:58:50 +0000791
Devang Pateleae15602008-02-05 02:39:50 +0000792 // Initialize remaining array elements.
Eli Friedman0f593122009-04-13 21:47:26 +0000793 // FIXME: This doesn't handle member pointers correctly!
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000794 llvm::Constant *fillC;
795 if (Expr *filler = ILE->getArrayFiller())
796 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
797 else
798 fillC = llvm::Constant::getNullValue(ElemTy);
799 if (!fillC)
800 return 0;
801 RewriteType |= (fillC->getType() != ElemTy);
Benjamin Kramer14c59822012-02-14 12:06:21 +0000802 Elts.resize(NumElements, fillC);
Devang Pateleae15602008-02-05 02:39:50 +0000803
Eli Friedmana04a1532008-05-30 19:58:50 +0000804 if (RewriteType) {
805 // FIXME: Try to avoid packing the array
Jay Foadef6de3d2011-07-11 09:56:20 +0000806 std::vector<llvm::Type*> Types;
Bill Wendlingf9ea9532012-02-07 00:13:27 +0000807 Types.reserve(NumInitableElts + NumElements);
Bill Wendlingfd3e5ef2012-02-06 23:46:08 +0000808 for (unsigned i = 0, e = Elts.size(); i < e; ++i)
Eli Friedmana04a1532008-05-30 19:58:50 +0000809 Types.push_back(Elts[i]->getType());
Chris Lattner2acc6e32011-07-18 04:24:23 +0000810 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000811 Types, true);
Owen Anderson08e25242009-07-27 22:29:56 +0000812 return llvm::ConstantStruct::get(SType, Elts);
Eli Friedmana04a1532008-05-30 19:58:50 +0000813 }
814
Mike Stump1eb44332009-09-09 15:08:12 +0000815 return llvm::ConstantArray::get(AType, Elts);
Devang Pateleae15602008-02-05 02:39:50 +0000816 }
817
Richard Smith1b5c3362012-09-11 05:51:06 +0000818 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) {
Anders Carlssonf6c43962009-07-31 21:34:04 +0000819 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
Eli Friedmana8234002008-05-30 10:24:46 +0000820 }
821
Anders Carlsson7d801ea2009-01-30 06:13:25 +0000822 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
Eli Friedman0f593122009-04-13 21:47:26 +0000823 return CGM.EmitNullConstant(E->getType());
Anders Carlsson7d801ea2009-01-30 06:13:25 +0000824 }
Mike Stump1eb44332009-09-09 15:08:12 +0000825
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000826 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
Eli Friedmana8234002008-05-30 10:24:46 +0000827 if (ILE->getType()->isArrayType())
828 return EmitArrayInitialization(ILE);
Devang Patel47fb6972008-01-29 23:23:18 +0000829
Jin-Gu Kang45e4e082012-09-05 08:37:43 +0000830 if (ILE->getType()->isRecordType())
Richard Smith1b5c3362012-09-11 05:51:06 +0000831 return EmitRecordInitialization(ILE);
Jin-Gu Kang45e4e082012-09-05 08:37:43 +0000832
Eli Friedman7ead5c72012-01-10 04:58:17 +0000833 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000834 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000835
John McCallfb8b69a2010-02-02 08:02:49 +0000836 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
837 if (!E->getConstructor()->isTrivial())
838 return 0;
839
Anders Carlsson2ca4f632010-02-05 18:38:45 +0000840 QualType Ty = E->getType();
841
842 // FIXME: We should not have to call getBaseElementType here.
843 const RecordType *RT =
844 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
845 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
846
847 // If the class doesn't have a trivial destructor, we can't emit it as a
848 // constant expr.
849 if (!RD->hasTrivialDestructor())
850 return 0;
851
John McCallfb8b69a2010-02-02 08:02:49 +0000852 // Only copy and default constructors can be trivial.
853
John McCallfb8b69a2010-02-02 08:02:49 +0000854
855 if (E->getNumArgs()) {
856 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000857 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
858 "trivial ctor has argument but isn't a copy/move ctor");
John McCallfb8b69a2010-02-02 08:02:49 +0000859
860 Expr *Arg = E->getArg(0);
861 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
862 "argument to copy ctor is of wrong type");
863
Chandler Carruth878b55c2010-02-02 12:15:55 +0000864 return Visit(Arg);
John McCallfb8b69a2010-02-02 08:02:49 +0000865 }
866
867 return CGM.EmitNullConstant(Ty);
868 }
869
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000870 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
Eli Friedman64f45a22011-11-01 02:23:42 +0000871 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000872 }
873
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000874 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
875 // This must be an @encode initializing an array in a static initializer.
876 // Don't emit it as the address of the string, emit the string data itself
877 // as an inline array.
878 std::string Str;
879 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
880 const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000881
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000882 // Resize the string to the right size, adding zeros at the end, or
883 // truncating as needed.
884 Str.resize(CAT->getSize().getZExtValue(), '\0');
Chris Lattner94010692012-02-05 02:30:40 +0000885 return llvm::ConstantDataArray::getString(VMContext, Str, false);
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000888 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
889 return Visit(E->getSubExpr());
890 }
Mike Stumpb83d2872009-02-19 22:01:56 +0000891
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000892 // Utility methods
Chris Lattner2acc6e32011-07-18 04:24:23 +0000893 llvm::Type *ConvertType(QualType T) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000894 return CGM.getTypes().ConvertType(T);
895 }
Anders Carlsson84005b42008-01-26 04:30:23 +0000896
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000897public:
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000898 llvm::Constant *EmitLValue(APValue::LValueBase LVBase) {
899 if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) {
Rafael Espindolada182612010-03-04 21:26:03 +0000900 if (Decl->hasAttr<WeakRefAttr>())
Eli Friedmana7e68452010-08-22 01:00:03 +0000901 return CGM.GetWeakRefReference(Decl);
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000902 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
Anders Carlsson555b4bb2009-09-10 23:43:36 +0000903 return CGM.GetAddrOfFunction(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000904 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000905 // We can never refer to a variable with local storage.
Mike Stump1eb44332009-09-09 15:08:12 +0000906 if (!VD->hasLocalStorage()) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000907 if (VD->isFileVarDecl() || VD->hasExternalStorage())
908 return CGM.GetAddrOfGlobalVar(VD);
Eli Friedman89e19b42013-01-03 00:39:26 +0000909 else if (VD->isLocalVarDecl())
910 return CGM.getStaticLocalDeclAddress(VD);
Steve Naroff248a7532008-04-15 22:42:06 +0000911 }
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000912 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913 return 0;
914 }
915
916 Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>());
917 switch (E->getStmtClass()) {
918 default: break;
919 case Expr::CompoundLiteralExprClass: {
920 // Note that due to the nature of compound literals, this is guaranteed
921 // to be the only use of the variable, so we just generate it here.
922 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
Eli Friedman58c65fc2011-12-22 00:04:00 +0000923 llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(),
924 CLE->getType(), CGF);
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000925 // FIXME: "Leaked" on failure.
926 if (C)
927 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
928 E->getType().isConstant(CGM.getContext()),
929 llvm::GlobalValue::InternalLinkage,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +0000930 C, ".compoundliteral", 0,
931 llvm::GlobalVariable::NotThreadLocal,
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000932 CGM.getContext().getTargetAddressSpace(E->getType()));
933 return C;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000934 }
Daniel Dunbar61432932008-08-13 23:20:05 +0000935 case Expr::StringLiteralClass:
936 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000937 case Expr::ObjCEncodeExprClass:
938 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000939 case Expr::ObjCStringLiteralClass: {
940 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000941 llvm::Constant *C =
942 CGM.getObjCRuntime().GenerateConstantString(SL->getString());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000943 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000944 }
Chris Lattner35345642008-12-12 05:18:02 +0000945 case Expr::PredefinedExprClass: {
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000946 unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
947 if (CGF) {
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +0000948 LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000949 return cast<llvm::Constant>(Res.getAddress());
950 } else if (Type == PredefinedExpr::PrettyFunction) {
951 return CGM.GetAddrOfConstantCString("top level", ".tmp");
952 }
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000954 return CGM.GetAddrOfConstantCString("", ".tmp");
Chris Lattner35345642008-12-12 05:18:02 +0000955 }
Eli Friedmanf0115892009-01-25 01:21:06 +0000956 case Expr::AddrLabelExprClass: {
957 assert(CGF && "Invalid address of label expression outside function.");
Chris Lattnerd9becd12009-10-28 23:59:40 +0000958 llvm::Constant *Ptr =
959 CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
960 return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
Eli Friedmanf0115892009-01-25 01:21:06 +0000961 }
Eli Friedman3941b182009-01-25 01:54:01 +0000962 case Expr::CallExprClass: {
963 CallExpr* CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +0000964 unsigned builtin = CE->isBuiltinCall();
David Chisnall0d13f6f2010-01-23 02:40:42 +0000965 if (builtin !=
966 Builtin::BI__builtin___CFStringMakeConstantString &&
967 builtin !=
968 Builtin::BI__builtin___NSStringMakeConstantString)
Eli Friedman3941b182009-01-25 01:54:01 +0000969 break;
970 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
971 const StringLiteral *Literal = cast<StringLiteral>(Arg);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000972 if (builtin ==
973 Builtin::BI__builtin___NSStringMakeConstantString) {
974 return CGM.getObjCRuntime().GenerateConstantString(Literal);
975 }
Steve Naroff33fdb732009-03-31 16:53:37 +0000976 // FIXME: need to deal with UCN conversion issues.
Steve Naroff8d4141f2009-04-01 13:55:36 +0000977 return CGM.GetAddrOfConstantCFString(Literal);
Eli Friedman3941b182009-01-25 01:54:01 +0000978 }
Mike Stumpbd65cac2009-02-19 01:01:04 +0000979 case Expr::BlockExprClass: {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000980 std::string FunctionName;
981 if (CGF)
982 FunctionName = CGF->CurFn->getName();
983 else
984 FunctionName = "global";
985
986 return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
Mike Stumpbd65cac2009-02-19 01:01:04 +0000987 }
Richard Smith47d21452011-12-27 12:18:28 +0000988 case Expr::CXXTypeidExprClass: {
989 CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E);
990 QualType T;
991 if (Typeid->isTypeOperand())
992 T = Typeid->getTypeOperand();
993 else
994 T = Typeid->getExprOperand()->getType();
995 return CGM.GetAddrOfRTTIDescriptor(T);
996 }
Nico Weberc5f80462012-10-11 10:13:44 +0000997 case Expr::CXXUuidofExprClass: {
998 return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E));
999 }
Eli Friedman546d94c2008-02-11 00:23:10 +00001000 }
Daniel Dunbard60f2fb2009-02-17 18:43:32 +00001001
1002 return 0;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +00001003 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +00001004};
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001006} // end anonymous namespace.
1007
Richard Smith2d6a5672012-01-14 04:30:29 +00001008llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
1009 CodeGenFunction *CGF) {
Fariborz Jahanianc2316db2013-01-10 23:28:43 +00001010 // Make a quick check if variable can be default NULL initialized
1011 // and avoid going through rest of code which may do, for c++11,
1012 // initialization of memory to all NULLs.
1013 if (!D.hasLocalStorage()) {
1014 QualType Ty = D.getType();
1015 if (Ty->isArrayType())
1016 Ty = Context.getBaseElementType(Ty);
1017 if (Ty->isRecordType())
1018 if (const CXXConstructExpr *E =
1019 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1020 const CXXConstructorDecl *CD = E->getConstructor();
1021 if (CD->isTrivial() && CD->isDefaultConstructor() &&
1022 Ty->getAsCXXRecordDecl()->hasTrivialDestructor())
1023 return EmitNullConstant(D.getType());
1024 }
1025 }
1026
Richard Smith2d6a5672012-01-14 04:30:29 +00001027 if (const APValue *Value = D.evaluateValue())
Richard Smitha3ca41f2012-03-02 23:27:11 +00001028 return EmitConstantValueForMemory(*Value, D.getType(), CGF);
Richard Smith2d6a5672012-01-14 04:30:29 +00001029
Richard Smith7ca48502012-02-13 22:16:19 +00001030 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1031 // reference is a constant expression, and the reference binds to a temporary,
1032 // then constant initialization is performed. ConstExprEmitter will
1033 // incorrectly emit a prvalue constant in this case, and the calling code
1034 // interprets that as the (pointer) value of the reference, rather than the
1035 // desired value of the referee.
1036 if (D.getType()->isReferenceType())
1037 return 0;
1038
Richard Smith2d6a5672012-01-14 04:30:29 +00001039 const Expr *E = D.getInit();
1040 assert(E && "No initializer to emit");
1041
1042 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
1043 if (C && C->getType()->isIntegerTy(1)) {
1044 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
1045 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1046 }
1047 return C;
1048}
1049
Lauro Ramos Venancio81373352008-02-26 21:41:45 +00001050llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
Anders Carlssone9352cc2009-04-08 04:48:15 +00001051 QualType DestType,
Chris Lattner96196622008-07-26 22:37:01 +00001052 CodeGenFunction *CGF) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +00001053 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Anders Carlsson1e5dc6e2009-04-11 01:08:03 +00001055 bool Success = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001056
Eli Friedman50c39ea2009-05-27 06:04:58 +00001057 if (DestType->isReferenceType())
1058 Success = E->EvaluateAsLValue(Result, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001059 else
Richard Smith51f47082011-10-29 00:50:52 +00001060 Success = E->EvaluateAsRValue(Result, Context);
Mike Stump1eb44332009-09-09 15:08:12 +00001061
Richard Smitha3ca41f2012-03-02 23:27:11 +00001062 llvm::Constant *C = 0;
Richard Smith2d6a5672012-01-14 04:30:29 +00001063 if (Success && !Result.HasSideEffects)
Richard Smitha3ca41f2012-03-02 23:27:11 +00001064 C = EmitConstantValue(Result.Val, DestType, CGF);
1065 else
1066 C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
Eli Friedman7dfa6392008-06-01 15:31:44 +00001067
Chris Lattner7f215c12010-06-26 21:52:32 +00001068 if (C && C->getType()->isIntegerTy(1)) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001069 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
Owen Anderson3c4972d2009-07-29 18:54:39 +00001070 C = llvm::ConstantExpr::getZExt(C, BoolTy);
Eli Friedman7dfa6392008-06-01 15:31:44 +00001071 }
1072 return C;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001073}
Eli Friedman0f593122009-04-13 21:47:26 +00001074
Richard Smith2d6a5672012-01-14 04:30:29 +00001075llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value,
1076 QualType DestType,
1077 CodeGenFunction *CGF) {
1078 switch (Value.getKind()) {
1079 case APValue::Uninitialized:
1080 llvm_unreachable("Constant expressions should be initialized.");
1081 case APValue::LValue: {
1082 llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
1083 llvm::Constant *Offset =
Chris Lattner8b418682012-02-07 00:39:47 +00001084 llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity());
Richard Smith2d6a5672012-01-14 04:30:29 +00001085
1086 llvm::Constant *C;
1087 if (APValue::LValueBase LVBase = Value.getLValueBase()) {
1088 // An array can be represented as an lvalue referring to the base.
1089 if (isa<llvm::ArrayType>(DestTy)) {
1090 assert(Offset->isNullValue() && "offset on array initializer");
1091 return ConstExprEmitter(*this, CGF).Visit(
1092 const_cast<Expr*>(LVBase.get<const Expr*>()));
1093 }
1094
1095 C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase);
1096
1097 // Apply offset if necessary.
1098 if (!Offset->isNullValue()) {
Chris Lattner8b418682012-02-07 00:39:47 +00001099 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Int8PtrTy);
Richard Smith2d6a5672012-01-14 04:30:29 +00001100 Casted = llvm::ConstantExpr::getGetElementPtr(Casted, Offset);
1101 C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
1102 }
1103
1104 // Convert to the appropriate type; this could be an lvalue for
1105 // an integer.
1106 if (isa<llvm::PointerType>(DestTy))
1107 return llvm::ConstantExpr::getBitCast(C, DestTy);
1108
1109 return llvm::ConstantExpr::getPtrToInt(C, DestTy);
1110 } else {
1111 C = Offset;
1112
1113 // Convert to the appropriate type; this could be an lvalue for
1114 // an integer.
1115 if (isa<llvm::PointerType>(DestTy))
1116 return llvm::ConstantExpr::getIntToPtr(C, DestTy);
1117
1118 // If the types don't match this should only be a truncate.
1119 if (C->getType() != DestTy)
1120 return llvm::ConstantExpr::getTrunc(C, DestTy);
1121
1122 return C;
1123 }
1124 }
Richard Smitha3ca41f2012-03-02 23:27:11 +00001125 case APValue::Int:
1126 return llvm::ConstantInt::get(VMContext, Value.getInt());
Richard Smith2d6a5672012-01-14 04:30:29 +00001127 case APValue::ComplexInt: {
1128 llvm::Constant *Complex[2];
1129
1130 Complex[0] = llvm::ConstantInt::get(VMContext,
1131 Value.getComplexIntReal());
1132 Complex[1] = llvm::ConstantInt::get(VMContext,
1133 Value.getComplexIntImag());
1134
1135 // FIXME: the target may want to specify that this is packed.
1136 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1137 Complex[1]->getType(),
1138 NULL);
1139 return llvm::ConstantStruct::get(STy, Complex);
1140 }
1141 case APValue::Float: {
1142 const llvm::APFloat &Init = Value.getFloat();
Joey Gouly19dbb202013-01-23 11:56:20 +00001143 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf &&
1144 !Context.getLangOpts().NativeHalfType)
Richard Smith2d6a5672012-01-14 04:30:29 +00001145 return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
1146 else
1147 return llvm::ConstantFP::get(VMContext, Init);
1148 }
1149 case APValue::ComplexFloat: {
1150 llvm::Constant *Complex[2];
1151
1152 Complex[0] = llvm::ConstantFP::get(VMContext,
1153 Value.getComplexFloatReal());
1154 Complex[1] = llvm::ConstantFP::get(VMContext,
1155 Value.getComplexFloatImag());
1156
1157 // FIXME: the target may want to specify that this is packed.
1158 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1159 Complex[1]->getType(),
1160 NULL);
1161 return llvm::ConstantStruct::get(STy, Complex);
1162 }
1163 case APValue::Vector: {
1164 SmallVector<llvm::Constant *, 4> Inits;
1165 unsigned NumElts = Value.getVectorLength();
1166
1167 for (unsigned i = 0; i != NumElts; ++i) {
1168 const APValue &Elt = Value.getVectorElt(i);
1169 if (Elt.isInt())
1170 Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
1171 else
1172 Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
1173 }
1174 return llvm::ConstantVector::get(Inits);
1175 }
1176 case APValue::AddrLabelDiff: {
1177 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1178 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
1179 llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF);
1180 llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF);
1181
1182 // Compute difference
1183 llvm::Type *ResultType = getTypes().ConvertType(DestType);
1184 LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
1185 RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
1186 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1187
1188 // LLVM is a bit sensitive about the exact format of the
1189 // address-of-label difference; make sure to truncate after
1190 // the subtraction.
1191 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1192 }
1193 case APValue::Struct:
1194 case APValue::Union:
1195 return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
1196 case APValue::Array: {
1197 const ArrayType *CAT = Context.getAsArrayType(DestType);
1198 unsigned NumElements = Value.getArraySize();
1199 unsigned NumInitElts = Value.getArrayInitializedElts();
1200
1201 std::vector<llvm::Constant*> Elts;
1202 Elts.reserve(NumElements);
1203
1204 // Emit array filler, if there is one.
1205 llvm::Constant *Filler = 0;
1206 if (Value.hasArrayFiller())
Richard Smitha3ca41f2012-03-02 23:27:11 +00001207 Filler = EmitConstantValueForMemory(Value.getArrayFiller(),
1208 CAT->getElementType(), CGF);
Richard Smith2d6a5672012-01-14 04:30:29 +00001209
1210 // Emit initializer elements.
1211 llvm::Type *CommonElementType = 0;
1212 for (unsigned I = 0; I < NumElements; ++I) {
1213 llvm::Constant *C = Filler;
1214 if (I < NumInitElts)
Richard Smitha3ca41f2012-03-02 23:27:11 +00001215 C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I),
1216 CAT->getElementType(), CGF);
Jordan Rose41f3f3a2013-03-05 01:27:54 +00001217 else
1218 assert(Filler && "Missing filler for implicit elements of initializer");
Richard Smith2d6a5672012-01-14 04:30:29 +00001219 if (I == 0)
1220 CommonElementType = C->getType();
1221 else if (C->getType() != CommonElementType)
1222 CommonElementType = 0;
1223 Elts.push_back(C);
1224 }
1225
1226 if (!CommonElementType) {
1227 // FIXME: Try to avoid packing the array
1228 std::vector<llvm::Type*> Types;
Bill Wendlingf9ea9532012-02-07 00:13:27 +00001229 Types.reserve(NumElements);
Bill Wendlingfd3e5ef2012-02-06 23:46:08 +00001230 for (unsigned i = 0, e = Elts.size(); i < e; ++i)
Richard Smith2d6a5672012-01-14 04:30:29 +00001231 Types.push_back(Elts[i]->getType());
1232 llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true);
1233 return llvm::ConstantStruct::get(SType, Elts);
1234 }
1235
1236 llvm::ArrayType *AType =
1237 llvm::ArrayType::get(CommonElementType, NumElements);
1238 return llvm::ConstantArray::get(AType, Elts);
1239 }
1240 case APValue::MemberPointer:
1241 return getCXXABI().EmitMemberPointer(Value, DestType);
1242 }
1243 llvm_unreachable("Unknown APValue kind");
1244}
1245
Richard Smith7401cf52011-11-22 22:48:32 +00001246llvm::Constant *
Richard Smitha3ca41f2012-03-02 23:27:11 +00001247CodeGenModule::EmitConstantValueForMemory(const APValue &Value,
1248 QualType DestType,
1249 CodeGenFunction *CGF) {
1250 llvm::Constant *C = EmitConstantValue(Value, DestType, CGF);
1251 if (C->getType()->isIntegerTy(1)) {
1252 llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType);
1253 C = llvm::ConstantExpr::getZExt(C, BoolTy);
1254 }
1255 return C;
1256}
1257
1258llvm::Constant *
Richard Smith7401cf52011-11-22 22:48:32 +00001259CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
1260 assert(E->isFileScope() && "not a file-scope compound literal expr");
1261 return ConstExprEmitter(*this, 0).EmitLValue(E);
1262}
1263
John McCall5808ce42011-02-03 08:15:49 +00001264llvm::Constant *
1265CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
1266 // Member pointer constants always have a very particular form.
1267 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1268 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1269
1270 // A member function pointer.
1271 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1272 return getCXXABI().EmitMemberPointer(method);
1273
1274 // Otherwise, a member data pointer.
Richard Smith2d6a5672012-01-14 04:30:29 +00001275 uint64_t fieldOffset = getContext().getFieldOffset(decl);
John McCall5808ce42011-02-03 08:15:49 +00001276 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1277 return getCXXABI().EmitMemberDataPointer(type, chars);
1278}
1279
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001280static void
1281FillInNullDataMemberPointers(CodeGenModule &CGM, QualType T,
Bill Wendling35f18a52012-02-07 00:04:27 +00001282 SmallVectorImpl<llvm::Constant *> &Elements,
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001283 uint64_t StartOffset) {
Ken Dyckc4d68db2011-03-22 00:24:31 +00001284 assert(StartOffset % CGM.getContext().getCharWidth() == 0 &&
1285 "StartOffset not byte aligned!");
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001286
John McCallf16aa102010-08-22 21:01:12 +00001287 if (CGM.getTypes().isZeroInitializable(T))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001288 return;
1289
1290 if (const ConstantArrayType *CAT =
1291 CGM.getContext().getAsConstantArrayType(T)) {
1292 QualType ElementTy = CAT->getElementType();
1293 uint64_t ElementSize = CGM.getContext().getTypeSize(ElementTy);
1294
1295 for (uint64_t I = 0, E = CAT->getSize().getZExtValue(); I != E; ++I) {
1296 FillInNullDataMemberPointers(CGM, ElementTy, Elements,
1297 StartOffset + I * ElementSize);
1298 }
1299 } else if (const RecordType *RT = T->getAs<RecordType>()) {
1300 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1301 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1302
1303 // Go through all bases and fill in any null pointer to data members.
1304 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1305 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson0a87b372010-05-27 18:51:01 +00001306 if (I->isVirtual()) {
Anders Carlssonada4b322010-11-22 18:42:14 +00001307 // Ignore virtual bases.
Anders Carlsson0a87b372010-05-27 18:51:01 +00001308 continue;
1309 }
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001310
1311 const CXXRecordDecl *BaseDecl =
1312 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1313
1314 // Ignore empty bases.
1315 if (BaseDecl->isEmpty())
1316 continue;
1317
1318 // Ignore bases that don't have any pointer to data members.
John McCallf16aa102010-08-22 21:01:12 +00001319 if (CGM.getTypes().isZeroInitializable(BaseDecl))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001320 continue;
1321
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001322 uint64_t BaseOffset =
1323 CGM.getContext().toBits(Layout.getBaseClassOffset(BaseDecl));
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001324 FillInNullDataMemberPointers(CGM, I->getType(),
1325 Elements, StartOffset + BaseOffset);
1326 }
1327
1328 // Visit all fields.
1329 unsigned FieldNo = 0;
1330 for (RecordDecl::field_iterator I = RD->field_begin(),
1331 E = RD->field_end(); I != E; ++I, ++FieldNo) {
1332 QualType FieldType = I->getType();
1333
John McCallf16aa102010-08-22 21:01:12 +00001334 if (CGM.getTypes().isZeroInitializable(FieldType))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001335 continue;
1336
1337 uint64_t FieldOffset = StartOffset + Layout.getFieldOffset(FieldNo);
1338 FillInNullDataMemberPointers(CGM, FieldType, Elements, FieldOffset);
1339 }
1340 } else {
1341 assert(T->isMemberPointerType() && "Should only see member pointers here!");
1342 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1343 "Should only see pointers to data members here!");
1344
Ken Dyckc4d68db2011-03-22 00:24:31 +00001345 CharUnits StartIndex = CGM.getContext().toCharUnitsFromBits(StartOffset);
1346 CharUnits EndIndex = StartIndex + CGM.getContext().getTypeSizeInChars(T);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001347
John McCall5808ce42011-02-03 08:15:49 +00001348 // FIXME: hardcodes Itanium member pointer representation!
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001349 llvm::Constant *NegativeOne =
Chris Lattner8b418682012-02-07 00:39:47 +00001350 llvm::ConstantInt::get(CGM.Int8Ty, -1ULL, /*isSigned*/true);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001351
1352 // Fill in the null data member pointer.
Ken Dyckc4d68db2011-03-22 00:24:31 +00001353 for (CharUnits I = StartIndex; I != EndIndex; ++I)
1354 Elements[I.getQuantity()] = NegativeOne;
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001355 }
1356}
1357
John McCall9b7da1c2011-02-15 06:40:56 +00001358static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001359 llvm::Type *baseType,
John McCall9b7da1c2011-02-15 06:40:56 +00001360 const CXXRecordDecl *base);
1361
Anders Carlssonada4b322010-11-22 18:42:14 +00001362static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
John McCall9b7da1c2011-02-15 06:40:56 +00001363 const CXXRecordDecl *record,
1364 bool asCompleteObject) {
1365 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001366 llvm::StructType *structure =
John McCall9b7da1c2011-02-15 06:40:56 +00001367 (asCompleteObject ? layout.getLLVMType()
1368 : layout.getBaseSubobjectLLVMType());
Anders Carlssonada4b322010-11-22 18:42:14 +00001369
John McCall9b7da1c2011-02-15 06:40:56 +00001370 unsigned numElements = structure->getNumElements();
1371 std::vector<llvm::Constant *> elements(numElements);
Anders Carlssonada4b322010-11-22 18:42:14 +00001372
John McCall9b7da1c2011-02-15 06:40:56 +00001373 // Fill in all the bases.
1374 for (CXXRecordDecl::base_class_const_iterator
1375 I = record->bases_begin(), E = record->bases_end(); I != E; ++I) {
Anders Carlssonada4b322010-11-22 18:42:14 +00001376 if (I->isVirtual()) {
John McCall9b7da1c2011-02-15 06:40:56 +00001377 // Ignore virtual bases; if we're laying out for a complete
1378 // object, we'll lay these out later.
Anders Carlssonada4b322010-11-22 18:42:14 +00001379 continue;
1380 }
1381
John McCall9b7da1c2011-02-15 06:40:56 +00001382 const CXXRecordDecl *base =
1383 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlssonada4b322010-11-22 18:42:14 +00001384
1385 // Ignore empty bases.
John McCall9b7da1c2011-02-15 06:40:56 +00001386 if (base->isEmpty())
Anders Carlssonada4b322010-11-22 18:42:14 +00001387 continue;
1388
John McCall9b7da1c2011-02-15 06:40:56 +00001389 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001390 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall9b7da1c2011-02-15 06:40:56 +00001391 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlssonada4b322010-11-22 18:42:14 +00001392 }
1393
John McCall9b7da1c2011-02-15 06:40:56 +00001394 // Fill in all the fields.
1395 for (RecordDecl::field_iterator I = record->field_begin(),
1396 E = record->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001397 const FieldDecl *field = *I;
Eli Friedman26e80cd2011-12-07 01:30:11 +00001398
1399 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
1400 // will fill in later.)
1401 if (!field->isBitField()) {
1402 unsigned fieldIndex = layout.getLLVMFieldNo(field);
1403 elements[fieldIndex] = CGM.EmitNullConstant(field->getType());
1404 }
1405
1406 // For unions, stop after the first named field.
1407 if (record->isUnion() && field->getDeclName())
1408 break;
John McCall9b7da1c2011-02-15 06:40:56 +00001409 }
1410
1411 // Fill in the virtual bases, if we're working with the complete object.
1412 if (asCompleteObject) {
1413 for (CXXRecordDecl::base_class_const_iterator
1414 I = record->vbases_begin(), E = record->vbases_end(); I != E; ++I) {
1415 const CXXRecordDecl *base =
1416 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1417
1418 // Ignore empty bases.
1419 if (base->isEmpty())
1420 continue;
1421
1422 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
1423
1424 // We might have already laid this field out.
1425 if (elements[fieldIndex]) continue;
1426
Chris Lattner2acc6e32011-07-18 04:24:23 +00001427 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall9b7da1c2011-02-15 06:40:56 +00001428 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1429 }
Anders Carlssonada4b322010-11-22 18:42:14 +00001430 }
1431
1432 // Now go through all other fields and zero them out.
John McCall9b7da1c2011-02-15 06:40:56 +00001433 for (unsigned i = 0; i != numElements; ++i) {
1434 if (!elements[i])
1435 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlssonada4b322010-11-22 18:42:14 +00001436 }
1437
John McCall9b7da1c2011-02-15 06:40:56 +00001438 return llvm::ConstantStruct::get(structure, elements);
1439}
1440
1441/// Emit the null constant for a base subobject.
1442static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001443 llvm::Type *baseType,
John McCall9b7da1c2011-02-15 06:40:56 +00001444 const CXXRecordDecl *base) {
1445 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
1446
1447 // Just zero out bases that don't have any pointer to data members.
1448 if (baseLayout.isZeroInitializableAsBase())
1449 return llvm::Constant::getNullValue(baseType);
1450
1451 // If the base type is a struct, we can just use its null constant.
1452 if (isa<llvm::StructType>(baseType)) {
1453 return EmitNullConstant(CGM, base, /*complete*/ false);
1454 }
1455
1456 // Otherwise, some bases are represented as arrays of i8 if the size
1457 // of the base is smaller than its corresponding LLVM type. Figure
1458 // out how many elements this base array has.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001459 llvm::ArrayType *baseArrayType = cast<llvm::ArrayType>(baseType);
John McCall9b7da1c2011-02-15 06:40:56 +00001460 unsigned numBaseElements = baseArrayType->getNumElements();
1461
1462 // Fill in null data member pointers.
Bill Wendling35f18a52012-02-07 00:04:27 +00001463 SmallVector<llvm::Constant *, 16> baseElements(numBaseElements);
John McCall9b7da1c2011-02-15 06:40:56 +00001464 FillInNullDataMemberPointers(CGM, CGM.getContext().getTypeDeclType(base),
1465 baseElements, 0);
1466
1467 // Now go through all other elements and zero them out.
1468 if (numBaseElements) {
Chris Lattner8b418682012-02-07 00:39:47 +00001469 llvm::Constant *i8_zero = llvm::Constant::getNullValue(CGM.Int8Ty);
John McCall9b7da1c2011-02-15 06:40:56 +00001470 for (unsigned i = 0; i != numBaseElements; ++i) {
1471 if (!baseElements[i])
1472 baseElements[i] = i8_zero;
1473 }
1474 }
1475
1476 return llvm::ConstantArray::get(baseArrayType, baseElements);
Anders Carlssonada4b322010-11-22 18:42:14 +00001477}
1478
Eli Friedman0f593122009-04-13 21:47:26 +00001479llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
John McCallf16aa102010-08-22 21:01:12 +00001480 if (getTypes().isZeroInitializable(T))
Anders Carlssonad3e7112009-08-24 17:16:23 +00001481 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Anders Carlsson2c12d032010-02-02 05:17:25 +00001482
Anders Carlsson237957c2009-08-09 18:26:27 +00001483 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Chris Lattner6ef016f2012-02-06 22:00:56 +00001484 llvm::ArrayType *ATy =
1485 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
Mike Stump1eb44332009-09-09 15:08:12 +00001486
Anders Carlsson237957c2009-08-09 18:26:27 +00001487 QualType ElementTy = CAT->getElementType();
1488
Anders Carlsson2c12d032010-02-02 05:17:25 +00001489 llvm::Constant *Element = EmitNullConstant(ElementTy);
1490 unsigned NumElements = CAT->getSize().getZExtValue();
Chris Lattner6ef016f2012-02-06 22:00:56 +00001491
1492 if (Element->isNullValue())
1493 return llvm::ConstantAggregateZero::get(ATy);
1494
1495 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
Anders Carlsson2c12d032010-02-02 05:17:25 +00001496 return llvm::ConstantArray::get(ATy, Array);
Anders Carlsson237957c2009-08-09 18:26:27 +00001497 }
Anders Carlssonfc3eaa42009-08-23 01:25:01 +00001498
1499 if (const RecordType *RT = T->getAs<RecordType>()) {
Anders Carlsson2c12d032010-02-02 05:17:25 +00001500 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall9b7da1c2011-02-15 06:40:56 +00001501 return ::EmitNullConstant(*this, RD, /*complete object*/ true);
Anders Carlssonfc3eaa42009-08-23 01:25:01 +00001502 }
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001504 assert(T->isMemberPointerType() && "Should only see member pointers here!");
Anders Carlsson2c12d032010-02-02 05:17:25 +00001505 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1506 "Should only see pointers to data members here!");
1507
1508 // Itanium C++ ABI 2.3:
1509 // A NULL pointer is represented as -1.
John McCall5808ce42011-02-03 08:15:49 +00001510 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman0f593122009-04-13 21:47:26 +00001511}
Eli Friedman2ed7cb62011-10-14 02:27:24 +00001512
1513llvm::Constant *
1514CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
1515 return ::EmitNullConstant(*this, Record, false);
1516}