-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpr.cpp
More file actions
5248 lines (4556 loc) · 180 KB
/
expr.cpp
File metadata and controls
5248 lines (4556 loc) · 180 KB
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2010-2011, Intel Corporation
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Intel Corporation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** @file expr.cpp
@brief Implementations of expression classes
*/
#include "expr.h"
#include "type.h"
#include "sym.h"
#include "ctx.h"
#include "module.h"
#include "util.h"
#include "llvmutil.h"
#include <list>
#include <set>
#include <stdio.h>
#include <llvm/Module.h>
#include <llvm/Function.h>
#include <llvm/Type.h>
#include <llvm/DerivedTypes.h>
#include <llvm/LLVMContext.h>
#include <llvm/Instructions.h>
#include <llvm/CallingConv.h>
#include <llvm/Target/TargetData.h>
#include <llvm/Support/IRBuilder.h>
#include <llvm/ExecutionEngine/GenericValue.h>
#include <llvm/Support/InstIterator.h>
/////////////////////////////////////////////////////////////////////////////////////
// Expr
llvm::Value *
Expr::GetLValue(FunctionEmitContext *ctx) const {
// Expressions that can't provide an lvalue can just return NULL
return NULL;
}
llvm::Constant *
Expr::GetConstant(const Type *type) const {
// The default is failure; just return NULL
return NULL;
}
Symbol *
Expr::GetBaseSymbol() const {
// Not all expressions can do this, so provide a generally-useful
// default
return NULL;
}
/** If a conversion from 'fromAtomicType' to 'toAtomicType' may cause lost
precision, issue a warning. Don't warn for conversions to bool and
conversions between signed and unsigned integers of the same size.
*/
static void
lMaybeIssuePrecisionWarning(const AtomicType *toAtomicType,
const AtomicType *fromAtomicType,
SourcePos pos, const char *errorMsgBase) {
switch (toAtomicType->basicType) {
case AtomicType::TYPE_BOOL:
case AtomicType::TYPE_INT8:
case AtomicType::TYPE_UINT8:
case AtomicType::TYPE_INT16:
case AtomicType::TYPE_UINT16:
case AtomicType::TYPE_INT32:
case AtomicType::TYPE_UINT32:
case AtomicType::TYPE_FLOAT:
case AtomicType::TYPE_INT64:
case AtomicType::TYPE_UINT64:
case AtomicType::TYPE_DOUBLE:
if ((int)toAtomicType->basicType < (int)fromAtomicType->basicType &&
toAtomicType->basicType != AtomicType::TYPE_BOOL &&
!(toAtomicType->basicType == AtomicType::TYPE_INT8 &&
fromAtomicType->basicType == AtomicType::TYPE_UINT8) &&
!(toAtomicType->basicType == AtomicType::TYPE_INT16 &&
fromAtomicType->basicType == AtomicType::TYPE_UINT16) &&
!(toAtomicType->basicType == AtomicType::TYPE_INT32 &&
fromAtomicType->basicType == AtomicType::TYPE_UINT32) &&
!(toAtomicType->basicType == AtomicType::TYPE_INT64 &&
fromAtomicType->basicType == AtomicType::TYPE_UINT64))
Warning(pos, "Conversion from type \"%s\" to type \"%s\" for %s"
" may lose information.",
fromAtomicType->GetString().c_str(), toAtomicType->GetString().c_str(),
errorMsgBase);
break;
default:
FATAL("logic error in lMaybeIssuePrecisionWarning()");
}
}
Expr *
Expr::TypeConv(const Type *toType, const char *errorMsgBase, bool failureOk,
bool issuePrecisionWarnings) {
/* This function is way too long and complex. Is type conversion stuff
always this messy, or can this be cleaned up somehow? */
assert(failureOk || errorMsgBase != NULL);
const Type *fromType = GetType();
if (toType == NULL || fromType == NULL)
return this;
// The types are equal; there's nothing to do
if (Type::Equal(toType, fromType))
return this;
if (fromType == AtomicType::Void) {
if (!failureOk)
Error(pos, "Can't convert from \"void\" to \"%s\" for %s.",
toType->GetString().c_str(), errorMsgBase);
return NULL;
}
if (toType == AtomicType::Void) {
if (!failureOk)
Error(pos, "Can't convert type \"%s\" to \"void\" for %s.",
fromType->GetString().c_str(), errorMsgBase);
return NULL;
}
if (toType->IsUniformType() && fromType->IsVaryingType()) {
if (!failureOk)
Error(pos, "Can't convert from varying type \"%s\" to uniform "
"type \"%s\" for %s.", fromType->GetString().c_str(),
toType->GetString().c_str(), errorMsgBase);
return NULL;
}
// Convert from type T -> const T; just return a TypeCast expr, which
// can handle this
if (Type::Equal(toType, fromType->GetAsConstType()))
return new TypeCastExpr(toType, this, pos);
if (dynamic_cast<const ReferenceType *>(fromType)) {
if (dynamic_cast<const ReferenceType *>(toType)) {
// Convert from a reference to a type to a const reference to a type;
// this is handled by TypeCastExpr
if (Type::Equal(toType->GetReferenceTarget(),
fromType->GetReferenceTarget()->GetAsConstType()))
return new TypeCastExpr(toType, this, pos);
const ArrayType *atFrom = dynamic_cast<const ArrayType *>(fromType->GetReferenceTarget());
const ArrayType *atTo = dynamic_cast<const ArrayType *>(toType->GetReferenceTarget());
if (atFrom != NULL && atTo != NULL &&
Type::Equal(atFrom->GetElementType(), atTo->GetElementType()))
return new TypeCastExpr(toType, this, pos);
else {
if (!failureOk)
Error(pos, "Can't convert between incompatible reference types \"%s\" "
"and \"%s\" for %s.", fromType->GetString().c_str(),
toType->GetString().c_str(), errorMsgBase);
return NULL;
}
}
else {
// convert from a reference T -> T
Expr *fromExpr = new DereferenceExpr(this, pos);
if (fromExpr->GetType() == NULL)
return NULL;
return fromExpr->TypeConv(toType, errorMsgBase, failureOk);
}
}
else if (dynamic_cast<const ReferenceType *>(toType)) {
// T -> reference T
Expr *fromExpr = new ReferenceExpr(this, pos);
if (fromExpr->GetType() == NULL)
return NULL;
return fromExpr->TypeConv(toType, errorMsgBase, failureOk);
}
else if (Type::Equal(toType, fromType->GetAsNonConstType()))
// convert: const T -> T (as long as T isn't a reference)
return new TypeCastExpr(toType, this, pos);
fromType = fromType->GetReferenceTarget();
toType = toType->GetReferenceTarget();
// I don't think this is necessary
//CO if (Type::Equal(toType, fromType))
//CO return fromExpr;
const ArrayType *toArrayType = dynamic_cast<const ArrayType *>(toType);
const ArrayType *fromArrayType = dynamic_cast<const ArrayType *>(fromType);
if (toArrayType && fromArrayType) {
if (Type::Equal(toArrayType->GetElementType(), fromArrayType->GetElementType())) {
// the case of different element counts should have returned
// out earlier, yes??
assert(toArrayType->GetElementCount() != fromArrayType->GetElementCount());
return new TypeCastExpr(new ReferenceType(toType, false), this, pos);
}
else if (Type::Equal(toArrayType->GetElementType(),
fromArrayType->GetElementType()->GetAsConstType())) {
// T[x] -> const T[x]
return new TypeCastExpr(new ReferenceType(toType, false), this, pos);
}
else {
if (!failureOk)
Error(pos, "Array type \"%s\" can't be converted to type \"%s\" for %s.",
fromType->GetString().c_str(), toType->GetString().c_str(),
errorMsgBase);
return NULL;
}
}
const VectorType *toVectorType = dynamic_cast<const VectorType *>(toType);
const VectorType *fromVectorType = dynamic_cast<const VectorType *>(fromType);
if (toVectorType && fromVectorType) {
// converting e.g. int<n> -> float<n>
if (fromVectorType->GetElementCount() != toVectorType->GetElementCount()) {
if (!failureOk)
Error(pos, "Can't convert between differently sized vector types "
"\"%s\" -> \"%s\" for %s.", fromType->GetString().c_str(),
toType->GetString().c_str(), errorMsgBase);
return NULL;
}
return new TypeCastExpr(toType, this, pos);
}
const StructType *toStructType = dynamic_cast<const StructType *>(toType);
const StructType *fromStructType = dynamic_cast<const StructType *>(fromType);
if (toStructType && fromStructType) {
if (!Type::Equal(toStructType->GetAsUniformType()->GetAsConstType(),
fromStructType->GetAsUniformType()->GetAsConstType())) {
if (!failureOk)
Error(pos, "Can't convert between different struct types "
"\"%s\" -> \"%s\".", fromStructType->GetString().c_str(),
toStructType->GetString().c_str());
return NULL;
}
return new TypeCastExpr(toType, this, pos);
}
const EnumType *toEnumType = dynamic_cast<const EnumType *>(toType);
const EnumType *fromEnumType = dynamic_cast<const EnumType *>(fromType);
if (toEnumType != NULL && fromEnumType != NULL) {
// No implicit conversions between different enum types
if (!Type::Equal(toEnumType->GetAsUniformType()->GetAsConstType(),
fromEnumType->GetAsUniformType()->GetAsConstType())) {
if (!failureOk)
Error(pos, "Can't convert between different enum types "
"\"%s\" -> \"%s\".", fromEnumType->GetString().c_str(),
toEnumType->GetString().c_str());
return NULL;
}
return new TypeCastExpr(toType, this, pos);
}
const AtomicType *toAtomicType = dynamic_cast<const AtomicType *>(toType);
const AtomicType *fromAtomicType = dynamic_cast<const AtomicType *>(fromType);
// enum -> atomic (integer, generally...) is always ok
if (fromEnumType != NULL) {
assert(toAtomicType != NULL || toVectorType != NULL);
return new TypeCastExpr(toType, this, pos);
}
// from here on out, the from type can only be atomic something or
// other...
if (fromAtomicType == NULL) {
if (!failureOk)
Error(pos, "Type conversion only possible from atomic types, not "
"from \"%s\" to \"%s\", for %s.", fromType->GetString().c_str(),
toType->GetString().c_str(), errorMsgBase);
return NULL;
}
// scalar -> short-vector conversions
if (toVectorType != NULL)
return new TypeCastExpr(toType, this, pos);
// ok, it better be a scalar->scalar conversion of some sort by now
if (toAtomicType == NULL) {
if (!failureOk)
Error(pos, "Type conversion only possible to atomic types, not "
"from \"%s\" to \"%s\", for %s.",
fromType->GetString().c_str(), toType->GetString().c_str(),
errorMsgBase);
return NULL;
}
if (!failureOk && issuePrecisionWarnings)
lMaybeIssuePrecisionWarning(toAtomicType, fromAtomicType, pos,
errorMsgBase);
return new TypeCastExpr(toType, this, pos);
}
///////////////////////////////////////////////////////////////////////////
/** Given an atomic or vector type, this returns a boolean type with the
same "shape". In other words, if the given type is a vector type of
three uniform ints, the returned type is a vector type of three uniform
bools. */
static const Type *
lMatchingBoolType(const Type *type) {
bool uniformTest = type->IsUniformType();
const AtomicType *boolBase = uniformTest ? AtomicType::UniformBool :
AtomicType::VaryingBool;
const VectorType *vt = dynamic_cast<const VectorType *>(type);
if (vt != NULL)
return new VectorType(boolBase, vt->GetElementCount());
else {
assert(dynamic_cast<const AtomicType *>(type) != NULL);
return boolBase;
}
}
///////////////////////////////////////////////////////////////////////////
// UnaryExpr
static llvm::Constant *
lLLVMConstantValue(const Type *type, llvm::LLVMContext *ctx, double value) {
const AtomicType *atomicType = dynamic_cast<const AtomicType *>(type);
const EnumType *enumType = dynamic_cast<const EnumType *>(type);
const VectorType *vectorType = dynamic_cast<const VectorType *>(type);
// This function is only called with, and only works for atomic, enum,
// and vector types.
assert(atomicType != NULL || enumType != NULL || vectorType != NULL);
if (atomicType != NULL || enumType != NULL) {
// If it's an atomic or enuemrator type, then figure out which of
// the llvmutil.h functions to call to get the corresponding
// constant and then call it...
bool isUniform = type->IsUniformType();
AtomicType::BasicType basicType = (enumType != NULL) ?
AtomicType::TYPE_UINT32 : atomicType->basicType;
switch (basicType) {
case AtomicType::TYPE_VOID:
FATAL("can't get constant value for void type");
return NULL;
case AtomicType::TYPE_BOOL:
if (isUniform)
return (value != 0.) ? LLVMTrue : LLVMFalse;
else
return LLVMBoolVector(value != 0.);
case AtomicType::TYPE_INT8: {
int i = (int)value;
assert((double)i == value);
return isUniform ? LLVMInt8(i) : LLVMInt8Vector(i);
}
case AtomicType::TYPE_UINT8: {
unsigned int i = (unsigned int)value;
return isUniform ? LLVMUInt8(i) : LLVMUInt8Vector(i);
}
case AtomicType::TYPE_INT16: {
int i = (int)value;
assert((double)i == value);
return isUniform ? LLVMInt16(i) : LLVMInt16Vector(i);
}
case AtomicType::TYPE_UINT16: {
unsigned int i = (unsigned int)value;
return isUniform ? LLVMUInt16(i) : LLVMUInt16Vector(i);
}
case AtomicType::TYPE_INT32: {
int i = (int)value;
assert((double)i == value);
return isUniform ? LLVMInt32(i) : LLVMInt32Vector(i);
}
case AtomicType::TYPE_UINT32: {
unsigned int i = (unsigned int)value;
return isUniform ? LLVMUInt32(i) : LLVMUInt32Vector(i);
}
case AtomicType::TYPE_FLOAT:
return isUniform ? LLVMFloat((float)value) :
LLVMFloatVector((float)value);
case AtomicType::TYPE_UINT64: {
uint64_t i = (uint64_t)value;
assert(value == (int64_t)i);
return isUniform ? LLVMUInt64(i) : LLVMUInt64Vector(i);
}
case AtomicType::TYPE_INT64: {
int64_t i = (int64_t)value;
assert((double)i == value);
return isUniform ? LLVMInt64(i) : LLVMInt64Vector(i);
}
case AtomicType::TYPE_DOUBLE:
return isUniform ? LLVMDouble(value) : LLVMDoubleVector(value);
default:
FATAL("logic error in lLLVMConstantValue");
return NULL;
}
}
// For vector types, first get the LLVM constant for the basetype with
// a recursive call to lLLVMConstantValue().
const Type *baseType = vectorType->GetBaseType();
llvm::Constant *constElement = lLLVMConstantValue(baseType, ctx, value);
LLVM_TYPE_CONST llvm::Type *llvmVectorType = vectorType->LLVMType(ctx);
// Now create a constant version of the corresponding LLVM type that we
// use to represent the VectorType.
// FIXME: this is a little ugly in that the fact that ispc represents
// uniform VectorTypes as LLVM VectorTypes and varying VectorTypes as
// LLVM ArrayTypes leaks into the code here; it feels like this detail
// should be better encapsulated?
if (baseType->IsUniformType()) {
LLVM_TYPE_CONST llvm::VectorType *lvt =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::VectorType>(llvmVectorType);
assert(lvt != NULL);
std::vector<llvm::Constant *> vals;
for (unsigned int i = 0; i < lvt->getNumElements(); ++i)
vals.push_back(constElement);
return llvm::ConstantVector::get(vals);
}
else {
LLVM_TYPE_CONST llvm::ArrayType *lat =
llvm::dyn_cast<LLVM_TYPE_CONST llvm::ArrayType>(llvmVectorType);
assert(lat != NULL);
std::vector<llvm::Constant *> vals;
for (unsigned int i = 0; i < lat->getNumElements(); ++i)
vals.push_back(constElement);
return llvm::ConstantArray::get(lat, vals);
}
}
/** Utility routine to emit code to do a {pre,post}-{inc,dec}rement of the
given expresion.
*/
static llvm::Value *
lEmitPrePostIncDec(UnaryExpr::Op op, Expr *expr, SourcePos pos,
FunctionEmitContext *ctx) {
const Type *type = expr->GetType();
// Get both the lvalue and the rvalue of the given expression
llvm::Value *lvalue = NULL, *rvalue = NULL;
if (dynamic_cast<const ReferenceType *>(type) != NULL) {
type = type->GetReferenceTarget();
lvalue = expr->GetValue(ctx);
Expr *deref = new DereferenceExpr(expr, expr->pos);
rvalue = deref->GetValue(ctx);
}
else {
lvalue = expr->GetLValue(ctx);
rvalue = expr->GetValue(ctx);
}
if (lvalue == NULL) {
// If we can't get a lvalue, then we have an error here
Error(expr->pos, "Can't %s-%s non-lvalues.",
(op == UnaryExpr::PreInc || op == UnaryExpr::PreDec) ? "pre" : "post",
(op == UnaryExpr::PreInc || op == UnaryExpr::PostInc) ? "increment" : "decrement");
return NULL;
}
// Emit code to do the appropriate addition/subtraction to the
// expression's old value
ctx->SetDebugPos(pos);
llvm::Value *binop = NULL;
int delta = (op == UnaryExpr::PreInc || op == UnaryExpr::PostInc) ? 1 : -1;
llvm::Constant *dval = lLLVMConstantValue(type, g->ctx, delta);
if (!type->IsFloatType())
binop = ctx->BinaryOperator(llvm::Instruction::Add, rvalue,
dval, "val_inc_or_dec");
else
binop = ctx->BinaryOperator(llvm::Instruction::FAdd, rvalue,
dval, "val_inc_or_dec");
#if 0
if (type->IsUniformType()) {
if (ctx->VaryingCFDepth() > 0)
Warning(expr->pos,
"Modifying \"uniform\" value under \"varying\" control flow. Beware.");
}
#endif
// And store the result out to the lvalue
ctx->StoreInst(binop, lvalue, ctx->GetMask(), type);
// And then if it's a pre increment/decrement, return the final
// computed result; otherwise return the previously-grabbed expression
// value.
return (op == UnaryExpr::PreInc || op == UnaryExpr::PreDec) ? binop : rvalue;
}
/** Utility routine to emit code to negate the given expression.
*/
static llvm::Value *
lEmitNegate(Expr *arg, SourcePos pos, FunctionEmitContext *ctx) {
const Type *type = arg->GetType();
llvm::Value *argVal = arg->GetValue(ctx);
if (type == NULL || argVal == NULL)
return NULL;
// Negate by subtracting from zero...
llvm::Value *zero = lLLVMConstantValue(type, g->ctx, 0.);
ctx->SetDebugPos(pos);
if (type->IsFloatType())
return ctx->BinaryOperator(llvm::Instruction::FSub, zero, argVal, "fnegate");
else {
assert(type->IsIntType());
return ctx->BinaryOperator(llvm::Instruction::Sub, zero, argVal, "inegate");
}
}
UnaryExpr::UnaryExpr(Op o, Expr *e, SourcePos p)
: Expr(p), op(o) {
expr = e;
}
llvm::Value *
UnaryExpr::GetValue(FunctionEmitContext *ctx) const {
if (expr == NULL)
return NULL;
ctx->SetDebugPos(pos);
switch (op) {
case PreInc:
case PreDec:
case PostInc:
case PostDec:
return lEmitPrePostIncDec(op, expr, pos, ctx);
case Negate:
return lEmitNegate(expr, pos, ctx);
case LogicalNot: {
llvm::Value *argVal = expr->GetValue(ctx);
return ctx->NotOperator(argVal, "logicalnot");
}
case BitNot: {
llvm::Value *argVal = expr->GetValue(ctx);
return ctx->NotOperator(argVal, "bitnot");
}
default:
FATAL("logic error");
return NULL;
}
}
const Type *
UnaryExpr::GetType() const {
if (expr == NULL)
return NULL;
const Type *type = expr->GetType();
if (type == NULL)
return NULL;
// For all unary expressions besides logical not, the returned type is
// the same as the source type. Logical not always returns a bool
// type, with the same shape as the input type.
switch (op) {
case PreInc:
case PreDec:
case PostInc:
case PostDec:
case Negate:
case BitNot:
return type;
case LogicalNot:
return lMatchingBoolType(type);
default:
FATAL("error");
return NULL;
}
}
Expr *
UnaryExpr::Optimize() {
if (!expr)
return NULL;
expr = expr->Optimize();
ConstExpr *constExpr = dynamic_cast<ConstExpr *>(expr);
// If the operand isn't a constant, then we can't do any optimization
// here...
if (constExpr == NULL)
return this;
const Type *type = constExpr->GetType();
bool isEnumType = dynamic_cast<const EnumType *>(type) != NULL;
const Type *baseType = type->GetAsNonConstType()->GetAsUniformType();
if (baseType == AtomicType::UniformInt8 ||
baseType == AtomicType::UniformUInt8 ||
baseType == AtomicType::UniformInt16 ||
baseType == AtomicType::UniformUInt16 ||
baseType == AtomicType::UniformInt64 ||
baseType == AtomicType::UniformUInt64)
// FIXME: should handle these at some point; for now we only do
// constant folding for bool, int32 and float types...
return this;
switch (op) {
case PreInc:
case PreDec:
case PostInc:
case PostDec:
// this shouldn't happen--it's illegal to modify a contant value..
// An error will be issued elsewhere...
return this;
case Negate: {
// Since we currently only handle int32 and floats here, it's safe
// to stuff whatever we have into a double, do the negate as a
// double, and then return a ConstExpr with the same type as the
// original...
double v[ISPC_MAX_NVEC];
int count = constExpr->AsDouble(v);
for (int i = 0; i < count; ++i)
v[i] = -v[i];
return new ConstExpr(constExpr, v);
}
case BitNot: {
if (type == AtomicType::UniformInt32 ||
type == AtomicType::VaryingInt32 ||
type == AtomicType::UniformConstInt32 ||
type == AtomicType::VaryingConstInt32) {
int32_t v[ISPC_MAX_NVEC];
int count = constExpr->AsInt32(v);
for (int i = 0; i < count; ++i)
v[i] = ~v[i];
return new ConstExpr(type, v, pos);
}
else if (type == AtomicType::UniformUInt32 ||
type == AtomicType::VaryingUInt32 ||
type == AtomicType::UniformConstUInt32 ||
type == AtomicType::VaryingConstUInt32 ||
isEnumType == true) {
uint32_t v[ISPC_MAX_NVEC];
int count = constExpr->AsUInt32(v);
for (int i = 0; i < count; ++i)
v[i] = ~v[i];
return new ConstExpr(type, v, pos);
}
else
FATAL("unexpected type in UnaryExpr::Optimize() / BitNot case");
}
case LogicalNot: {
assert(type == AtomicType::UniformBool ||
type == AtomicType::VaryingBool ||
type == AtomicType::UniformConstBool ||
type == AtomicType::VaryingConstBool);
bool v[ISPC_MAX_NVEC];
int count = constExpr->AsBool(v);
for (int i = 0; i < count; ++i)
v[i] = !v[i];
return new ConstExpr(type, v, pos);
}
default:
FATAL("unexpected op in UnaryExpr::Optimize()");
return NULL;
}
}
Expr *
UnaryExpr::TypeCheck() {
if (expr != NULL)
expr = expr->TypeCheck();
if (expr == NULL)
// something went wrong in type checking...
return NULL;
const Type *type = expr->GetType();
if (type == NULL)
return NULL;
if (op == PreInc || op == PreDec || op == PostInc || op == PostDec) {
if (!type->IsNumericType()) {
Error(expr->pos, "Can only pre/post increment float and integer "
"types, not \"%s\".", type->GetString().c_str());
return NULL;
}
return this;
}
// don't do this for pre/post increment/decrement
if (dynamic_cast<const ReferenceType *>(type)) {
expr = new DereferenceExpr(expr, pos);
type = expr->GetType();
}
if (op == Negate) {
if (!type->IsNumericType()) {
Error(expr->pos, "Negate not allowed for non-numeric type \"%s\".",
type->GetString().c_str());
return NULL;
}
}
else if (op == LogicalNot) {
const Type *boolType = lMatchingBoolType(type);
expr = expr->TypeConv(boolType, "logical not");
if (!expr)
return NULL;
}
else if (op == BitNot) {
if (!type->IsIntType()) {
Error(expr->pos, "~ operator can only be used with integer types, "
"not \"%s\".", type->GetString().c_str());
return NULL;
}
}
return this;
}
void
UnaryExpr::Print() const {
if (!expr || !GetType())
return;
printf("[ %s ] (", GetType()->GetString().c_str());
if (op == PreInc) printf("++");
if (op == PreDec) printf("--");
if (op == Negate) printf("-");
if (op == LogicalNot) printf("!");
if (op == BitNot) printf("~");
printf("(");
expr->Print();
printf(")");
if (op == PostInc) printf("++");
if (op == PostDec) printf("--");
printf(")");
pos.Print();
}
///////////////////////////////////////////////////////////////////////////
// BinaryExpr
static const char *
lOpString(BinaryExpr::Op op) {
switch (op) {
case BinaryExpr::Add: return "+";
case BinaryExpr::Sub: return "-";
case BinaryExpr::Mul: return "*";
case BinaryExpr::Div: return "/";
case BinaryExpr::Mod: return "%";
case BinaryExpr::Shl: return "<<";
case BinaryExpr::Shr: return ">>";
case BinaryExpr::Lt: return "<";
case BinaryExpr::Gt: return ">";
case BinaryExpr::Le: return "<=";
case BinaryExpr::Ge: return ">=";
case BinaryExpr::Equal: return "==";
case BinaryExpr::NotEqual: return "!=";
case BinaryExpr::BitAnd: return "&";
case BinaryExpr::BitXor: return "^";
case BinaryExpr::BitOr: return "|";
case BinaryExpr::LogicalAnd: return "&&";
case BinaryExpr::LogicalOr: return "||";
case BinaryExpr::Comma: return ",";
default:
FATAL("unimplemented case in lOpString()");
return "";
}
}
/** Utility routine to emit the binary bitwise operator corresponding to
the given BinaryExpr::Op.
*/
static llvm::Value *
lEmitBinaryBitOp(BinaryExpr::Op op, llvm::Value *arg0Val,
llvm::Value *arg1Val, FunctionEmitContext *ctx) {
llvm::Instruction::BinaryOps inst;
switch (op) {
case BinaryExpr::Shl: inst = llvm::Instruction::Shl; break;
case BinaryExpr::Shr: inst = llvm::Instruction::AShr; break;
case BinaryExpr::BitAnd: inst = llvm::Instruction::And; break;
case BinaryExpr::BitXor: inst = llvm::Instruction::Xor; break;
case BinaryExpr::BitOr: inst = llvm::Instruction::Or; break;
default:
FATAL("logic error in lEmitBinaryBitOp()");
return NULL;
}
return ctx->BinaryOperator(inst, arg0Val, arg1Val, "bitop");
}
/** Utility routine to emit binary arithmetic operator based on the given
BinaryExpr::Op.
*/
static llvm::Value *
lEmitBinaryArith(BinaryExpr::Op op, llvm::Value *e0Val, llvm::Value *e1Val,
const Type *type, FunctionEmitContext *ctx, SourcePos pos) {
llvm::Instruction::BinaryOps inst;
bool isFloatOp = type->IsFloatType();
bool isUnsignedOp = type->IsUnsignedType();
switch (op) {
case BinaryExpr::Add:
inst = isFloatOp ? llvm::Instruction::FAdd : llvm::Instruction::Add;
break;
case BinaryExpr::Sub:
inst = isFloatOp ? llvm::Instruction::FSub : llvm::Instruction::Sub;
break;
case BinaryExpr::Mul:
inst = isFloatOp ? llvm::Instruction::FMul : llvm::Instruction::Mul;
break;
case BinaryExpr::Div:
if (type->IsVaryingType() && !isFloatOp)
PerformanceWarning(pos, "Division with varying integer types is "
"very inefficient.");
inst = isFloatOp ? llvm::Instruction::FDiv :
(isUnsignedOp ? llvm::Instruction::UDiv : llvm::Instruction::SDiv);
break;
case BinaryExpr::Mod:
if (type->IsVaryingType() && !isFloatOp)
PerformanceWarning(pos, "Modulus operator with varying types is "
"very inefficient.");
inst = isFloatOp ? llvm::Instruction::FRem :
(isUnsignedOp ? llvm::Instruction::URem : llvm::Instruction::SRem);
break;
default:
FATAL("Invalid op type passed to lEmitBinaryArith()");
return NULL;
}
return ctx->BinaryOperator(inst, e0Val, e1Val, "binop");
}
/** Utility routine to emit a binary comparison operator based on the given
BinaryExpr::Op.
*/
static llvm::Value *
lEmitBinaryCmp(BinaryExpr::Op op, llvm::Value *e0Val, llvm::Value *e1Val,
const Type *type, FunctionEmitContext *ctx, SourcePos pos) {
bool isFloatOp = type->IsFloatType();
bool isUnsignedOp = type->IsUnsignedType();
llvm::CmpInst::Predicate pred;
switch (op) {
case BinaryExpr::Lt:
pred = isFloatOp ? llvm::CmpInst::FCMP_OLT :
(isUnsignedOp ? llvm::CmpInst::ICMP_ULT : llvm::CmpInst::ICMP_SLT);
break;
case BinaryExpr::Gt:
pred = isFloatOp ? llvm::CmpInst::FCMP_OGT :
(isUnsignedOp ? llvm::CmpInst::ICMP_UGT : llvm::CmpInst::ICMP_SGT);
break;
case BinaryExpr::Le:
pred = isFloatOp ? llvm::CmpInst::FCMP_OLE :
(isUnsignedOp ? llvm::CmpInst::ICMP_ULE : llvm::CmpInst::ICMP_SLE);
break;
case BinaryExpr::Ge:
pred = isFloatOp ? llvm::CmpInst::FCMP_OGE :
(isUnsignedOp ? llvm::CmpInst::ICMP_UGE : llvm::CmpInst::ICMP_SGE);
break;
case BinaryExpr::Equal:
pred = isFloatOp ? llvm::CmpInst::FCMP_OEQ : llvm::CmpInst::ICMP_EQ;
break;
case BinaryExpr::NotEqual:
pred = isFloatOp ? llvm::CmpInst::FCMP_ONE : llvm::CmpInst::ICMP_NE;
break;
default:
FATAL("error in lEmitBinaryCmp()");
return NULL;
}
llvm::Value *cmp = ctx->CmpInst(isFloatOp ? llvm::Instruction::FCmp :
llvm::Instruction::ICmp,
pred, e0Val, e1Val, "bincmp");
// This is a little ugly: CmpInst returns i1 values, but we use vectors
// of i32s for varying bool values; type convert the result here if
// needed.
if (type->IsVaryingType())
cmp = ctx->I1VecToBoolVec(cmp);
return cmp;
}
BinaryExpr::BinaryExpr(Op o, Expr *a, Expr *b, SourcePos p)
: Expr(p), op(o) {
arg0 = a;
arg1 = b;
}
llvm::Value *
BinaryExpr::GetValue(FunctionEmitContext *ctx) const {
if (!arg0 || !arg1)
return NULL;
llvm::Value *e0Val = arg0->GetValue(ctx);
llvm::Value *e1Val = arg1->GetValue(ctx);
ctx->SetDebugPos(pos);
switch (op) {
case Add:
case Sub:
case Mul:
case Div:
case Mod:
return lEmitBinaryArith(op, e0Val, e1Val, arg0->GetType(), ctx, pos);
case Lt:
case Gt:
case Le:
case Ge:
case Equal:
case NotEqual:
return lEmitBinaryCmp(op, e0Val, e1Val, arg0->GetType(), ctx, pos);
case Shl:
case Shr:
case BitAnd:
case BitXor:
case BitOr: {
if (op == Shr && arg1->GetType()->IsVaryingType() &&
dynamic_cast<ConstExpr *>(arg1) == NULL)
PerformanceWarning(pos, "Shift right is extremely inefficient for "
"varying shift amounts.");
return lEmitBinaryBitOp(op, e0Val, e1Val, ctx);
}
case LogicalAnd:
return ctx->BinaryOperator(llvm::Instruction::And, e0Val, e1Val,
"logical_and");
case LogicalOr:
return ctx->BinaryOperator(llvm::Instruction::Or, e0Val, e1Val,
"logical_or");
case Comma:
return e1Val;
default:
FATAL("logic error");
return NULL;
}
}
const Type *
BinaryExpr::GetType() const {
if (arg0 == NULL || arg1 == NULL)
return NULL;
const Type *type0 = arg0->GetType(), *type1 = arg1->GetType();
if (type0 == NULL || type1 == NULL)
return NULL;
if (!type0->IsBoolType() && !type0->IsNumericType()) {
Error(arg0->pos, "First operand to binary operator \"%s\" is of invalid "
"type \"%s\".", lOpString(op), type0->GetString().c_str());
return NULL;
}
if (!type1->IsBoolType() && !type1->IsNumericType()) {
Error(arg1->pos,
"Second operand to binary operator \"%s\" is of invalid "
"type \"%s\".", lOpString(op), type1->GetString().c_str());
return NULL;
}
const Type *promotedType = Type::MoreGeneralType(type0, type1, pos,
lOpString(op));
// I don't think that MoreGeneralType should be able to fail after the
// type checks above.
assert(promotedType != NULL);
switch (op) {
case Add:
case Sub:
case Mul:
case Div: