-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwnt_ArrayLiteral.cpp
491 lines (402 loc) · 14.1 KB
/
wnt_ArrayLiteral.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
/*=====================================================================
wnt_ArrayLiteral.cpp
--------------------
Copyright Glare Technologies Limited 2015 -
=====================================================================*/
#include "wnt_ArrayLiteral.h"
#include "wnt_ASTNode.h"
#include "wnt_SourceBuffer.h"
#include "wnt_RefCounting.h"
#include "VMState.h"
#include "Value.h"
#include "Linker.h"
#include "BuiltInFunctionImpl.h"
#include "LLVMUtils.h"
#include "LLVMTypeUtils.h"
#include "ProofUtils.h"
#include "utils/StringUtils.h"
#include "maths/mathstypes.h"
#ifdef _MSC_VER // If compiling with Visual C++
#pragma warning(push, 0) // Disable warnings
#endif
#include "llvm/IR/Type.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Instructions.h"
#include "llvm/ExecutionEngine/Interpreter.h"
#include "llvm/ExecutionEngine/GenericValue.h"
#include "llvm/Support/raw_ostream.h"
#include <llvm/IR/CallingConv.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/Intrinsics.h>
#ifdef _MSC_VER
#pragma warning(pop) // Re-enable warnings
#endif
using std::vector;
using std::string;
namespace Winter
{
ArrayLiteral::ArrayLiteral(const std::vector<ASTNodeRef>& elems, const SrcLocation& loc, bool has_int_suffix_, int int_suffix_)
: ASTNode(ArrayLiteralType, loc),
elements(elems),
has_int_suffix(has_int_suffix_),
int_suffix(int_suffix_)
{
if(has_int_suffix && int_suffix <= 0)
throw ExceptionWithPosition("Array literal int suffix must be > 0.", errorContext(*this));
if(has_int_suffix && elems.size() != 1)
throw ExceptionWithPosition("Array literal with int suffix must have only one explicit elem.", errorContext(*this));
if(elems.empty())
throw ExceptionWithPosition("Array literal can't be empty.", errorContext(*this));
}
TypeRef ArrayLiteral::type() const
{
// if Array literal contains a yet-unbound function, then the type is not known yet and will be NULL.
const TypeRef e0_type = elements[0]->type();
if(e0_type.isNull()) return NULL;
TypeRef array_type;
if(has_int_suffix)
array_type = new ArrayType(TypeVRef(e0_type), this->int_suffix);
else
array_type = new ArrayType(TypeVRef(e0_type), elements.size());
array_type->address_space = "__constant";
return array_type;
}
ValueRef ArrayLiteral::exec(VMState& vmstate)
{
if(has_int_suffix)
{
ValueRef v = this->elements[0]->exec(vmstate);
vector<ValueRef> elem_values(int_suffix, v);
return new ArrayValue(elem_values);
}
else
{
vector<ValueRef> elem_values(elements.size());
for(unsigned int i=0; i<this->elements.size(); ++i)
elem_values[i] = this->elements[i]->exec(vmstate);
return new ArrayValue(elem_values);
}
}
void ArrayLiteral::print(int depth, std::ostream& s) const
{
printMargin(depth, s);
s << "Array literal\n";
for(unsigned int i=0; i<this->elements.size(); ++i)
{
this->elements[i]->print(depth + 1, s);
}
}
std::string ArrayLiteral::sourceString(int depth) const
{
std::string s = "[";
for(size_t i=0; i<elements.size(); ++i)
{
s += elements[i]->sourceString(depth);
if(i + 1 < elements.size())
s += ", ";
}
s += "]a";
return s;
}
std::string ArrayLiteral::emitOpenCLC(EmitOpenCLCodeParams& params) const
{
// Work out which type this is
/*Type::TypeType type;
for(size_t i=0; i<this->elements.size(); ++i)
{
if(this->elements[i]->nodeType() == ASTNode::FloatLiteralType)
{
type = Type::FloatType;
break;
}
else if(this->elements[i]->nodeType() == ASTNode::IntLiteralType)
{
type = Type::IntType;
// don't break, keep going to see if we hit a float literal.
}
}*/
TypeRef this_type = this->type();
assert(this_type->getType() == Type::ArrayTypeType);
ArrayType* array_type = static_cast<ArrayType*>(this_type.getPointer());
std::string s = "__constant ";
if(array_type->elem_type->getType() == Type::FloatType)
s += "float ";
else if(array_type->elem_type->getType() == Type::IntType)
s += "int ";
else
throw ExceptionWithPosition("Array literal must be of int or float type for OpenCL emission currently.", errorContext(this));
const std::string name = "array_literal_" + toString(params.uid++);
s += name + "[] = {";
for(size_t i=0; i<this->elements.size(); ++i)
{
s += this->elements[i]->emitOpenCLC(params);
if(i + 1 < this->elements.size())
s += ", ";
}
s += "};\n";
params.file_scope_code += s;
return name;
}
// See NamedConstant::emitOpenCLC()
std::string ArrayLiteral::getFileScopeOpenCLC(EmitOpenCLCodeParams& params, const std::string& varname) const
{
TypeRef this_type = this->type();
assert(this_type->getType() == Type::ArrayTypeType);
ArrayType* array_type = static_cast<ArrayType*>(this_type.getPointer());
std::string s = "__constant ";
if(array_type->elem_type->getType() == Type::FloatType)
s += "float ";
else if(array_type->elem_type->getType() == Type::IntType)
s += "int ";
else
throw ExceptionWithPosition("Array literal must be of int or float type for OpenCL emission currently.", errorContext(this));
const std::string name = varname;
s += name + "[] = {";
for(size_t i=0; i<this->elements.size(); ++i)
{
s += this->elements[i]->emitOpenCLC(params);
if(i + 1 < this->elements.size())
s += ", ";
}
s += "};\n";
return s;
}
void ArrayLiteral::traverse(TraversalPayload& payload, std::vector<ASTNode*>& stack)
{
/*if(payload.operation == TraversalPayload::ConstantFolding)
{
for(size_t i=0; i<elements.size(); ++i)
checkFoldExpression(elements[i], payload);
}
else */
stack.push_back(this);
for(unsigned int i=0; i<this->elements.size(); ++i)
{
this->elements[i]->traverse(payload, stack);
}
stack.pop_back();
if(payload.operation == TraversalPayload::TypeCheck)
{
// Check all the element expression types match the computed element type.
const TypeRef elem_type = this->elements[0]->type();
for(unsigned int i=0; i<this->elements.size(); ++i)
if(*elem_type != *this->elements[i]->type())
throw ExceptionWithPosition("Array element " + ::toString(i) + " did not have required type " + elem_type->toString() + ".",
errorContext(*this, payload));
}
else if(payload.operation == TraversalPayload::ComputeCanConstantFold)
{
/*this->can_constant_fold = true;
for(size_t i=0; i<elements.size(); ++i)
can_constant_fold = can_constant_fold && elements[i]->can_constant_fold;
this->can_constant_fold = this->can_constant_fold && expressionIsWellTyped(*this, payload);*/
this->can_maybe_constant_fold = true;
for(size_t i=0; i<elements.size(); ++i)
{
const bool elem_is_literal = checkFoldExpression(elements[i], payload, stack);
this->can_maybe_constant_fold = this->can_maybe_constant_fold && elem_is_literal;
}
}
}
void ArrayLiteral::updateChild(const ASTNode* old_val, ASTNodeRef& new_val)
{
for(size_t i=0; i<this->elements.size(); ++i)
if(this->elements[i].ptr() == old_val)
{
this->elements[i] = new_val;
return;
}
assert(0);
}
static bool areAllElementsIntLiterals(const std::vector<ASTNodeRef>& elements)
{
for(size_t i=0; i<elements.size(); ++i)
if(elements[i]->nodeType() != ASTNode::IntLiteralType)
return false;
return true;
}
static bool areAllElementsFloatLiterals(const std::vector<ASTNodeRef>& elements)
{
for(size_t i=0; i<elements.size(); ++i)
if(elements[i]->nodeType() != ASTNode::FloatLiteralType)
return false;
return true;
}
static bool areAllElementsDoubleLiterals(const std::vector<ASTNodeRef>& elements)
{
for(size_t i=0; i<elements.size(); ++i)
if(elements[i]->nodeType() != ASTNode::DoubleLiteralType)
return false;
return true;
}
llvm::Value* ArrayLiteral::emitLLVMCode(EmitLLVMCodeParams& params, llvm::Value* ret_space_ptr) const
{
//if(!ret_space_ptr)
//{
// Check if all elements in the array are literals, of a type that LLVM supports in constant global arrays. If so, use a constant global array.
// TODO: can probably allow more types here.
if(areAllElementsIntLiterals(this->elements) || areAllElementsFloatLiterals(this->elements) || areAllElementsDoubleLiterals(this->elements))
{
vector<llvm::Constant*> array_llvm_values;
if(has_int_suffix)
{
llvm::Value* element_0_value = this->elements[0]->emitLLVMCode(params);
if(!llvm::isa<llvm::Constant>(element_0_value))
throw ExceptionWithPosition("Internal error: expected constant.", errorContext(this));
array_llvm_values.resize(int_suffix);
for(int i=0; i<int_suffix; ++i)
array_llvm_values[i] = static_cast<llvm::Constant*>(element_0_value);
}
else
{
array_llvm_values.resize(elements.size());
for(size_t i=0; i<elements.size(); ++i)
{
llvm::Value* element_value = this->elements[i]->emitLLVMCode(params);
if(!llvm::isa<llvm::Constant>(element_value))
throw ExceptionWithPosition("Internal error: expected constant.", errorContext(this));
array_llvm_values[i] = static_cast<llvm::Constant*>(element_value);
}
}
assert(this->type()->LLVMType(*params.module)->isArrayTy());
llvm::GlobalVariable* global = new llvm::GlobalVariable(
*params.module,
this->type()->LLVMType(*params.module), // This type (array type)
true, // is constant
llvm::GlobalVariable::PrivateLinkage, // llvm::GlobalVariable::InternalLinkage,
llvm::ConstantArray::get(
(llvm::ArrayType*)this->type()->LLVMType(*params.module),
array_llvm_values
)
);
global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); // Mark as unnamed_addr - this means the address is not significant, so multiple arrays with the same contents can be combined.
return global;
}
llvm::Value* array_addr;
if(ret_space_ptr)
array_addr = ret_space_ptr;
else
{
// Allocate space on stack for array
// Emit the alloca in the entry block for better code-gen.
// We will emit the alloca at the start of the block, so that it doesn't go after any terminator instructions already created which have to be at the end of the block.
llvm::IRBuilder<> entry_block_builder(¶ms.currently_building_func->getEntryBlock(), params.currently_building_func->getEntryBlock().getFirstInsertionPt());
array_addr = entry_block_builder.CreateAlloca(
this->type()->LLVMType(*params.module), // This type (array type)
llvm::ConstantInt::get(*params.context, llvm::APInt(32, 1, true)), // num elems
//this->elements[0]->type()->LLVMType(*params.context),
//llvm::ConstantInt::get(*params.context, llvm::APInt(32, this->elements.size(), true)), // num elems
"Array literal space"
);
}
llvm::Type* array_llvm_type = this->type()->LLVMType(*params.module);
// For each element in the literal
if(has_int_suffix)
{
// NOTE: could optimise this more (share value etc..)
for(int i=0; i<int_suffix; ++i)
{
llvm::Value* indices[] = {
llvm::ConstantInt::get(*params.context, llvm::APInt(64, 0)), // get the zero-th array
llvm::ConstantInt::get(*params.context, llvm::APInt(64, i)) // get the i-th element in the array
};
llvm::Value* element_ptr = LLVMUtils::createInBoundsGEP(*params.builder, array_addr, array_llvm_type, indices);
if(this->elements[0]->type()->passByValue())
{
llvm::Value* element_value = this->elements[0]->emitLLVMCode(params);
// Store the element in the array
params.builder->CreateStore(
element_value, // value
element_ptr // ptr
);
}
else
{
// Element is pass-by-pointer, for example a structure.
// So just emit code that will store it directly in the array.
this->elements[0]->emitLLVMCode(params, element_ptr);
}
}
}
else
{
for(unsigned int i=0; i<this->elements.size(); ++i)
{
llvm::Value* indices[] = {
llvm::ConstantInt::get(*params.context, llvm::APInt(64, 0)), // get the zero-th array
llvm::ConstantInt::get(*params.context, llvm::APInt(64, i)) // get the i-th element in the array
};
llvm::Value* element_ptr = LLVMUtils::createInBoundsGEP(*params.builder, array_addr, array_llvm_type, indices);
if(this->elements[i]->type()->passByValue())
{
llvm::Value* element_value = this->elements[i]->emitLLVMCode(params);
// Store the element in the array
params.builder->CreateStore(
element_value, // value
element_ptr // ptr
);
}
else
{
// Element is pass-by-pointer, for example a structure.
// So just emit code that will store it directly in the array.
this->elements[i]->emitLLVMCode(params, element_ptr);
}
}
}
return array_addr;//NOTE: this correct?
}
Reference<ASTNode> ArrayLiteral::clone(CloneMapType& clone_map)
{
std::vector<ASTNodeRef> elems(this->elements.size());
for(size_t i=0; i<elements.size(); ++i)
elems[i] = this->elements[i]->clone(clone_map);
ArrayLiteral* a = new ArrayLiteral(elems, srcLocation(), has_int_suffix, int_suffix);
clone_map.insert(std::make_pair(this, a));
return a;
}
bool ArrayLiteral::isConstant() const
{
for(size_t i=0; i<elements.size(); ++i)
if(!elements[i]->isConstant())
return false;
return true;
}
size_t ArrayLiteral::getTimeBound(GetTimeBoundParams& params) const
{
if(has_int_suffix)
return elements[0]->getTimeBound(params) + int_suffix; // Time to compute elem 0 and then copy time.
else
{
size_t sum = 0;
for(size_t i=0; i<elements.size(); ++i)
sum += elements[i]->getTimeBound(params);
return sum;
}
}
GetSpaceBoundResults ArrayLiteral::getSpaceBound(GetSpaceBoundParams& params) const
{
// Compute space to compute the element values:
GetSpaceBoundResults sum(0, 0);
if(has_int_suffix)
{
sum += elements[0]->getSpaceBound(params);
}
else
{
for(size_t i=0; i<elements.size(); ++i)
sum += elements[i]->getSpaceBound(params);
}
//TEMP array is always stored on the stack currently, so no need to add heap space
return sum;
}
size_t ArrayLiteral::getSubtreeCodeComplexity() const
{
size_t sum = 0;
for(size_t i=0; i<elements.size(); ++i)
sum += elements[i]->getSubtreeCodeComplexity();
return sum;
}
} // end namespace Winter