forked from ispc/ispc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stmt.cpp
3845 lines (3247 loc) · 133 KB
/
stmt.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
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-2014, 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 stmt.cpp
@brief File with definitions classes related to statements in the language
*/
#include "stmt.h"
#include "ctx.h"
#include "util.h"
#include "expr.h"
#include "type.h"
#include "func.h"
#include "sym.h"
#include "module.h"
#include "llvmutil.h"
#include <stdio.h>
#include <map>
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
#include <llvm/Module.h>
#include <llvm/Type.h>
#include <llvm/Instructions.h>
#include <llvm/Function.h>
#include <llvm/DerivedTypes.h>
#include <llvm/LLVMContext.h>
#include <llvm/Metadata.h>
#include <llvm/CallingConv.h>
#else
#include <llvm/IR/Module.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Metadata.h>
#include <llvm/IR/CallingConv.h>
#endif
#include <llvm/Support/raw_ostream.h>
///////////////////////////////////////////////////////////////////////////
// Stmt
Stmt *
Stmt::Optimize() {
return this;
}
///////////////////////////////////////////////////////////////////////////
// ExprStmt
ExprStmt::ExprStmt(Expr *e, SourcePos p)
: Stmt(p, ExprStmtID) {
expr = e;
}
void
ExprStmt::EmitCode(FunctionEmitContext *ctx) const {
if (!ctx->GetCurrentBasicBlock())
return;
ctx->SetDebugPos(pos);
if (expr)
expr->GetValue(ctx);
}
Stmt *
ExprStmt::TypeCheck() {
return this;
}
void
ExprStmt::Print(int indent) const {
if (!expr)
return;
printf("%*c", indent, ' ');
printf("Expr stmt: ");
pos.Print();
expr->Print();
printf("\n");
}
void
ExprStmt::GetComments(std::map<int, std::string>* comments) const {
//const Type* t = expr->GetType();
int linenumber = this->pos.first_line;
std::string comment = expr->GetComment();
auto old_comment = comments->find(linenumber);
// if exist already comment, append to end.
if(old_comment != comments->end())
old_comment->second += "; " + comment;
else
comments->insert(std::make_pair(linenumber, comment));
}
int
ExprStmt::EstimateCost() const {
return 0;
}
///////////////////////////////////////////////////////////////////////////
// DeclStmt
DeclStmt::DeclStmt(const std::vector<VariableDeclaration> &v, SourcePos p)
: Stmt(p, DeclStmtID), vars(v) {
}
static bool
lHasUnsizedArrays(const Type *type) {
const ArrayType *at = CastType<ArrayType>(type);
if (at == NULL)
return false;
if (at->GetElementCount() == 0)
return true;
else
return lHasUnsizedArrays(at->GetElementType());
}
#ifdef ISPC_NVPTX_ENABLED
static llvm::Value* lConvertToGenericPtr(FunctionEmitContext *ctx, llvm::Value *value, const SourcePos ¤tPos, const bool variable = false)
{
if (!value->getType()->isPointerTy() || g->target->getISA() != Target::NVPTX)
return value;
llvm::PointerType *pt = llvm::dyn_cast<llvm::PointerType>(value->getType());
const int addressSpace = pt->getAddressSpace();
if (addressSpace != 3 && addressSpace != 4)
return value;
llvm::Type *elTy = pt->getElementType();
/* convert elTy addrspace(3)* to i64* addrspace(3)* */
llvm::PointerType *Int64Ptr3 = llvm::PointerType::get(LLVMTypes::Int64Type, addressSpace);
value = ctx->BitCastInst(value, Int64Ptr3, "gep2gen_cast1");
/* convert i64* addrspace(3) to i64* */
llvm::Function *__cvt2gen = m->module->getFunction(
addressSpace == 3 ? (variable ? "__cvt_loc2gen_var" : "__cvt_loc2gen") : "__cvt_const2gen");
std::vector<llvm::Value *> __cvt2gen_args;
__cvt2gen_args.push_back(value);
value = llvm::CallInst::Create(__cvt2gen, __cvt2gen_args, variable ? "gep2gen_cvt_var" : "gep2gen_cvt", ctx->GetCurrentBasicBlock());
/* compute offset */
if (addressSpace == 3)
{
assert(elTy->isArrayTy());
const int numElTot = elTy->getArrayNumElements();
const int numEl = numElTot/4;
#if 0
fprintf(stderr, " --- detected addrspace(3) sz= %d --- \n", numEl);
#endif
llvm::ArrayType *arrTy = llvm::dyn_cast<llvm::ArrayType>(pt->getArrayElementType());
assert(arrTy != NULL);
llvm::Type *arrElTy = arrTy->getElementType();
#if 0
if (arrElTy->isArrayTy())
Error(currentPos, "Currently \"nvptx\" target doesn't support array-of-array");
#endif
/* convert i64* to errElTy* */
llvm::PointerType *arrElTyPt0 = llvm::PointerType::get(arrElTy, 0);
value = ctx->BitCastInst(value, arrElTyPt0, "gep2gen_cast2");
llvm::Function *func_warp_index = m->module->getFunction("__warp_index");
llvm::Value *warpId = ctx->CallInst(func_warp_index, NULL, std::vector<llvm::Value*>(), "gep2gen_warp_index");
llvm::Value *offset = ctx->BinaryOperator(llvm::Instruction::Mul, warpId, LLVMInt32(numEl), "gep2gen_offset");
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
value = llvm::GetElementPtrInst::Create(value, offset, "gep2gen_offset", ctx->GetCurrentBasicBlock());
#else
value = llvm::GetElementPtrInst::Create(NULL, value, offset, "gep2gen_offset", ctx->GetCurrentBasicBlock());
#endif
}
/* convert arrElTy* to elTy* */
llvm::PointerType *elTyPt0 = llvm::PointerType::get(elTy, 0);
value = ctx->BitCastInst(value, elTyPt0, "gep2gen_cast3");
return value;
}
#endif /* ISPC_NVPTX_ENABLED */
void
DeclStmt::EmitCode(FunctionEmitContext *ctx) const {
if (!ctx->GetCurrentBasicBlock())
return;
for (unsigned int i = 0; i < vars.size(); ++i) {
Symbol *sym = vars[i].sym;
AssertPos(pos, sym != NULL);
if (sym->type == NULL)
continue;
Expr *initExpr = vars[i].init;
// Now that we're in the thick of emitting code, it's easy for us
// to find out the level of nesting of varying control flow we're
// in at this declaration. So we can finally set that
// Symbol::varyingCFDepth variable.
// @todo It's disgusting to be doing this here.
sym->varyingCFDepth = ctx->VaryingCFDepth();
ctx->SetDebugPos(sym->pos);
// If it's an array that was declared without a size but has an
// initializer list, then use the number of elements in the
// initializer list to finally set the array's size.
sym->type = ArrayType::SizeUnsizedArrays(sym->type, initExpr);
if (sym->type == NULL)
continue;
if (lHasUnsizedArrays(sym->type)) {
Error(pos, "Illegal to declare an unsized array variable without "
"providing an initializer expression to set its size.");
continue;
}
// References must have initializer expressions as well.
if (IsReferenceType(sym->type) == true) {
if (initExpr == NULL) {
Error(sym->pos, "Must provide initializer for reference-type "
"variable \"%s\".", sym->name.c_str());
continue;
}
if (IsReferenceType(initExpr->GetType()) == false) {
const Type *initLVType = initExpr->GetLValueType();
if (initLVType == NULL) {
Error(initExpr->pos, "Initializer for reference-type variable "
"\"%s\" must have an lvalue type.", sym->name.c_str());
continue;
}
if (initLVType->IsUniformType() == false) {
Error(initExpr->pos, "Initializer for reference-type variable "
"\"%s\" must have a uniform lvalue type.", sym->name.c_str());
continue;
}
}
}
llvm::Type *llvmType = sym->type->LLVMType(g->ctx);
if (llvmType == NULL) {
AssertPos(pos, m->errorCount > 0);
return;
}
if (sym->storageClass == SC_STATIC) {
#ifdef ISPC_NVPTX_ENABLED
if (g->target->getISA() == Target::NVPTX && !sym->type->IsConstType())
{
Error(sym->pos,
"Non-constant static variable ""\"%s\" is not supported with ""\"nvptx\" target.",
sym->name.c_str());
return;
}
if (g->target->getISA() == Target::NVPTX && sym->type->IsVaryingType())
PerformanceWarning(sym->pos,
"\"const static varying\" variable ""\"%s\" is stored in __global address space with ""\"nvptx\" target.",
sym->name.c_str());
if (g->target->getISA() == Target::NVPTX && sym->type->IsUniformType())
PerformanceWarning(sym->pos,
"\"const static uniform\" variable ""\"%s\" is stored in __constant address space with ""\"nvptx\" target.",
sym->name.c_str());
#endif /* ISPC_NVPTX_ENABLED */
// For static variables, we need a compile-time constant value
// for its initializer; if there's no initializer, we use a
// zero value.
llvm::Constant *cinit = NULL;
if (initExpr != NULL) {
if (PossiblyResolveFunctionOverloads(initExpr, sym->type) == false)
continue;
// FIXME: we only need this for function pointers; it was
// already done for atomic types and enums in
// DeclStmt::TypeCheck()...
if (llvm::dyn_cast<ExprList>(initExpr) == NULL) {
initExpr = TypeConvertExpr(initExpr, sym->type,
"initializer");
// FIXME: and this is only needed to re-establish
// constant-ness so that GetConstant below works for
// constant artithmetic expressions...
initExpr = ::Optimize(initExpr);
}
cinit = initExpr->GetConstant(sym->type);
if (cinit == NULL)
Error(initExpr->pos, "Initializer for static variable "
"\"%s\" must be a constant.", sym->name.c_str());
}
if (cinit == NULL)
cinit = llvm::Constant::getNullValue(llvmType);
// Allocate space for the static variable in global scope, so
// that it persists across function calls
#ifdef ISPC_NVPTX_ENABLED
int addressSpace = 0;
if (g->target->getISA() == Target::NVPTX &&
sym->type->IsConstType() &&
sym->type->IsUniformType())
addressSpace = 4;
sym->storagePtr =
new llvm::GlobalVariable(*m->module, llvmType,
sym->type->IsConstType(),
llvm::GlobalValue::InternalLinkage, cinit,
llvm::Twine("static.") +
llvm::Twine(sym->pos.first_line) +
llvm::Twine(".") + sym->name.c_str(),
NULL,
llvm::GlobalVariable::NotThreadLocal,
addressSpace);
sym->storagePtr = lConvertToGenericPtr(ctx, sym->storagePtr, sym->pos);
#else /* ISPC_NVPTX_ENABLED */
sym->storagePtr =
new llvm::GlobalVariable(*m->module, llvmType,
sym->type->IsConstType(),
llvm::GlobalValue::InternalLinkage, cinit,
llvm::Twine("static.") +
llvm::Twine(sym->pos.first_line) +
llvm::Twine(".") + sym->name.c_str());
#endif /* ISPC_NVPTX_ENABLED */
// Tell the FunctionEmitContext about the variable
ctx->EmitVariableDebugInfo(sym);
}
#ifdef ISPC_NVPTX_ENABLED
else if ((sym->type->IsUniformType() || sym->type->IsSOAType()) &&
/* NVPTX:
* only non-constant uniform data types are stored in shared memory
* constant uniform are automatically promoted to varying
*/
!sym->type->IsConstType() &&
#if 1
sym->type->IsArrayType() &&
#endif
g->target->getISA() == Target::NVPTX)
{
PerformanceWarning(sym->pos,
"Non-constant \"uniform\" data types might be slow with \"nvptx\" target. "
"Unless data sharing between program instances is desired, try \"const [static] uniform\", \"varying\" or \"uniform new uniform \"+\"delete\" if possible.");
/* with __shared__ memory everything must be an array */
int nel = 4;
ArrayType *nat;
bool variable = true;
if (sym->type->IsArrayType())
{
const ArrayType *at = CastType<ArrayType>(sym->type);
/* we must scale # elements by 4, because a thread-block will run 4 warps
* or 128 threads.
* ***note-to-me***:please define these value (128threads/4warps)
* in nvptx-target definition
* instead of compile-time constants
*/
nel *= at->GetElementCount();
if (sym->type->IsSOAType())
nel *= sym->type->GetSOAWidth();
nat = new ArrayType(at->GetElementType(), nel);
variable = false;
}
else
nat = new ArrayType(sym->type, nel);
llvm::Type *llvmTypeUn = nat->LLVMType(g->ctx);
llvm::Constant *cinit = llvm::UndefValue::get(llvmTypeUn);
sym->storagePtr =
new llvm::GlobalVariable(*m->module, llvmTypeUn,
sym->type->IsConstType(),
llvm::GlobalValue::InternalLinkage,
cinit,
llvm::Twine("local_") +
llvm::Twine(sym->pos.first_line) +
llvm::Twine("_") + sym->name.c_str(),
NULL,
llvm::GlobalVariable::NotThreadLocal,
/*AddressSpace=*/3);
sym->storagePtr = lConvertToGenericPtr(ctx, sym->storagePtr, sym->pos, variable);
llvm::PointerType *ptrTy = llvm::PointerType::get(sym->type->LLVMType(g->ctx),0);
sym->storagePtr = ctx->BitCastInst(sym->storagePtr, ptrTy, "uniform_decl");
// Tell the FunctionEmitContext about the variable; must do
// this before the initializer stuff.
ctx->EmitVariableDebugInfo(sym);
if (initExpr == 0 && sym->type->IsConstType())
Error(sym->pos, "Missing initializer for const variable "
"\"%s\".", sym->name.c_str());
// And then get it initialized...
sym->parentFunction = ctx->GetFunction();
InitSymbol(sym->storagePtr, sym->type, initExpr, ctx, sym->pos);
}
#endif /* ISPC_NVPTX_ENABLED */
else
{
// For non-static variables, allocate storage on the stack
sym->storagePtr = ctx->AllocaInst(llvmType, sym->name.c_str());
// Tell the FunctionEmitContext about the variable; must do
// this before the initializer stuff.
ctx->EmitVariableDebugInfo(sym);
if (initExpr == 0 && sym->type->IsConstType())
Error(sym->pos, "Missing initializer for const variable "
"\"%s\".", sym->name.c_str());
// And then get it initialized...
sym->parentFunction = ctx->GetFunction();
InitSymbol(sym->storagePtr, sym->type, initExpr, ctx, sym->pos);
}
}
}
Stmt *
DeclStmt::Optimize() {
for (unsigned int i = 0; i < vars.size(); ++i) {
Expr *init = vars[i].init;
if (init != NULL && llvm::dyn_cast<ExprList>(init) == NULL) {
// If the variable is const-qualified, after we've optimized
// the initializer expression, see if we have a ConstExpr. If
// so, save it in Symbol::constValue where it can be used in
// optimizing later expressions that have this symbol in them.
// Note that there are cases where the expression may be
// constant but where we don't have a ConstExpr; an example is
// const arrays--the ConstExpr implementation just can't
// represent an array of values.
//
// All this is fine in terms of the code that's generated in
// the end (LLVM's constant folding stuff is good), but it
// means that the ispc compiler's ability to reason about what
// is definitely a compile-time constant for things like
// computing array sizes from non-trivial expressions is
// consequently limited.
Symbol *sym = vars[i].sym;
if (sym->type && sym->type->IsConstType() &&
Type::Equal(init->GetType(), sym->type))
sym->constValue = llvm::dyn_cast<ConstExpr>(init);
}
}
return this;
}
Stmt *
DeclStmt::TypeCheck() {
bool encounteredError = false;
for (unsigned int i = 0; i < vars.size(); ++i) {
if (vars[i].sym == NULL) {
encounteredError = true;
continue;
}
if (vars[i].init == NULL)
continue;
// get the right type for stuff like const float foo = 2; so that
// the int->float type conversion is in there and we don't return
// an int as the constValue later...
const Type *type = vars[i].sym->type;
if (CastType<AtomicType>(type) != NULL ||
CastType<EnumType>(type) != NULL) {
// If it's an expr list with an atomic type, we'll later issue
// an error. Need to leave vars[i].init as is in that case so
// it is in fact caught later, though.
if (llvm::dyn_cast<ExprList>(vars[i].init) == NULL) {
vars[i].init = TypeConvertExpr(vars[i].init, type,
"initializer");
if (vars[i].init == NULL)
encounteredError = true;
}
}
}
return encounteredError ? NULL : this;
}
void
DeclStmt::Print(int indent) const {
printf("%*cDecl Stmt:", indent, ' ');
pos.Print();
for (unsigned int i = 0; i < vars.size(); ++i) {
printf("%*cVariable %s (%s)", indent+4, ' ',
vars[i].sym->name.c_str(),
vars[i].sym->type->GetString().c_str());
if (vars[i].init != NULL) {
printf(" = ");
vars[i].init->Print();
}
printf("\n");
}
printf("\n");
}
void
DeclStmt::GetComments(std::map<int, std::string>* comments) const {
int linenumber = pos.first_line;
std::string comment = "";
for (unsigned int i = 0; i < vars.size(); ++i) {
comment += "[" + vars[i].sym->type->GetComment() + "] " + vars[i].sym->name;
if(vars[i].init != NULL)
comment += " = " + vars[i].init->GetComment();
if(i != vars.size() - 1)
comment += ", ";
}
auto old_comment = comments->find(linenumber);
// if exist already comment, append to end.
if(old_comment != comments->end())
old_comment->second += "; " + comment;
else
comments->insert(std::make_pair(linenumber, comment));
}
int
DeclStmt::EstimateCost() const {
return 0;
}
///////////////////////////////////////////////////////////////////////////
// IfStmt
IfStmt::IfStmt(Expr *t, Stmt *ts, Stmt *fs, bool checkCoherence, SourcePos p)
: Stmt(p, IfStmtID), test(t), trueStmts(ts), falseStmts(fs),
doAllCheck(checkCoherence &&
!g->opt.disableCoherentControlFlow) {
}
static void
lEmitIfStatements(FunctionEmitContext *ctx, Stmt *stmts, const char *trueOrFalse) {
if (!stmts)
return;
if (llvm::dyn_cast<StmtList>(stmts) == NULL)
ctx->StartScope();
ctx->AddInstrumentationPoint(trueOrFalse);
stmts->EmitCode(ctx);
if (llvm::dyn_cast<const StmtList>(stmts) == NULL)
ctx->EndScope();
}
/** Returns true if the "true" block for the if statement consists of a
single 'break' statement, and the "false" block is empty. */
/*
static bool
lCanApplyBreakOptimization(Stmt *trueStmts, Stmt *falseStmts) {
if (falseStmts != NULL) {
if (StmtList *sl = llvm::dyn_cast<StmtList>(falseStmts)) {
return (sl->stmts.size() == 0);
}
else
return false;
}
if (llvm::dyn_cast<BreakStmt>(trueStmts))
return true;
else if (StmtList *sl = llvm::dyn_cast<StmtList>(trueStmts))
return (sl->stmts.size() == 1 &&
llvm::dyn_cast<BreakStmt>(sl->stmts[0]) != NULL);
else
return false;
}
*/
void
IfStmt::EmitCode(FunctionEmitContext *ctx) const {
// First check all of the things that might happen due to errors
// earlier in compilation and bail out if needed so that we don't
// dereference NULL pointers in the below...
if (!ctx->GetCurrentBasicBlock())
return;
if (!test)
return;
const Type *testType = test->GetType();
if (!testType)
return;
ctx->SetDebugPos(pos);
bool isUniform = testType->IsUniformType();
llvm::Value *testValue = test->GetValue(ctx);
if (testValue == NULL)
return;
#ifdef ISPC_NVPTX_ENABLED
#if 0
if (!isUniform && g->target->getISA() == Target::NVPTX)
{
/* With "nvptx" target, SIMT hardware takes care of non-uniform
* control flow. We trick ISPC to generate uniform control flow.
*/
testValue = ctx->ExtractInst(testValue, 0);
isUniform = true;
}
#endif
#endif /* ISPC_NVPTX_ENABLED */
if (isUniform) {
ctx->StartUniformIf();
if (doAllCheck)
Warning(test->pos, "Uniform condition supplied to \"cif\" statement.");
// 'If' statements with uniform conditions are relatively
// straightforward. We evaluate the condition and then jump to
// either the 'then' or 'else' clause depending on its value.
llvm::BasicBlock *bthen = ctx->CreateBasicBlock("if_then");
llvm::BasicBlock *belse = ctx->CreateBasicBlock("if_else");
llvm::BasicBlock *bexit = ctx->CreateBasicBlock("if_exit");
// Jump to the appropriate basic block based on the value of
// the 'if' test
ctx->BranchInst(bthen, belse, testValue);
// Emit code for the 'true' case
ctx->SetCurrentBasicBlock(bthen);
lEmitIfStatements(ctx, trueStmts, "true");
if (ctx->GetCurrentBasicBlock())
ctx->BranchInst(bexit);
// Emit code for the 'false' case
ctx->SetCurrentBasicBlock(belse);
lEmitIfStatements(ctx, falseStmts, "false");
if (ctx->GetCurrentBasicBlock())
ctx->BranchInst(bexit);
// Set the active basic block to the newly-created exit block
// so that subsequent emitted code starts there.
ctx->SetCurrentBasicBlock(bexit);
ctx->EndIf();
}
/*
// Disabled for performance reasons. Change to an optional compile-time opt switch.
else if (lCanApplyBreakOptimization(trueStmts, falseStmts)) {
// If we have a simple break statement inside the 'if' and are
// under varying control flow, just update the execution mask
// directly and don't emit code for the statements. This leads to
// better code for this case--this is surprising and should be
// root-caused further, but for now this gives us performance
// benefit in this case.
ctx->SetInternalMaskAndNot(ctx->GetInternalMask(), testValue);
}
*/
else
emitVaryingIf(ctx, testValue);
}
Stmt *
IfStmt::TypeCheck() {
if (test != NULL) {
const Type *testType = test->GetType();
if (testType != NULL) {
bool isUniform = (testType->IsUniformType() &&
!g->opt.disableUniformControlFlow);
test = TypeConvertExpr(test, isUniform ? AtomicType::UniformBool :
AtomicType::VaryingBool,
"\"if\" statement test");
if (test == NULL)
return NULL;
}
}
return this;
}
int
IfStmt::EstimateCost() const {
const Type *type;
if (test == NULL || (type = test->GetType()) == NULL)
return 0;
return type->IsUniformType() ? COST_UNIFORM_IF : COST_VARYING_IF;
}
void
IfStmt::Print(int indent) const {
printf("%*cIf Stmt %s", indent, ' ', doAllCheck ? "DO ALL CHECK" : "");
pos.Print();
printf("\n%*cTest: ", indent+4, ' ');
test->Print();
printf("\n");
if (trueStmts) {
printf("%*cTrue:\n", indent+4, ' ');
trueStmts->Print(indent+8);
}
if (falseStmts) {
printf("%*cFalse:\n", indent+4, ' ');
falseStmts->Print(indent+8);
}
}
void
IfStmt::GetComments(std::map<int, std::string>* comments) const {
int linenumber = pos.first_line;
std::string testString = (test != NULL)? test->GetComment() : "";
std::string comment = "if (" + testString + ")" + (doAllCheck ? " DO ALL CHECK" : "");
auto old_comment = comments->find(linenumber);
// if exist already comment, append to end.
if(old_comment != comments->end())
old_comment->second += "; " + comment;
else
comments->insert(std::make_pair(linenumber, comment));
if(trueStmts != NULL) trueStmts->GetComments(comments);
if(falseStmts != NULL) falseStmts->GetComments(comments);
}
/** Emit code to run both the true and false statements for the if test,
with the mask set appropriately before running each one.
*/
void
IfStmt::emitMaskedTrueAndFalse(FunctionEmitContext *ctx, llvm::Value *oldMask,
llvm::Value *test) const {
if (trueStmts) {
ctx->SetInternalMaskAnd(oldMask, test);
lEmitIfStatements(ctx, trueStmts, "if: expr mixed, true statements");
// under varying control flow,, returns can't stop instruction
// emission, so this better be non-NULL...
AssertPos(ctx->GetDebugPos(), ctx->GetCurrentBasicBlock());
}
if (falseStmts) {
ctx->SetInternalMaskAndNot(oldMask, test);
lEmitIfStatements(ctx, falseStmts, "if: expr mixed, false statements");
AssertPos(ctx->GetDebugPos(), ctx->GetCurrentBasicBlock());
}
}
/** Emit code for an if test that checks the mask and the test values and
tries to be smart about jumping over code that doesn't need to be run.
*/
void
IfStmt::emitVaryingIf(FunctionEmitContext *ctx, llvm::Value *ltest) const {
llvm::Value *oldMask = ctx->GetInternalMask();
if (doAllCheck) {
// We can't tell if the mask going into the if is all on at the
// compile time. Emit code to check for this and then either run
// the code for the 'all on' or the 'mixed' case depending on the
// mask's value at runtime.
llvm::BasicBlock *bAllOn = ctx->CreateBasicBlock("cif_mask_all");
llvm::BasicBlock *bMixedOn = ctx->CreateBasicBlock("cif_mask_mixed");
llvm::BasicBlock *bDone = ctx->CreateBasicBlock("cif_done");
// Jump to either bAllOn or bMixedOn, depending on the mask's value
llvm::Value *maskAllQ = ctx->All(ctx->GetFullMask());
ctx->BranchInst(bAllOn, bMixedOn, maskAllQ);
// Emit code for the 'mask all on' case
ctx->SetCurrentBasicBlock(bAllOn);
emitMaskAllOn(ctx, ltest, bDone);
// And emit code for the mixed mask case
ctx->SetCurrentBasicBlock(bMixedOn);
emitMaskMixed(ctx, oldMask, ltest, bDone);
// When done, set the current basic block to the block that the two
// paths above jump to when they're done.
ctx->SetCurrentBasicBlock(bDone);
}
else if (trueStmts != NULL || falseStmts != NULL) {
// If there is nothing that is potentially unsafe to run with all
// lanes off in the true and false statements and if the total
// complexity of those two is relatively simple, then we'll go
// ahead and emit straightline code that runs both sides, updating
// the mask accordingly. This is useful for efficiently compiling
// things like:
//
// if (foo) x = 0;
// else ++x;
//
// Where the overhead of checking if any of the program instances wants
// to run one side or the other is more than the actual computation.
// SafeToRunWithMaskAllOff() checks to make sure that we don't do this
// for potentially dangerous code like:
//
// if (index < count) array[index] = 0;
//
// where our use of blend for conditional assignments doesn't check
// for the 'all lanes' off case.
int trueFalseCost = (::EstimateCost(trueStmts) +
::EstimateCost(falseStmts));
bool costIsAcceptable = (trueFalseCost <
PREDICATE_SAFE_IF_STATEMENT_COST);
bool safeToRunWithAllLanesOff = (SafeToRunWithMaskAllOff(trueStmts) &&
SafeToRunWithMaskAllOff(falseStmts));
Debug(pos, "If statement: true cost %d (safe %d), false cost %d (safe %d).",
::EstimateCost(trueStmts), (int)SafeToRunWithMaskAllOff(trueStmts),
::EstimateCost(falseStmts), (int)SafeToRunWithMaskAllOff(falseStmts));
if (safeToRunWithAllLanesOff &&
(costIsAcceptable || g->opt.disableCoherentControlFlow)) {
ctx->StartVaryingIf(oldMask);
emitMaskedTrueAndFalse(ctx, oldMask, ltest);
AssertPos(pos, ctx->GetCurrentBasicBlock());
ctx->EndIf();
}
else {
llvm::BasicBlock *bDone = ctx->CreateBasicBlock("if_done");
emitMaskMixed(ctx, oldMask, ltest, bDone);
ctx->SetCurrentBasicBlock(bDone);
}
}
}
/** Emits code for 'if' tests under the case where we know that the program
mask is all on going into the 'if'.
*/
void
IfStmt::emitMaskAllOn(FunctionEmitContext *ctx, llvm::Value *ltest,
llvm::BasicBlock *bDone) const {
// We start by explicitly storing "all on" into the mask mask. Note
// that this doesn't change its actual value, but doing so lets the
// compiler see what's going on so that subsequent optimizations for
// code emitted here can operate with the knowledge that the mask is
// definitely all on (until it modifies the mask itself).
AssertPos(pos, !g->opt.disableCoherentControlFlow);
if (!g->opt.disableMaskAllOnOptimizations)
ctx->SetInternalMask(LLVMMaskAllOn);
llvm::Value *oldFunctionMask = ctx->GetFunctionMask();
if (!g->opt.disableMaskAllOnOptimizations)
ctx->SetFunctionMask(LLVMMaskAllOn);
// First, check the value of the test. If it's all on, then we jump to
// a basic block that will only have code for the true case.
llvm::BasicBlock *bTestAll = ctx->CreateBasicBlock("cif_test_all");
llvm::BasicBlock *bTestNoneCheck = ctx->CreateBasicBlock("cif_test_none_check");
llvm::Value *testAllQ = ctx->All(ltest);
ctx->BranchInst(bTestAll, bTestNoneCheck, testAllQ);
// Emit code for the 'test is all true' case
ctx->SetCurrentBasicBlock(bTestAll);
ctx->StartVaryingIf(LLVMMaskAllOn);
lEmitIfStatements(ctx, trueStmts, "if: all on mask, expr all true");
ctx->EndIf();
if (ctx->GetCurrentBasicBlock() != NULL)
// bblock may legitimately be NULL since if there's a return stmt
// or break or continue we can actually jump and end emission since
// we know all of the lanes are following this path...
ctx->BranchInst(bDone);
// The test isn't all true. Now emit code to determine if it's all
// false, or has mixed values.
ctx->SetCurrentBasicBlock(bTestNoneCheck);
llvm::BasicBlock *bTestNone = ctx->CreateBasicBlock("cif_test_none");
llvm::BasicBlock *bTestMixed = ctx->CreateBasicBlock("cif_test_mixed");
llvm::Value *testMixedQ = ctx->Any(ltest);
ctx->BranchInst(bTestMixed, bTestNone, testMixedQ);
// Emit code for the 'test is all false' case
ctx->SetCurrentBasicBlock(bTestNone);
ctx->StartVaryingIf(LLVMMaskAllOn);
lEmitIfStatements(ctx, falseStmts, "if: all on mask, expr all false");
ctx->EndIf();
if (ctx->GetCurrentBasicBlock())
// bblock may be NULL since if there's a return stmt or break or
// continue we can actually jump or whatever and end emission...
ctx->BranchInst(bDone);
// Finally emit code for the 'mixed true/false' case. We unavoidably
// need to run both the true and the false statements.
ctx->SetCurrentBasicBlock(bTestMixed);
ctx->StartVaryingIf(LLVMMaskAllOn);
emitMaskedTrueAndFalse(ctx, LLVMMaskAllOn, ltest);
// In this case, return/break/continue isn't allowed to jump and end
// emission.
AssertPos(pos, ctx->GetCurrentBasicBlock());
ctx->EndIf();
ctx->BranchInst(bDone);
ctx->SetCurrentBasicBlock(bDone);
ctx->SetFunctionMask(oldFunctionMask);
}
/** Emit code for an 'if' test where the lane mask is known to be mixed
on/off going into it.
*/
void
IfStmt::emitMaskMixed(FunctionEmitContext *ctx, llvm::Value *oldMask,
llvm::Value *ltest, llvm::BasicBlock *bDone) const {
ctx->StartVaryingIf(oldMask);
llvm::BasicBlock *bNext = ctx->CreateBasicBlock("safe_if_after_true");
llvm::BasicBlock *bRunTrue = ctx->CreateBasicBlock("safe_if_run_true");
ctx->SetInternalMaskAnd(oldMask, ltest);
// Do any of the program instances want to run the 'true'
// block? If not, jump ahead to bNext.
#ifdef ISPC_NVPTX_ENABLED
#if 0
llvm::Value *maskAnyTrueQ = ctx->ExtractInst(ctx->GetFullMask(),0);
#else
llvm::Value *maskAnyTrueQ = ctx->Any(ctx->GetFullMask());
#endif
#else /* ISPC_NVPTX_ENABLED */
llvm::Value *maskAnyTrueQ = ctx->Any(ctx->GetFullMask());
#endif /* ISPC_NVPTX_ENABLED */
ctx->BranchInst(bRunTrue, bNext, maskAnyTrueQ);
// Emit statements for true
ctx->SetCurrentBasicBlock(bRunTrue);
if (trueStmts != NULL)
lEmitIfStatements(ctx, trueStmts, "if: expr mixed, true statements");
AssertPos(pos, ctx->GetCurrentBasicBlock());
ctx->BranchInst(bNext);
ctx->SetCurrentBasicBlock(bNext);
// False...
llvm::BasicBlock *bRunFalse = ctx->CreateBasicBlock("safe_if_run_false");
ctx->SetInternalMaskAndNot(oldMask, ltest);
// Similarly, check to see if any of the instances want to
// run the 'false' block...
#ifdef ISPC_NVPTX_ENABLED
#if 0
llvm::Value *maskAnyFalseQ = ctx->ExtractInst(ctx->GetFullMask(),0);
#else
llvm::Value *maskAnyFalseQ = ctx->Any(ctx->GetFullMask());
#endif
#else /* ISPC_NVPTX_ENABLED */
llvm::Value *maskAnyFalseQ = ctx->Any(ctx->GetFullMask());
#endif /* ISPC_NVPTX_ENABLED */
ctx->BranchInst(bRunFalse, bDone, maskAnyFalseQ);
// Emit code for false
ctx->SetCurrentBasicBlock(bRunFalse);
if (falseStmts)
lEmitIfStatements(ctx, falseStmts, "if: expr mixed, false statements");
AssertPos(pos, ctx->GetCurrentBasicBlock());
ctx->BranchInst(bDone);
ctx->SetCurrentBasicBlock(bDone);
ctx->EndIf();
}
///////////////////////////////////////////////////////////////////////////
// DoStmt
struct VaryingBCCheckInfo {
VaryingBCCheckInfo() {
varyingControlFlowDepth = 0;
foundVaryingBreakOrContinue = false;
}
int varyingControlFlowDepth;
bool foundVaryingBreakOrContinue;
};
/** Returns true if the given node is an 'if' statement where the test
condition has varying type. */
static bool
lIsVaryingFor(ASTNode *node) {
IfStmt *ifStmt;
if ((ifStmt = llvm::dyn_cast<IfStmt>(node)) != NULL &&
ifStmt->test != NULL) {