blob: e88c28737c61b198a8cdcba3d0fe6cd4ff30106f [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"
15#include "CodeGenModule.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000017#include "CGObjCRuntime.h"
Daniel Dunbar2924ade2010-03-30 22:26:10 +000018#include "CGRecordLayout.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"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000024#include "llvm/Constants.h"
25#include "llvm/Function.h"
26#include "llvm/GlobalVariable.h"
Eli Friedmana8234002008-05-30 10:24:46 +000027#include "llvm/Target/TargetData.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;
Anders Carlsson4c98efd2009-07-24 15:20:52 +000043 std::vector<llvm::Constant *> Elements;
Chris Lattnereba3e5a2010-04-13 17:45:57 +000044public:
45 static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
46 InitListExpr *ILE);
47
48private:
Anders Carlsson4c98efd2009-07-24 15:20:52 +000049 ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
Ken Dyckdc496392011-03-17 01:33:18 +000050 : CGM(CGM), CGF(CGF), Packed(false),
51 NextFieldOffsetInChars(CharUnits::Zero()),
Ken Dyck7d2f9d52011-03-18 01:26:17 +000052 LLVMStructAlignment(CharUnits::One()) { }
Anders Carlsson4c98efd2009-07-24 15:20:52 +000053
Mike Stump1eb44332009-09-09 15:08:12 +000054 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
Chris Lattner8ce9e452010-04-13 18:16:19 +000055 llvm::Constant *InitExpr);
Mike Stump1eb44332009-09-09 15:08:12 +000056
Chris Lattner18806662010-07-05 17:04:23 +000057 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
58 llvm::ConstantInt *InitExpr);
Mike Stump1eb44332009-09-09 15:08:12 +000059
Ken Dyckc29ea8f2011-03-11 23:42:54 +000060 void AppendPadding(CharUnits PadSize);
Mike Stump1eb44332009-09-09 15:08:12 +000061
Ken Dyck106ca042011-03-11 02:17:05 +000062 void AppendTailPadding(CharUnits RecordSize);
Anders Carlssond24393b2009-07-27 01:23:51 +000063
Chris Lattnereba3e5a2010-04-13 17:45:57 +000064 void ConvertStructToPacked();
Anders Carlsson31f2f9c2009-10-02 02:15:20 +000065
Chris Lattnereba3e5a2010-04-13 17:45:57 +000066 bool Build(InitListExpr *ILE);
Mike Stump1eb44332009-09-09 15:08:12 +000067
Ken Dyck7d2f9d52011-03-18 01:26:17 +000068 CharUnits getAlignment(const llvm::Constant *C) const {
69 if (Packed) return CharUnits::One();
70 return CharUnits::fromQuantity(
71 CGM.getTargetData().getABITypeAlignment(C->getType()));
Anders Carlsson4c98efd2009-07-24 15:20:52 +000072 }
Mike Stump1eb44332009-09-09 15:08:12 +000073
Ken Dyck15c152e2011-03-18 01:12:13 +000074 CharUnits getSizeInChars(const llvm::Constant *C) const {
75 return CharUnits::fromQuantity(
76 CGM.getTargetData().getTypeAllocSize(C->getType()));
Anders Carlsson4c98efd2009-07-24 15:20:52 +000077 }
Anders Carlsson4c98efd2009-07-24 15:20:52 +000078};
Mike Stump1eb44332009-09-09 15:08:12 +000079
Chris Lattnereba3e5a2010-04-13 17:45:57 +000080bool ConstStructBuilder::
Chris Lattner8ce9e452010-04-13 18:16:19 +000081AppendField(const FieldDecl *Field, uint64_t FieldOffset,
82 llvm::Constant *InitCst) {
Ken Dyck6925cc42011-03-15 01:09:02 +000083
84 const ASTContext &Context = CGM.getContext();
85
86 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnereba3e5a2010-04-13 17:45:57 +000087
Ken Dyckdc496392011-03-17 01:33:18 +000088 assert(NextFieldOffsetInChars <= FieldOffsetInChars
Chris Lattnereba3e5a2010-04-13 17:45:57 +000089 && "Field offset mismatch!");
90
Ken Dyck7d2f9d52011-03-18 01:26:17 +000091 CharUnits FieldAlignment = getAlignment(InitCst);
Chris Lattnereba3e5a2010-04-13 17:45:57 +000092
93 // Round up the field offset to the alignment of the field type.
Ken Dyckdc496392011-03-17 01:33:18 +000094 CharUnits AlignedNextFieldOffsetInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +000095 NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
Chris Lattnereba3e5a2010-04-13 17:45:57 +000096
Ken Dyckdc496392011-03-17 01:33:18 +000097 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +000098 assert(!Packed && "Alignment is wrong even with a packed struct!");
99
100 // Convert the struct to a packed struct.
101 ConvertStructToPacked();
102
Ken Dyckdc496392011-03-17 01:33:18 +0000103 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000104 }
105
Ken Dyckdc496392011-03-17 01:33:18 +0000106 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000107 // We need to append padding.
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000108 AppendPadding(
Ken Dyckdc496392011-03-17 01:33:18 +0000109 FieldOffsetInChars - NextFieldOffsetInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000110
Ken Dyckdc496392011-03-17 01:33:18 +0000111 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000112 "Did not add enough padding!");
113
Ken Dyckdc496392011-03-17 01:33:18 +0000114 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000115 }
116
117 // Add the field.
Chris Lattner8ce9e452010-04-13 18:16:19 +0000118 Elements.push_back(InitCst);
Ken Dyckdc496392011-03-17 01:33:18 +0000119 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
Ken Dyck15c152e2011-03-18 01:12:13 +0000120 getSizeInChars(InitCst);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000121
122 if (Packed)
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000123 assert(LLVMStructAlignment == CharUnits::One() &&
124 "Packed struct not byte-aligned!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000125 else
126 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
127
128 return true;
129}
130
Chris Lattner18806662010-07-05 17:04:23 +0000131void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
132 uint64_t FieldOffset,
133 llvm::ConstantInt *CI) {
Ken Dyckf004da42011-03-12 12:03:11 +0000134 const ASTContext &Context = CGM.getContext();
Ken Dyck4f318c02011-03-19 00:57:28 +0000135 const uint64_t CharWidth = Context.getCharWidth();
Ken Dyckdc496392011-03-17 01:33:18 +0000136 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
137 if (FieldOffset > NextFieldOffsetInBits) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000138 // We need to add padding.
Ken Dyckf004da42011-03-12 12:03:11 +0000139 CharUnits PadSize = Context.toCharUnitsFromBits(
Ken Dyckdc496392011-03-17 01:33:18 +0000140 llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
Ken Dyckf004da42011-03-12 12:03:11 +0000141 Context.Target.getCharAlign()));
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000142
Ken Dyckf004da42011-03-12 12:03:11 +0000143 AppendPadding(PadSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000144 }
145
146 uint64_t FieldSize =
Ken Dyckf004da42011-03-12 12:03:11 +0000147 Field->getBitWidth()->EvaluateAsInt(Context).getZExtValue();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000148
149 llvm::APInt FieldValue = CI->getValue();
150
151 // Promote the size of FieldValue if necessary
152 // FIXME: This should never occur, but currently it can because initializer
153 // constants are cast to bool, and because clang is not enforcing bitfield
154 // width limits.
155 if (FieldSize > FieldValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +0000156 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000157
158 // Truncate the size of FieldValue to the bit field size.
159 if (FieldSize < FieldValue.getBitWidth())
Jay Foad9f71a8f2010-12-07 08:25:34 +0000160 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000161
Ken Dyckdc496392011-03-17 01:33:18 +0000162 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
163 if (FieldOffset < NextFieldOffsetInBits) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000164 // Either part of the field or the entire field can go into the previous
165 // byte.
166 assert(!Elements.empty() && "Elements can't be empty!");
167
Ken Dyckdc496392011-03-17 01:33:18 +0000168 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000169
170 bool FitsCompletelyInPreviousByte =
171 BitsInPreviousByte >= FieldValue.getBitWidth();
172
173 llvm::APInt Tmp = FieldValue;
174
175 if (!FitsCompletelyInPreviousByte) {
176 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
177
178 if (CGM.getTargetData().isBigEndian()) {
179 Tmp = Tmp.lshr(NewFieldWidth);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000180 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000181
182 // We want the remaining high bits.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000183 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000184 } else {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000185 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000186
187 // We want the remaining low bits.
188 FieldValue = FieldValue.lshr(BitsInPreviousByte);
Jay Foad9f71a8f2010-12-07 08:25:34 +0000189 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000190 }
191 }
192
Ken Dyck4f318c02011-03-19 00:57:28 +0000193 Tmp = Tmp.zext(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000194 if (CGM.getTargetData().isBigEndian()) {
195 if (FitsCompletelyInPreviousByte)
196 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
197 } else {
Ken Dyck4f318c02011-03-19 00:57:28 +0000198 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000199 }
200
Chris Lattner2bc00252010-07-05 18:03:30 +0000201 // 'or' in the bits that go into the previous byte.
202 llvm::Value *LastElt = Elements.back();
203 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000204 Tmp |= Val->getValue();
Chris Lattner2bc00252010-07-05 18:03:30 +0000205 else {
206 assert(isa<llvm::UndefValue>(LastElt));
207 // If there is an undef field that we're adding to, it can either be a
208 // scalar undef (in which case, we just replace it with our field) or it
209 // is an array. If it is an array, we have to pull one byte off the
210 // array so that the other undef bytes stay around.
211 if (!isa<llvm::IntegerType>(LastElt->getType())) {
212 // The undef padding will be a multibyte array, create a new smaller
213 // padding and then an hole for our i8 to get plopped into.
214 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
215 "Expected array padding of undefs");
216 const llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
Ken Dyck4f318c02011-03-19 00:57:28 +0000217 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
Chris Lattner2bc00252010-07-05 18:03:30 +0000218 AT->getNumElements() != 0 &&
219 "Expected non-empty array padding of undefs");
220
221 // Remove the padding array.
Ken Dyckdc496392011-03-17 01:33:18 +0000222 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
Chris Lattner2bc00252010-07-05 18:03:30 +0000223 Elements.pop_back();
224
225 // Add the padding back in two chunks.
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000226 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
227 AppendPadding(CharUnits::One());
Chris Lattner2bc00252010-07-05 18:03:30 +0000228 assert(isa<llvm::UndefValue>(Elements.back()) &&
Ken Dyck4f318c02011-03-19 00:57:28 +0000229 Elements.back()->getType()->isIntegerTy(CharWidth) &&
Chris Lattner2bc00252010-07-05 18:03:30 +0000230 "Padding addition didn't work right");
231 }
232 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000233
234 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
235
236 if (FitsCompletelyInPreviousByte)
Chris Lattner18806662010-07-05 17:04:23 +0000237 return;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000238 }
239
Ken Dyck4f318c02011-03-19 00:57:28 +0000240 while (FieldValue.getBitWidth() > CharWidth) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000241 llvm::APInt Tmp;
242
243 if (CGM.getTargetData().isBigEndian()) {
244 // We want the high bits.
Ken Dyck4f318c02011-03-19 00:57:28 +0000245 Tmp =
246 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000247 } else {
248 // We want the low bits.
Ken Dyck4f318c02011-03-19 00:57:28 +0000249 Tmp = FieldValue.trunc(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000250
Ken Dyck4f318c02011-03-19 00:57:28 +0000251 FieldValue = FieldValue.lshr(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000252 }
253
254 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
Ken Dyck199c1892011-03-19 01:28:06 +0000255 ++NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000256
Ken Dyck4f318c02011-03-19 00:57:28 +0000257 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000258 }
259
260 assert(FieldValue.getBitWidth() > 0 &&
261 "Should have at least one bit left!");
Ken Dyck4f318c02011-03-19 00:57:28 +0000262 assert(FieldValue.getBitWidth() <= CharWidth &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000263 "Should not have more than a byte left!");
264
Ken Dyck4f318c02011-03-19 00:57:28 +0000265 if (FieldValue.getBitWidth() < CharWidth) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000266 if (CGM.getTargetData().isBigEndian()) {
267 unsigned BitWidth = FieldValue.getBitWidth();
268
Ken Dyck4f318c02011-03-19 00:57:28 +0000269 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000270 } else
Ken Dyck4f318c02011-03-19 00:57:28 +0000271 FieldValue = FieldValue.zext(CharWidth);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000272 }
273
274 // Append the last element.
275 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
276 FieldValue));
Ken Dyck199c1892011-03-19 01:28:06 +0000277 ++NextFieldOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000278}
279
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000280void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
281 if (PadSize.isZero())
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000282 return;
283
284 const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext());
Ken Dyckc29ea8f2011-03-11 23:42:54 +0000285 if (PadSize > CharUnits::One())
286 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000287
Nuno Lopescdb30b42010-04-16 20:56:35 +0000288 llvm::Constant *C = llvm::UndefValue::get(Ty);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000289 Elements.push_back(C);
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000290 assert(getAlignment(C) == CharUnits::One() &&
291 "Padding must have 1 byte alignment!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000292
Ken Dyck15c152e2011-03-18 01:12:13 +0000293 NextFieldOffsetInChars += getSizeInChars(C);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000294}
295
Ken Dyck106ca042011-03-11 02:17:05 +0000296void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
Ken Dyckdc496392011-03-17 01:33:18 +0000297 assert(NextFieldOffsetInChars <= RecordSize &&
Ken Dyck106ca042011-03-11 02:17:05 +0000298 "Size mismatch!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000299
Ken Dyckdc496392011-03-17 01:33:18 +0000300 AppendPadding(RecordSize - NextFieldOffsetInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000301}
302
303void ConstStructBuilder::ConvertStructToPacked() {
304 std::vector<llvm::Constant *> PackedElements;
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000305 CharUnits ElementOffsetInChars = CharUnits::Zero();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000306
307 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
308 llvm::Constant *C = Elements[i];
309
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000310 CharUnits ElementAlign = CharUnits::fromQuantity(
311 CGM.getTargetData().getABITypeAlignment(C->getType()));
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000312 CharUnits AlignedElementOffsetInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000313 ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000314
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000315 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000316 // We need some padding.
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000317 CharUnits NumChars =
318 AlignedElementOffsetInChars - ElementOffsetInChars;
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000319
320 const llvm::Type *Ty = llvm::Type::getInt8Ty(CGM.getLLVMContext());
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000321 if (NumChars > CharUnits::One())
322 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000323
Nuno Lopescdb30b42010-04-16 20:56:35 +0000324 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000325 PackedElements.push_back(Padding);
Ken Dyck15c152e2011-03-18 01:12:13 +0000326 ElementOffsetInChars += getSizeInChars(Padding);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000327 }
328
329 PackedElements.push_back(C);
Ken Dyck15c152e2011-03-18 01:12:13 +0000330 ElementOffsetInChars += getSizeInChars(C);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000331 }
332
Ken Dyck4a5c87e2011-03-18 00:55:06 +0000333 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000334 "Packing the struct changed its size!");
335
336 Elements = PackedElements;
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000337 LLVMStructAlignment = CharUnits::One();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000338 Packed = true;
339}
340
341bool ConstStructBuilder::Build(InitListExpr *ILE) {
342 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
343 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
344
345 unsigned FieldNo = 0;
346 unsigned ElementNo = 0;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000347 const FieldDecl *LastFD = 0;
348 bool IsMsStruct = RD->hasAttr<MsStructAttr>();
349
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000350 for (RecordDecl::field_iterator Field = RD->field_begin(),
Chris Lattner8ce9e452010-04-13 18:16:19 +0000351 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000352 if (IsMsStruct) {
353 // Zero-length bitfields following non-bitfield members are
354 // ignored:
Fariborz Jahanian855a8e72011-05-03 20:21:04 +0000355 if (CGM.getContext().ZeroBitfieldFollowsNonBitfield((*Field), LastFD)) {
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000356 --FieldNo;
357 continue;
358 }
359 LastFD = (*Field);
360 }
Chris Lattner8ce9e452010-04-13 18:16:19 +0000361
362 // If this is a union, skip all the fields that aren't being initialized.
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000363 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
364 continue;
365
Chris Lattner8ce9e452010-04-13 18:16:19 +0000366 // Don't emit anonymous bitfields, they just affect layout.
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000367 if (Field->isBitField() && !Field->getIdentifier()) {
368 LastFD = (*Field);
Chris Lattner8ce9e452010-04-13 18:16:19 +0000369 continue;
Fariborz Jahanian07a8a212011-04-28 22:49:46 +0000370 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000371
Chris Lattner8ce9e452010-04-13 18:16:19 +0000372 // Get the initializer. A struct can include fields without initializers,
373 // we just use explicit null values for them.
374 llvm::Constant *EltInit;
375 if (ElementNo < ILE->getNumInits())
376 EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
377 Field->getType(), CGF);
378 else
379 EltInit = CGM.EmitNullConstant(Field->getType());
Eli Friedmanf0ca0ee2010-07-17 23:55:01 +0000380
381 if (!EltInit)
382 return false;
Chris Lattner8ce9e452010-04-13 18:16:19 +0000383
384 if (!Field->isBitField()) {
385 // Handle non-bitfield members.
386 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit))
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000387 return false;
388 } else {
Chris Lattner8ce9e452010-04-13 18:16:19 +0000389 // Otherwise we have a bitfield.
Chris Lattner18806662010-07-05 17:04:23 +0000390 AppendBitField(*Field, Layout.getFieldOffset(FieldNo),
391 cast<llvm::ConstantInt>(EltInit));
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000392 }
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000393 }
394
Ken Dyckdc496392011-03-17 01:33:18 +0000395 CharUnits LayoutSizeInChars = Layout.getSize();
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000396
Ken Dyckdc496392011-03-17 01:33:18 +0000397 if (NextFieldOffsetInChars > LayoutSizeInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000398 // If the struct is bigger than the size of the record type,
399 // we must have a flexible array member at the end.
400 assert(RD->hasFlexibleArrayMember() &&
401 "Must have flexible array member if struct is bigger than type!");
402
403 // No tail padding is necessary.
404 return true;
405 }
406
Ken Dyckdc496392011-03-17 01:33:18 +0000407 CharUnits LLVMSizeInChars =
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000408 NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000409
410 // Check if we need to convert the struct to a packed struct.
Ken Dyckdc496392011-03-17 01:33:18 +0000411 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
412 LLVMSizeInChars > LayoutSizeInChars) {
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000413 assert(!Packed && "Size mismatch!");
414
415 ConvertStructToPacked();
Ken Dyckdc496392011-03-17 01:33:18 +0000416 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000417 "Converting to packed did not help!");
418 }
419
420 // Append tail padding if necessary.
Ken Dyckdc496392011-03-17 01:33:18 +0000421 AppendTailPadding(LayoutSizeInChars);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000422
Ken Dyckdc496392011-03-17 01:33:18 +0000423 assert(LayoutSizeInChars == NextFieldOffsetInChars &&
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000424 "Tail padding mismatch!");
425
426 return true;
427}
428
429llvm::Constant *ConstStructBuilder::
430 BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF, InitListExpr *ILE) {
431 ConstStructBuilder Builder(CGM, CGF);
432
433 if (!Builder.Build(ILE))
434 return 0;
435
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000436 // Pick the type to use. If the type is layout identical to the ConvertType
437 // type then use it, otherwise use whatever the builder produced for us.
438 const llvm::StructType *STy =
439 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
440 Builder.Elements,Builder.Packed);
441 const llvm::Type *ILETy = CGM.getTypes().ConvertType(ILE->getType());
442 if (const llvm::StructType *ILESTy = dyn_cast<llvm::StructType>(ILETy)) {
443 if (ILESTy->isLayoutIdentical(STy))
444 STy = ILESTy;
445 }
446
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000447 llvm::Constant *Result =
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000448 llvm::ConstantStruct::get(STy, Builder.Elements);
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000449
Ken Dyck15c152e2011-03-18 01:12:13 +0000450 assert(Builder.NextFieldOffsetInChars.RoundUpToAlignment(
Ken Dyck7d2f9d52011-03-18 01:26:17 +0000451 Builder.getAlignment(Result)) ==
Ken Dyck15c152e2011-03-18 01:12:13 +0000452 Builder.getSizeInChars(Result) && "Size mismatch!");
Chris Lattnereba3e5a2010-04-13 17:45:57 +0000453
454 return Result;
455}
456
457
458//===----------------------------------------------------------------------===//
459// ConstExprEmitter
460//===----------------------------------------------------------------------===//
461
Benjamin Kramer85b45212009-11-28 19:45:26 +0000462class ConstExprEmitter :
Anders Carlsson84005b42008-01-26 04:30:23 +0000463 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000464 CodeGenModule &CGM;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000465 CodeGenFunction *CGF;
Owen Andersona1cf15f2009-07-14 23:10:40 +0000466 llvm::LLVMContext &VMContext;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000467public:
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000468 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
Owen Andersona1cf15f2009-07-14 23:10:40 +0000469 : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000470 }
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000472 //===--------------------------------------------------------------------===//
473 // Visitor Methods
474 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000476 llvm::Constant *VisitStmt(Stmt *S) {
Anders Carlsson069880e2009-03-03 16:43:34 +0000477 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000478 }
Mike Stump1eb44332009-09-09 15:08:12 +0000479
480 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
481 return Visit(PE->getSubExpr());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Peter Collingbournef111d932011-04-15 00:35:48 +0000484 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
485 return Visit(GE->getResultExpr());
486 }
487
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000488 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
489 return Visit(E->getInitializer());
490 }
John McCall5808ce42011-02-03 08:15:49 +0000491
Anders Carlssonf57b4e42009-10-03 15:02:02 +0000492 llvm::Constant *VisitUnaryAddrOf(UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000493 if (E->getType()->isMemberPointerType())
494 return CGM.getMemberPointerConstant(E);
Anders Carlsson45147d02010-02-02 03:37:46 +0000495
Anders Carlssonf57b4e42009-10-03 15:02:02 +0000496 return 0;
497 }
498
Chris Lattner3ae9f482009-10-13 07:14:16 +0000499 llvm::Constant *VisitBinSub(BinaryOperator *E) {
500 // This must be a pointer/pointer subtraction. This only happens for
501 // address of label.
502 if (!isa<AddrLabelExpr>(E->getLHS()->IgnoreParenNoopCasts(CGM.getContext())) ||
503 !isa<AddrLabelExpr>(E->getRHS()->IgnoreParenNoopCasts(CGM.getContext())))
504 return 0;
505
506 llvm::Constant *LHS = CGM.EmitConstantExpr(E->getLHS(),
507 E->getLHS()->getType(), CGF);
508 llvm::Constant *RHS = CGM.EmitConstantExpr(E->getRHS(),
509 E->getRHS()->getType(), CGF);
510
511 const llvm::Type *ResultType = ConvertType(E->getType());
512 LHS = llvm::ConstantExpr::getPtrToInt(LHS, ResultType);
513 RHS = llvm::ConstantExpr::getPtrToInt(RHS, ResultType);
514
515 // No need to divide by element size, since addr of label is always void*,
516 // which has size 1 in GNUish.
517 return llvm::ConstantExpr::getSub(LHS, RHS);
518 }
519
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000520 llvm::Constant *VisitCastExpr(CastExpr* E) {
John McCall8bba1f42011-03-15 21:17:48 +0000521 Expr *subExpr = E->getSubExpr();
522 llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
523 if (!C) return 0;
524
525 const llvm::Type *destType = ConvertType(E->getType());
526
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000527 switch (E->getCastKind()) {
John McCall2de56d12010-08-25 11:45:40 +0000528 case CK_ToUnion: {
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000529 // GCC cast to union extension
530 assert(E->getType()->isUnionType() &&
531 "Destination type is not union type!");
Mike Stump1eb44332009-09-09 15:08:12 +0000532
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000533 // Build a struct with the union sub-element as the first member,
534 // and padded to the appropriate size
535 std::vector<llvm::Constant*> Elts;
536 std::vector<const llvm::Type*> Types;
537 Elts.push_back(C);
538 Types.push_back(C->getType());
539 unsigned CurSize = CGM.getTargetData().getTypeAllocSize(C->getType());
John McCall8bba1f42011-03-15 21:17:48 +0000540 unsigned TotalSize = CGM.getTargetData().getTypeAllocSize(destType);
Mike Stump1eb44332009-09-09 15:08:12 +0000541
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000542 assert(CurSize <= TotalSize && "Union size mismatch!");
543 if (unsigned NumPadBytes = TotalSize - CurSize) {
Owen Anderson0032b272009-08-13 21:57:51 +0000544 const llvm::Type *Ty = llvm::Type::getInt8Ty(VMContext);
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000545 if (NumPadBytes > 1)
546 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000547
Nuno Lopescdb30b42010-04-16 20:56:35 +0000548 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000549 Types.push_back(Ty);
550 }
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000552 llvm::StructType* STy =
553 llvm::StructType::get(C->getType()->getContext(), Types, false);
Anders Carlssonaaed50d2009-07-31 21:38:39 +0000554 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes81e51e22009-01-17 00:48:48 +0000555 }
John McCall2de56d12010-08-25 11:45:40 +0000556 case CK_NullToMemberPointer: {
John McCalld608cdb2010-08-22 10:59:02 +0000557 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
John McCall0bab0cd2010-08-23 01:21:21 +0000558 return CGM.getCXXABI().EmitNullMemberPointer(MPT);
John McCalld608cdb2010-08-22 10:59:02 +0000559 }
Anders Carlsson2c51f092009-10-03 15:13:22 +0000560
John McCall8bba1f42011-03-15 21:17:48 +0000561 case CK_DerivedToBaseMemberPointer:
562 case CK_BaseToDerivedMemberPointer:
John McCall0bab0cd2010-08-23 01:21:21 +0000563 return CGM.getCXXABI().EmitMemberPointerConversion(C, E);
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000564
John McCall8bba1f42011-03-15 21:17:48 +0000565 case CK_LValueToRValue:
566 case CK_NoOp:
567 return C;
Anders Carlssonbb378cb2009-10-18 20:31:03 +0000568
John McCall8bba1f42011-03-15 21:17:48 +0000569 case CK_AnyPointerToObjCPointerCast:
570 case CK_AnyPointerToBlockPointerCast:
571 case CK_LValueBitCast:
572 case CK_BitCast:
573 if (C->getType() == destType) return C;
574 return llvm::ConstantExpr::getBitCast(C, destType);
Chris Lattner430656e2009-10-13 22:12:09 +0000575
John McCall8bba1f42011-03-15 21:17:48 +0000576 case CK_Dependent: llvm_unreachable("saw dependent cast!");
577
578 // These will never be supported.
579 case CK_ObjCObjectLValueCast:
580 case CK_GetObjCProperty:
581 case CK_ToVoid:
582 case CK_Dynamic:
John McCallf85e1932011-06-15 23:02:42 +0000583 case CK_ObjCProduceObject:
584 case CK_ObjCConsumeObject:
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000585 return 0;
John McCall8bba1f42011-03-15 21:17:48 +0000586
587 // These might need to be supported for constexpr.
588 case CK_UserDefinedConversion:
589 case CK_ConstructorConversion:
590 return 0;
591
592 // These should eventually be supported.
593 case CK_ArrayToPointerDecay:
594 case CK_FunctionToPointerDecay:
595 case CK_BaseToDerived:
596 case CK_DerivedToBase:
597 case CK_UncheckedDerivedToBase:
598 case CK_MemberPointerToBoolean:
599 case CK_VectorSplat:
600 case CK_FloatingRealToComplex:
601 case CK_FloatingComplexToReal:
602 case CK_FloatingComplexToBoolean:
603 case CK_FloatingComplexCast:
604 case CK_FloatingComplexToIntegralComplex:
605 case CK_IntegralRealToComplex:
606 case CK_IntegralComplexToReal:
607 case CK_IntegralComplexToBoolean:
608 case CK_IntegralComplexCast:
609 case CK_IntegralComplexToFloatingComplex:
610 return 0;
611
612 case CK_PointerToIntegral:
613 if (!E->getType()->isBooleanType())
614 return llvm::ConstantExpr::getPtrToInt(C, destType);
615 // fallthrough
616
617 case CK_PointerToBoolean:
618 return llvm::ConstantExpr::getICmp(llvm::CmpInst::ICMP_EQ, C,
619 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(C->getType())));
620
621 case CK_NullToPointer:
622 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(destType));
623
624 case CK_IntegralCast: {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000625 bool isSigned = subExpr->getType()->isSignedIntegerOrEnumerationType();
John McCall8bba1f42011-03-15 21:17:48 +0000626 return llvm::ConstantExpr::getIntegerCast(C, destType, isSigned);
Eli Friedmanddd2b6e2009-02-22 07:29:04 +0000627 }
John McCall8bba1f42011-03-15 21:17:48 +0000628
629 case CK_IntegralToPointer: {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000630 bool isSigned = subExpr->getType()->isSignedIntegerOrEnumerationType();
John McCall8bba1f42011-03-15 21:17:48 +0000631 C = llvm::ConstantExpr::getIntegerCast(C, CGM.IntPtrTy, isSigned);
632 return llvm::ConstantExpr::getIntToPtr(C, destType);
633 }
634
635 case CK_IntegralToBoolean:
636 return llvm::ConstantExpr::getICmp(llvm::CmpInst::ICMP_EQ, C,
637 llvm::Constant::getNullValue(C->getType()));
638
639 case CK_IntegralToFloating:
Douglas Gregor575a1c92011-05-20 16:38:50 +0000640 if (subExpr->getType()->isSignedIntegerOrEnumerationType())
John McCall8bba1f42011-03-15 21:17:48 +0000641 return llvm::ConstantExpr::getSIToFP(C, destType);
642 else
643 return llvm::ConstantExpr::getUIToFP(C, destType);
644
645 case CK_FloatingToIntegral:
Douglas Gregor575a1c92011-05-20 16:38:50 +0000646 if (E->getType()->isSignedIntegerOrEnumerationType())
John McCall8bba1f42011-03-15 21:17:48 +0000647 return llvm::ConstantExpr::getFPToSI(C, destType);
648 else
649 return llvm::ConstantExpr::getFPToUI(C, destType);
650
651 case CK_FloatingToBoolean:
652 return llvm::ConstantExpr::getFCmp(llvm::CmpInst::FCMP_UNE, C,
653 llvm::Constant::getNullValue(C->getType()));
654
655 case CK_FloatingCast:
656 return llvm::ConstantExpr::getFPCast(C, destType);
Anders Carlsson0086ccb2009-08-22 23:54:44 +0000657 }
Matt Beaumont-Gay17d12fe2011-03-17 00:46:34 +0000658 llvm_unreachable("Invalid CastKind");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000659 }
Devang Pateleae15602008-02-05 02:39:50 +0000660
Chris Lattner04421082008-04-08 04:40:51 +0000661 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
662 return Visit(DAE->getExpr());
663 }
664
Douglas Gregor03e80032011-06-21 17:03:29 +0000665 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
666 return Visit(E->GetTemporaryExpr());
667 }
668
Eli Friedmana8234002008-05-30 10:24:46 +0000669 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
Nuno Lopesa75b71f2010-04-18 19:06:43 +0000670 unsigned NumInitElements = ILE->getNumInits();
Benjamin Kramer0483a6f2011-03-02 21:27:44 +0000671 if (NumInitElements == 1 && ILE->getType() == ILE->getInit(0)->getType() &&
Nuno Lopesa75b71f2010-04-18 19:06:43 +0000672 (isa<StringLiteral>(ILE->getInit(0)) ||
673 isa<ObjCEncodeExpr>(ILE->getInit(0))))
674 return Visit(ILE->getInit(0));
675
Nuno Lopes67847042010-04-16 23:19:41 +0000676 std::vector<llvm::Constant*> Elts;
677 const llvm::ArrayType *AType =
678 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
Devang Pateleae15602008-02-05 02:39:50 +0000679 const llvm::Type *ElemTy = AType->getElementType();
680 unsigned NumElements = AType->getNumElements();
681
Mike Stump1eb44332009-09-09 15:08:12 +0000682 // Initialising an array requires us to automatically
Devang Pateleae15602008-02-05 02:39:50 +0000683 // initialise any elements that have not been initialised explicitly
684 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
685
686 // Copy initializer elements.
687 unsigned i = 0;
Eli Friedmana04a1532008-05-30 19:58:50 +0000688 bool RewriteType = false;
Devang Pateleae15602008-02-05 02:39:50 +0000689 for (; i < NumInitableElts; ++i) {
Anders Carlssone9352cc2009-04-08 04:48:15 +0000690 Expr *Init = ILE->getInit(i);
691 llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000692 if (!C)
693 return 0;
Eli Friedmana04a1532008-05-30 19:58:50 +0000694 RewriteType |= (C->getType() != ElemTy);
Devang Pateleae15602008-02-05 02:39:50 +0000695 Elts.push_back(C);
696 }
Eli Friedmana04a1532008-05-30 19:58:50 +0000697
Devang Pateleae15602008-02-05 02:39:50 +0000698 // Initialize remaining array elements.
Eli Friedman0f593122009-04-13 21:47:26 +0000699 // FIXME: This doesn't handle member pointers correctly!
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000700 llvm::Constant *fillC;
701 if (Expr *filler = ILE->getArrayFiller())
702 fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
703 else
704 fillC = llvm::Constant::getNullValue(ElemTy);
705 if (!fillC)
706 return 0;
707 RewriteType |= (fillC->getType() != ElemTy);
Devang Pateleae15602008-02-05 02:39:50 +0000708 for (; i < NumElements; ++i)
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000709 Elts.push_back(fillC);
Devang Pateleae15602008-02-05 02:39:50 +0000710
Eli Friedmana04a1532008-05-30 19:58:50 +0000711 if (RewriteType) {
712 // FIXME: Try to avoid packing the array
713 std::vector<const llvm::Type*> Types;
714 for (unsigned i = 0; i < Elts.size(); ++i)
715 Types.push_back(Elts[i]->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000716 const llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
Owen Anderson47a434f2009-08-05 23:18:46 +0000717 Types, true);
Owen Anderson08e25242009-07-27 22:29:56 +0000718 return llvm::ConstantStruct::get(SType, Elts);
Eli Friedmana04a1532008-05-30 19:58:50 +0000719 }
720
Mike Stump1eb44332009-09-09 15:08:12 +0000721 return llvm::ConstantArray::get(AType, Elts);
Devang Pateleae15602008-02-05 02:39:50 +0000722 }
723
Eli Friedmana8234002008-05-30 10:24:46 +0000724 llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
Anders Carlsson8dca3b32009-07-27 05:54:15 +0000725 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
Devang Pateleae15602008-02-05 02:39:50 +0000726 }
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Eli Friedmana8234002008-05-30 10:24:46 +0000728 llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
Anders Carlssonf6c43962009-07-31 21:34:04 +0000729 return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
Eli Friedmana8234002008-05-30 10:24:46 +0000730 }
731
Anders Carlsson7d801ea2009-01-30 06:13:25 +0000732 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
Eli Friedman0f593122009-04-13 21:47:26 +0000733 return CGM.EmitNullConstant(E->getType());
Anders Carlsson7d801ea2009-01-30 06:13:25 +0000734 }
Mike Stump1eb44332009-09-09 15:08:12 +0000735
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000736 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
Eli Friedmana8234002008-05-30 10:24:46 +0000737 if (ILE->getType()->isScalarType()) {
738 // We have a scalar in braces. Just use the first element.
Anders Carlssone9352cc2009-04-08 04:48:15 +0000739 if (ILE->getNumInits() > 0) {
740 Expr *Init = ILE->getInit(0);
741 return CGM.EmitConstantExpr(Init, Init->getType(), CGF);
742 }
Eli Friedman0f593122009-04-13 21:47:26 +0000743 return CGM.EmitNullConstant(ILE->getType());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000744 }
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Eli Friedmana8234002008-05-30 10:24:46 +0000746 if (ILE->getType()->isArrayType())
747 return EmitArrayInitialization(ILE);
Devang Patel47fb6972008-01-29 23:23:18 +0000748
Anders Carlsson01a79ac2009-11-21 23:56:04 +0000749 if (ILE->getType()->isRecordType())
Eli Friedmana8234002008-05-30 10:24:46 +0000750 return EmitStructInitialization(ILE);
751
752 if (ILE->getType()->isUnionType())
753 return EmitUnionInitialization(ILE);
754
Eli Friedman8ac55492010-01-02 23:43:59 +0000755 // If ILE was a constant vector, we would have handled it already.
Eli Friedmana8234002008-05-30 10:24:46 +0000756 if (ILE->getType()->isVectorType())
Eli Friedman8ac55492010-01-02 23:43:59 +0000757 return 0;
Eli Friedmana8234002008-05-30 10:24:46 +0000758
Devang Pateleae15602008-02-05 02:39:50 +0000759 assert(0 && "Unable to handle InitListExpr");
Chris Lattner2b94fe32008-03-01 08:45:05 +0000760 // Get rid of control reaches end of void function warning.
761 // Not reached.
762 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000763 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000764
John McCallfb8b69a2010-02-02 08:02:49 +0000765 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
766 if (!E->getConstructor()->isTrivial())
767 return 0;
768
Anders Carlsson2ca4f632010-02-05 18:38:45 +0000769 QualType Ty = E->getType();
770
771 // FIXME: We should not have to call getBaseElementType here.
772 const RecordType *RT =
773 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
774 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
775
776 // If the class doesn't have a trivial destructor, we can't emit it as a
777 // constant expr.
778 if (!RD->hasTrivialDestructor())
779 return 0;
780
John McCallfb8b69a2010-02-02 08:02:49 +0000781 // Only copy and default constructors can be trivial.
782
John McCallfb8b69a2010-02-02 08:02:49 +0000783
784 if (E->getNumArgs()) {
785 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
786 assert(E->getConstructor()->isCopyConstructor() &&
787 "trivial ctor has argument but isn't a copy ctor");
788
789 Expr *Arg = E->getArg(0);
790 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
791 "argument to copy ctor is of wrong type");
792
Chandler Carruth878b55c2010-02-02 12:15:55 +0000793 return Visit(Arg);
John McCallfb8b69a2010-02-02 08:02:49 +0000794 }
795
796 return CGM.EmitNullConstant(Ty);
797 }
798
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000799 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000800 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Mike Stump1eb44332009-09-09 15:08:12 +0000801
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000802 // This must be a string initializing an array in a static initializer.
803 // Don't emit it as the address of the string, emit the string data itself
804 // as an inline array.
Owen Anderson0032b272009-08-13 21:57:51 +0000805 return llvm::ConstantArray::get(VMContext,
806 CGM.GetStringForStringLiteral(E), false);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000807 }
808
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000809 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
810 // This must be an @encode initializing an array in a static initializer.
811 // Don't emit it as the address of the string, emit the string data itself
812 // as an inline array.
813 std::string Str;
814 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
815 const ConstantArrayType *CAT = cast<ConstantArrayType>(E->getType());
Mike Stump1eb44332009-09-09 15:08:12 +0000816
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000817 // Resize the string to the right size, adding zeros at the end, or
818 // truncating as needed.
819 Str.resize(CAT->getSize().getZExtValue(), '\0');
Owen Anderson0032b272009-08-13 21:57:51 +0000820 return llvm::ConstantArray::get(VMContext, Str, false);
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000821 }
Mike Stump1eb44332009-09-09 15:08:12 +0000822
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000823 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
824 return Visit(E->getSubExpr());
825 }
Mike Stumpb83d2872009-02-19 22:01:56 +0000826
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000827 // Utility methods
828 const llvm::Type *ConvertType(QualType T) {
829 return CGM.getTypes().ConvertType(T);
830 }
Anders Carlsson84005b42008-01-26 04:30:23 +0000831
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000832public:
Anders Carlsson84005b42008-01-26 04:30:23 +0000833 llvm::Constant *EmitLValue(Expr *E) {
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000834 switch (E->getStmtClass()) {
Eli Friedman546d94c2008-02-11 00:23:10 +0000835 default: break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000836 case Expr::CompoundLiteralExprClass: {
837 // Note that due to the nature of compound literals, this is guaranteed
838 // to be the only use of the variable, so we just generate it here.
Anders Carlsson84005b42008-01-26 04:30:23 +0000839 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
840 llvm::Constant* C = Visit(CLE->getInitializer());
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000841 // FIXME: "Leaked" on failure.
842 if (C)
Owen Anderson1c431b32009-07-08 19:05:04 +0000843 C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
Eli Friedmand15d8c62009-08-26 20:01:39 +0000844 E->getType().isConstant(CGM.getContext()),
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000845 llvm::GlobalValue::InternalLinkage,
Eli Friedmand15d8c62009-08-26 20:01:39 +0000846 C, ".compoundliteral", 0, false,
Peter Collingbourne207f4d82011-03-18 22:38:29 +0000847 CGM.getContext().getTargetAddressSpace(E->getType()));
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000848 return C;
Anders Carlsson84005b42008-01-26 04:30:23 +0000849 }
Douglas Gregora2813ce2009-10-23 18:54:35 +0000850 case Expr::DeclRefExprClass: {
Rafael Espindolada182612010-03-04 21:26:03 +0000851 ValueDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
852 if (Decl->hasAttr<WeakRefAttr>())
Eli Friedmana7e68452010-08-22 01:00:03 +0000853 return CGM.GetWeakRefReference(Decl);
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000854 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
Anders Carlsson555b4bb2009-09-10 23:43:36 +0000855 return CGM.GetAddrOfFunction(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000856 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000857 // We can never refer to a variable with local storage.
Mike Stump1eb44332009-09-09 15:08:12 +0000858 if (!VD->hasLocalStorage()) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000859 if (VD->isFileVarDecl() || VD->hasExternalStorage())
860 return CGM.GetAddrOfGlobalVar(VD);
John McCallb6bbcc92010-10-15 04:57:14 +0000861 else if (VD->isLocalVarDecl()) {
Daniel Dunbard01b6692009-02-24 18:41:57 +0000862 assert(CGF && "Can't access static local vars without CGF");
863 return CGF->GetAddrOfStaticLocalVar(VD);
864 }
Steve Naroff248a7532008-04-15 22:42:06 +0000865 }
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000866 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000867 break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000868 }
Daniel Dunbar61432932008-08-13 23:20:05 +0000869 case Expr::StringLiteralClass:
870 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000871 case Expr::ObjCEncodeExprClass:
872 return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000873 case Expr::ObjCStringLiteralClass: {
874 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000875 llvm::Constant *C =
876 CGM.getObjCRuntime().GenerateConstantString(SL->getString());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000877 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000878 }
Chris Lattner35345642008-12-12 05:18:02 +0000879 case Expr::PredefinedExprClass: {
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000880 unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
881 if (CGF) {
Daniel Dunbar3ec0baf2010-08-21 03:01:12 +0000882 LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000883 return cast<llvm::Constant>(Res.getAddress());
884 } else if (Type == PredefinedExpr::PrettyFunction) {
885 return CGM.GetAddrOfConstantCString("top level", ".tmp");
886 }
Mike Stump1eb44332009-09-09 15:08:12 +0000887
Eli Friedmanf70b24e2009-11-14 08:37:13 +0000888 return CGM.GetAddrOfConstantCString("", ".tmp");
Chris Lattner35345642008-12-12 05:18:02 +0000889 }
Eli Friedmanf0115892009-01-25 01:21:06 +0000890 case Expr::AddrLabelExprClass: {
891 assert(CGF && "Invalid address of label expression outside function.");
Chris Lattnerd9becd12009-10-28 23:59:40 +0000892 llvm::Constant *Ptr =
893 CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
894 return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
Eli Friedmanf0115892009-01-25 01:21:06 +0000895 }
Eli Friedman3941b182009-01-25 01:54:01 +0000896 case Expr::CallExprClass: {
897 CallExpr* CE = cast<CallExpr>(E);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000898 unsigned builtin = CE->isBuiltinCall(CGM.getContext());
899 if (builtin !=
900 Builtin::BI__builtin___CFStringMakeConstantString &&
901 builtin !=
902 Builtin::BI__builtin___NSStringMakeConstantString)
Eli Friedman3941b182009-01-25 01:54:01 +0000903 break;
904 const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
905 const StringLiteral *Literal = cast<StringLiteral>(Arg);
David Chisnall0d13f6f2010-01-23 02:40:42 +0000906 if (builtin ==
907 Builtin::BI__builtin___NSStringMakeConstantString) {
908 return CGM.getObjCRuntime().GenerateConstantString(Literal);
909 }
Steve Naroff33fdb732009-03-31 16:53:37 +0000910 // FIXME: need to deal with UCN conversion issues.
Steve Naroff8d4141f2009-04-01 13:55:36 +0000911 return CGM.GetAddrOfConstantCFString(Literal);
Eli Friedman3941b182009-01-25 01:54:01 +0000912 }
Mike Stumpbd65cac2009-02-19 01:01:04 +0000913 case Expr::BlockExprClass: {
Anders Carlsson4de9fce2009-03-01 01:09:12 +0000914 std::string FunctionName;
915 if (CGF)
916 FunctionName = CGF->CurFn->getName();
917 else
918 FunctionName = "global";
919
920 return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
Mike Stumpbd65cac2009-02-19 01:01:04 +0000921 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000922 }
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000923
924 return 0;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000925 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000926};
Mike Stump1eb44332009-09-09 15:08:12 +0000927
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000928} // end anonymous namespace.
929
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000930llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
Anders Carlssone9352cc2009-04-08 04:48:15 +0000931 QualType DestType,
Chris Lattner96196622008-07-26 22:37:01 +0000932 CodeGenFunction *CGF) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000933 Expr::EvalResult Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Anders Carlsson1e5dc6e2009-04-11 01:08:03 +0000935 bool Success = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Eli Friedman50c39ea2009-05-27 06:04:58 +0000937 if (DestType->isReferenceType())
938 Success = E->EvaluateAsLValue(Result, Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000939 else
Anders Carlsson1e5dc6e2009-04-11 01:08:03 +0000940 Success = E->Evaluate(Result, Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Eli Friedman55f9bdd2009-11-14 08:51:33 +0000942 if (Success && !Result.HasSideEffects) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000943 switch (Result.Val.getKind()) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +0000944 case APValue::Uninitialized:
Daniel Dunbard60f2fb2009-02-17 18:43:32 +0000945 assert(0 && "Constant expressions should be initialized.");
946 return 0;
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000947 case APValue::LValue: {
Anders Carlsson1e5dc6e2009-04-11 01:08:03 +0000948 const llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
Mike Stump1eb44332009-09-09 15:08:12 +0000949 llvm::Constant *Offset =
950 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext),
Ken Dycka7305832010-01-15 12:37:54 +0000951 Result.Val.getLValueOffset().getQuantity());
Mike Stump1eb44332009-09-09 15:08:12 +0000952
Daniel Dunbare20de512009-02-19 21:44:24 +0000953 llvm::Constant *C;
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000954 if (const Expr *LVBase = Result.Val.getLValueBase()) {
Daniel Dunbare20de512009-02-19 21:44:24 +0000955 C = ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000956
Daniel Dunbare20de512009-02-19 21:44:24 +0000957 // Apply offset if necessary.
958 if (!Offset->isNullValue()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +0000959 const llvm::Type *Type = llvm::Type::getInt8PtrTy(VMContext);
Owen Anderson3c4972d2009-07-29 18:54:39 +0000960 llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, Type);
961 Casted = llvm::ConstantExpr::getGetElementPtr(Casted, &Offset, 1);
962 C = llvm::ConstantExpr::getBitCast(Casted, C->getType());
Daniel Dunbare20de512009-02-19 21:44:24 +0000963 }
964
965 // Convert to the appropriate type; this could be an lvalue for
966 // an integer.
Anders Carlsson12e330c2009-04-10 04:59:59 +0000967 if (isa<llvm::PointerType>(DestTy))
Owen Anderson3c4972d2009-07-29 18:54:39 +0000968 return llvm::ConstantExpr::getBitCast(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000969
Owen Anderson3c4972d2009-07-29 18:54:39 +0000970 return llvm::ConstantExpr::getPtrToInt(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000971 } else {
972 C = Offset;
973
974 // Convert to the appropriate type; this could be an lvalue for
975 // an integer.
Anders Carlsson12e330c2009-04-10 04:59:59 +0000976 if (isa<llvm::PointerType>(DestTy))
Owen Anderson3c4972d2009-07-29 18:54:39 +0000977 return llvm::ConstantExpr::getIntToPtr(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000978
979 // If the types don't match this should only be a truncate.
Anders Carlsson12e330c2009-04-10 04:59:59 +0000980 if (C->getType() != DestTy)
Owen Anderson3c4972d2009-07-29 18:54:39 +0000981 return llvm::ConstantExpr::getTrunc(C, DestTy);
Daniel Dunbare20de512009-02-19 21:44:24 +0000982
983 return C;
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000984 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000985 }
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000986 case APValue::Int: {
Mike Stump1eb44332009-09-09 15:08:12 +0000987 llvm::Constant *C = llvm::ConstantInt::get(VMContext,
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000988 Result.Val.getInt());
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Chris Lattner7f215c12010-06-26 21:52:32 +0000990 if (C->getType()->isIntegerTy(1)) {
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000991 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
Owen Anderson3c4972d2009-07-29 18:54:39 +0000992 C = llvm::ConstantExpr::getZExt(C, BoolTy);
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000993 }
994 return C;
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000995 }
Daniel Dunbara5fd07b2009-01-28 22:24:07 +0000996 case APValue::ComplexInt: {
997 llvm::Constant *Complex[2];
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000999 Complex[0] = llvm::ConstantInt::get(VMContext,
1000 Result.Val.getComplexIntReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001001 Complex[1] = llvm::ConstantInt::get(VMContext,
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001002 Result.Val.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00001003
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001004 // FIXME: the target may want to specify that this is packed.
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001005 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1006 Complex[1]->getType(),
1007 NULL);
1008 return llvm::ConstantStruct::get(STy, Complex);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001009 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +00001010 case APValue::Float:
Owen Andersonbc0a2222009-07-27 21:00:51 +00001011 return llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
Anders Carlssonaa432562008-11-17 01:58:55 +00001012 case APValue::ComplexFloat: {
1013 llvm::Constant *Complex[2];
Mike Stump1eb44332009-09-09 15:08:12 +00001014
1015 Complex[0] = llvm::ConstantFP::get(VMContext,
Owen Andersonbc0a2222009-07-27 21:00:51 +00001016 Result.Val.getComplexFloatReal());
1017 Complex[1] = llvm::ConstantFP::get(VMContext,
1018 Result.Val.getComplexFloatImag());
Mike Stump1eb44332009-09-09 15:08:12 +00001019
Nick Lewycky0d36dd22009-09-19 20:00:52 +00001020 // FIXME: the target may want to specify that this is packed.
Chris Lattnerc5cbb902011-06-20 04:01:35 +00001021 llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
1022 Complex[1]->getType(),
1023 NULL);
1024 return llvm::ConstantStruct::get(STy, Complex);
Anders Carlssonaa432562008-11-17 01:58:55 +00001025 }
Nate Begeman3d309f92009-01-18 01:01:34 +00001026 case APValue::Vector: {
1027 llvm::SmallVector<llvm::Constant *, 4> Inits;
1028 unsigned NumElts = Result.Val.getVectorLength();
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Anton Yartsevd06fea82011-03-27 09:32:40 +00001030 if (Context.getLangOptions().AltiVec &&
1031 isa<CastExpr>(E) &&
1032 cast<CastExpr>(E)->getCastKind() == CK_VectorSplat) {
1033 // AltiVec vector initialization with a single literal
1034 APValue &Elt = Result.Val.getVectorElt(0);
1035
1036 llvm::Constant* InitValue = Elt.isInt()
1037 ? cast<llvm::Constant>
1038 (llvm::ConstantInt::get(VMContext, Elt.getInt()))
1039 : cast<llvm::Constant>
1040 (llvm::ConstantFP::get(VMContext, Elt.getFloat()));
1041
1042 for (unsigned i = 0; i != NumElts; ++i)
1043 Inits.push_back(InitValue);
1044
1045 } else {
1046 for (unsigned i = 0; i != NumElts; ++i) {
1047 APValue &Elt = Result.Val.getVectorElt(i);
1048 if (Elt.isInt())
1049 Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
1050 else
1051 Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
1052 }
Nate Begeman3d309f92009-01-18 01:01:34 +00001053 }
Chris Lattnerfb018d12011-02-15 00:14:06 +00001054 return llvm::ConstantVector::get(Inits);
Nate Begeman3d309f92009-01-18 01:01:34 +00001055 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +00001056 }
1057 }
Eli Friedman7dfa6392008-06-01 15:31:44 +00001058
1059 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
Chris Lattner7f215c12010-06-26 21:52:32 +00001060 if (C && C->getType()->isIntegerTy(1)) {
Eli Friedman7dfa6392008-06-01 15:31:44 +00001061 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
Owen Anderson3c4972d2009-07-29 18:54:39 +00001062 C = llvm::ConstantExpr::getZExt(C, BoolTy);
Eli Friedman7dfa6392008-06-01 15:31:44 +00001063 }
1064 return C;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001065}
Eli Friedman0f593122009-04-13 21:47:26 +00001066
John McCall5808ce42011-02-03 08:15:49 +00001067static uint64_t getFieldOffset(ASTContext &C, const FieldDecl *field) {
1068 const ASTRecordLayout &layout = C.getASTRecordLayout(field->getParent());
1069 return layout.getFieldOffset(field->getFieldIndex());
1070}
1071
1072llvm::Constant *
1073CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
1074 // Member pointer constants always have a very particular form.
1075 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
1076 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
1077
1078 // A member function pointer.
1079 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
1080 return getCXXABI().EmitMemberPointer(method);
1081
1082 // Otherwise, a member data pointer.
1083 uint64_t fieldOffset;
1084 if (const FieldDecl *field = dyn_cast<FieldDecl>(decl))
1085 fieldOffset = getFieldOffset(getContext(), field);
1086 else {
1087 const IndirectFieldDecl *ifield = cast<IndirectFieldDecl>(decl);
1088
1089 fieldOffset = 0;
1090 for (IndirectFieldDecl::chain_iterator ci = ifield->chain_begin(),
1091 ce = ifield->chain_end(); ci != ce; ++ci)
1092 fieldOffset += getFieldOffset(getContext(), cast<FieldDecl>(*ci));
1093 }
1094
1095 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
1096 return getCXXABI().EmitMemberDataPointer(type, chars);
1097}
1098
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001099static void
1100FillInNullDataMemberPointers(CodeGenModule &CGM, QualType T,
1101 std::vector<llvm::Constant *> &Elements,
1102 uint64_t StartOffset) {
Ken Dyckc4d68db2011-03-22 00:24:31 +00001103 assert(StartOffset % CGM.getContext().getCharWidth() == 0 &&
1104 "StartOffset not byte aligned!");
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001105
John McCallf16aa102010-08-22 21:01:12 +00001106 if (CGM.getTypes().isZeroInitializable(T))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001107 return;
1108
1109 if (const ConstantArrayType *CAT =
1110 CGM.getContext().getAsConstantArrayType(T)) {
1111 QualType ElementTy = CAT->getElementType();
1112 uint64_t ElementSize = CGM.getContext().getTypeSize(ElementTy);
1113
1114 for (uint64_t I = 0, E = CAT->getSize().getZExtValue(); I != E; ++I) {
1115 FillInNullDataMemberPointers(CGM, ElementTy, Elements,
1116 StartOffset + I * ElementSize);
1117 }
1118 } else if (const RecordType *RT = T->getAs<RecordType>()) {
1119 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1120 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1121
1122 // Go through all bases and fill in any null pointer to data members.
1123 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1124 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson0a87b372010-05-27 18:51:01 +00001125 if (I->isVirtual()) {
Anders Carlssonada4b322010-11-22 18:42:14 +00001126 // Ignore virtual bases.
Anders Carlsson0a87b372010-05-27 18:51:01 +00001127 continue;
1128 }
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001129
1130 const CXXRecordDecl *BaseDecl =
1131 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1132
1133 // Ignore empty bases.
1134 if (BaseDecl->isEmpty())
1135 continue;
1136
1137 // Ignore bases that don't have any pointer to data members.
John McCallf16aa102010-08-22 21:01:12 +00001138 if (CGM.getTypes().isZeroInitializable(BaseDecl))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001139 continue;
1140
Anders Carlssona14f5972010-10-31 23:22:37 +00001141 uint64_t BaseOffset = Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001142 FillInNullDataMemberPointers(CGM, I->getType(),
1143 Elements, StartOffset + BaseOffset);
1144 }
1145
1146 // Visit all fields.
1147 unsigned FieldNo = 0;
1148 for (RecordDecl::field_iterator I = RD->field_begin(),
1149 E = RD->field_end(); I != E; ++I, ++FieldNo) {
1150 QualType FieldType = I->getType();
1151
John McCallf16aa102010-08-22 21:01:12 +00001152 if (CGM.getTypes().isZeroInitializable(FieldType))
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001153 continue;
1154
1155 uint64_t FieldOffset = StartOffset + Layout.getFieldOffset(FieldNo);
1156 FillInNullDataMemberPointers(CGM, FieldType, Elements, FieldOffset);
1157 }
1158 } else {
1159 assert(T->isMemberPointerType() && "Should only see member pointers here!");
1160 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1161 "Should only see pointers to data members here!");
1162
Ken Dyckc4d68db2011-03-22 00:24:31 +00001163 CharUnits StartIndex = CGM.getContext().toCharUnitsFromBits(StartOffset);
1164 CharUnits EndIndex = StartIndex + CGM.getContext().getTypeSizeInChars(T);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001165
John McCall5808ce42011-02-03 08:15:49 +00001166 // FIXME: hardcodes Itanium member pointer representation!
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001167 llvm::Constant *NegativeOne =
1168 llvm::ConstantInt::get(llvm::Type::getInt8Ty(CGM.getLLVMContext()),
John McCall5808ce42011-02-03 08:15:49 +00001169 -1ULL, /*isSigned*/true);
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001170
1171 // Fill in the null data member pointer.
Ken Dyckc4d68db2011-03-22 00:24:31 +00001172 for (CharUnits I = StartIndex; I != EndIndex; ++I)
1173 Elements[I.getQuantity()] = NegativeOne;
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001174 }
1175}
1176
John McCall9b7da1c2011-02-15 06:40:56 +00001177static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1178 const llvm::Type *baseType,
1179 const CXXRecordDecl *base);
1180
Anders Carlssonada4b322010-11-22 18:42:14 +00001181static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
John McCall9b7da1c2011-02-15 06:40:56 +00001182 const CXXRecordDecl *record,
1183 bool asCompleteObject) {
1184 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
1185 const llvm::StructType *structure =
1186 (asCompleteObject ? layout.getLLVMType()
1187 : layout.getBaseSubobjectLLVMType());
Anders Carlssonada4b322010-11-22 18:42:14 +00001188
John McCall9b7da1c2011-02-15 06:40:56 +00001189 unsigned numElements = structure->getNumElements();
1190 std::vector<llvm::Constant *> elements(numElements);
Anders Carlssonada4b322010-11-22 18:42:14 +00001191
John McCall9b7da1c2011-02-15 06:40:56 +00001192 // Fill in all the bases.
1193 for (CXXRecordDecl::base_class_const_iterator
1194 I = record->bases_begin(), E = record->bases_end(); I != E; ++I) {
Anders Carlssonada4b322010-11-22 18:42:14 +00001195 if (I->isVirtual()) {
John McCall9b7da1c2011-02-15 06:40:56 +00001196 // Ignore virtual bases; if we're laying out for a complete
1197 // object, we'll lay these out later.
Anders Carlssonada4b322010-11-22 18:42:14 +00001198 continue;
1199 }
1200
John McCall9b7da1c2011-02-15 06:40:56 +00001201 const CXXRecordDecl *base =
1202 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlssonada4b322010-11-22 18:42:14 +00001203
1204 // Ignore empty bases.
John McCall9b7da1c2011-02-15 06:40:56 +00001205 if (base->isEmpty())
Anders Carlssonada4b322010-11-22 18:42:14 +00001206 continue;
1207
John McCall9b7da1c2011-02-15 06:40:56 +00001208 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
1209 const llvm::Type *baseType = structure->getElementType(fieldIndex);
1210 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlssonada4b322010-11-22 18:42:14 +00001211 }
1212
John McCall9b7da1c2011-02-15 06:40:56 +00001213 // Fill in all the fields.
1214 for (RecordDecl::field_iterator I = record->field_begin(),
1215 E = record->field_end(); I != E; ++I) {
1216 const FieldDecl *field = *I;
Anders Carlssonada4b322010-11-22 18:42:14 +00001217
1218 // Ignore bit fields.
John McCall9b7da1c2011-02-15 06:40:56 +00001219 if (field->isBitField())
Anders Carlssonada4b322010-11-22 18:42:14 +00001220 continue;
1221
John McCall9b7da1c2011-02-15 06:40:56 +00001222 unsigned fieldIndex = layout.getLLVMFieldNo(field);
1223 elements[fieldIndex] = CGM.EmitNullConstant(field->getType());
1224 }
1225
1226 // Fill in the virtual bases, if we're working with the complete object.
1227 if (asCompleteObject) {
1228 for (CXXRecordDecl::base_class_const_iterator
1229 I = record->vbases_begin(), E = record->vbases_end(); I != E; ++I) {
1230 const CXXRecordDecl *base =
1231 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1232
1233 // Ignore empty bases.
1234 if (base->isEmpty())
1235 continue;
1236
1237 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
1238
1239 // We might have already laid this field out.
1240 if (elements[fieldIndex]) continue;
1241
1242 const llvm::Type *baseType = structure->getElementType(fieldIndex);
1243 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
1244 }
Anders Carlssonada4b322010-11-22 18:42:14 +00001245 }
1246
1247 // Now go through all other fields and zero them out.
John McCall9b7da1c2011-02-15 06:40:56 +00001248 for (unsigned i = 0; i != numElements; ++i) {
1249 if (!elements[i])
1250 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlssonada4b322010-11-22 18:42:14 +00001251 }
1252
John McCall9b7da1c2011-02-15 06:40:56 +00001253 return llvm::ConstantStruct::get(structure, elements);
1254}
1255
1256/// Emit the null constant for a base subobject.
1257static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
1258 const llvm::Type *baseType,
1259 const CXXRecordDecl *base) {
1260 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
1261
1262 // Just zero out bases that don't have any pointer to data members.
1263 if (baseLayout.isZeroInitializableAsBase())
1264 return llvm::Constant::getNullValue(baseType);
1265
1266 // If the base type is a struct, we can just use its null constant.
1267 if (isa<llvm::StructType>(baseType)) {
1268 return EmitNullConstant(CGM, base, /*complete*/ false);
1269 }
1270
1271 // Otherwise, some bases are represented as arrays of i8 if the size
1272 // of the base is smaller than its corresponding LLVM type. Figure
1273 // out how many elements this base array has.
1274 const llvm::ArrayType *baseArrayType = cast<llvm::ArrayType>(baseType);
1275 unsigned numBaseElements = baseArrayType->getNumElements();
1276
1277 // Fill in null data member pointers.
1278 std::vector<llvm::Constant *> baseElements(numBaseElements);
1279 FillInNullDataMemberPointers(CGM, CGM.getContext().getTypeDeclType(base),
1280 baseElements, 0);
1281
1282 // Now go through all other elements and zero them out.
1283 if (numBaseElements) {
1284 const llvm::Type *i8 = llvm::Type::getInt8Ty(CGM.getLLVMContext());
1285 llvm::Constant *i8_zero = llvm::Constant::getNullValue(i8);
1286 for (unsigned i = 0; i != numBaseElements; ++i) {
1287 if (!baseElements[i])
1288 baseElements[i] = i8_zero;
1289 }
1290 }
1291
1292 return llvm::ConstantArray::get(baseArrayType, baseElements);
Anders Carlssonada4b322010-11-22 18:42:14 +00001293}
1294
Eli Friedman0f593122009-04-13 21:47:26 +00001295llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
John McCallf16aa102010-08-22 21:01:12 +00001296 if (getTypes().isZeroInitializable(T))
Anders Carlssonad3e7112009-08-24 17:16:23 +00001297 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Anders Carlsson2c12d032010-02-02 05:17:25 +00001298
Anders Carlsson237957c2009-08-09 18:26:27 +00001299 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001300
Anders Carlsson237957c2009-08-09 18:26:27 +00001301 QualType ElementTy = CAT->getElementType();
1302
Anders Carlsson2c12d032010-02-02 05:17:25 +00001303 llvm::Constant *Element = EmitNullConstant(ElementTy);
1304 unsigned NumElements = CAT->getSize().getZExtValue();
1305 std::vector<llvm::Constant *> Array(NumElements);
1306 for (unsigned i = 0; i != NumElements; ++i)
1307 Array[i] = Element;
Mike Stump1eb44332009-09-09 15:08:12 +00001308
Anders Carlsson2c12d032010-02-02 05:17:25 +00001309 const llvm::ArrayType *ATy =
1310 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
1311 return llvm::ConstantArray::get(ATy, Array);
Anders Carlsson237957c2009-08-09 18:26:27 +00001312 }
Anders Carlssonfc3eaa42009-08-23 01:25:01 +00001313
1314 if (const RecordType *RT = T->getAs<RecordType>()) {
Anders Carlsson2c12d032010-02-02 05:17:25 +00001315 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall9b7da1c2011-02-15 06:40:56 +00001316 return ::EmitNullConstant(*this, RD, /*complete object*/ true);
Anders Carlssonfc3eaa42009-08-23 01:25:01 +00001317 }
Mike Stump1eb44332009-09-09 15:08:12 +00001318
Anders Carlssona83fb4b2010-05-18 16:51:41 +00001319 assert(T->isMemberPointerType() && "Should only see member pointers here!");
Anders Carlsson2c12d032010-02-02 05:17:25 +00001320 assert(!T->getAs<MemberPointerType>()->getPointeeType()->isFunctionType() &&
1321 "Should only see pointers to data members here!");
1322
1323 // Itanium C++ ABI 2.3:
1324 // A NULL pointer is represented as -1.
John McCall5808ce42011-02-03 08:15:49 +00001325 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman0f593122009-04-13 21:47:26 +00001326}