forked from ispc/ispc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
opt.cpp
5696 lines (4973 loc) · 229 KB
/
opt.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-2016, 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 opt.cpp
@brief Implementations of various ispc optimization passes that operate
on the LLVM IR.
*/
#include "opt.h"
#include "ctx.h"
#include "sym.h"
#include "module.h"
#include "util.h"
#include "llvmutil.h"
#include <stdio.h>
#include <map>
#include <set>
#include <llvm/Pass.h>
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
#include <llvm/Module.h>
#include <llvm/Instructions.h>
#include <llvm/Intrinsics.h>
#include <llvm/Function.h>
#include <llvm/BasicBlock.h>
#include <llvm/Constants.h>
#ifdef ISPC_NVPTX_ENABLED
#include <llvm/InlineAsm.h>
#endif /* ISPC_NVPTX_ENABLED */
#else // LLVM 3.3+
#include <llvm/IR/Module.h>
#include <llvm/IR/Instructions.h>
#include <llvm/IR/Intrinsics.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Constants.h>
#ifdef ISPC_NVPTX_ENABLED
#include <llvm/IR/InlineAsm.h>
#endif /* ISPC_NVPTX_ENABLED */
#endif
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_4 // LLVM 3.4+
#include <llvm/Transforms/Instrumentation.h>
#endif
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
#include "llvm/PassManager.h"
#else // LLVM 3.7+
#include "llvm/IR/LegacyPassManager.h"
#endif
#include <llvm/PassRegistry.h>
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_5 // LLVM 3.5+
#include <llvm/IR/Verifier.h>
#include <llvm/IR/IRPrintingPasses.h>
#include <llvm/IR/PatternMatch.h>
#include <llvm/IR/DebugInfo.h>
#else // < 3.5
#include <llvm/Analysis/Verifier.h>
#include <llvm/Assembly/PrintModulePass.h>
#include <llvm/Support/PatternMatch.h>
#include <llvm/DebugInfo.h>
#endif
#include <llvm/Analysis/ConstantFolding.h>
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
#include <llvm/Target/TargetLibraryInfo.h>
#else // LLVM 3.7+
#include <llvm/Analysis/TargetLibraryInfo.h>
#endif
#include <llvm/ADT/Triple.h>
#include <llvm/ADT/SmallSet.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/IPO.h>
#include <llvm/Transforms/Utils/BasicBlockUtils.h>
#include <llvm/Target/TargetOptions.h>
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
#include <llvm/DataLayout.h>
#else // LLVM 3.3+
#include <llvm/IR/DataLayout.h>
#include <llvm/Analysis/TargetTransformInfo.h>
#endif
#include <llvm/Target/TargetMachine.h>
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_8 // LLVM 3.8+
#include <llvm/Analysis/BasicAliasAnalysis.h>
#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
#endif
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_9 // LLVM 3.9+
#include "llvm/Transforms/IPO/FunctionAttrs.h"
#include "llvm/Transforms/Scalar/GVN.h"
#endif
#include <llvm/Analysis/Passes.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Support/Dwarf.h>
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_6
#include <llvm/IR/IntrinsicInst.h>
#endif
#ifdef ISPC_IS_LINUX
#include <alloca.h>
#elif defined(ISPC_IS_WINDOWS)
#include <malloc.h>
#ifndef __MINGW32__
#define alloca _alloca
#endif
#endif // ISPC_IS_WINDOWS
#ifndef PRId64
#define PRId64 "lld"
#endif
#ifndef PRIu64
#define PRIu64 "llu"
#endif
static llvm::Pass *CreateIntrinsicsOptPass();
static llvm::Pass *CreateInstructionSimplifyPass();
static llvm::Pass *CreatePeepholePass();
static llvm::Pass *CreateImproveMemoryOpsPass();
static llvm::Pass *CreateGatherCoalescePass();
static llvm::Pass *CreateReplacePseudoMemoryOpsPass();
static llvm::Pass *CreateIsCompileTimeConstantPass(bool isLastTry);
static llvm::Pass *CreateMakeInternalFuncsStaticPass();
static llvm::Pass *CreateDebugPass(char * output);
static llvm::Pass *CreateReplaceStdlibShiftPass();
static llvm::Pass *CreateFixBooleanSelectPass();
#ifdef ISPC_NVPTX_ENABLED
static llvm::Pass *CreatePromoteLocalToPrivatePass();
#endif /* ISPC_NVPTX_ENABLED */
#define DEBUG_START_PASS(NAME) \
if (g->debugPrint && \
(getenv("FUNC") == NULL || \
!strncmp(bb.getParent()->getName().str().c_str(), getenv("FUNC"), \
strlen(getenv("FUNC"))))) { \
fprintf(stderr, "Start of " NAME "\n"); \
fprintf(stderr, "---------------\n"); \
bb.dump(); \
fprintf(stderr, "---------------\n\n"); \
} else /* eat semicolon */
#define DEBUG_END_PASS(NAME) \
if (g->debugPrint && \
(getenv("FUNC") == NULL || \
!strncmp(bb.getParent()->getName().str().c_str(), getenv("FUNC"), \
strlen(getenv("FUNC"))))) { \
fprintf(stderr, "End of " NAME " %s\n", modifiedAny ? "** CHANGES **" : ""); \
fprintf(stderr, "---------------\n"); \
bb.dump(); \
fprintf(stderr, "---------------\n\n"); \
} else /* eat semicolon */
///////////////////////////////////////////////////////////////////////////
/** This utility routine copies the metadata (if any) attached to the
'from' instruction in the IR to the 'to' instruction.
For flexibility, this function takes an llvm::Value rather than an
llvm::Instruction for the 'to' parameter; at some places in the code
below, we sometimes use a llvm::Value to start out storing a value and
then later store instructions. If a llvm::Value is passed to this, the
routine just returns without doing anything; if it is in fact an
LLVM::Instruction, then the metadata can be copied to it.
*/
static void
lCopyMetadata(llvm::Value *vto, const llvm::Instruction *from) {
llvm::Instruction *to = llvm::dyn_cast<llvm::Instruction>(vto);
if (!to)
return;
llvm::SmallVector<std::pair<unsigned int, llvm::MDNode *>, 8> metadata;
from->getAllMetadata(metadata);
for (unsigned int i = 0; i < metadata.size(); ++i)
to->setMetadata(metadata[i].first, metadata[i].second);
}
/** We have a protocol with the front-end LLVM IR code generation process
that allows us to encode the source file position that corresponds with
instructions. (For example, this allows us to issue performance
warnings related to things like scatter and gather after optimization
has been performed, so that we aren't warning about scatters and
gathers that have been improved to stores and loads by optimization
passes.) Note that this is slightly redundant with the source file
position encoding generated for debugging symbols, though we don't
always generate debugging information but we do always generate this
position data.
This function finds the SourcePos that the metadata in the instruction
(if present) corresponds to. See the implementation of
FunctionEmitContext::addGSMetadata(), which encodes the source position during
code generation.
@param inst Instruction to try to find the source position of
@param pos Output variable in which to store the position
@returns True if source file position metadata was present and *pos
has been set. False otherwise.
*/
static bool
lGetSourcePosFromMetadata(const llvm::Instruction *inst, SourcePos *pos) {
llvm::MDNode *filename = inst->getMetadata("filename");
llvm::MDNode *first_line = inst->getMetadata("first_line");
llvm::MDNode *first_column = inst->getMetadata("first_column");
llvm::MDNode *last_line = inst->getMetadata("last_line");
llvm::MDNode *last_column = inst->getMetadata("last_column");
if (!filename || !first_line || !first_column || !last_line || !last_column)
return false;
// All of these asserts are things that FunctionEmitContext::addGSMetadata() is
// expected to have done in its operation
llvm::MDString *str = llvm::dyn_cast<llvm::MDString>(filename->getOperand(0));
Assert(str);
llvm::ConstantInt *first_lnum =
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5
llvm::dyn_cast<llvm::ConstantInt>(first_line->getOperand(0));
#else /* LLVN 3.6+ */
llvm::mdconst::extract<llvm::ConstantInt>(first_line->getOperand(0));
#endif
Assert(first_lnum);
llvm::ConstantInt *first_colnum =
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5
llvm::dyn_cast<llvm::ConstantInt>(first_column->getOperand(0));
#else /* LLVN 3.6+ */
llvm::mdconst::extract<llvm::ConstantInt>(first_column->getOperand(0));
#endif
Assert(first_column);
llvm::ConstantInt *last_lnum =
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5
llvm::dyn_cast<llvm::ConstantInt>(last_line->getOperand(0));
#else /* LLVN 3.6+ */
llvm::mdconst::extract<llvm::ConstantInt>(last_line->getOperand(0));
#endif
Assert(last_lnum);
llvm::ConstantInt *last_colnum =
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_5
llvm::dyn_cast<llvm::ConstantInt>(last_column->getOperand(0));
#else /* LLVN 3.6+ */
llvm::mdconst::extract<llvm::ConstantInt>(last_column->getOperand(0));
#endif
Assert(last_column);
*pos = SourcePos(str->getString().data(), (int)first_lnum->getZExtValue(),
(int)first_colnum->getZExtValue(), (int)last_lnum->getZExtValue(),
(int)last_colnum->getZExtValue());
return true;
}
static llvm::Instruction *
lCallInst(llvm::Function *func, llvm::Value *arg0, llvm::Value *arg1,
const char *name, llvm::Instruction *insertBefore = NULL) {
llvm::Value *args[2] = { arg0, arg1 };
llvm::ArrayRef<llvm::Value *> newArgArray(&args[0], &args[2]);
return llvm::CallInst::Create(func, newArgArray, name, insertBefore);
}
static llvm::Instruction *
lCallInst(llvm::Function *func, llvm::Value *arg0, llvm::Value *arg1,
llvm::Value *arg2, const char *name,
llvm::Instruction *insertBefore = NULL) {
llvm::Value *args[3] = { arg0, arg1, arg2 };
llvm::ArrayRef<llvm::Value *> newArgArray(&args[0], &args[3]);
return llvm::CallInst::Create(func, newArgArray, name, insertBefore);
}
static llvm::Instruction *
lCallInst(llvm::Function *func, llvm::Value *arg0, llvm::Value *arg1,
llvm::Value *arg2, llvm::Value *arg3, const char *name,
llvm::Instruction *insertBefore = NULL) {
llvm::Value *args[4] = { arg0, arg1, arg2, arg3 };
llvm::ArrayRef<llvm::Value *> newArgArray(&args[0], &args[4]);
return llvm::CallInst::Create(func, newArgArray, name, insertBefore);
}
static llvm::Instruction *
lCallInst(llvm::Function *func, llvm::Value *arg0, llvm::Value *arg1,
llvm::Value *arg2, llvm::Value *arg3, llvm::Value *arg4,
const char *name, llvm::Instruction *insertBefore = NULL) {
llvm::Value *args[5] = { arg0, arg1, arg2, arg3, arg4 };
llvm::ArrayRef<llvm::Value *> newArgArray(&args[0], &args[5]);
return llvm::CallInst::Create(func, newArgArray, name, insertBefore);
}
static llvm::Instruction *
lCallInst(llvm::Function *func, llvm::Value *arg0, llvm::Value *arg1,
llvm::Value *arg2, llvm::Value *arg3, llvm::Value *arg4,
llvm::Value *arg5, const char *name,
llvm::Instruction *insertBefore = NULL) {
llvm::Value *args[6] = { arg0, arg1, arg2, arg3, arg4, arg5 };
llvm::ArrayRef<llvm::Value *> newArgArray(&args[0], &args[6]);
return llvm::CallInst::Create(func, newArgArray, name, insertBefore);
}
static llvm::Instruction *
lGEPInst(llvm::Value *ptr, llvm::Value *offset, const char *name,
llvm::Instruction *insertBefore) {
llvm::Value *index[1] = { offset };
llvm::ArrayRef<llvm::Value *> arrayRef(&index[0], &index[1]);
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
return llvm::GetElementPtrInst::Create(ptr, arrayRef, name,
insertBefore);
#else // LLVM 3.7+
return llvm::GetElementPtrInst::Create(PTYPE(ptr), ptr, arrayRef,
name, insertBefore);
#endif
}
/** Given a vector of constant values (int, float, or bool) representing an
execution mask, convert it to a bitvector where the 0th bit corresponds
to the first vector value and so forth.
*/
static uint64_t
lConstElementsToMask(const llvm::SmallVector<llvm::Constant *,
ISPC_MAX_NVEC> &elements) {
Assert(elements.size() <= 64);
uint64_t mask = 0;
for (unsigned int i = 0; i < elements.size(); ++i) {
llvm::APInt intMaskValue;
// SSE has the "interesting" approach of encoding blending
// masks as <n x float>.
llvm::ConstantFP *cf = llvm::dyn_cast<llvm::ConstantFP>(elements[i]);
if (cf != NULL) {
llvm::APFloat apf = cf->getValueAPF();
intMaskValue = apf.bitcastToAPInt();
}
else {
// Otherwise get it as an int
llvm::ConstantInt *ci = llvm::dyn_cast<llvm::ConstantInt>(elements[i]);
Assert(ci != NULL); // vs return -1 if NULL?
intMaskValue = ci->getValue();
}
// Is the high-bit set? If so, OR in the appropriate bit in
// the result mask
if (intMaskValue.countLeadingOnes() > 0)
mask |= (1ull << i);
}
return mask;
}
/** Given an llvm::Value represinting a vector mask, see if the value is a
constant. If so, return true and set *bits to be the integer mask
found by taking the high bits of the mask values in turn and
concatenating them into a single integer. In other words, given the
4-wide mask: < 0xffffffff, 0, 0, 0xffffffff >, we have 0b1001 = 9.
*/
static bool
lGetMask(llvm::Value *factor, uint64_t *mask) {
llvm::ConstantDataVector *cdv = llvm::dyn_cast<llvm::ConstantDataVector>(factor);
if (cdv != NULL) {
llvm::SmallVector<llvm::Constant *, ISPC_MAX_NVEC> elements;
for (int i = 0; i < (int)cdv->getNumElements(); ++i)
elements.push_back(cdv->getElementAsConstant(i));
*mask = lConstElementsToMask(elements);
return true;
}
llvm::ConstantVector *cv = llvm::dyn_cast<llvm::ConstantVector>(factor);
if (cv != NULL) {
llvm::SmallVector<llvm::Constant *, ISPC_MAX_NVEC> elements;
for (int i = 0; i < (int)cv->getNumOperands(); ++i) {
llvm::Constant *c =
llvm::dyn_cast<llvm::Constant>(cv->getOperand(i));
if (c == NULL)
return false;
if (llvm::isa<llvm::ConstantExpr>(cv->getOperand(i)) )
return false; // We can not handle constant expressions here
elements.push_back(c);
}
*mask = lConstElementsToMask(elements);
return true;
}
else if (llvm::isa<llvm::ConstantAggregateZero>(factor)) {
*mask = 0;
return true;
}
else {
#if 0
llvm::ConstantExpr *ce = llvm::dyn_cast<llvm::ConstantExpr>(factor);
if (ce != NULL) {
llvm::TargetMachine *targetMachine = g->target->GetTargetMachine();
const llvm::TargetData *td = targetMachine->getTargetData();
llvm::Constant *c = llvm::ConstantFoldConstantExpression(ce, td);
c->dump();
factor = c;
}
// else we should be able to handle it above...
Assert(!llvm::isa<llvm::Constant>(factor));
#endif
return false;
}
}
enum MaskStatus { ALL_ON, ALL_OFF, MIXED, UNKNOWN };
/** Determines if the given mask value is all on, all off, mixed, or
unknown at compile time.
*/
static MaskStatus
lGetMaskStatus(llvm::Value *mask, int vecWidth = -1) {
uint64_t bits;
if (lGetMask(mask, &bits) == false)
return UNKNOWN;
if (bits == 0)
return ALL_OFF;
if (vecWidth == -1)
vecWidth = g->target->getVectorWidth();
Assert(vecWidth <= 64);
for (int i = 0; i < vecWidth; ++i) {
if ((bits & (1ull << i)) == 0)
return MIXED;
}
return ALL_ON;
}
///////////////////////////////////////////////////////////////////////////
// This is a wrap over class llvm::PassManager. This duplicates PassManager function run()
// and change PassManager function add by adding some checks and debug passes.
// This wrap can control:
// - If we want to switch off optimization with given number.
// - If we want to dump LLVM IR after optimization with given number.
// - If we want to generate LLVM IR debug for gdb after optimization with given number.
class DebugPassManager {
public:
DebugPassManager():number(0){}
void add(llvm::Pass * P, int stage);
bool run(llvm::Module& M) {return PM.run(M);}
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
llvm::PassManager& getPM() {return PM;}
#else /* LLVM 3.7+ */
llvm::legacy::PassManager& getPM() {return PM;}
#endif
private:
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
llvm::PassManager PM;
#else /* LLVM 3.7+ */
llvm::legacy::PassManager PM;
#endif
int number;
};
void
DebugPassManager::add(llvm::Pass * P, int stage = -1) {
// taking number of optimization
if (stage == -1) {
number++;
}
else {
number = stage;
}
if (g->off_stages.find(number) == g->off_stages.end()) {
// adding optimization (not switched off)
PM.add(P);
if (g->debug_stages.find(number) != g->debug_stages.end()) {
// adding dump of LLVM IR after optimization
char buf[100];
sprintf(buf, "\n\n*****LLVM IR after phase %d: %s*****\n\n",
number, P->getPassName());
PM.add(CreateDebugPass(buf));
}
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_4 || ISPC_LLVM_VERSION == ISPC_LLVM_3_5 // only 3.4 and 3.5
if (g->debugIR == number) {
// adding generating of LLVM IR debug after optimization
char buf[100];
sprintf(buf, "Debug_IR_after_%d_phase.bc", number);
PM.add(llvm::createDebugIRPass(true, true, ".", buf));
}
#endif
}
}
///////////////////////////////////////////////////////////////////////////
void
Optimize(llvm::Module *module, int optLevel) {
if (g->debugPrint) {
printf("*** Code going into optimization ***\n");
module->dump();
}
DebugPassManager optPM;
optPM.add(llvm::createVerifierPass(),0);
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
llvm::TargetLibraryInfo *targetLibraryInfo =
new llvm::TargetLibraryInfo(llvm::Triple(module->getTargetTriple()));
optPM.add(targetLibraryInfo);
#else // LLVM 3.7+
optPM.add(new llvm::TargetLibraryInfoWrapperPass(llvm::Triple(module->getTargetTriple())));
#endif
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_4
optPM.add(new llvm::DataLayout(*g->target->getDataLayout()));
#elif ISPC_LLVM_VERSION == ISPC_LLVM_3_5
optPM.add(new llvm::DataLayoutPass(*g->target->getDataLayout()));
#elif ISPC_LLVM_VERSION == ISPC_LLVM_3_6
llvm::DataLayoutPass *dlp= new llvm::DataLayoutPass();
dlp->doInitialization(*module);
optPM.add(dlp);
#endif // LLVM 3.7+ doesn't have DataLayoutPass anymore.
llvm::TargetMachine *targetMachine = g->target->GetTargetMachine();
#if ISPC_LLVM_VERSION == ISPC_LLVM_3_2
optPM.add(new llvm::TargetTransformInfo(targetMachine->getScalarTargetTransformInfo(),
targetMachine->getVectorTargetTransformInfo()));
#elif ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
targetMachine->addAnalysisPasses(optPM.getPM());
#else // LLVM 3.7+
optPM.getPM().add(createTargetTransformInfoWrapperPass(targetMachine->getTargetIRAnalysis()));
#endif
optPM.add(llvm::createIndVarSimplifyPass());
if (optLevel == 0) {
// This is more or less the minimum set of optimizations that we
// need to do to generate code that will actually run. (We can't
// run absolutely no optimizations, since the front-end needs us to
// take the various __pseudo_* functions it has emitted and turn
// them into something that can actually execute.
optPM.add(CreateImproveMemoryOpsPass(), 100);
#ifdef ISPC_NVPTX_ENABLED
if (g->opt.disableGatherScatterOptimizations == false &&
g->target->getVectorWidth() > 1)
#endif /* ISPC_NVPTX_ENABLED */
optPM.add(CreateImproveMemoryOpsPass(), 100);
if (g->opt.disableHandlePseudoMemoryOps == false)
optPM.add(CreateReplacePseudoMemoryOpsPass());
optPM.add(CreateIntrinsicsOptPass(), 102);
optPM.add(CreateIsCompileTimeConstantPass(true));
optPM.add(llvm::createFunctionInliningPass());
optPM.add(CreateMakeInternalFuncsStaticPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createGlobalDCEPass());
}
else {
llvm::PassRegistry *registry = llvm::PassRegistry::getPassRegistry();
llvm::initializeCore(*registry);
llvm::initializeScalarOpts(*registry);
llvm::initializeIPO(*registry);
llvm::initializeAnalysis(*registry);
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_7
llvm::initializeIPA(*registry);
#endif
llvm::initializeTransformUtils(*registry);
llvm::initializeInstCombine(*registry);
llvm::initializeInstrumentation(*registry);
llvm::initializeTarget(*registry);
optPM.add(llvm::createGlobalDCEPass(), 185);
// Setup to use LLVM default AliasAnalysis
// Ideally, we want call:
// llvm::PassManagerBuilder pm_Builder;
// pm_Builder.OptLevel = optLevel;
// pm_Builder.addInitialAliasAnalysisPasses(optPM);
// but the addInitialAliasAnalysisPasses() is a private function
// so we explicitly enable them here.
// Need to keep sync with future LLVM change
// An alternative is to call populateFunctionPassManager()
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_7
optPM.add(llvm::createTypeBasedAliasAnalysisPass(), 190);
optPM.add(llvm::createBasicAliasAnalysisPass());
#else
optPM.add(llvm::createTypeBasedAAWrapperPass(), 190);
optPM.add(llvm::createBasicAAWrapperPass());
#endif
optPM.add(llvm::createCFGSimplificationPass());
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
optPM.add(llvm::createScalarReplAggregatesPass());
#else
optPM.add(llvm::createSROAPass());
#endif
optPM.add(llvm::createEarlyCSEPass());
optPM.add(llvm::createLowerExpectIntrinsicPass());
// Early optimizations to try to reduce the total amount of code to
// work with if we can
optPM.add(llvm::createReassociatePass(), 200);
optPM.add(llvm::createConstantPropagationPass());
optPM.add(llvm::createDeadInstEliminationPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPromoteMemoryToRegisterPass());
optPM.add(llvm::createAggressiveDCEPass());
if (g->opt.disableGatherScatterOptimizations == false &&
g->target->getVectorWidth() > 1) {
optPM.add(llvm::createInstructionCombiningPass(), 210);
optPM.add(CreateImproveMemoryOpsPass());
}
if (!g->opt.disableMaskAllOnOptimizations) {
optPM.add(CreateIntrinsicsOptPass(), 215);
optPM.add(CreateInstructionSimplifyPass());
}
optPM.add(llvm::createDeadInstEliminationPass(), 220);
// Max struct size threshold for scalar replacement is
// 1) 4 fields (r,g,b,w)
// 2) field size: vectorWidth * sizeof(float)
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
const int field_limit = 4;
int sr_threshold = g->target->getVectorWidth() * sizeof(float) * field_limit;
#endif
// On to more serious optimizations
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
optPM.add(llvm::createScalarReplAggregatesPass(sr_threshold));
#else
optPM.add(llvm::createSROAPass());
#endif
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPromoteMemoryToRegisterPass());
optPM.add(llvm::createGlobalOptimizerPass());
optPM.add(llvm::createReassociatePass());
optPM.add(llvm::createIPConstantPropagationPass());
#ifdef ISPC_NVPTX_ENABLED
if (g->target->getISA() != Target::NVPTX)
#endif /* ISPC_NVPTX_ENABLED */
optPM.add(CreateReplaceStdlibShiftPass(),229);
optPM.add(llvm::createDeadArgEliminationPass(),230);
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPruneEHPass());
#if ISPC_LLVM_VERSION >= ISPC_LLVM_3_9 // 3.9+
optPM.add(llvm::createPostOrderFunctionAttrsLegacyPass());
optPM.add(llvm::createReversePostOrderFunctionAttrsPass());
#elif ISPC_LLVM_VERSION == ISPC_LLVM_3_8 // 3.8
optPM.add(llvm::createPostOrderFunctionAttrsPass());
optPM.add(llvm::createReversePostOrderFunctionAttrsPass());
#else // 3.7 and earlier
optPM.add(llvm::createFunctionAttrsPass());
#endif
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createConstantPropagationPass());
optPM.add(llvm::createDeadInstEliminationPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createArgumentPromotionPass());
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_3
// Starting from 3.4 this functionality was moved to
// InstructionCombiningPass. See r184459 for details.
optPM.add(llvm::createSimplifyLibCallsPass(), 240);
#endif
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createInstructionCombiningPass(), 241);
optPM.add(llvm::createJumpThreadingPass());
optPM.add(llvm::createCFGSimplificationPass());
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
optPM.add(llvm::createScalarReplAggregatesPass(sr_threshold));
#else
optPM.add(llvm::createSROAPass());
#endif
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createTailCallEliminationPass());
if (!g->opt.disableMaskAllOnOptimizations) {
optPM.add(CreateIntrinsicsOptPass(), 250);
optPM.add(CreateInstructionSimplifyPass());
}
if (g->opt.disableGatherScatterOptimizations == false &&
g->target->getVectorWidth() > 1) {
optPM.add(llvm::createInstructionCombiningPass(), 255);
optPM.add(CreateImproveMemoryOpsPass());
if (g->opt.disableCoalescing == false &&
g->target->getISA() != Target::GENERIC) {
// It is important to run this here to make it easier to
// finding matching gathers we can coalesce..
optPM.add(llvm::createEarlyCSEPass(), 260);
optPM.add(CreateGatherCoalescePass());
}
}
optPM.add(llvm::createFunctionInliningPass(), 265);
optPM.add(llvm::createConstantPropagationPass());
optPM.add(CreateIntrinsicsOptPass());
optPM.add(CreateInstructionSimplifyPass());
if (g->opt.disableGatherScatterOptimizations == false &&
g->target->getVectorWidth() > 1) {
optPM.add(llvm::createInstructionCombiningPass(), 270);
optPM.add(CreateImproveMemoryOpsPass());
}
optPM.add(llvm::createIPSCCPPass(), 275);
optPM.add(llvm::createDeadArgEliminationPass());
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
if (g->opt.disableHandlePseudoMemoryOps == false) {
optPM.add(CreateReplacePseudoMemoryOpsPass(),280);
}
optPM.add(CreateIntrinsicsOptPass(),281);
optPM.add(CreateInstructionSimplifyPass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createArgumentPromotionPass());
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
optPM.add(llvm::createScalarReplAggregatesPass(sr_threshold, false));
#else
optPM.add(llvm::createSROAPass());
#endif
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(CreateInstructionSimplifyPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createReassociatePass());
optPM.add(llvm::createLoopRotatePass());
optPM.add(llvm::createLICMPass());
optPM.add(llvm::createLoopUnswitchPass(false));
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(CreateInstructionSimplifyPass());
optPM.add(llvm::createIndVarSimplifyPass());
optPM.add(llvm::createLoopIdiomPass());
optPM.add(llvm::createLoopDeletionPass());
if (g->opt.unrollLoops) {
optPM.add(llvm::createLoopUnrollPass(), 300);
}
optPM.add(llvm::createGVNPass(), 301);
optPM.add(CreateIsCompileTimeConstantPass(true));
optPM.add(CreateIntrinsicsOptPass());
optPM.add(CreateInstructionSimplifyPass());
optPM.add(llvm::createMemCpyOptPass());
optPM.add(llvm::createSCCPPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(CreateInstructionSimplifyPass());
optPM.add(llvm::createJumpThreadingPass());
optPM.add(llvm::createCorrelatedValuePropagationPass());
optPM.add(llvm::createDeadStoreEliminationPass());
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(CreateInstructionSimplifyPass());
optPM.add(CreatePeepholePass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createStripDeadPrototypesPass());
optPM.add(CreateMakeInternalFuncsStaticPass());
optPM.add(llvm::createGlobalDCEPass());
optPM.add(llvm::createConstantMergePass());
// Should be the last
optPM.add(CreateFixBooleanSelectPass(), 400);
#ifdef ISPC_NVPTX_ENABLED
if (g->target->getISA() == Target::NVPTX)
{
optPM.add(CreatePromoteLocalToPrivatePass());
optPM.add(llvm::createGlobalDCEPass());
optPM.add(llvm::createTypeBasedAliasAnalysisPass());
optPM.add(llvm::createBasicAliasAnalysisPass());
optPM.add(llvm::createCFGSimplificationPass());
// Here clang has an experimental pass SROAPass instead of
// ScalarReplAggregatesPass. We should add it in the future.
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_6
optPM.add(llvm::createScalarReplAggregatesPass());
#else
optPM.add(llvm::createSROAPass());
#endif
optPM.add(llvm::createEarlyCSEPass());
optPM.add(llvm::createLowerExpectIntrinsicPass());
optPM.add(llvm::createTypeBasedAliasAnalysisPass());
optPM.add(llvm::createBasicAliasAnalysisPass());
// Early optimizations to try to reduce the total amount of code to
// work with if we can
optPM.add(llvm::createReassociatePass());
optPM.add(llvm::createConstantPropagationPass());
optPM.add(llvm::createDeadInstEliminationPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPromoteMemoryToRegisterPass());
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createDeadInstEliminationPass());
// On to more serious optimizations
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPromoteMemoryToRegisterPass());
optPM.add(llvm::createGlobalOptimizerPass());
optPM.add(llvm::createReassociatePass());
optPM.add(llvm::createIPConstantPropagationPass());
optPM.add(llvm::createDeadArgEliminationPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createPruneEHPass());
optPM.add(llvm::createFunctionAttrsPass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createConstantPropagationPass());
optPM.add(llvm::createDeadInstEliminationPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createArgumentPromotionPass());
#if ISPC_LLVM_VERSION <= ISPC_LLVM_3_3
// Starting from 3.4 this functionality was moved to
// InstructionCombiningPass. See r184459 for details.
optPM.add(llvm::createSimplifyLibCallsPass());
#endif
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createJumpThreadingPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createTailCallEliminationPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createConstantPropagationPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createIPSCCPPass());
optPM.add(llvm::createDeadArgEliminationPass());
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createArgumentPromotionPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createReassociatePass());
optPM.add(llvm::createLoopRotatePass());
optPM.add(llvm::createLICMPass());
// optPM.add(llvm::createLoopUnswitchPass(false));
#if 1
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createIndVarSimplifyPass());
optPM.add(llvm::createLoopIdiomPass());
optPM.add(llvm::createLoopDeletionPass());
optPM.add(llvm::createLoopUnrollPass());
optPM.add(llvm::createGVNPass());
optPM.add(llvm::createMemCpyOptPass());
optPM.add(llvm::createSCCPPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createJumpThreadingPass());
optPM.add(llvm::createCorrelatedValuePropagationPass());
optPM.add(llvm::createDeadStoreEliminationPass());
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createCFGSimplificationPass());
optPM.add(llvm::createInstructionCombiningPass());
optPM.add(llvm::createFunctionInliningPass());
optPM.add(llvm::createAggressiveDCEPass());
optPM.add(llvm::createStripDeadPrototypesPass());
optPM.add(llvm::createGlobalDCEPass());
optPM.add(llvm::createConstantMergePass());
#endif
}
#endif /* ISPC_NVPTX_ENABLED */
}
// Finish up by making sure we didn't mess anything up in the IR along
// the way.
optPM.add(llvm::createVerifierPass(), LAST_OPT_NUMBER);
optPM.run(*module);
if (g->debugPrint) {
printf("\n*****\nFINAL OUTPUT\n*****\n");
module->dump();
}
}
///////////////////////////////////////////////////////////////////////////
// IntrinsicsOpt
/** This is a relatively simple optimization pass that does a few small
optimizations that LLVM's x86 optimizer doesn't currently handle.
(Specifically, MOVMSK of a constant can be replaced with the
corresponding constant value, BLENDVPS and AVX masked load/store with
either an 'all on' or 'all off' masks can be replaced with simpler
operations.
@todo The better thing to do would be to submit a patch to LLVM to get
these; they're presumably pretty simple patterns to match.
*/
class IntrinsicsOpt : public llvm::BasicBlockPass {
public:
IntrinsicsOpt() : BasicBlockPass(ID) {};
const char *getPassName() const { return "Intrinsics Cleanup Optimization"; }
bool runOnBasicBlock(llvm::BasicBlock &BB);
static char ID;
private:
struct MaskInstruction {
MaskInstruction(llvm::Function *f) { function = f; }
llvm::Function *function;
};
std::vector<MaskInstruction> maskInstructions;
/** Structure that records everything we need to know about a blend
instruction for this optimization pass.
*/
struct BlendInstruction {
BlendInstruction(llvm::Function *f, uint64_t ao, int o0, int o1, int of)
: function(f), allOnMask(ao), op0(o0), op1(o1), opFactor(of) { }
/** Function pointer for the blend instruction */
llvm::Function *function;
/** Mask value for an "all on" mask for this instruction */
uint64_t allOnMask;
/** The operand number in the llvm CallInst corresponds to the
first operand to blend with. */
int op0;
/** The operand number in the CallInst corresponding to the second
operand to blend with. */
int op1;
/** The operand in the call inst where the blending factor is
found. */
int opFactor;
};
std::vector<BlendInstruction> blendInstructions;
bool matchesMaskInstruction(llvm::Function *function);
BlendInstruction *matchingBlendInstruction(llvm::Function *function);
};
char IntrinsicsOpt::ID = 0;
/** Given an llvm::Value, return true if we can determine that it's an
undefined value. This only makes a weak attempt at chasing this down,
only detecting flat-out undef values, and bitcasts of undef values.
@todo Is it worth working harder to find more of these? It starts to
get tricky, since having an undef operand doesn't necessarily mean that
the result will be undefined. (And for that matter, is there an LLVM
call that will do this for us?)
*/
static bool
lIsUndef(llvm::Value *value) {
if (llvm::isa<llvm::UndefValue>(value))
return true;