blob: 651b05a26f7f964c039f630327930aa6548b039d [file] [log] [blame]
Anders Carlsson610ee712008-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 McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000016#include "CGObjCRuntime.h"
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000017#include "CGRecordLayout.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000019#include "ConstantEmitter.h"
Yaxun Liu402804b2016-12-15 08:09:08 +000020#include "TargetInfo.h"
Chris Lattnere50e9012008-10-06 05:59:01 +000021#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Anders Carlssone1d5ca52009-07-24 15:20:52 +000023#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/GlobalVariable.h"
Anders Carlsson610ee712008-01-26 01:36:00 +000030using namespace clang;
31using namespace CodeGen;
32
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000033//===----------------------------------------------------------------------===//
34// ConstStructBuilder
35//===----------------------------------------------------------------------===//
36
37namespace {
Yunzhong Gaocb779302015-06-10 00:27:52 +000038class ConstExprEmitter;
Benjamin Kramer337e3a52009-11-28 19:45:26 +000039class ConstStructBuilder {
Anders Carlssone1d5ca52009-07-24 15:20:52 +000040 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +000041 ConstantEmitter &Emitter;
Anders Carlssone1d5ca52009-07-24 15:20:52 +000042
Mike Stump11289f42009-09-09 15:08:12 +000043 bool Packed;
Ken Dyckdb205d12011-03-17 01:33:18 +000044 CharUnits NextFieldOffsetInChars;
Ken Dycka1b35102011-03-18 01:26:17 +000045 CharUnits LLVMStructAlignment;
Bill Wendling7ac74722012-02-07 00:54:58 +000046 SmallVector<llvm::Constant *, 32> Elements;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000047public:
John McCallde0fe072017-08-15 21:42:52 +000048 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
49 ConstExprEmitter *ExprEmitter,
Yunzhong Gaocb779302015-06-10 00:27:52 +000050 llvm::ConstantStruct *Base,
John McCallde0fe072017-08-15 21:42:52 +000051 InitListExpr *Updater,
52 QualType ValTy);
53 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
54 InitListExpr *ILE, QualType StructTy);
55 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +000056 const APValue &Value, QualType ValTy);
57
58private:
John McCallde0fe072017-08-15 21:42:52 +000059 ConstStructBuilder(ConstantEmitter &emitter)
Fangrui Song6907ce22018-07-30 19:24:48 +000060 : CGM(emitter.CGM), Emitter(emitter), Packed(false),
Ken Dyckdb205d12011-03-17 01:33:18 +000061 NextFieldOffsetInChars(CharUnits::Zero()),
Ken Dycka1b35102011-03-18 01:26:17 +000062 LLVMStructAlignment(CharUnits::One()) { }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000063
Richard Smithdafff942012-01-14 04:30:29 +000064 void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
Chris Lattnerff0e2a32010-04-13 18:16:19 +000065 llvm::Constant *InitExpr);
Mike Stump11289f42009-09-09 15:08:12 +000066
Richard Smithc8998922012-02-23 08:33:23 +000067 void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
68
Chris Lattner9a3459f2010-07-05 17:04:23 +000069 void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
70 llvm::ConstantInt *InitExpr);
Mike Stump11289f42009-09-09 15:08:12 +000071
Ken Dyck30a87e32011-03-11 23:42:54 +000072 void AppendPadding(CharUnits PadSize);
Mike Stump11289f42009-09-09 15:08:12 +000073
Ken Dyck327b77a2011-03-11 02:17:05 +000074 void AppendTailPadding(CharUnits RecordSize);
Anders Carlssonba4c6d12009-07-27 01:23:51 +000075
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000076 void ConvertStructToPacked();
Richard Smithdafff942012-01-14 04:30:29 +000077
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000078 bool Build(InitListExpr *ILE);
Yunzhong Gaocb779302015-06-10 00:27:52 +000079 bool Build(ConstExprEmitter *Emitter, llvm::ConstantStruct *Base,
80 InitListExpr *Updater);
John McCallde0fe072017-08-15 21:42:52 +000081 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +000082 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
Richard Smithdafff942012-01-14 04:30:29 +000083 llvm::Constant *Finalize(QualType Ty);
Mike Stump11289f42009-09-09 15:08:12 +000084
Ken Dycka1b35102011-03-18 01:26:17 +000085 CharUnits getAlignment(const llvm::Constant *C) const {
86 if (Packed) return CharUnits::One();
87 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000088 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000089 }
Mike Stump11289f42009-09-09 15:08:12 +000090
Ken Dyck33fa9ee2011-03-18 01:12:13 +000091 CharUnits getSizeInChars(const llvm::Constant *C) const {
92 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000093 CGM.getDataLayout().getTypeAllocSize(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000094 }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000095};
Mike Stump11289f42009-09-09 15:08:12 +000096
Richard Smithdafff942012-01-14 04:30:29 +000097void ConstStructBuilder::
Chris Lattnerff0e2a32010-04-13 18:16:19 +000098AppendField(const FieldDecl *Field, uint64_t FieldOffset,
99 llvm::Constant *InitCst) {
Ken Dyck1c80fd12011-03-15 01:09:02 +0000100 const ASTContext &Context = CGM.getContext();
101
102 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000103
Richard Smithc8998922012-02-23 08:33:23 +0000104 AppendBytes(FieldOffsetInChars, InitCst);
105}
106
107void ConstStructBuilder::
108AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
109
Ken Dyckdb205d12011-03-17 01:33:18 +0000110 assert(NextFieldOffsetInChars <= FieldOffsetInChars
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000111 && "Field offset mismatch!");
112
Ken Dycka1b35102011-03-18 01:26:17 +0000113 CharUnits FieldAlignment = getAlignment(InitCst);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000114
115 // Round up the field offset to the alignment of the field type.
Ken Dyckdb205d12011-03-17 01:33:18 +0000116 CharUnits AlignedNextFieldOffsetInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000117 NextFieldOffsetInChars.alignTo(FieldAlignment);
Chandler Carruthbf972bb2014-10-19 19:41:46 +0000118
Ken Dyckdb205d12011-03-17 01:33:18 +0000119 if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000120 // We need to append padding.
Richard Smithdafff942012-01-14 04:30:29 +0000121 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000122
Ken Dyckdb205d12011-03-17 01:33:18 +0000123 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000124 "Did not add enough padding!");
125
David Majnemer8e133962014-10-19 23:40:06 +0000126 AlignedNextFieldOffsetInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000127 NextFieldOffsetInChars.alignTo(FieldAlignment);
David Majnemer8e133962014-10-19 23:40:06 +0000128 }
129
130 if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
131 assert(!Packed && "Alignment is wrong even with a packed struct!");
132
133 // Convert the struct to a packed struct.
134 ConvertStructToPacked();
135
136 // After we pack the struct, we may need to insert padding.
137 if (NextFieldOffsetInChars < FieldOffsetInChars) {
138 // We need to append padding.
139 AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
140
141 assert(NextFieldOffsetInChars == FieldOffsetInChars &&
142 "Did not add enough padding!");
143 }
Ken Dyckdb205d12011-03-17 01:33:18 +0000144 AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000145 }
146
147 // Add the field.
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000148 Elements.push_back(InitCst);
Ken Dyckdb205d12011-03-17 01:33:18 +0000149 NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000150 getSizeInChars(InitCst);
Richard Smithdafff942012-01-14 04:30:29 +0000151
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000152 if (Packed)
Richard Smithdafff942012-01-14 04:30:29 +0000153 assert(LLVMStructAlignment == CharUnits::One() &&
Ken Dycka1b35102011-03-18 01:26:17 +0000154 "Packed struct not byte-aligned!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000155 else
156 LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000157}
158
Chris Lattner9a3459f2010-07-05 17:04:23 +0000159void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
160 uint64_t FieldOffset,
161 llvm::ConstantInt *CI) {
Ken Dycka862d952011-03-12 12:03:11 +0000162 const ASTContext &Context = CGM.getContext();
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000163 const uint64_t CharWidth = Context.getCharWidth();
Ken Dyckdb205d12011-03-17 01:33:18 +0000164 uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
165 if (FieldOffset > NextFieldOffsetInBits) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000166 // We need to add padding.
Ken Dycka862d952011-03-12 12:03:11 +0000167 CharUnits PadSize = Context.toCharUnitsFromBits(
Rui Ueyama83aa9792016-01-14 21:00:27 +0000168 llvm::alignTo(FieldOffset - NextFieldOffsetInBits,
169 Context.getTargetInfo().getCharAlign()));
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000170
Ken Dycka862d952011-03-12 12:03:11 +0000171 AppendPadding(PadSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000172 }
173
Richard Smithcaf33902011-10-10 18:28:20 +0000174 uint64_t FieldSize = Field->getBitWidthValue(Context);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000175
176 llvm::APInt FieldValue = CI->getValue();
177
178 // Promote the size of FieldValue if necessary
179 // FIXME: This should never occur, but currently it can because initializer
180 // constants are cast to bool, and because clang is not enforcing bitfield
181 // width limits.
182 if (FieldSize > FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000183 FieldValue = FieldValue.zext(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000184
185 // Truncate the size of FieldValue to the bit field size.
186 if (FieldSize < FieldValue.getBitWidth())
Jay Foad6d4db0c2010-12-07 08:25:34 +0000187 FieldValue = FieldValue.trunc(FieldSize);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000188
Ken Dyckdb205d12011-03-17 01:33:18 +0000189 NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
190 if (FieldOffset < NextFieldOffsetInBits) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000191 // Either part of the field or the entire field can go into the previous
192 // byte.
193 assert(!Elements.empty() && "Elements can't be empty!");
194
Ken Dyckdb205d12011-03-17 01:33:18 +0000195 unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000196
197 bool FitsCompletelyInPreviousByte =
198 BitsInPreviousByte >= FieldValue.getBitWidth();
199
200 llvm::APInt Tmp = FieldValue;
201
202 if (!FitsCompletelyInPreviousByte) {
203 unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
204
Micah Villmowdd31ca12012-10-08 16:25:52 +0000205 if (CGM.getDataLayout().isBigEndian()) {
Craig Topper73daaa82017-04-19 05:17:33 +0000206 Tmp.lshrInPlace(NewFieldWidth);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000207 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000208
209 // We want the remaining high bits.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000210 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000211 } else {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000212 Tmp = Tmp.trunc(BitsInPreviousByte);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000213
214 // We want the remaining low bits.
Craig Topper73daaa82017-04-19 05:17:33 +0000215 FieldValue.lshrInPlace(BitsInPreviousByte);
Jay Foad6d4db0c2010-12-07 08:25:34 +0000216 FieldValue = FieldValue.trunc(NewFieldWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000217 }
218 }
219
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000220 Tmp = Tmp.zext(CharWidth);
Micah Villmowdd31ca12012-10-08 16:25:52 +0000221 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000222 if (FitsCompletelyInPreviousByte)
223 Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
224 } else {
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000225 Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000226 }
227
Chris Lattner53b479f2010-07-05 18:03:30 +0000228 // 'or' in the bits that go into the previous byte.
229 llvm::Value *LastElt = Elements.back();
230 if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000231 Tmp |= Val->getValue();
Chris Lattner53b479f2010-07-05 18:03:30 +0000232 else {
233 assert(isa<llvm::UndefValue>(LastElt));
234 // If there is an undef field that we're adding to, it can either be a
235 // scalar undef (in which case, we just replace it with our field) or it
236 // is an array. If it is an array, we have to pull one byte off the
237 // array so that the other undef bytes stay around.
238 if (!isa<llvm::IntegerType>(LastElt->getType())) {
239 // The undef padding will be a multibyte array, create a new smaller
240 // padding and then an hole for our i8 to get plopped into.
241 assert(isa<llvm::ArrayType>(LastElt->getType()) &&
242 "Expected array padding of undefs");
Chris Lattner2192fe52011-07-18 04:24:23 +0000243 llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000244 assert(AT->getElementType()->isIntegerTy(CharWidth) &&
Chris Lattner53b479f2010-07-05 18:03:30 +0000245 AT->getNumElements() != 0 &&
246 "Expected non-empty array padding of undefs");
Fangrui Song6907ce22018-07-30 19:24:48 +0000247
Chris Lattner53b479f2010-07-05 18:03:30 +0000248 // Remove the padding array.
Ken Dyckdb205d12011-03-17 01:33:18 +0000249 NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
Chris Lattner53b479f2010-07-05 18:03:30 +0000250 Elements.pop_back();
Fangrui Song6907ce22018-07-30 19:24:48 +0000251
Chris Lattner53b479f2010-07-05 18:03:30 +0000252 // Add the padding back in two chunks.
Ken Dyck30a87e32011-03-11 23:42:54 +0000253 AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
254 AppendPadding(CharUnits::One());
Chris Lattner53b479f2010-07-05 18:03:30 +0000255 assert(isa<llvm::UndefValue>(Elements.back()) &&
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000256 Elements.back()->getType()->isIntegerTy(CharWidth) &&
Chris Lattner53b479f2010-07-05 18:03:30 +0000257 "Padding addition didn't work right");
258 }
259 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000260
261 Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
262
263 if (FitsCompletelyInPreviousByte)
Chris Lattner9a3459f2010-07-05 17:04:23 +0000264 return;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000265 }
266
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000267 while (FieldValue.getBitWidth() > CharWidth) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000268 llvm::APInt Tmp;
269
Micah Villmowdd31ca12012-10-08 16:25:52 +0000270 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000271 // We want the high bits.
Fangrui Song6907ce22018-07-30 19:24:48 +0000272 Tmp =
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000273 FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000274 } else {
275 // We want the low bits.
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000276 Tmp = FieldValue.trunc(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000277
Craig Topper73daaa82017-04-19 05:17:33 +0000278 FieldValue.lshrInPlace(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000279 }
280
281 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
Ken Dyck6d470d92011-03-19 01:28:06 +0000282 ++NextFieldOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000283
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000284 FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000285 }
286
287 assert(FieldValue.getBitWidth() > 0 &&
288 "Should have at least one bit left!");
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000289 assert(FieldValue.getBitWidth() <= CharWidth &&
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000290 "Should not have more than a byte left!");
291
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000292 if (FieldValue.getBitWidth() < CharWidth) {
Micah Villmowdd31ca12012-10-08 16:25:52 +0000293 if (CGM.getDataLayout().isBigEndian()) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000294 unsigned BitWidth = FieldValue.getBitWidth();
295
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000296 FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000297 } else
Ken Dyck0f2f30b2011-03-19 00:57:28 +0000298 FieldValue = FieldValue.zext(CharWidth);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000299 }
300
301 // Append the last element.
302 Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
303 FieldValue));
Ken Dyck6d470d92011-03-19 01:28:06 +0000304 ++NextFieldOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000305}
306
Ken Dyck30a87e32011-03-11 23:42:54 +0000307void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
308 if (PadSize.isZero())
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000309 return;
310
Chris Lattnerece04092012-02-07 00:39:47 +0000311 llvm::Type *Ty = CGM.Int8Ty;
Ken Dyck30a87e32011-03-11 23:42:54 +0000312 if (PadSize > CharUnits::One())
313 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000314
Nuno Lopes5863c992010-04-16 20:56:35 +0000315 llvm::Constant *C = llvm::UndefValue::get(Ty);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000316 Elements.push_back(C);
Fangrui Song6907ce22018-07-30 19:24:48 +0000317 assert(getAlignment(C) == CharUnits::One() &&
Ken Dycka1b35102011-03-18 01:26:17 +0000318 "Padding must have 1 byte alignment!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000319
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000320 NextFieldOffsetInChars += getSizeInChars(C);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000321}
322
Ken Dyck327b77a2011-03-11 02:17:05 +0000323void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000324 assert(NextFieldOffsetInChars <= RecordSize &&
Ken Dyck327b77a2011-03-11 02:17:05 +0000325 "Size mismatch!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000326
Ken Dyckdb205d12011-03-17 01:33:18 +0000327 AppendPadding(RecordSize - NextFieldOffsetInChars);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000328}
329
330void ConstStructBuilder::ConvertStructToPacked() {
Bill Wendling1e375fa2012-02-07 00:04:27 +0000331 SmallVector<llvm::Constant *, 16> PackedElements;
Ken Dyck4e54dca2011-03-18 00:55:06 +0000332 CharUnits ElementOffsetInChars = CharUnits::Zero();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000333
334 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
335 llvm::Constant *C = Elements[i];
336
Ken Dycka1b35102011-03-18 01:26:17 +0000337 CharUnits ElementAlign = CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +0000338 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Ken Dyck4e54dca2011-03-18 00:55:06 +0000339 CharUnits AlignedElementOffsetInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000340 ElementOffsetInChars.alignTo(ElementAlign);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000341
Ken Dyck4e54dca2011-03-18 00:55:06 +0000342 if (AlignedElementOffsetInChars > ElementOffsetInChars) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000343 // We need some padding.
Ken Dyck4e54dca2011-03-18 00:55:06 +0000344 CharUnits NumChars =
345 AlignedElementOffsetInChars - ElementOffsetInChars;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000346
Chris Lattnerece04092012-02-07 00:39:47 +0000347 llvm::Type *Ty = CGM.Int8Ty;
Ken Dyck4e54dca2011-03-18 00:55:06 +0000348 if (NumChars > CharUnits::One())
349 Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000350
Nuno Lopes5863c992010-04-16 20:56:35 +0000351 llvm::Constant *Padding = llvm::UndefValue::get(Ty);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000352 PackedElements.push_back(Padding);
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000353 ElementOffsetInChars += getSizeInChars(Padding);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000354 }
355
356 PackedElements.push_back(C);
Ken Dyck33fa9ee2011-03-18 01:12:13 +0000357 ElementOffsetInChars += getSizeInChars(C);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000358 }
359
Ken Dyck4e54dca2011-03-18 00:55:06 +0000360 assert(ElementOffsetInChars == NextFieldOffsetInChars &&
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000361 "Packing the struct changed its size!");
362
Bill Wendling1e375fa2012-02-07 00:04:27 +0000363 Elements.swap(PackedElements);
Ken Dycka1b35102011-03-18 01:26:17 +0000364 LLVMStructAlignment = CharUnits::One();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000365 Packed = true;
366}
Fangrui Song6907ce22018-07-30 19:24:48 +0000367
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000368bool ConstStructBuilder::Build(InitListExpr *ILE) {
369 RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
370 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
371
372 unsigned FieldNo = 0;
373 unsigned ElementNo = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000374
375 // Bail out if we have base classes. We could support these, but they only
376 // arise in C++1z where we will have already constant folded most interesting
377 // cases. FIXME: There are still a few more cases we can handle this way.
378 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
379 if (CXXRD->getNumBases())
380 return false;
381
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000382 for (RecordDecl::field_iterator Field = RD->field_begin(),
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000383 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000384 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000385 if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000386 continue;
387
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000388 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedman2782dac2013-06-26 20:50:34 +0000389 if (Field->isUnnamedBitfield())
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000390 continue;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000391
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000392 // Get the initializer. A struct can include fields without initializers,
393 // we just use explicit null values for them.
394 llvm::Constant *EltInit;
395 if (ElementNo < ILE->getNumInits())
John McCallde0fe072017-08-15 21:42:52 +0000396 EltInit = Emitter.tryEmitPrivateForMemory(ILE->getInit(ElementNo++),
397 Field->getType());
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000398 else
John McCallde0fe072017-08-15 21:42:52 +0000399 EltInit = Emitter.emitNullForMemory(Field->getType());
Eli Friedman3ee10222010-07-17 23:55:01 +0000400
401 if (!EltInit)
402 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000403
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000404 if (!Field->isBitField()) {
405 // Handle non-bitfield members.
David Blaikie40ed2972012-06-06 20:45:41 +0000406 AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000407 } else {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000408 // Otherwise we have a bitfield.
David Majnemer8062eb62015-03-14 22:24:38 +0000409 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
410 AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
411 } else {
412 // We are trying to initialize a bitfield with a non-trivial constant,
413 // this must require run-time code.
414 return false;
415 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000416 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000417 }
418
Richard Smithdafff942012-01-14 04:30:29 +0000419 return true;
420}
421
Richard Smithc8998922012-02-23 08:33:23 +0000422namespace {
423struct BaseInfo {
424 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
425 : Decl(Decl), Offset(Offset), Index(Index) {
426 }
427
428 const CXXRecordDecl *Decl;
429 CharUnits Offset;
430 unsigned Index;
431
432 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
433};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000434}
Richard Smithc8998922012-02-23 08:33:23 +0000435
John McCallde0fe072017-08-15 21:42:52 +0000436bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000437 bool IsPrimaryBase,
Richard Smithc8998922012-02-23 08:33:23 +0000438 const CXXRecordDecl *VTableClass,
439 CharUnits Offset) {
Richard Smithdafff942012-01-14 04:30:29 +0000440 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
441
Richard Smithc8998922012-02-23 08:33:23 +0000442 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
443 // Add a vtable pointer, if we need one and it hasn't already been added.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000444 if (CD->isDynamicClass() && !IsPrimaryBase) {
445 llvm::Constant *VTableAddressPoint =
446 CGM.getCXXABI().getVTableAddressPointForConstExpr(
447 BaseSubobject(CD, Offset), VTableClass);
448 AppendBytes(Offset, VTableAddressPoint);
449 }
Richard Smithc8998922012-02-23 08:33:23 +0000450
451 // Accumulate and sort bases, in order to visit them in address order, which
452 // may not be the same as declaration order.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000453 SmallVector<BaseInfo, 8> Bases;
Richard Smithc8998922012-02-23 08:33:23 +0000454 Bases.reserve(CD->getNumBases());
Richard Smithdafff942012-01-14 04:30:29 +0000455 unsigned BaseNo = 0;
Richard Smithc8998922012-02-23 08:33:23 +0000456 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
Richard Smithdafff942012-01-14 04:30:29 +0000457 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
Richard Smithc8998922012-02-23 08:33:23 +0000458 assert(!Base->isVirtual() && "should not have virtual bases here");
Richard Smithdafff942012-01-14 04:30:29 +0000459 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
460 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Richard Smithc8998922012-02-23 08:33:23 +0000461 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
462 }
463 std::stable_sort(Bases.begin(), Bases.end());
Richard Smithdafff942012-01-14 04:30:29 +0000464
Richard Smithc8998922012-02-23 08:33:23 +0000465 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
466 BaseInfo &Base = Bases[I];
Richard Smithdafff942012-01-14 04:30:29 +0000467
Richard Smithc8998922012-02-23 08:33:23 +0000468 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
469 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000470 VTableClass, Offset + Base.Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000471 }
472 }
473
474 unsigned FieldNo = 0;
Eli Friedmana154dd52012-03-30 03:55:31 +0000475 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000476
477 for (RecordDecl::field_iterator Field = RD->field_begin(),
478 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Richard Smithdafff942012-01-14 04:30:29 +0000479 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie40ed2972012-06-06 20:45:41 +0000480 if (RD->isUnion() && Val.getUnionField() != *Field)
Richard Smithdafff942012-01-14 04:30:29 +0000481 continue;
482
483 // Don't emit anonymous bitfields, they just affect layout.
Eli Friedman2782dac2013-06-26 20:50:34 +0000484 if (Field->isUnnamedBitfield())
Richard Smithdafff942012-01-14 04:30:29 +0000485 continue;
Richard Smithdafff942012-01-14 04:30:29 +0000486
487 // Emit the value of the initializer.
488 const APValue &FieldValue =
489 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
490 llvm::Constant *EltInit =
John McCallde0fe072017-08-15 21:42:52 +0000491 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
492 if (!EltInit)
493 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000494
495 if (!Field->isBitField()) {
496 // Handle non-bitfield members.
David Blaikie40ed2972012-06-06 20:45:41 +0000497 AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
Richard Smithdafff942012-01-14 04:30:29 +0000498 } else {
499 // Otherwise we have a bitfield.
David Blaikie40ed2972012-06-06 20:45:41 +0000500 AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smithdafff942012-01-14 04:30:29 +0000501 cast<llvm::ConstantInt>(EltInit));
502 }
503 }
John McCallde0fe072017-08-15 21:42:52 +0000504
505 return true;
Richard Smithdafff942012-01-14 04:30:29 +0000506}
507
508llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
509 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
510 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
511
Ken Dyckdb205d12011-03-17 01:33:18 +0000512 CharUnits LayoutSizeInChars = Layout.getSize();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000513
Ken Dyckdb205d12011-03-17 01:33:18 +0000514 if (NextFieldOffsetInChars > LayoutSizeInChars) {
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000515 // If the struct is bigger than the size of the record type,
516 // we must have a flexible array member at the end.
517 assert(RD->hasFlexibleArrayMember() &&
518 "Must have flexible array member if struct is bigger than type!");
Richard Smithdafff942012-01-14 04:30:29 +0000519
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000520 // No tail padding is necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000521 } else {
522 // Append tail padding if necessary.
Richard Smithdafff942012-01-14 04:30:29 +0000523 CharUnits LLVMSizeInChars =
Rui Ueyama83aa9792016-01-14 21:00:27 +0000524 NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
David Majnemer8e133962014-10-19 23:40:06 +0000525
526 if (LLVMSizeInChars != LayoutSizeInChars)
527 AppendTailPadding(LayoutSizeInChars);
528
Rui Ueyama83aa9792016-01-14 21:00:27 +0000529 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
Richard Smithdafff942012-01-14 04:30:29 +0000530
531 // Check if we need to convert the struct to a packed struct.
532 if (NextFieldOffsetInChars <= LayoutSizeInChars &&
533 LLVMSizeInChars > LayoutSizeInChars) {
534 assert(!Packed && "Size mismatch!");
535
536 ConvertStructToPacked();
537 assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
538 "Converting to packed did not help!");
539 }
540
Rui Ueyama83aa9792016-01-14 21:00:27 +0000541 LLVMSizeInChars = NextFieldOffsetInChars.alignTo(LLVMStructAlignment);
David Majnemer8e133962014-10-19 23:40:06 +0000542
543 assert(LayoutSizeInChars == LLVMSizeInChars &&
Richard Smithdafff942012-01-14 04:30:29 +0000544 "Tail padding mismatch!");
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000545 }
546
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000547 // Pick the type to use. If the type is layout identical to the ConvertType
548 // type then use it, otherwise use whatever the builder produced for us.
Chris Lattner2192fe52011-07-18 04:24:23 +0000549 llvm::StructType *STy =
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000550 llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +0000551 Elements, Packed);
552 llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
553 if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
554 if (ValSTy->isLayoutIdentical(STy))
555 STy = ValSTy;
Chris Lattnere64d7ba2011-06-20 04:01:35 +0000556 }
Richard Smithdafff942012-01-14 04:30:29 +0000557
558 llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
559
Rui Ueyama83aa9792016-01-14 21:00:27 +0000560 assert(NextFieldOffsetInChars.alignTo(getAlignment(Result)) ==
561 getSizeInChars(Result) &&
562 "Size mismatch!");
Richard Smithdafff942012-01-14 04:30:29 +0000563
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000564 return Result;
565}
566
John McCallde0fe072017-08-15 21:42:52 +0000567llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
568 ConstExprEmitter *ExprEmitter,
Yunzhong Gaocb779302015-06-10 00:27:52 +0000569 llvm::ConstantStruct *Base,
John McCallde0fe072017-08-15 21:42:52 +0000570 InitListExpr *Updater,
571 QualType ValTy) {
572 ConstStructBuilder Builder(Emitter);
573 if (!Builder.Build(ExprEmitter, Base, Updater))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000574 return nullptr;
John McCallde0fe072017-08-15 21:42:52 +0000575 return Builder.Finalize(ValTy);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000576}
577
John McCallde0fe072017-08-15 21:42:52 +0000578llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
579 InitListExpr *ILE,
580 QualType ValTy) {
581 ConstStructBuilder Builder(Emitter);
Richard Smithdafff942012-01-14 04:30:29 +0000582
583 if (!Builder.Build(ILE))
Craig Topper8a13c412014-05-21 05:09:00 +0000584 return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +0000585
John McCallde0fe072017-08-15 21:42:52 +0000586 return Builder.Finalize(ValTy);
Richard Smithdafff942012-01-14 04:30:29 +0000587}
588
John McCallde0fe072017-08-15 21:42:52 +0000589llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +0000590 const APValue &Val,
591 QualType ValTy) {
John McCallde0fe072017-08-15 21:42:52 +0000592 ConstStructBuilder Builder(Emitter);
Richard Smithc8998922012-02-23 08:33:23 +0000593
594 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
595 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
John McCallde0fe072017-08-15 21:42:52 +0000596 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
597 return nullptr;
Richard Smithc8998922012-02-23 08:33:23 +0000598
Richard Smithdafff942012-01-14 04:30:29 +0000599 return Builder.Finalize(ValTy);
600}
601
602
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000603//===----------------------------------------------------------------------===//
604// ConstExprEmitter
605//===----------------------------------------------------------------------===//
Richard Smithdd5bdd82012-01-17 21:42:19 +0000606
John McCallde0fe072017-08-15 21:42:52 +0000607static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
608 CodeGenFunction *CGF,
609 const CompoundLiteralExpr *E) {
610 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
611 if (llvm::GlobalVariable *Addr =
612 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
613 return ConstantAddress(Addr, Align);
614
Alexander Richardson6d989432017-10-15 18:48:14 +0000615 LangAS addressSpace = E->getType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000616
617 ConstantEmitter emitter(CGM, CGF);
618 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
619 addressSpace, E->getType());
620 if (!C) {
621 assert(!E->isFileScope() &&
622 "file-scope compound literal did not have constant initializer!");
623 return ConstantAddress::invalid();
624 }
625
626 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
627 CGM.isTypeConstant(E->getType(), true),
628 llvm::GlobalValue::InternalLinkage,
629 C, ".compoundliteral", nullptr,
630 llvm::GlobalVariable::NotThreadLocal,
631 CGM.getContext().getTargetAddressSpace(addressSpace));
632 emitter.finalize(GV);
633 GV->setAlignment(Align.getQuantity());
634 CGM.setAddrOfConstantCompoundLiteral(E, GV);
635 return ConstantAddress(GV, Align);
636}
637
Richard Smith3e268632018-05-23 23:41:38 +0000638static llvm::Constant *
639EmitArrayConstant(CodeGenModule &CGM, const ConstantArrayType *DestType,
640 llvm::Type *CommonElementType, unsigned ArrayBound,
641 SmallVectorImpl<llvm::Constant *> &Elements,
642 llvm::Constant *Filler) {
643 // Figure out how long the initial prefix of non-zero elements is.
644 unsigned NonzeroLength = ArrayBound;
645 if (Elements.size() < NonzeroLength && Filler->isNullValue())
646 NonzeroLength = Elements.size();
647 if (NonzeroLength == Elements.size()) {
648 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
649 --NonzeroLength;
650 }
651
652 if (NonzeroLength == 0) {
653 return llvm::ConstantAggregateZero::get(
654 CGM.getTypes().ConvertType(QualType(DestType, 0)));
655 }
656
657 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
658 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
659 if (TrailingZeroes >= 8) {
660 assert(Elements.size() >= NonzeroLength &&
661 "missing initializer for non-zero element");
Richard Smith83497d92018-07-19 21:38:56 +0000662
663 // If all the elements had the same type up to the trailing zeroes, emit a
664 // struct of two arrays (the nonzero data and the zeroinitializer).
665 if (CommonElementType && NonzeroLength >= 8) {
666 llvm::Constant *Initial = llvm::ConstantArray::get(
Richard Smith4c656882018-07-19 23:24:41 +0000667 llvm::ArrayType::get(CommonElementType, NonzeroLength),
Richard Smith83497d92018-07-19 21:38:56 +0000668 makeArrayRef(Elements).take_front(NonzeroLength));
669 Elements.resize(2);
670 Elements[0] = Initial;
671 } else {
672 Elements.resize(NonzeroLength + 1);
673 }
674
Richard Smith3e268632018-05-23 23:41:38 +0000675 auto *FillerType =
676 CommonElementType
677 ? CommonElementType
678 : CGM.getTypes().ConvertType(DestType->getElementType());
679 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
680 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
681 CommonElementType = nullptr;
682 } else if (Elements.size() != ArrayBound) {
683 // Otherwise pad to the right size with the filler if necessary.
684 Elements.resize(ArrayBound, Filler);
685 if (Filler->getType() != CommonElementType)
686 CommonElementType = nullptr;
687 }
688
689 // If all elements have the same type, just emit an array constant.
690 if (CommonElementType)
691 return llvm::ConstantArray::get(
692 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
693
694 // We have mixed types. Use a packed struct.
695 llvm::SmallVector<llvm::Type *, 16> Types;
696 Types.reserve(Elements.size());
697 for (llvm::Constant *Elt : Elements)
698 Types.push_back(Elt->getType());
699 llvm::StructType *SType =
700 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
701 return llvm::ConstantStruct::get(SType, Elements);
702}
703
Richard Smithdd5bdd82012-01-17 21:42:19 +0000704/// This class only needs to handle two cases:
705/// 1) Literals (this is used by APValue emission to emit literals).
706/// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
707/// constant fold these types).
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000708class ConstExprEmitter :
John McCallde0fe072017-08-15 21:42:52 +0000709 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
Anders Carlsson610ee712008-01-26 01:36:00 +0000710 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +0000711 ConstantEmitter &Emitter;
Owen Anderson170229f2009-07-14 23:10:40 +0000712 llvm::LLVMContext &VMContext;
Anders Carlsson610ee712008-01-26 01:36:00 +0000713public:
John McCallde0fe072017-08-15 21:42:52 +0000714 ConstExprEmitter(ConstantEmitter &emitter)
715 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
Anders Carlsson610ee712008-01-26 01:36:00 +0000716 }
Mike Stump11289f42009-09-09 15:08:12 +0000717
Anders Carlsson610ee712008-01-26 01:36:00 +0000718 //===--------------------------------------------------------------------===//
719 // Visitor Methods
720 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000721
John McCallde0fe072017-08-15 21:42:52 +0000722 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
Craig Topper8a13c412014-05-21 05:09:00 +0000723 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +0000724 }
Mike Stump11289f42009-09-09 15:08:12 +0000725
John McCallde0fe072017-08-15 21:42:52 +0000726 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
727 return Visit(PE->getSubExpr(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +0000728 }
Mike Stump11289f42009-09-09 15:08:12 +0000729
John McCall7c454bb2011-07-15 05:09:51 +0000730 llvm::Constant *
John McCallde0fe072017-08-15 21:42:52 +0000731 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
732 QualType T) {
733 return Visit(PE->getReplacement(), T);
John McCall7c454bb2011-07-15 05:09:51 +0000734 }
735
John McCallde0fe072017-08-15 21:42:52 +0000736 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
737 QualType T) {
738 return Visit(GE->getResultExpr(), T);
Peter Collingbourne91147592011-04-15 00:35:48 +0000739 }
740
John McCallde0fe072017-08-15 21:42:52 +0000741 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
742 return Visit(CE->getChosenSubExpr(), T);
Eli Friedman4c27ac22013-07-16 22:40:53 +0000743 }
744
John McCallde0fe072017-08-15 21:42:52 +0000745 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
746 return Visit(E->getInitializer(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +0000747 }
John McCallf3a88602011-02-03 08:15:49 +0000748
John McCallde0fe072017-08-15 21:42:52 +0000749 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000750 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
John McCallde0fe072017-08-15 21:42:52 +0000751 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
John McCall2de87f62011-03-15 21:17:48 +0000752 Expr *subExpr = E->getSubExpr();
John McCall2de87f62011-03-15 21:17:48 +0000753
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000754 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +0000755 case CK_ToUnion: {
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000756 // GCC cast to union extension
757 assert(E->getType()->isUnionType() &&
758 "Destination type is not union type!");
Mike Stump11289f42009-09-09 15:08:12 +0000759
John McCallde0fe072017-08-15 21:42:52 +0000760 auto field = E->getTargetUnionField();
761
762 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
763 if (!C) return nullptr;
764
765 auto destTy = ConvertType(destType);
766 if (C->getType() == destTy) return C;
767
Anders Carlssond65ab042009-07-31 21:38:39 +0000768 // Build a struct with the union sub-element as the first member,
John McCallde0fe072017-08-15 21:42:52 +0000769 // and padded to the appropriate size.
Bill Wendling99729582012-02-07 00:13:27 +0000770 SmallVector<llvm::Constant*, 2> Elts;
771 SmallVector<llvm::Type*, 2> Types;
Anders Carlssond65ab042009-07-31 21:38:39 +0000772 Elts.push_back(C);
773 Types.push_back(C->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +0000774 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
John McCallde0fe072017-08-15 21:42:52 +0000775 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
Mike Stump11289f42009-09-09 15:08:12 +0000776
Anders Carlssond65ab042009-07-31 21:38:39 +0000777 assert(CurSize <= TotalSize && "Union size mismatch!");
778 if (unsigned NumPadBytes = TotalSize - CurSize) {
Chris Lattnerece04092012-02-07 00:39:47 +0000779 llvm::Type *Ty = CGM.Int8Ty;
Anders Carlssond65ab042009-07-31 21:38:39 +0000780 if (NumPadBytes > 1)
781 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000782
Nuno Lopes5863c992010-04-16 20:56:35 +0000783 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssond65ab042009-07-31 21:38:39 +0000784 Types.push_back(Ty);
785 }
Mike Stump11289f42009-09-09 15:08:12 +0000786
John McCallde0fe072017-08-15 21:42:52 +0000787 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
Anders Carlssond65ab042009-07-31 21:38:39 +0000788 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes4d78cf02009-01-17 00:48:48 +0000789 }
Anders Carlsson9500ad12009-10-18 20:31:03 +0000790
John McCallde0fe072017-08-15 21:42:52 +0000791 case CK_AddressSpaceConversion: {
792 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
793 if (!C) return nullptr;
Alexander Richardson6d989432017-10-15 18:48:14 +0000794 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
795 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000796 llvm::Type *destTy = ConvertType(E->getType());
797 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
798 destAS, destTy);
799 }
David Tweede1468322013-12-11 13:39:46 +0000800
John McCall2de87f62011-03-15 21:17:48 +0000801 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +0000802 case CK_AtomicToNonAtomic:
803 case CK_NonAtomicToAtomic:
John McCall2de87f62011-03-15 21:17:48 +0000804 case CK_NoOp:
Eli Friedman4c27ac22013-07-16 22:40:53 +0000805 case CK_ConstructorConversion:
John McCallde0fe072017-08-15 21:42:52 +0000806 return Visit(subExpr, destType);
Anders Carlsson9500ad12009-10-18 20:31:03 +0000807
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +0000808 case CK_IntToOCLSampler:
809 llvm_unreachable("global sampler variables are not generated");
810
John McCall2de87f62011-03-15 21:17:48 +0000811 case CK_Dependent: llvm_unreachable("saw dependent cast!");
812
Eli Friedman34866c72012-08-31 00:14:07 +0000813 case CK_BuiltinFnToFnPtr:
814 llvm_unreachable("builtin functions are handled elsewhere");
815
John McCallc62bb392012-02-15 01:22:51 +0000816 case CK_ReinterpretMemberPointer:
817 case CK_DerivedToBaseMemberPointer:
John McCallde0fe072017-08-15 21:42:52 +0000818 case CK_BaseToDerivedMemberPointer: {
819 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
820 if (!C) return nullptr;
John McCallc62bb392012-02-15 01:22:51 +0000821 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
John McCallde0fe072017-08-15 21:42:52 +0000822 }
John McCallc62bb392012-02-15 01:22:51 +0000823
John McCall2de87f62011-03-15 21:17:48 +0000824 // These will never be supported.
825 case CK_ObjCObjectLValueCast:
John McCall2d637d22011-09-10 06:18:15 +0000826 case CK_ARCProduceObject:
827 case CK_ARCConsumeObject:
828 case CK_ARCReclaimReturnedObject:
829 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +0000830 case CK_CopyAndAutoreleaseBlockObject:
Craig Topper8a13c412014-05-21 05:09:00 +0000831 return nullptr;
John McCall2de87f62011-03-15 21:17:48 +0000832
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000833 // These don't need to be handled here because Evaluate knows how to
Richard Smithdd5bdd82012-01-17 21:42:19 +0000834 // evaluate them in the cases where they can be folded.
John McCallc62bb392012-02-15 01:22:51 +0000835 case CK_BitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +0000836 case CK_ToVoid:
837 case CK_Dynamic:
838 case CK_LValueBitCast:
839 case CK_NullToMemberPointer:
Richard Smithdd5bdd82012-01-17 21:42:19 +0000840 case CK_UserDefinedConversion:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000841 case CK_CPointerToObjCPointerCast:
842 case CK_BlockPointerToObjCPointerCast:
843 case CK_AnyPointerToBlockPointerCast:
John McCall2de87f62011-03-15 21:17:48 +0000844 case CK_ArrayToPointerDecay:
845 case CK_FunctionToPointerDecay:
846 case CK_BaseToDerived:
847 case CK_DerivedToBase:
848 case CK_UncheckedDerivedToBase:
849 case CK_MemberPointerToBoolean:
850 case CK_VectorSplat:
851 case CK_FloatingRealToComplex:
852 case CK_FloatingComplexToReal:
853 case CK_FloatingComplexToBoolean:
854 case CK_FloatingComplexCast:
855 case CK_FloatingComplexToIntegralComplex:
856 case CK_IntegralRealToComplex:
857 case CK_IntegralComplexToReal:
858 case CK_IntegralComplexToBoolean:
859 case CK_IntegralComplexCast:
860 case CK_IntegralComplexToFloatingComplex:
John McCall2de87f62011-03-15 21:17:48 +0000861 case CK_PointerToIntegral:
John McCall2de87f62011-03-15 21:17:48 +0000862 case CK_PointerToBoolean:
John McCall2de87f62011-03-15 21:17:48 +0000863 case CK_NullToPointer:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000864 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +0000865 case CK_BooleanToSignedIntegral:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +0000866 case CK_IntegralToPointer:
John McCall2de87f62011-03-15 21:17:48 +0000867 case CK_IntegralToBoolean:
John McCall2de87f62011-03-15 21:17:48 +0000868 case CK_IntegralToFloating:
John McCall2de87f62011-03-15 21:17:48 +0000869 case CK_FloatingToIntegral:
John McCall2de87f62011-03-15 21:17:48 +0000870 case CK_FloatingToBoolean:
John McCall2de87f62011-03-15 21:17:48 +0000871 case CK_FloatingCast:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +0000872 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +0000873 case CK_ZeroToOCLQueue:
Craig Topper8a13c412014-05-21 05:09:00 +0000874 return nullptr;
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +0000875 }
Matt Beaumont-Gay145e2eb2011-03-17 00:46:34 +0000876 llvm_unreachable("Invalid CastKind");
Anders Carlsson610ee712008-01-26 01:36:00 +0000877 }
Devang Patela703a672008-02-05 02:39:50 +0000878
John McCallde0fe072017-08-15 21:42:52 +0000879 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE, QualType T) {
880 return Visit(DAE->getExpr(), T);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000881 }
882
John McCallde0fe072017-08-15 21:42:52 +0000883 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
Richard Smith852c9db2013-04-20 22:23:05 +0000884 // No need for a DefaultInitExprScope: we don't handle 'this' in a
885 // constant expression.
John McCallde0fe072017-08-15 21:42:52 +0000886 return Visit(DIE->getExpr(), T);
Richard Smith852c9db2013-04-20 22:23:05 +0000887 }
888
John McCallde0fe072017-08-15 21:42:52 +0000889 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
Tim Shen4a05bb82016-06-21 20:29:17 +0000890 if (!E->cleanupsHaveSideEffects())
John McCallde0fe072017-08-15 21:42:52 +0000891 return Visit(E->getSubExpr(), T);
Tim Shen4a05bb82016-06-21 20:29:17 +0000892 return nullptr;
893 }
894
John McCallde0fe072017-08-15 21:42:52 +0000895 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
896 QualType T) {
897 return Visit(E->GetTemporaryExpr(), T);
Douglas Gregorfe314812011-06-21 17:03:29 +0000898 }
899
John McCallde0fe072017-08-15 21:42:52 +0000900 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
Richard Smith3e268632018-05-23 23:41:38 +0000901 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
902 assert(CAT && "can't emit array init for non-constant-bound array");
Richard Smith9ec1e482012-04-15 02:50:59 +0000903 unsigned NumInitElements = ILE->getNumInits();
Richard Smith3e268632018-05-23 23:41:38 +0000904 unsigned NumElements = CAT->getSize().getZExtValue();
Devang Patela703a672008-02-05 02:39:50 +0000905
Mike Stump11289f42009-09-09 15:08:12 +0000906 // Initialising an array requires us to automatically
Devang Patela703a672008-02-05 02:39:50 +0000907 // initialise any elements that have not been initialised explicitly
908 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
909
Richard Smith3e268632018-05-23 23:41:38 +0000910 QualType EltType = CAT->getElementType();
John McCallde0fe072017-08-15 21:42:52 +0000911
David Majnemer90d85442014-12-28 23:46:59 +0000912 // Initialize remaining array elements.
Richard Smith3e268632018-05-23 23:41:38 +0000913 llvm::Constant *fillC = nullptr;
914 if (Expr *filler = ILE->getArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +0000915 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
Richard Smith3e268632018-05-23 23:41:38 +0000916 if (!fillC)
917 return nullptr;
918 }
David Majnemer90d85442014-12-28 23:46:59 +0000919
Devang Patela703a672008-02-05 02:39:50 +0000920 // Copy initializer elements.
John McCallde0fe072017-08-15 21:42:52 +0000921 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +0000922 if (fillC && fillC->isNullValue())
923 Elts.reserve(NumInitableElts + 1);
924 else
925 Elts.reserve(NumElements);
Benjamin Kramer8001f742012-02-14 12:06:21 +0000926
Richard Smith3e268632018-05-23 23:41:38 +0000927 llvm::Type *CommonElementType = nullptr;
Benjamin Kramer8001f742012-02-14 12:06:21 +0000928 for (unsigned i = 0; i < NumInitableElts; ++i) {
Anders Carlsson80f97ab2009-04-08 04:48:15 +0000929 Expr *Init = ILE->getInit(i);
John McCallde0fe072017-08-15 21:42:52 +0000930 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
Daniel Dunbar38ad1e62009-02-17 18:43:32 +0000931 if (!C)
Craig Topper8a13c412014-05-21 05:09:00 +0000932 return nullptr;
Richard Smith3e268632018-05-23 23:41:38 +0000933 if (i == 0)
934 CommonElementType = C->getType();
935 else if (C->getType() != CommonElementType)
936 CommonElementType = nullptr;
Devang Patela703a672008-02-05 02:39:50 +0000937 Elts.push_back(C);
938 }
Eli Friedman34994cb2008-05-30 19:58:50 +0000939
Richard Smith3e268632018-05-23 23:41:38 +0000940 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
941 fillC);
Devang Patela703a672008-02-05 02:39:50 +0000942 }
943
John McCallde0fe072017-08-15 21:42:52 +0000944 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
945 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
Eli Friedmana2eaffc2008-05-30 10:24:46 +0000946 }
947
John McCallde0fe072017-08-15 21:42:52 +0000948 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
949 QualType T) {
950 return CGM.EmitNullConstant(T);
Anders Carlsson02714ed2009-01-30 06:13:25 +0000951 }
Mike Stump11289f42009-09-09 15:08:12 +0000952
John McCallde0fe072017-08-15 21:42:52 +0000953 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
Richard Smith122f88d2016-12-06 23:52:28 +0000954 if (ILE->isTransparent())
John McCallde0fe072017-08-15 21:42:52 +0000955 return Visit(ILE->getInit(0), T);
Richard Smith122f88d2016-12-06 23:52:28 +0000956
Eli Friedmana2eaffc2008-05-30 10:24:46 +0000957 if (ILE->getType()->isArrayType())
John McCallde0fe072017-08-15 21:42:52 +0000958 return EmitArrayInitialization(ILE, T);
Devang Patel45a65d22008-01-29 23:23:18 +0000959
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +0000960 if (ILE->getType()->isRecordType())
John McCallde0fe072017-08-15 21:42:52 +0000961 return EmitRecordInitialization(ILE, T);
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +0000962
Craig Topper8a13c412014-05-21 05:09:00 +0000963 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +0000964 }
Eli Friedmana2433112008-02-21 17:57:49 +0000965
Yunzhong Gaocb779302015-06-10 00:27:52 +0000966 llvm::Constant *EmitDesignatedInitUpdater(llvm::Constant *Base,
John McCallde0fe072017-08-15 21:42:52 +0000967 InitListExpr *Updater,
968 QualType destType) {
969 if (auto destAT = CGM.getContext().getAsArrayType(destType)) {
970 llvm::ArrayType *AType = cast<llvm::ArrayType>(ConvertType(destType));
Yunzhong Gaocb779302015-06-10 00:27:52 +0000971 llvm::Type *ElemType = AType->getElementType();
972
973 unsigned NumInitElements = Updater->getNumInits();
974 unsigned NumElements = AType->getNumElements();
Fangrui Song6907ce22018-07-30 19:24:48 +0000975
Yunzhong Gaocb779302015-06-10 00:27:52 +0000976 std::vector<llvm::Constant *> Elts;
977 Elts.reserve(NumElements);
978
John McCallde0fe072017-08-15 21:42:52 +0000979 QualType destElemType = destAT->getElementType();
980
981 if (auto DataArray = dyn_cast<llvm::ConstantDataArray>(Base))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000982 for (unsigned i = 0; i != NumElements; ++i)
983 Elts.push_back(DataArray->getElementAsConstant(i));
John McCallde0fe072017-08-15 21:42:52 +0000984 else if (auto Array = dyn_cast<llvm::ConstantArray>(Base))
Yunzhong Gaocb779302015-06-10 00:27:52 +0000985 for (unsigned i = 0; i != NumElements; ++i)
986 Elts.push_back(Array->getOperand(i));
987 else
988 return nullptr; // FIXME: other array types not implemented
989
990 llvm::Constant *fillC = nullptr;
991 if (Expr *filler = Updater->getArrayFiller())
992 if (!isa<NoInitExpr>(filler))
John McCallde0fe072017-08-15 21:42:52 +0000993 fillC = Emitter.tryEmitAbstractForMemory(filler, destElemType);
Yunzhong Gaocb779302015-06-10 00:27:52 +0000994 bool RewriteType = (fillC && fillC->getType() != ElemType);
995
996 for (unsigned i = 0; i != NumElements; ++i) {
997 Expr *Init = nullptr;
998 if (i < NumInitElements)
999 Init = Updater->getInit(i);
1000
1001 if (!Init && fillC)
1002 Elts[i] = fillC;
1003 else if (!Init || isa<NoInitExpr>(Init))
1004 ; // Do nothing.
1005 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
John McCallde0fe072017-08-15 21:42:52 +00001006 Elts[i] = EmitDesignatedInitUpdater(Elts[i], ChildILE, destElemType);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001007 else
John McCallde0fe072017-08-15 21:42:52 +00001008 Elts[i] = Emitter.tryEmitPrivateForMemory(Init, destElemType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001009
Yunzhong Gaocb779302015-06-10 00:27:52 +00001010 if (!Elts[i])
1011 return nullptr;
1012 RewriteType |= (Elts[i]->getType() != ElemType);
1013 }
1014
1015 if (RewriteType) {
1016 std::vector<llvm::Type *> Types;
1017 Types.reserve(NumElements);
1018 for (unsigned i = 0; i != NumElements; ++i)
1019 Types.push_back(Elts[i]->getType());
1020 llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
1021 Types, true);
1022 return llvm::ConstantStruct::get(SType, Elts);
1023 }
1024
1025 return llvm::ConstantArray::get(AType, Elts);
1026 }
1027
John McCallde0fe072017-08-15 21:42:52 +00001028 if (destType->isRecordType())
1029 return ConstStructBuilder::BuildStruct(Emitter, this,
1030 dyn_cast<llvm::ConstantStruct>(Base), Updater, destType);
Yunzhong Gaocb779302015-06-10 00:27:52 +00001031
1032 return nullptr;
1033 }
1034
John McCallde0fe072017-08-15 21:42:52 +00001035 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1036 QualType destType) {
1037 auto C = Visit(E->getBase(), destType);
1038 if (!C) return nullptr;
1039 return EmitDesignatedInitUpdater(C, E->getUpdater(), destType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001040 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00001041
John McCallde0fe072017-08-15 21:42:52 +00001042 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
John McCall49786a62010-02-02 08:02:49 +00001043 if (!E->getConstructor()->isTrivial())
Craig Topper8a13c412014-05-21 05:09:00 +00001044 return nullptr;
John McCall49786a62010-02-02 08:02:49 +00001045
Anders Carlssoncb86e102010-02-05 18:38:45 +00001046 // FIXME: We should not have to call getBaseElementType here.
Fangrui Song6907ce22018-07-30 19:24:48 +00001047 const RecordType *RT =
Anders Carlssoncb86e102010-02-05 18:38:45 +00001048 CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
1049 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Fangrui Song6907ce22018-07-30 19:24:48 +00001050
Anders Carlssoncb86e102010-02-05 18:38:45 +00001051 // If the class doesn't have a trivial destructor, we can't emit it as a
1052 // constant expr.
1053 if (!RD->hasTrivialDestructor())
Craig Topper8a13c412014-05-21 05:09:00 +00001054 return nullptr;
1055
John McCall49786a62010-02-02 08:02:49 +00001056 // Only copy and default constructors can be trivial.
1057
John McCall49786a62010-02-02 08:02:49 +00001058
1059 if (E->getNumArgs()) {
1060 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001061 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1062 "trivial ctor has argument but isn't a copy/move ctor");
John McCall49786a62010-02-02 08:02:49 +00001063
1064 Expr *Arg = E->getArg(0);
1065 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1066 "argument to copy ctor is of wrong type");
1067
John McCallde0fe072017-08-15 21:42:52 +00001068 return Visit(Arg, Ty);
John McCall49786a62010-02-02 08:02:49 +00001069 }
1070
1071 return CGM.EmitNullConstant(Ty);
1072 }
1073
John McCallde0fe072017-08-15 21:42:52 +00001074 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
Eli Friedmanfcec6302011-11-01 02:23:42 +00001075 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson610ee712008-01-26 01:36:00 +00001076 }
1077
John McCallde0fe072017-08-15 21:42:52 +00001078 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001079 // This must be an @encode initializing an array in a static initializer.
1080 // Don't emit it as the address of the string, emit the string data itself
1081 // as an inline array.
1082 std::string Str;
1083 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
John McCallde0fe072017-08-15 21:42:52 +00001084 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00001085
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001086 // Resize the string to the right size, adding zeros at the end, or
1087 // truncating as needed.
1088 Str.resize(CAT->getSize().getZExtValue(), '\0');
Chris Lattner9c818332012-02-05 02:30:40 +00001089 return llvm::ConstantDataArray::getString(VMContext, Str, false);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001090 }
Mike Stump11289f42009-09-09 15:08:12 +00001091
John McCallde0fe072017-08-15 21:42:52 +00001092 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1093 return Visit(E->getSubExpr(), T);
Eli Friedman045bf4f2008-05-29 11:22:45 +00001094 }
Mike Stumpa6703322009-02-19 22:01:56 +00001095
Anders Carlsson610ee712008-01-26 01:36:00 +00001096 // Utility methods
Chris Lattner2192fe52011-07-18 04:24:23 +00001097 llvm::Type *ConvertType(QualType T) {
Anders Carlsson610ee712008-01-26 01:36:00 +00001098 return CGM.getTypes().ConvertType(T);
1099 }
Anders Carlssona4139112008-01-26 02:08:50 +00001100};
Mike Stump11289f42009-09-09 15:08:12 +00001101
Anders Carlsson610ee712008-01-26 01:36:00 +00001102} // end anonymous namespace.
1103
John McCallde0fe072017-08-15 21:42:52 +00001104bool ConstStructBuilder::Build(ConstExprEmitter *ExprEmitter,
Yunzhong Gaocb779302015-06-10 00:27:52 +00001105 llvm::ConstantStruct *Base,
1106 InitListExpr *Updater) {
1107 assert(Base && "base expression should not be empty");
1108
1109 QualType ExprType = Updater->getType();
1110 RecordDecl *RD = ExprType->getAs<RecordType>()->getDecl();
1111 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
1112 const llvm::StructLayout *BaseLayout = CGM.getDataLayout().getStructLayout(
1113 Base->getType());
1114 unsigned FieldNo = -1;
1115 unsigned ElementNo = 0;
1116
Richard Smith872307e2016-03-08 22:17:41 +00001117 // Bail out if we have base classes. We could support these, but they only
1118 // arise in C++1z where we will have already constant folded most interesting
1119 // cases. FIXME: There are still a few more cases we can handle this way.
1120 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1121 if (CXXRD->getNumBases())
1122 return false;
1123
Yunzhong Gaocb779302015-06-10 00:27:52 +00001124 for (FieldDecl *Field : RD->fields()) {
1125 ++FieldNo;
1126
1127 if (RD->isUnion() && Updater->getInitializedFieldInUnion() != Field)
1128 continue;
1129
1130 // Skip anonymous bitfields.
1131 if (Field->isUnnamedBitfield())
1132 continue;
1133
1134 llvm::Constant *EltInit = Base->getOperand(ElementNo);
1135
1136 // Bail out if the type of the ConstantStruct does not have the same layout
1137 // as the type of the InitListExpr.
1138 if (CGM.getTypes().ConvertType(Field->getType()) != EltInit->getType() ||
1139 Layout.getFieldOffset(ElementNo) !=
1140 BaseLayout->getElementOffsetInBits(ElementNo))
1141 return false;
1142
1143 // Get the initializer. If we encounter an empty field or a NoInitExpr,
1144 // we use values from the base expression.
1145 Expr *Init = nullptr;
1146 if (ElementNo < Updater->getNumInits())
1147 Init = Updater->getInit(ElementNo);
1148
1149 if (!Init || isa<NoInitExpr>(Init))
1150 ; // Do nothing.
1151 else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init))
John McCallde0fe072017-08-15 21:42:52 +00001152 EltInit = ExprEmitter->EmitDesignatedInitUpdater(EltInit, ChildILE,
1153 Field->getType());
Yunzhong Gaocb779302015-06-10 00:27:52 +00001154 else
John McCallde0fe072017-08-15 21:42:52 +00001155 EltInit = Emitter.tryEmitPrivateForMemory(Init, Field->getType());
Yunzhong Gaocb779302015-06-10 00:27:52 +00001156
1157 ++ElementNo;
1158
1159 if (!EltInit)
1160 return false;
1161
1162 if (!Field->isBitField())
1163 AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit);
1164 else if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(EltInit))
1165 AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI);
1166 else
1167 // Initializing a bitfield with a non-trivial constant?
1168 return false;
1169 }
1170
1171 return true;
1172}
1173
John McCallde0fe072017-08-15 21:42:52 +00001174llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1175 AbstractState saved) {
1176 Abstract = saved.OldValue;
1177
1178 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1179 "created a placeholder while doing an abstract emission?");
1180
1181 // No validation necessary for now.
1182 // No cleanup to do for now.
1183 return C;
1184}
1185
1186llvm::Constant *
1187ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1188 auto state = pushAbstract();
1189 auto C = tryEmitPrivateForVarInit(D);
1190 return validateAndPopAbstract(C, state);
1191}
1192
1193llvm::Constant *
1194ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1195 auto state = pushAbstract();
1196 auto C = tryEmitPrivate(E, destType);
1197 return validateAndPopAbstract(C, state);
1198}
1199
1200llvm::Constant *
1201ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1202 auto state = pushAbstract();
1203 auto C = tryEmitPrivate(value, destType);
1204 return validateAndPopAbstract(C, state);
1205}
1206
1207llvm::Constant *
1208ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1209 auto state = pushAbstract();
1210 auto C = tryEmitPrivate(E, destType);
1211 C = validateAndPopAbstract(C, state);
1212 if (!C) {
1213 CGM.Error(E->getExprLoc(),
1214 "internal error: could not emit constant value \"abstractly\"");
1215 C = CGM.EmitNullConstant(destType);
1216 }
1217 return C;
1218}
1219
1220llvm::Constant *
1221ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1222 QualType destType) {
1223 auto state = pushAbstract();
1224 auto C = tryEmitPrivate(value, destType);
1225 C = validateAndPopAbstract(C, state);
1226 if (!C) {
1227 CGM.Error(loc,
1228 "internal error: could not emit constant value \"abstractly\"");
1229 C = CGM.EmitNullConstant(destType);
1230 }
1231 return C;
1232}
1233
1234llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1235 initializeNonAbstract(D.getType().getAddressSpace());
1236 return markIfFailed(tryEmitPrivateForVarInit(D));
1237}
1238
1239llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
Alexander Richardson6d989432017-10-15 18:48:14 +00001240 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001241 QualType destType) {
1242 initializeNonAbstract(destAddrSpace);
1243 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1244}
1245
1246llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
Alexander Richardson6d989432017-10-15 18:48:14 +00001247 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001248 QualType destType) {
1249 initializeNonAbstract(destAddrSpace);
1250 auto C = tryEmitPrivateForMemory(value, destType);
1251 assert(C && "couldn't emit constant value non-abstractly?");
1252 return C;
1253}
1254
1255llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1256 assert(!Abstract && "cannot get current address for abstract constant");
1257
1258
1259
1260 // Make an obviously ill-formed global that should blow up compilation
1261 // if it survives.
1262 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1263 llvm::GlobalValue::PrivateLinkage,
1264 /*init*/ nullptr,
1265 /*name*/ "",
1266 /*before*/ nullptr,
1267 llvm::GlobalVariable::NotThreadLocal,
1268 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1269
1270 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1271
1272 return global;
1273}
1274
1275void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1276 llvm::GlobalValue *placeholder) {
1277 assert(!PlaceholderAddresses.empty());
1278 assert(PlaceholderAddresses.back().first == nullptr);
1279 assert(PlaceholderAddresses.back().second == placeholder);
1280 PlaceholderAddresses.back().first = signal;
1281}
1282
1283namespace {
1284 struct ReplacePlaceholders {
1285 CodeGenModule &CGM;
1286
1287 /// The base address of the global.
1288 llvm::Constant *Base;
1289 llvm::Type *BaseValueTy = nullptr;
1290
1291 /// The placeholder addresses that were registered during emission.
1292 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1293
1294 /// The locations of the placeholder signals.
1295 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1296
1297 /// The current index stack. We use a simple unsigned stack because
1298 /// we assume that placeholders will be relatively sparse in the
1299 /// initializer, but we cache the index values we find just in case.
1300 llvm::SmallVector<unsigned, 8> Indices;
1301 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1302
1303 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1304 ArrayRef<std::pair<llvm::Constant*,
1305 llvm::GlobalVariable*>> addresses)
1306 : CGM(CGM), Base(base),
1307 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1308 }
1309
1310 void replaceInInitializer(llvm::Constant *init) {
1311 // Remember the type of the top-most initializer.
1312 BaseValueTy = init->getType();
1313
1314 // Initialize the stack.
1315 Indices.push_back(0);
1316 IndexValues.push_back(nullptr);
1317
1318 // Recurse into the initializer.
1319 findLocations(init);
1320
1321 // Check invariants.
1322 assert(IndexValues.size() == Indices.size() && "mismatch");
1323 assert(Indices.size() == 1 && "didn't pop all indices");
1324
1325 // Do the replacement; this basically invalidates 'init'.
1326 assert(Locations.size() == PlaceholderAddresses.size() &&
1327 "missed a placeholder?");
1328
1329 // We're iterating over a hashtable, so this would be a source of
1330 // non-determinism in compiler output *except* that we're just
1331 // messing around with llvm::Constant structures, which never itself
1332 // does anything that should be visible in compiler output.
1333 for (auto &entry : Locations) {
1334 assert(entry.first->getParent() == nullptr && "not a placeholder!");
1335 entry.first->replaceAllUsesWith(entry.second);
1336 entry.first->eraseFromParent();
1337 }
1338 }
1339
1340 private:
1341 void findLocations(llvm::Constant *init) {
1342 // Recurse into aggregates.
1343 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1344 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1345 Indices.push_back(i);
1346 IndexValues.push_back(nullptr);
1347
1348 findLocations(agg->getOperand(i));
1349
1350 IndexValues.pop_back();
1351 Indices.pop_back();
1352 }
1353 return;
1354 }
1355
1356 // Otherwise, check for registered constants.
1357 while (true) {
1358 auto it = PlaceholderAddresses.find(init);
1359 if (it != PlaceholderAddresses.end()) {
1360 setLocation(it->second);
1361 break;
1362 }
1363
1364 // Look through bitcasts or other expressions.
1365 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1366 init = expr->getOperand(0);
1367 } else {
1368 break;
1369 }
1370 }
1371 }
1372
1373 void setLocation(llvm::GlobalVariable *placeholder) {
1374 assert(Locations.find(placeholder) == Locations.end() &&
1375 "already found location for placeholder!");
1376
1377 // Lazily fill in IndexValues with the values from Indices.
1378 // We do this in reverse because we should always have a strict
1379 // prefix of indices from the start.
1380 assert(Indices.size() == IndexValues.size());
1381 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1382 if (IndexValues[i]) {
1383#ifndef NDEBUG
1384 for (size_t j = 0; j != i + 1; ++j) {
1385 assert(IndexValues[j] &&
1386 isa<llvm::ConstantInt>(IndexValues[j]) &&
1387 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1388 == Indices[j]);
1389 }
1390#endif
1391 break;
1392 }
1393
1394 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1395 }
1396
1397 // Form a GEP and then bitcast to the placeholder type so that the
1398 // replacement will succeed.
1399 llvm::Constant *location =
1400 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1401 Base, IndexValues);
1402 location = llvm::ConstantExpr::getBitCast(location,
1403 placeholder->getType());
1404
1405 Locations.insert({placeholder, location});
1406 }
1407 };
1408}
1409
1410void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1411 assert(InitializedNonAbstract &&
1412 "finalizing emitter that was used for abstract emission?");
1413 assert(!Finalized && "finalizing emitter multiple times");
1414 assert(global->getInitializer());
1415
1416 // Note that we might also be Failed.
1417 Finalized = true;
1418
1419 if (!PlaceholderAddresses.empty()) {
1420 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1421 .replaceInInitializer(global->getInitializer());
1422 PlaceholderAddresses.clear(); // satisfy
1423 }
1424}
1425
1426ConstantEmitter::~ConstantEmitter() {
1427 assert((!InitializedNonAbstract || Finalized || Failed) &&
1428 "not finalized after being initialized for non-abstract emission");
1429 assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1430}
1431
1432static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1433 if (auto AT = type->getAs<AtomicType>()) {
1434 return CGM.getContext().getQualifiedType(AT->getValueType(),
1435 type.getQualifiers());
1436 }
1437 return type;
1438}
1439
1440llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
Fariborz Jahaniancc7f0082013-01-10 23:28:43 +00001441 // Make a quick check if variable can be default NULL initialized
1442 // and avoid going through rest of code which may do, for c++11,
1443 // initialization of memory to all NULLs.
Richard Smith3f1d6de2018-05-21 20:36:58 +00001444 if (!D.hasLocalStorage()) {
1445 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1446 if (Ty->isRecordType())
1447 if (const CXXConstructExpr *E =
1448 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1449 const CXXConstructorDecl *CD = E->getConstructor();
1450 if (CD->isTrivial() && CD->isDefaultConstructor())
1451 return CGM.EmitNullConstant(D.getType());
1452 }
1453 }
John McCallde0fe072017-08-15 21:42:52 +00001454
1455 QualType destType = D.getType();
1456
1457 // Try to emit the initializer. Note that this can allow some things that
1458 // are not allowed by tryEmitPrivateForMemory alone.
1459 if (auto value = D.evaluateValue()) {
1460 return tryEmitPrivateForMemory(*value, destType);
1461 }
Richard Smithdafff942012-01-14 04:30:29 +00001462
Richard Smith6331c402012-02-13 22:16:19 +00001463 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1464 // reference is a constant expression, and the reference binds to a temporary,
1465 // then constant initialization is performed. ConstExprEmitter will
1466 // incorrectly emit a prvalue constant in this case, and the calling code
1467 // interprets that as the (pointer) value of the reference, rather than the
1468 // desired value of the referee.
John McCallde0fe072017-08-15 21:42:52 +00001469 if (destType->isReferenceType())
Craig Topper8a13c412014-05-21 05:09:00 +00001470 return nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00001471
Richard Smithdafff942012-01-14 04:30:29 +00001472 const Expr *E = D.getInit();
1473 assert(E && "No initializer to emit");
1474
John McCallde0fe072017-08-15 21:42:52 +00001475 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1476 auto C =
1477 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1478 return (C ? emitForMemory(C, destType) : nullptr);
1479}
1480
1481llvm::Constant *
1482ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1483 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1484 auto C = tryEmitAbstract(E, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001485 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001486}
1487
1488llvm::Constant *
1489ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1490 QualType destType) {
1491 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1492 auto C = tryEmitAbstract(value, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001493 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001494}
1495
1496llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1497 QualType destType) {
1498 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1499 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1500 return (C ? emitForMemory(C, destType) : nullptr);
1501}
1502
1503llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1504 QualType destType) {
1505 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1506 auto C = tryEmitPrivate(value, nonMemoryDestType);
1507 return (C ? emitForMemory(C, destType) : nullptr);
1508}
1509
1510llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1511 llvm::Constant *C,
1512 QualType destType) {
1513 // For an _Atomic-qualified constant, we may need to add tail padding.
1514 if (auto AT = destType->getAs<AtomicType>()) {
1515 QualType destValueType = AT->getValueType();
1516 C = emitForMemory(CGM, C, destValueType);
1517
1518 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1519 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1520 if (innerSize == outerSize)
1521 return C;
1522
1523 assert(innerSize < outerSize && "emitted over-large constant for atomic");
1524 llvm::Constant *elts[] = {
1525 C,
1526 llvm::ConstantAggregateZero::get(
1527 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1528 };
1529 return llvm::ConstantStruct::getAnon(elts);
Richard Smithdafff942012-01-14 04:30:29 +00001530 }
John McCallde0fe072017-08-15 21:42:52 +00001531
1532 // Zero-extend bool.
1533 if (C->getType()->isIntegerTy(1)) {
1534 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1535 return llvm::ConstantExpr::getZExt(C, boolTy);
1536 }
1537
Richard Smithdafff942012-01-14 04:30:29 +00001538 return C;
1539}
1540
John McCallde0fe072017-08-15 21:42:52 +00001541llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1542 QualType destType) {
Anders Carlsson38eef1d2008-12-01 02:42:14 +00001543 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +00001544
Anders Carlssond8e39bb2009-04-11 01:08:03 +00001545 bool Success = false;
Mike Stump11289f42009-09-09 15:08:12 +00001546
John McCallde0fe072017-08-15 21:42:52 +00001547 if (destType->isReferenceType())
1548 Success = E->EvaluateAsLValue(Result, CGM.getContext());
Mike Stump11289f42009-09-09 15:08:12 +00001549 else
John McCallde0fe072017-08-15 21:42:52 +00001550 Success = E->EvaluateAsRValue(Result, CGM.getContext());
Mike Stump11289f42009-09-09 15:08:12 +00001551
John McCallde0fe072017-08-15 21:42:52 +00001552 llvm::Constant *C;
Richard Smithdafff942012-01-14 04:30:29 +00001553 if (Success && !Result.HasSideEffects)
John McCallde0fe072017-08-15 21:42:52 +00001554 C = tryEmitPrivate(Result.Val, destType);
Richard Smithbc6387672012-03-02 23:27:11 +00001555 else
John McCallde0fe072017-08-15 21:42:52 +00001556 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
Eli Friedman10c24172008-06-01 15:31:44 +00001557
Eli Friedman10c24172008-06-01 15:31:44 +00001558 return C;
Anders Carlsson610ee712008-01-26 01:36:00 +00001559}
Eli Friedman20bb5e02009-04-13 21:47:26 +00001560
Yaxun Liu402804b2016-12-15 08:09:08 +00001561llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1562 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1563}
1564
John McCall99e5e982017-08-17 05:03:55 +00001565namespace {
1566/// A struct which can be used to peephole certain kinds of finalization
1567/// that normally happen during l-value emission.
1568struct ConstantLValue {
1569 llvm::Constant *Value;
1570 bool HasOffsetApplied;
1571
1572 /*implicit*/ ConstantLValue(llvm::Constant *value,
1573 bool hasOffsetApplied = false)
1574 : Value(value), HasOffsetApplied(false) {}
1575
1576 /*implicit*/ ConstantLValue(ConstantAddress address)
1577 : ConstantLValue(address.getPointer()) {}
1578};
1579
1580/// A helper class for emitting constant l-values.
1581class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1582 ConstantLValue> {
1583 CodeGenModule &CGM;
1584 ConstantEmitter &Emitter;
1585 const APValue &Value;
1586 QualType DestType;
1587
1588 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1589 friend StmtVisitorBase;
1590
1591public:
1592 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1593 QualType destType)
1594 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1595
1596 llvm::Constant *tryEmit();
1597
1598private:
1599 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1600 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1601
1602 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
1603 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1604 ConstantLValue VisitStringLiteral(const StringLiteral *E);
1605 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1606 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1607 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1608 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1609 ConstantLValue VisitCallExpr(const CallExpr *E);
1610 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1611 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
1612 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E);
1613 ConstantLValue VisitMaterializeTemporaryExpr(
1614 const MaterializeTemporaryExpr *E);
1615
1616 bool hasNonZeroOffset() const {
1617 return !Value.getLValueOffset().isZero();
1618 }
1619
1620 /// Return the value offset.
1621 llvm::Constant *getOffset() {
1622 return llvm::ConstantInt::get(CGM.Int64Ty,
1623 Value.getLValueOffset().getQuantity());
1624 }
1625
1626 /// Apply the value offset to the given constant.
1627 llvm::Constant *applyOffset(llvm::Constant *C) {
1628 if (!hasNonZeroOffset())
1629 return C;
1630
1631 llvm::Type *origPtrTy = C->getType();
1632 unsigned AS = origPtrTy->getPointerAddressSpace();
1633 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1634 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1635 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1636 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1637 return C;
1638 }
1639};
1640
1641}
1642
1643llvm::Constant *ConstantLValueEmitter::tryEmit() {
1644 const APValue::LValueBase &base = Value.getLValueBase();
1645
1646 // Certain special array initializers are represented in APValue
1647 // as l-values referring to the base expression which generates the
1648 // array. This happens with e.g. string literals. These should
1649 // probably just get their own representation kind in APValue.
1650 if (DestType->isArrayType()) {
1651 assert(!hasNonZeroOffset() && "offset on array initializer");
1652 auto expr = const_cast<Expr*>(base.get<const Expr*>());
1653 return ConstExprEmitter(Emitter).Visit(expr, DestType);
1654 }
1655
1656 // Otherwise, the destination type should be a pointer or reference
1657 // type, but it might also be a cast thereof.
1658 //
1659 // FIXME: the chain of casts required should be reflected in the APValue.
1660 // We need this in order to correctly handle things like a ptrtoint of a
1661 // non-zero null pointer and addrspace casts that aren't trivially
1662 // represented in LLVM IR.
1663 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1664 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1665
1666 // If there's no base at all, this is a null or absolute pointer,
1667 // possibly cast back to an integer type.
1668 if (!base) {
1669 return tryEmitAbsolute(destTy);
1670 }
1671
1672 // Otherwise, try to emit the base.
1673 ConstantLValue result = tryEmitBase(base);
1674
1675 // If that failed, we're done.
1676 llvm::Constant *value = result.Value;
1677 if (!value) return nullptr;
1678
1679 // Apply the offset if necessary and not already done.
1680 if (!result.HasOffsetApplied) {
1681 value = applyOffset(value);
1682 }
1683
1684 // Convert to the appropriate type; this could be an lvalue for
1685 // an integer. FIXME: performAddrSpaceCast
1686 if (isa<llvm::PointerType>(destTy))
1687 return llvm::ConstantExpr::getPointerCast(value, destTy);
1688
1689 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1690}
1691
1692/// Try to emit an absolute l-value, such as a null pointer or an integer
1693/// bitcast to pointer type.
1694llvm::Constant *
1695ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
1696 auto offset = getOffset();
1697
1698 // If we're producing a pointer, this is easy.
1699 if (auto destPtrTy = cast<llvm::PointerType>(destTy)) {
1700 if (Value.isNullPointer()) {
1701 // FIXME: integer offsets from non-zero null pointers.
1702 return CGM.getNullPointer(destPtrTy, DestType);
1703 }
1704
1705 // Convert the integer to a pointer-sized integer before converting it
1706 // to a pointer.
1707 // FIXME: signedness depends on the original integer type.
1708 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
1709 llvm::Constant *C = offset;
1710 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1711 /*isSigned*/ false);
1712 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
1713 return C;
1714 }
1715
1716 // Otherwise, we're basically returning an integer constant.
1717
1718 // FIXME: this does the wrong thing with ptrtoint of a null pointer,
1719 // but since we don't know the original pointer type, there's not much
1720 // we can do about it.
1721
1722 auto C = getOffset();
1723 C = llvm::ConstantExpr::getIntegerCast(C, destTy, /*isSigned*/ false);
1724 return C;
1725}
1726
1727ConstantLValue
1728ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1729 // Handle values.
1730 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1731 if (D->hasAttr<WeakRefAttr>())
1732 return CGM.GetWeakRefReference(D).getPointer();
1733
1734 if (auto FD = dyn_cast<FunctionDecl>(D))
1735 return CGM.GetAddrOfFunction(FD);
1736
1737 if (auto VD = dyn_cast<VarDecl>(D)) {
1738 // We can never refer to a variable with local storage.
1739 if (!VD->hasLocalStorage()) {
1740 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1741 return CGM.GetAddrOfGlobalVar(VD);
1742
1743 if (VD->isLocalVarDecl()) {
1744 return CGM.getOrCreateStaticVarDecl(
1745 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
1746 }
1747 }
1748 }
1749
1750 return nullptr;
1751 }
1752
1753 // Otherwise, it must be an expression.
1754 return Visit(base.get<const Expr*>());
1755}
1756
1757ConstantLValue
1758ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1759 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1760}
1761
1762ConstantLValue
1763ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1764 return CGM.GetAddrOfConstantStringFromLiteral(E);
1765}
1766
1767ConstantLValue
1768ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1769 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1770}
1771
1772ConstantLValue
1773ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1774 auto C = CGM.getObjCRuntime().GenerateConstantString(E->getString());
1775 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(E->getType()));
1776}
1777
1778ConstantLValue
1779ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
1780 if (auto CGF = Emitter.CGF) {
1781 LValue Res = CGF->EmitPredefinedLValue(E);
1782 return cast<ConstantAddress>(Res.getAddress());
1783 }
1784
1785 auto kind = E->getIdentType();
1786 if (kind == PredefinedExpr::PrettyFunction) {
1787 return CGM.GetAddrOfConstantCString("top level", ".tmp");
1788 }
1789
1790 return CGM.GetAddrOfConstantCString("", ".tmp");
1791}
1792
1793ConstantLValue
1794ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1795 assert(Emitter.CGF && "Invalid address of label expression outside function");
1796 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1797 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1798 CGM.getTypes().ConvertType(E->getType()));
1799 return Ptr;
1800}
1801
1802ConstantLValue
1803ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1804 unsigned builtin = E->getBuiltinCallee();
1805 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1806 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1807 return nullptr;
1808
1809 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1810 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1811 return CGM.getObjCRuntime().GenerateConstantString(literal);
1812 } else {
1813 // FIXME: need to deal with UCN conversion issues.
1814 return CGM.GetAddrOfConstantCFString(literal);
1815 }
1816}
1817
1818ConstantLValue
1819ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1820 StringRef functionName;
1821 if (auto CGF = Emitter.CGF)
1822 functionName = CGF->CurFn->getName();
1823 else
1824 functionName = "global";
1825
1826 return CGM.GetAddrOfGlobalBlock(E, functionName);
1827}
1828
1829ConstantLValue
1830ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1831 QualType T;
1832 if (E->isTypeOperand())
1833 T = E->getTypeOperand(CGM.getContext());
1834 else
1835 T = E->getExprOperand()->getType();
1836 return CGM.GetAddrOfRTTIDescriptor(T);
1837}
1838
1839ConstantLValue
1840ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
1841 return CGM.GetAddrOfUuidDescriptor(E);
1842}
1843
1844ConstantLValue
1845ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1846 const MaterializeTemporaryExpr *E) {
1847 assert(E->getStorageDuration() == SD_Static);
1848 SmallVector<const Expr *, 2> CommaLHSs;
1849 SmallVector<SubobjectAdjustment, 2> Adjustments;
1850 const Expr *Inner = E->GetTemporaryExpr()
1851 ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
1852 return CGM.GetAddrOfGlobalTemporary(E, Inner);
1853}
1854
John McCallde0fe072017-08-15 21:42:52 +00001855llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
1856 QualType DestType) {
Richard Smithdafff942012-01-14 04:30:29 +00001857 switch (Value.getKind()) {
1858 case APValue::Uninitialized:
1859 llvm_unreachable("Constant expressions should be initialized.");
John McCall99e5e982017-08-17 05:03:55 +00001860 case APValue::LValue:
1861 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
Richard Smithbc6387672012-03-02 23:27:11 +00001862 case APValue::Int:
John McCallde0fe072017-08-15 21:42:52 +00001863 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
Richard Smithdafff942012-01-14 04:30:29 +00001864 case APValue::ComplexInt: {
1865 llvm::Constant *Complex[2];
1866
John McCallde0fe072017-08-15 21:42:52 +00001867 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001868 Value.getComplexIntReal());
John McCallde0fe072017-08-15 21:42:52 +00001869 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001870 Value.getComplexIntImag());
1871
1872 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00001873 llvm::StructType *STy =
1874 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00001875 return llvm::ConstantStruct::get(STy, Complex);
1876 }
1877 case APValue::Float: {
1878 const llvm::APFloat &Init = Value.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001879 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
John McCallde0fe072017-08-15 21:42:52 +00001880 !CGM.getContext().getLangOpts().NativeHalfType &&
Akira Hatanaka502775a2017-12-09 00:02:37 +00001881 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
John McCallde0fe072017-08-15 21:42:52 +00001882 return llvm::ConstantInt::get(CGM.getLLVMContext(),
1883 Init.bitcastToAPInt());
Richard Smithdafff942012-01-14 04:30:29 +00001884 else
John McCallde0fe072017-08-15 21:42:52 +00001885 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
Richard Smithdafff942012-01-14 04:30:29 +00001886 }
1887 case APValue::ComplexFloat: {
1888 llvm::Constant *Complex[2];
1889
John McCallde0fe072017-08-15 21:42:52 +00001890 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001891 Value.getComplexFloatReal());
John McCallde0fe072017-08-15 21:42:52 +00001892 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00001893 Value.getComplexFloatImag());
1894
1895 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00001896 llvm::StructType *STy =
1897 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00001898 return llvm::ConstantStruct::get(STy, Complex);
1899 }
1900 case APValue::Vector: {
Richard Smithdafff942012-01-14 04:30:29 +00001901 unsigned NumElts = Value.getVectorLength();
George Burgess IV533ff002015-12-11 00:23:35 +00001902 SmallVector<llvm::Constant *, 4> Inits(NumElts);
Richard Smithdafff942012-01-14 04:30:29 +00001903
George Burgess IV533ff002015-12-11 00:23:35 +00001904 for (unsigned I = 0; I != NumElts; ++I) {
1905 const APValue &Elt = Value.getVectorElt(I);
Richard Smithdafff942012-01-14 04:30:29 +00001906 if (Elt.isInt())
John McCallde0fe072017-08-15 21:42:52 +00001907 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
George Burgess IV533ff002015-12-11 00:23:35 +00001908 else if (Elt.isFloat())
John McCallde0fe072017-08-15 21:42:52 +00001909 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
Richard Smithdafff942012-01-14 04:30:29 +00001910 else
George Burgess IV533ff002015-12-11 00:23:35 +00001911 llvm_unreachable("unsupported vector element type");
Richard Smithdafff942012-01-14 04:30:29 +00001912 }
1913 return llvm::ConstantVector::get(Inits);
1914 }
1915 case APValue::AddrLabelDiff: {
1916 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
1917 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
John McCallde0fe072017-08-15 21:42:52 +00001918 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
1919 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
1920 if (!LHS || !RHS) return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00001921
1922 // Compute difference
John McCallde0fe072017-08-15 21:42:52 +00001923 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
1924 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
1925 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
Richard Smithdafff942012-01-14 04:30:29 +00001926 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
1927
1928 // LLVM is a bit sensitive about the exact format of the
1929 // address-of-label difference; make sure to truncate after
1930 // the subtraction.
1931 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
1932 }
1933 case APValue::Struct:
1934 case APValue::Union:
John McCallde0fe072017-08-15 21:42:52 +00001935 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00001936 case APValue::Array: {
Richard Smith3e268632018-05-23 23:41:38 +00001937 const ConstantArrayType *CAT =
1938 CGM.getContext().getAsConstantArrayType(DestType);
Richard Smithdafff942012-01-14 04:30:29 +00001939 unsigned NumElements = Value.getArraySize();
1940 unsigned NumInitElts = Value.getArrayInitializedElts();
1941
Richard Smithdafff942012-01-14 04:30:29 +00001942 // Emit array filler, if there is one.
Craig Topper8a13c412014-05-21 05:09:00 +00001943 llvm::Constant *Filler = nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00001944 if (Value.hasArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00001945 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
1946 CAT->getElementType());
Richard Smith3e268632018-05-23 23:41:38 +00001947 if (!Filler)
1948 return nullptr;
Hans Wennborg156349f2018-05-23 08:24:01 +00001949 }
David Majnemer90d85442014-12-28 23:46:59 +00001950
Richard Smith3e268632018-05-23 23:41:38 +00001951 // Emit initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00001952 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00001953 if (Filler && Filler->isNullValue())
1954 Elts.reserve(NumInitElts + 1);
1955 else
1956 Elts.reserve(NumElements);
1957
1958 llvm::Type *CommonElementType = nullptr;
1959 for (unsigned I = 0; I < NumInitElts; ++I) {
1960 llvm::Constant *C = tryEmitPrivateForMemory(
1961 Value.getArrayInitializedElt(I), CAT->getElementType());
John McCallde0fe072017-08-15 21:42:52 +00001962 if (!C) return nullptr;
1963
Richard Smithdafff942012-01-14 04:30:29 +00001964 if (I == 0)
1965 CommonElementType = C->getType();
1966 else if (C->getType() != CommonElementType)
Craig Topper8a13c412014-05-21 05:09:00 +00001967 CommonElementType = nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00001968 Elts.push_back(C);
1969 }
1970
Balaji V. Iyer749e8282018-08-08 00:01:21 +00001971 // This means that the array type is probably "IncompleteType" or some
1972 // type that is not ConstantArray.
1973 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
1974 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
1975 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
1976 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
1977 NumElements);
1978 return llvm::ConstantAggregateZero::get(AType);
1979 }
1980
Richard Smith3e268632018-05-23 23:41:38 +00001981 return EmitArrayConstant(CGM, CAT, CommonElementType, NumElements, Elts,
1982 Filler);
Richard Smithdafff942012-01-14 04:30:29 +00001983 }
1984 case APValue::MemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00001985 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00001986 }
1987 llvm_unreachable("Unknown APValue kind");
1988}
1989
George Burgess IV1a39b862016-12-28 07:27:40 +00001990llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
1991 const CompoundLiteralExpr *E) {
1992 return EmittedCompoundLiterals.lookup(E);
1993}
1994
1995void CodeGenModule::setAddrOfConstantCompoundLiteral(
1996 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
1997 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
1998 (void)Ok;
1999 assert(Ok && "CLE has already been emitted!");
2000}
2001
John McCall7f416cc2015-09-08 08:05:57 +00002002ConstantAddress
Richard Smith2d988f02011-11-22 22:48:32 +00002003CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2004 assert(E->isFileScope() && "not a file-scope compound literal expr");
John McCallde0fe072017-08-15 21:42:52 +00002005 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
Richard Smith2d988f02011-11-22 22:48:32 +00002006}
2007
John McCallf3a88602011-02-03 08:15:49 +00002008llvm::Constant *
2009CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2010 // Member pointer constants always have a very particular form.
2011 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2012 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2013
2014 // A member function pointer.
2015 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
David Majnemere2be95b2015-06-23 07:31:01 +00002016 return getCXXABI().EmitMemberFunctionPointer(method);
John McCallf3a88602011-02-03 08:15:49 +00002017
2018 // Otherwise, a member data pointer.
Richard Smithdafff942012-01-14 04:30:29 +00002019 uint64_t fieldOffset = getContext().getFieldOffset(decl);
John McCallf3a88602011-02-03 08:15:49 +00002020 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2021 return getCXXABI().EmitMemberDataPointer(type, chars);
2022}
2023
John McCall0217dfc22011-02-15 06:40:56 +00002024static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002025 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002026 const CXXRecordDecl *base);
2027
Anders Carlsson849ea412010-11-22 18:42:14 +00002028static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
Yaxun Liu402804b2016-12-15 08:09:08 +00002029 const RecordDecl *record,
John McCall0217dfc22011-02-15 06:40:56 +00002030 bool asCompleteObject) {
2031 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2192fe52011-07-18 04:24:23 +00002032 llvm::StructType *structure =
John McCall0217dfc22011-02-15 06:40:56 +00002033 (asCompleteObject ? layout.getLLVMType()
2034 : layout.getBaseSubobjectLLVMType());
Anders Carlsson849ea412010-11-22 18:42:14 +00002035
John McCall0217dfc22011-02-15 06:40:56 +00002036 unsigned numElements = structure->getNumElements();
2037 std::vector<llvm::Constant *> elements(numElements);
Anders Carlsson849ea412010-11-22 18:42:14 +00002038
Yaxun Liu402804b2016-12-15 08:09:08 +00002039 auto CXXR = dyn_cast<CXXRecordDecl>(record);
John McCall0217dfc22011-02-15 06:40:56 +00002040 // Fill in all the bases.
Yaxun Liu402804b2016-12-15 08:09:08 +00002041 if (CXXR) {
2042 for (const auto &I : CXXR->bases()) {
2043 if (I.isVirtual()) {
2044 // Ignore virtual bases; if we're laying out for a complete
2045 // object, we'll lay these out later.
2046 continue;
2047 }
2048
2049 const CXXRecordDecl *base =
2050 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2051
2052 // Ignore empty bases.
2053 if (base->isEmpty() ||
2054 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2055 .isZero())
2056 continue;
2057
2058 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2059 llvm::Type *baseType = structure->getElementType(fieldIndex);
2060 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlsson849ea412010-11-22 18:42:14 +00002061 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002062 }
2063
John McCall0217dfc22011-02-15 06:40:56 +00002064 // Fill in all the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002065 for (const auto *Field : record->fields()) {
Eli Friedmandae858a2011-12-07 01:30:11 +00002066 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2067 // will fill in later.)
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002068 if (!Field->isBitField()) {
2069 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2070 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
Eli Friedmandae858a2011-12-07 01:30:11 +00002071 }
2072
2073 // For unions, stop after the first named field.
David Majnemer4e51dfc2015-05-30 09:12:07 +00002074 if (record->isUnion()) {
2075 if (Field->getIdentifier())
2076 break;
George Karpenkov39e51372018-07-28 02:16:13 +00002077 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
David Majnemer4e51dfc2015-05-30 09:12:07 +00002078 if (FieldRD->findFirstNamedDataMember())
2079 break;
2080 }
John McCall0217dfc22011-02-15 06:40:56 +00002081 }
2082
2083 // Fill in the virtual bases, if we're working with the complete object.
Yaxun Liu402804b2016-12-15 08:09:08 +00002084 if (CXXR && asCompleteObject) {
2085 for (const auto &I : CXXR->vbases()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002086 const CXXRecordDecl *base =
Aaron Ballman445a9392014-03-13 16:15:17 +00002087 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
John McCall0217dfc22011-02-15 06:40:56 +00002088
2089 // Ignore empty bases.
2090 if (base->isEmpty())
2091 continue;
2092
2093 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2094
2095 // We might have already laid this field out.
2096 if (elements[fieldIndex]) continue;
2097
Chris Lattner2192fe52011-07-18 04:24:23 +00002098 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall0217dfc22011-02-15 06:40:56 +00002099 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2100 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002101 }
2102
2103 // Now go through all other fields and zero them out.
John McCall0217dfc22011-02-15 06:40:56 +00002104 for (unsigned i = 0; i != numElements; ++i) {
2105 if (!elements[i])
2106 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlsson849ea412010-11-22 18:42:14 +00002107 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002108
John McCall0217dfc22011-02-15 06:40:56 +00002109 return llvm::ConstantStruct::get(structure, elements);
2110}
2111
2112/// Emit the null constant for a base subobject.
2113static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002114 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002115 const CXXRecordDecl *base) {
2116 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2117
2118 // Just zero out bases that don't have any pointer to data members.
2119 if (baseLayout.isZeroInitializableAsBase())
2120 return llvm::Constant::getNullValue(baseType);
2121
David Majnemer2213bfe2014-10-17 01:00:43 +00002122 // Otherwise, we can just use its null constant.
2123 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
Anders Carlsson849ea412010-11-22 18:42:14 +00002124}
2125
John McCallde0fe072017-08-15 21:42:52 +00002126llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2127 QualType T) {
2128 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2129}
2130
Eli Friedman20bb5e02009-04-13 21:47:26 +00002131llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
Yaxun Liu402804b2016-12-15 08:09:08 +00002132 if (T->getAs<PointerType>())
2133 return getNullPointer(
2134 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2135
John McCall614dbdc2010-08-22 21:01:12 +00002136 if (getTypes().isZeroInitializable(T))
Anders Carlsson867b48f2009-08-24 17:16:23 +00002137 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Fangrui Song6907ce22018-07-30 19:24:48 +00002138
Anders Carlssonf48123b2009-08-09 18:26:27 +00002139 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Chris Lattner72977a12012-02-06 22:00:56 +00002140 llvm::ArrayType *ATy =
2141 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
Mike Stump11289f42009-09-09 15:08:12 +00002142
Anders Carlssonf48123b2009-08-09 18:26:27 +00002143 QualType ElementTy = CAT->getElementType();
2144
John McCallde0fe072017-08-15 21:42:52 +00002145 llvm::Constant *Element =
2146 ConstantEmitter::emitNullForMemory(*this, ElementTy);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002147 unsigned NumElements = CAT->getSize().getZExtValue();
Chris Lattner72977a12012-02-06 22:00:56 +00002148 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002149 return llvm::ConstantArray::get(ATy, Array);
Anders Carlssonf48123b2009-08-09 18:26:27 +00002150 }
Anders Carlssond606de72009-08-23 01:25:01 +00002151
Yaxun Liu402804b2016-12-15 08:09:08 +00002152 if (const RecordType *RT = T->getAs<RecordType>())
2153 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002154
David Majnemer5fd33e02015-04-24 01:25:08 +00002155 assert(T->isMemberDataPointerType() &&
Anders Carlssone8bfe412010-02-02 05:17:25 +00002156 "Should only see pointers to data members here!");
David Majnemer2213bfe2014-10-17 01:00:43 +00002157
John McCallf3a88602011-02-03 08:15:49 +00002158 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman20bb5e02009-04-13 21:47:26 +00002159}
Eli Friedmanfde961d2011-10-14 02:27:24 +00002160
2161llvm::Constant *
2162CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2163 return ::EmitNullConstant(*this, Record, false);
2164}