forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSPIRVModuleAnalysis.cpp
More file actions
2105 lines (1980 loc) · 84.3 KB
/
Copy pathSPIRVModuleAnalysis.cpp
File metadata and controls
2105 lines (1980 loc) · 84.3 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
//===- SPIRVModuleAnalysis.cpp - analysis of global instrs & regs - C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// The analysis collects instructions that should be output at the module level
// and performs the global register numbering.
//
// The results of this analysis are used in AsmPrinter to rename registers
// globally and to output required instructions at the module level.
//
//===----------------------------------------------------------------------===//
#include "SPIRVModuleAnalysis.h"
#include "MCTargetDesc/SPIRVBaseInfo.h"
#include "MCTargetDesc/SPIRVMCTargetDesc.h"
#include "SPIRV.h"
#include "SPIRVSubtarget.h"
#include "SPIRVTargetMachine.h"
#include "SPIRVUtils.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/TargetPassConfig.h"
using namespace llvm;
#define DEBUG_TYPE "spirv-module-analysis"
static cl::opt<bool>
SPVDumpDeps("spv-dump-deps",
cl::desc("Dump MIR with SPIR-V dependencies info"),
cl::Optional, cl::init(false));
static cl::list<SPIRV::Capability::Capability>
AvoidCapabilities("avoid-spirv-capabilities",
cl::desc("SPIR-V capabilities to avoid if there are "
"other options enabling a feature"),
cl::ZeroOrMore, cl::Hidden,
cl::values(clEnumValN(SPIRV::Capability::Shader, "Shader",
"SPIR-V Shader capability")));
// Use sets instead of cl::list to check "if contains" condition
struct AvoidCapabilitiesSet {
SmallSet<SPIRV::Capability::Capability, 4> S;
AvoidCapabilitiesSet() { S.insert_range(AvoidCapabilities); }
};
char llvm::SPIRVModuleAnalysis::ID = 0;
INITIALIZE_PASS(SPIRVModuleAnalysis, DEBUG_TYPE, "SPIRV module analysis", true,
true)
// Retrieve an unsigned from an MDNode with a list of them as operands.
static unsigned getMetadataUInt(MDNode *MdNode, unsigned OpIndex,
unsigned DefaultVal = 0) {
if (MdNode && OpIndex < MdNode->getNumOperands()) {
const auto &Op = MdNode->getOperand(OpIndex);
return mdconst::extract<ConstantInt>(Op)->getZExtValue();
}
return DefaultVal;
}
static SPIRV::Requirements
getSymbolicOperandRequirements(SPIRV::OperandCategory::OperandCategory Category,
unsigned i, const SPIRVSubtarget &ST,
SPIRV::RequirementHandler &Reqs) {
// A set of capabilities to avoid if there is another option.
AvoidCapabilitiesSet AvoidCaps;
if (!ST.isShader())
AvoidCaps.S.insert(SPIRV::Capability::Shader);
VersionTuple ReqMinVer = getSymbolicOperandMinVersion(Category, i);
VersionTuple ReqMaxVer = getSymbolicOperandMaxVersion(Category, i);
VersionTuple SPIRVVersion = ST.getSPIRVVersion();
bool MinVerOK = SPIRVVersion.empty() || SPIRVVersion >= ReqMinVer;
bool MaxVerOK =
ReqMaxVer.empty() || SPIRVVersion.empty() || SPIRVVersion <= ReqMaxVer;
CapabilityList ReqCaps = getSymbolicOperandCapabilities(Category, i);
ExtensionList ReqExts = getSymbolicOperandExtensions(Category, i);
if (ReqCaps.empty()) {
if (ReqExts.empty()) {
if (MinVerOK && MaxVerOK)
return {true, {}, {}, ReqMinVer, ReqMaxVer};
return {false, {}, {}, VersionTuple(), VersionTuple()};
}
} else if (MinVerOK && MaxVerOK) {
if (ReqCaps.size() == 1) {
auto Cap = ReqCaps[0];
if (Reqs.isCapabilityAvailable(Cap))
return {true, {Cap}, ReqExts, ReqMinVer, ReqMaxVer};
} else {
// By SPIR-V specification: "If an instruction, enumerant, or other
// feature specifies multiple enabling capabilities, only one such
// capability needs to be declared to use the feature." However, one
// capability may be preferred over another. We use command line
// argument(s) and AvoidCapabilities to avoid selection of certain
// capabilities if there are other options.
CapabilityList UseCaps;
for (auto Cap : ReqCaps)
if (Reqs.isCapabilityAvailable(Cap))
UseCaps.push_back(Cap);
for (size_t i = 0, Sz = UseCaps.size(); i < Sz; ++i) {
auto Cap = UseCaps[i];
if (i == Sz - 1 || !AvoidCaps.S.contains(Cap))
return {true, {Cap}, ReqExts, ReqMinVer, ReqMaxVer};
}
}
}
// If there are no capabilities, or we can't satisfy the version or
// capability requirements, use the list of extensions (if the subtarget
// can handle them all).
if (llvm::all_of(ReqExts, [&ST](const SPIRV::Extension::Extension &Ext) {
return ST.canUseExtension(Ext);
})) {
return {true,
{},
ReqExts,
VersionTuple(),
VersionTuple()}; // TODO: add versions to extensions.
}
return {false, {}, {}, VersionTuple(), VersionTuple()};
}
void SPIRVModuleAnalysis::setBaseInfo(const Module &M) {
MAI.MaxID = 0;
for (int i = 0; i < SPIRV::NUM_MODULE_SECTIONS; i++)
MAI.MS[i].clear();
MAI.RegisterAliasTable.clear();
MAI.InstrsToDelete.clear();
MAI.FuncMap.clear();
MAI.GlobalVarList.clear();
MAI.ExtInstSetMap.clear();
MAI.Reqs.clear();
MAI.Reqs.initAvailableCapabilities(*ST);
// TODO: determine memory model and source language from the configuratoin.
if (auto MemModel = M.getNamedMetadata("spirv.MemoryModel")) {
auto MemMD = MemModel->getOperand(0);
MAI.Addr = static_cast<SPIRV::AddressingModel::AddressingModel>(
getMetadataUInt(MemMD, 0));
MAI.Mem =
static_cast<SPIRV::MemoryModel::MemoryModel>(getMetadataUInt(MemMD, 1));
} else {
// TODO: Add support for VulkanMemoryModel.
MAI.Mem = ST->isShader() ? SPIRV::MemoryModel::GLSL450
: SPIRV::MemoryModel::OpenCL;
if (MAI.Mem == SPIRV::MemoryModel::OpenCL) {
unsigned PtrSize = ST->getPointerSize();
MAI.Addr = PtrSize == 32 ? SPIRV::AddressingModel::Physical32
: PtrSize == 64 ? SPIRV::AddressingModel::Physical64
: SPIRV::AddressingModel::Logical;
} else {
// TODO: Add support for PhysicalStorageBufferAddress.
MAI.Addr = SPIRV::AddressingModel::Logical;
}
}
// Get the OpenCL version number from metadata.
// TODO: support other source languages.
if (auto VerNode = M.getNamedMetadata("opencl.ocl.version")) {
MAI.SrcLang = SPIRV::SourceLanguage::OpenCL_C;
// Construct version literal in accordance with SPIRV-LLVM-Translator.
// TODO: support multiple OCL version metadata.
assert(VerNode->getNumOperands() > 0 && "Invalid SPIR");
auto VersionMD = VerNode->getOperand(0);
unsigned MajorNum = getMetadataUInt(VersionMD, 0, 2);
unsigned MinorNum = getMetadataUInt(VersionMD, 1);
unsigned RevNum = getMetadataUInt(VersionMD, 2);
// Prevent Major part of OpenCL version to be 0
MAI.SrcLangVersion =
(std::max(1U, MajorNum) * 100 + MinorNum) * 1000 + RevNum;
} else {
// If there is no information about OpenCL version we are forced to generate
// OpenCL 1.0 by default for the OpenCL environment to avoid puzzling
// run-times with Unknown/0.0 version output. For a reference, LLVM-SPIRV
// Translator avoids potential issues with run-times in a similar manner.
if (!ST->isShader()) {
MAI.SrcLang = SPIRV::SourceLanguage::OpenCL_CPP;
MAI.SrcLangVersion = 100000;
} else {
MAI.SrcLang = SPIRV::SourceLanguage::Unknown;
MAI.SrcLangVersion = 0;
}
}
if (auto ExtNode = M.getNamedMetadata("opencl.used.extensions")) {
for (unsigned I = 0, E = ExtNode->getNumOperands(); I != E; ++I) {
MDNode *MD = ExtNode->getOperand(I);
if (!MD || MD->getNumOperands() == 0)
continue;
for (unsigned J = 0, N = MD->getNumOperands(); J != N; ++J)
MAI.SrcExt.insert(cast<MDString>(MD->getOperand(J))->getString());
}
}
// Update required capabilities for this memory model, addressing model and
// source language.
MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::MemoryModelOperand,
MAI.Mem, *ST);
MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::SourceLanguageOperand,
MAI.SrcLang, *ST);
MAI.Reqs.getAndAddRequirements(SPIRV::OperandCategory::AddressingModelOperand,
MAI.Addr, *ST);
if (!ST->isShader()) {
// TODO: check if it's required by default.
MAI.ExtInstSetMap[static_cast<unsigned>(
SPIRV::InstructionSet::OpenCL_std)] = MAI.getNextIDRegister();
}
}
// Appends the signature of the decoration instructions that decorate R to
// Signature.
static void appendDecorationsForReg(const MachineRegisterInfo &MRI, Register R,
InstrSignature &Signature) {
for (MachineInstr &UseMI : MRI.use_instructions(R)) {
// We don't handle OpDecorateId because getting the register alias for the
// ID can cause problems, and we do not need it for now.
if (UseMI.getOpcode() != SPIRV::OpDecorate &&
UseMI.getOpcode() != SPIRV::OpMemberDecorate)
continue;
for (unsigned I = 0; I < UseMI.getNumOperands(); ++I) {
const MachineOperand &MO = UseMI.getOperand(I);
if (MO.isReg())
continue;
Signature.push_back(hash_value(MO));
}
}
}
// Returns a representation of an instruction as a vector of MachineOperand
// hash values, see llvm::hash_value(const MachineOperand &MO) for details.
// This creates a signature of the instruction with the same content
// that MachineOperand::isIdenticalTo uses for comparison.
static InstrSignature instrToSignature(const MachineInstr &MI,
SPIRV::ModuleAnalysisInfo &MAI,
bool UseDefReg) {
Register DefReg;
InstrSignature Signature{MI.getOpcode()};
for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
const MachineOperand &MO = MI.getOperand(i);
size_t h;
if (MO.isReg()) {
if (!UseDefReg && MO.isDef()) {
assert(!DefReg.isValid() && "Multiple def registers.");
DefReg = MO.getReg();
continue;
}
Register RegAlias = MAI.getRegisterAlias(MI.getMF(), MO.getReg());
if (!RegAlias.isValid()) {
LLVM_DEBUG({
dbgs() << "Unexpectedly, no global id found for the operand ";
MO.print(dbgs());
dbgs() << "\nInstruction: ";
MI.print(dbgs());
dbgs() << "\n";
});
report_fatal_error("All v-regs must have been mapped to global id's");
}
// mimic llvm::hash_value(const MachineOperand &MO)
h = hash_combine(MO.getType(), (unsigned)RegAlias, MO.getSubReg(),
MO.isDef());
} else {
h = hash_value(MO);
}
Signature.push_back(h);
}
if (DefReg.isValid()) {
// Decorations change the semantics of the current instruction. So two
// identical instruction with different decorations cannot be merged. That
// is why we add the decorations to the signature.
appendDecorationsForReg(MI.getMF()->getRegInfo(), DefReg, Signature);
}
return Signature;
}
bool SPIRVModuleAnalysis::isDeclSection(const MachineRegisterInfo &MRI,
const MachineInstr &MI) {
unsigned Opcode = MI.getOpcode();
switch (Opcode) {
case SPIRV::OpTypeForwardPointer:
// omit now, collect later
return false;
case SPIRV::OpVariable:
return static_cast<SPIRV::StorageClass::StorageClass>(
MI.getOperand(2).getImm()) != SPIRV::StorageClass::Function;
case SPIRV::OpFunction:
case SPIRV::OpFunctionParameter:
return true;
}
if (GR->hasConstFunPtr() && Opcode == SPIRV::OpUndef) {
Register DefReg = MI.getOperand(0).getReg();
for (MachineInstr &UseMI : MRI.use_instructions(DefReg)) {
if (UseMI.getOpcode() != SPIRV::OpConstantFunctionPointerINTEL)
continue;
// it's a dummy definition, FP constant refers to a function,
// and this is resolved in another way; let's skip this definition
assert(UseMI.getOperand(2).isReg() &&
UseMI.getOperand(2).getReg() == DefReg);
MAI.setSkipEmission(&MI);
return false;
}
}
return TII->isTypeDeclInstr(MI) || TII->isConstantInstr(MI) ||
TII->isInlineAsmDefInstr(MI);
}
// This is a special case of a function pointer refering to a possibly
// forward function declaration. The operand is a dummy OpUndef that
// requires a special treatment.
void SPIRVModuleAnalysis::visitFunPtrUse(
Register OpReg, InstrGRegsMap &SignatureToGReg,
std::map<const Value *, unsigned> &GlobalToGReg, const MachineFunction *MF,
const MachineInstr &MI) {
const MachineOperand *OpFunDef =
GR->getFunctionDefinitionByUse(&MI.getOperand(2));
assert(OpFunDef && OpFunDef->isReg());
// find the actual function definition and number it globally in advance
const MachineInstr *OpDefMI = OpFunDef->getParent();
assert(OpDefMI && OpDefMI->getOpcode() == SPIRV::OpFunction);
const MachineFunction *FunDefMF = OpDefMI->getParent()->getParent();
const MachineRegisterInfo &FunDefMRI = FunDefMF->getRegInfo();
do {
visitDecl(FunDefMRI, SignatureToGReg, GlobalToGReg, FunDefMF, *OpDefMI);
OpDefMI = OpDefMI->getNextNode();
} while (OpDefMI && (OpDefMI->getOpcode() == SPIRV::OpFunction ||
OpDefMI->getOpcode() == SPIRV::OpFunctionParameter));
// associate the function pointer with the newly assigned global number
MCRegister GlobalFunDefReg =
MAI.getRegisterAlias(FunDefMF, OpFunDef->getReg());
assert(GlobalFunDefReg.isValid() &&
"Function definition must refer to a global register");
MAI.setRegisterAlias(MF, OpReg, GlobalFunDefReg);
}
// Depth first recursive traversal of dependencies. Repeated visits are guarded
// by MAI.hasRegisterAlias().
void SPIRVModuleAnalysis::visitDecl(
const MachineRegisterInfo &MRI, InstrGRegsMap &SignatureToGReg,
std::map<const Value *, unsigned> &GlobalToGReg, const MachineFunction *MF,
const MachineInstr &MI) {
unsigned Opcode = MI.getOpcode();
// Process each operand of the instruction to resolve dependencies
for (const MachineOperand &MO : MI.operands()) {
if (!MO.isReg() || MO.isDef())
continue;
Register OpReg = MO.getReg();
// Handle function pointers special case
if (Opcode == SPIRV::OpConstantFunctionPointerINTEL &&
MRI.getRegClass(OpReg) == &SPIRV::pIDRegClass) {
visitFunPtrUse(OpReg, SignatureToGReg, GlobalToGReg, MF, MI);
continue;
}
// Skip already processed instructions
if (MAI.hasRegisterAlias(MF, MO.getReg()))
continue;
// Recursively visit dependencies
if (const MachineInstr *OpDefMI = MRI.getUniqueVRegDef(OpReg)) {
if (isDeclSection(MRI, *OpDefMI))
visitDecl(MRI, SignatureToGReg, GlobalToGReg, MF, *OpDefMI);
continue;
}
// Handle the unexpected case of no unique definition for the SPIR-V
// instruction
LLVM_DEBUG({
dbgs() << "Unexpectedly, no unique definition for the operand ";
MO.print(dbgs());
dbgs() << "\nInstruction: ";
MI.print(dbgs());
dbgs() << "\n";
});
report_fatal_error(
"No unique definition is found for the virtual register");
}
MCRegister GReg;
bool IsFunDef = false;
if (TII->isSpecConstantInstr(MI)) {
GReg = MAI.getNextIDRegister();
MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
} else if (Opcode == SPIRV::OpFunction ||
Opcode == SPIRV::OpFunctionParameter) {
GReg = handleFunctionOrParameter(MF, MI, GlobalToGReg, IsFunDef);
} else if (Opcode == SPIRV::OpTypeStruct ||
Opcode == SPIRV::OpConstantComposite) {
GReg = handleTypeDeclOrConstant(MI, SignatureToGReg);
const MachineInstr *NextInstr = MI.getNextNode();
while (NextInstr &&
((Opcode == SPIRV::OpTypeStruct &&
NextInstr->getOpcode() == SPIRV::OpTypeStructContinuedINTEL) ||
(Opcode == SPIRV::OpConstantComposite &&
NextInstr->getOpcode() ==
SPIRV::OpConstantCompositeContinuedINTEL))) {
MCRegister Tmp = handleTypeDeclOrConstant(*NextInstr, SignatureToGReg);
MAI.setRegisterAlias(MF, NextInstr->getOperand(0).getReg(), Tmp);
MAI.setSkipEmission(NextInstr);
NextInstr = NextInstr->getNextNode();
}
} else if (TII->isTypeDeclInstr(MI) || TII->isConstantInstr(MI) ||
TII->isInlineAsmDefInstr(MI)) {
GReg = handleTypeDeclOrConstant(MI, SignatureToGReg);
} else if (Opcode == SPIRV::OpVariable) {
GReg = handleVariable(MF, MI, GlobalToGReg);
} else {
LLVM_DEBUG({
dbgs() << "\nInstruction: ";
MI.print(dbgs());
dbgs() << "\n";
});
llvm_unreachable("Unexpected instruction is visited");
}
MAI.setRegisterAlias(MF, MI.getOperand(0).getReg(), GReg);
if (!IsFunDef)
MAI.setSkipEmission(&MI);
}
MCRegister SPIRVModuleAnalysis::handleFunctionOrParameter(
const MachineFunction *MF, const MachineInstr &MI,
std::map<const Value *, unsigned> &GlobalToGReg, bool &IsFunDef) {
const Value *GObj = GR->getGlobalObject(MF, MI.getOperand(0).getReg());
assert(GObj && "Unregistered global definition");
const Function *F = dyn_cast<Function>(GObj);
if (!F)
F = dyn_cast<Argument>(GObj)->getParent();
assert(F && "Expected a reference to a function or an argument");
IsFunDef = !F->isDeclaration();
auto [It, Inserted] = GlobalToGReg.try_emplace(GObj);
if (!Inserted)
return It->second;
MCRegister GReg = MAI.getNextIDRegister();
It->second = GReg;
if (!IsFunDef)
MAI.MS[SPIRV::MB_ExtFuncDecls].push_back(&MI);
return GReg;
}
MCRegister
SPIRVModuleAnalysis::handleTypeDeclOrConstant(const MachineInstr &MI,
InstrGRegsMap &SignatureToGReg) {
InstrSignature MISign = instrToSignature(MI, MAI, false);
auto [It, Inserted] = SignatureToGReg.try_emplace(MISign);
if (!Inserted)
return It->second;
MCRegister GReg = MAI.getNextIDRegister();
It->second = GReg;
MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
return GReg;
}
MCRegister SPIRVModuleAnalysis::handleVariable(
const MachineFunction *MF, const MachineInstr &MI,
std::map<const Value *, unsigned> &GlobalToGReg) {
MAI.GlobalVarList.push_back(&MI);
const Value *GObj = GR->getGlobalObject(MF, MI.getOperand(0).getReg());
assert(GObj && "Unregistered global definition");
auto [It, Inserted] = GlobalToGReg.try_emplace(GObj);
if (!Inserted)
return It->second;
MCRegister GReg = MAI.getNextIDRegister();
It->second = GReg;
MAI.MS[SPIRV::MB_TypeConstVars].push_back(&MI);
return GReg;
}
void SPIRVModuleAnalysis::collectDeclarations(const Module &M) {
InstrGRegsMap SignatureToGReg;
std::map<const Value *, unsigned> GlobalToGReg;
for (auto F = M.begin(), E = M.end(); F != E; ++F) {
MachineFunction *MF = MMI->getMachineFunction(*F);
if (!MF)
continue;
const MachineRegisterInfo &MRI = MF->getRegInfo();
unsigned PastHeader = 0;
for (MachineBasicBlock &MBB : *MF) {
for (MachineInstr &MI : MBB) {
if (MI.getNumOperands() == 0)
continue;
unsigned Opcode = MI.getOpcode();
if (Opcode == SPIRV::OpFunction) {
if (PastHeader == 0) {
PastHeader = 1;
continue;
}
} else if (Opcode == SPIRV::OpFunctionParameter) {
if (PastHeader < 2)
continue;
} else if (PastHeader > 0) {
PastHeader = 2;
}
const MachineOperand &DefMO = MI.getOperand(0);
switch (Opcode) {
case SPIRV::OpExtension:
MAI.Reqs.addExtension(SPIRV::Extension::Extension(DefMO.getImm()));
MAI.setSkipEmission(&MI);
break;
case SPIRV::OpCapability:
MAI.Reqs.addCapability(SPIRV::Capability::Capability(DefMO.getImm()));
MAI.setSkipEmission(&MI);
if (PastHeader > 0)
PastHeader = 2;
break;
default:
if (DefMO.isReg() && isDeclSection(MRI, MI) &&
!MAI.hasRegisterAlias(MF, DefMO.getReg()))
visitDecl(MRI, SignatureToGReg, GlobalToGReg, MF, MI);
}
}
}
}
}
// Look for IDs declared with Import linkage, and map the corresponding function
// to the register defining that variable (which will usually be the result of
// an OpFunction). This lets us call externally imported functions using
// the correct ID registers.
void SPIRVModuleAnalysis::collectFuncNames(MachineInstr &MI,
const Function *F) {
if (MI.getOpcode() == SPIRV::OpDecorate) {
// If it's got Import linkage.
auto Dec = MI.getOperand(1).getImm();
if (Dec == static_cast<unsigned>(SPIRV::Decoration::LinkageAttributes)) {
auto Lnk = MI.getOperand(MI.getNumOperands() - 1).getImm();
if (Lnk == static_cast<unsigned>(SPIRV::LinkageType::Import)) {
// Map imported function name to function ID register.
const Function *ImportedFunc =
F->getParent()->getFunction(getStringImm(MI, 2));
Register Target = MI.getOperand(0).getReg();
MAI.FuncMap[ImportedFunc] = MAI.getRegisterAlias(MI.getMF(), Target);
}
}
} else if (MI.getOpcode() == SPIRV::OpFunction) {
// Record all internal OpFunction declarations.
Register Reg = MI.defs().begin()->getReg();
MCRegister GlobalReg = MAI.getRegisterAlias(MI.getMF(), Reg);
assert(GlobalReg.isValid());
MAI.FuncMap[F] = GlobalReg;
}
}
// Collect the given instruction in the specified MS. We assume global register
// numbering has already occurred by this point. We can directly compare reg
// arguments when detecting duplicates.
static void collectOtherInstr(MachineInstr &MI, SPIRV::ModuleAnalysisInfo &MAI,
SPIRV::ModuleSectionType MSType, InstrTraces &IS,
bool Append = true) {
MAI.setSkipEmission(&MI);
InstrSignature MISign = instrToSignature(MI, MAI, true);
auto FoundMI = IS.insert(MISign);
if (!FoundMI.second)
return; // insert failed, so we found a duplicate; don't add it to MAI.MS
// No duplicates, so add it.
if (Append)
MAI.MS[MSType].push_back(&MI);
else
MAI.MS[MSType].insert(MAI.MS[MSType].begin(), &MI);
}
// Some global instructions make reference to function-local ID regs, so cannot
// be correctly collected until these registers are globally numbered.
void SPIRVModuleAnalysis::processOtherInstrs(const Module &M) {
InstrTraces IS;
for (auto F = M.begin(), E = M.end(); F != E; ++F) {
if ((*F).isDeclaration())
continue;
MachineFunction *MF = MMI->getMachineFunction(*F);
assert(MF);
for (MachineBasicBlock &MBB : *MF)
for (MachineInstr &MI : MBB) {
if (MAI.getSkipEmission(&MI))
continue;
const unsigned OpCode = MI.getOpcode();
if (OpCode == SPIRV::OpString) {
collectOtherInstr(MI, MAI, SPIRV::MB_DebugStrings, IS);
} else if (OpCode == SPIRV::OpExtInst && MI.getOperand(2).isImm() &&
MI.getOperand(2).getImm() ==
SPIRV::InstructionSet::
NonSemantic_Shader_DebugInfo_100) {
MachineOperand Ins = MI.getOperand(3);
namespace NS = SPIRV::NonSemanticExtInst;
static constexpr int64_t GlobalNonSemanticDITy[] = {
NS::DebugSource, NS::DebugCompilationUnit, NS::DebugInfoNone,
NS::DebugTypeBasic, NS::DebugTypePointer};
bool IsGlobalDI = false;
for (unsigned Idx = 0; Idx < std::size(GlobalNonSemanticDITy); ++Idx)
IsGlobalDI |= Ins.getImm() == GlobalNonSemanticDITy[Idx];
if (IsGlobalDI)
collectOtherInstr(MI, MAI, SPIRV::MB_NonSemanticGlobalDI, IS);
} else if (OpCode == SPIRV::OpName || OpCode == SPIRV::OpMemberName) {
collectOtherInstr(MI, MAI, SPIRV::MB_DebugNames, IS);
} else if (OpCode == SPIRV::OpEntryPoint) {
collectOtherInstr(MI, MAI, SPIRV::MB_EntryPoints, IS);
} else if (TII->isAliasingInstr(MI)) {
collectOtherInstr(MI, MAI, SPIRV::MB_AliasingInsts, IS);
} else if (TII->isDecorationInstr(MI)) {
collectOtherInstr(MI, MAI, SPIRV::MB_Annotations, IS);
collectFuncNames(MI, &*F);
} else if (TII->isConstantInstr(MI)) {
// Now OpSpecConstant*s are not in DT,
// but they need to be collected anyway.
collectOtherInstr(MI, MAI, SPIRV::MB_TypeConstVars, IS);
} else if (OpCode == SPIRV::OpFunction) {
collectFuncNames(MI, &*F);
} else if (OpCode == SPIRV::OpTypeForwardPointer) {
collectOtherInstr(MI, MAI, SPIRV::MB_TypeConstVars, IS, false);
}
}
}
}
// Number registers in all functions globally from 0 onwards and store
// the result in global register alias table. Some registers are already
// numbered.
void SPIRVModuleAnalysis::numberRegistersGlobally(const Module &M) {
for (auto F = M.begin(), E = M.end(); F != E; ++F) {
if ((*F).isDeclaration())
continue;
MachineFunction *MF = MMI->getMachineFunction(*F);
assert(MF);
for (MachineBasicBlock &MBB : *MF) {
for (MachineInstr &MI : MBB) {
for (MachineOperand &Op : MI.operands()) {
if (!Op.isReg())
continue;
Register Reg = Op.getReg();
if (MAI.hasRegisterAlias(MF, Reg))
continue;
MCRegister NewReg = MAI.getNextIDRegister();
MAI.setRegisterAlias(MF, Reg, NewReg);
}
if (MI.getOpcode() != SPIRV::OpExtInst)
continue;
auto Set = MI.getOperand(2).getImm();
auto [It, Inserted] = MAI.ExtInstSetMap.try_emplace(Set);
if (Inserted)
It->second = MAI.getNextIDRegister();
}
}
}
}
// RequirementHandler implementations.
void SPIRV::RequirementHandler::getAndAddRequirements(
SPIRV::OperandCategory::OperandCategory Category, uint32_t i,
const SPIRVSubtarget &ST) {
addRequirements(getSymbolicOperandRequirements(Category, i, ST, *this));
}
void SPIRV::RequirementHandler::recursiveAddCapabilities(
const CapabilityList &ToPrune) {
for (const auto &Cap : ToPrune) {
AllCaps.insert(Cap);
CapabilityList ImplicitDecls =
getSymbolicOperandCapabilities(OperandCategory::CapabilityOperand, Cap);
recursiveAddCapabilities(ImplicitDecls);
}
}
void SPIRV::RequirementHandler::addCapabilities(const CapabilityList &ToAdd) {
for (const auto &Cap : ToAdd) {
bool IsNewlyInserted = AllCaps.insert(Cap).second;
if (!IsNewlyInserted) // Don't re-add if it's already been declared.
continue;
CapabilityList ImplicitDecls =
getSymbolicOperandCapabilities(OperandCategory::CapabilityOperand, Cap);
recursiveAddCapabilities(ImplicitDecls);
MinimalCaps.push_back(Cap);
}
}
void SPIRV::RequirementHandler::addRequirements(
const SPIRV::Requirements &Req) {
if (!Req.IsSatisfiable)
report_fatal_error("Adding SPIR-V requirements this target can't satisfy.");
if (Req.Cap.has_value())
addCapabilities({Req.Cap.value()});
addExtensions(Req.Exts);
if (!Req.MinVer.empty()) {
if (!MaxVersion.empty() && Req.MinVer > MaxVersion) {
LLVM_DEBUG(dbgs() << "Conflicting version requirements: >= " << Req.MinVer
<< " and <= " << MaxVersion << "\n");
report_fatal_error("Adding SPIR-V requirements that can't be satisfied.");
}
if (MinVersion.empty() || Req.MinVer > MinVersion)
MinVersion = Req.MinVer;
}
if (!Req.MaxVer.empty()) {
if (!MinVersion.empty() && Req.MaxVer < MinVersion) {
LLVM_DEBUG(dbgs() << "Conflicting version requirements: <= " << Req.MaxVer
<< " and >= " << MinVersion << "\n");
report_fatal_error("Adding SPIR-V requirements that can't be satisfied.");
}
if (MaxVersion.empty() || Req.MaxVer < MaxVersion)
MaxVersion = Req.MaxVer;
}
}
void SPIRV::RequirementHandler::checkSatisfiable(
const SPIRVSubtarget &ST) const {
// Report as many errors as possible before aborting the compilation.
bool IsSatisfiable = true;
auto TargetVer = ST.getSPIRVVersion();
if (!MaxVersion.empty() && !TargetVer.empty() && MaxVersion < TargetVer) {
LLVM_DEBUG(
dbgs() << "Target SPIR-V version too high for required features\n"
<< "Required max version: " << MaxVersion << " target version "
<< TargetVer << "\n");
IsSatisfiable = false;
}
if (!MinVersion.empty() && !TargetVer.empty() && MinVersion > TargetVer) {
LLVM_DEBUG(dbgs() << "Target SPIR-V version too low for required features\n"
<< "Required min version: " << MinVersion
<< " target version " << TargetVer << "\n");
IsSatisfiable = false;
}
if (!MinVersion.empty() && !MaxVersion.empty() && MinVersion > MaxVersion) {
LLVM_DEBUG(
dbgs()
<< "Version is too low for some features and too high for others.\n"
<< "Required SPIR-V min version: " << MinVersion
<< " required SPIR-V max version " << MaxVersion << "\n");
IsSatisfiable = false;
}
for (auto Cap : MinimalCaps) {
if (AvailableCaps.contains(Cap))
continue;
LLVM_DEBUG(dbgs() << "Capability not supported: "
<< getSymbolicOperandMnemonic(
OperandCategory::CapabilityOperand, Cap)
<< "\n");
IsSatisfiable = false;
}
for (auto Ext : AllExtensions) {
if (ST.canUseExtension(Ext))
continue;
LLVM_DEBUG(dbgs() << "Extension not supported: "
<< getSymbolicOperandMnemonic(
OperandCategory::ExtensionOperand, Ext)
<< "\n");
IsSatisfiable = false;
}
if (!IsSatisfiable)
report_fatal_error("Unable to meet SPIR-V requirements for this target.");
}
// Add the given capabilities and all their implicitly defined capabilities too.
void SPIRV::RequirementHandler::addAvailableCaps(const CapabilityList &ToAdd) {
for (const auto Cap : ToAdd)
if (AvailableCaps.insert(Cap).second)
addAvailableCaps(getSymbolicOperandCapabilities(
SPIRV::OperandCategory::CapabilityOperand, Cap));
}
void SPIRV::RequirementHandler::removeCapabilityIf(
const Capability::Capability ToRemove,
const Capability::Capability IfPresent) {
if (AllCaps.contains(IfPresent))
AllCaps.erase(ToRemove);
}
namespace llvm {
namespace SPIRV {
void RequirementHandler::initAvailableCapabilities(const SPIRVSubtarget &ST) {
// Provided by both all supported Vulkan versions and OpenCl.
addAvailableCaps({Capability::Shader, Capability::Linkage, Capability::Int8,
Capability::Int16});
if (ST.isAtLeastSPIRVVer(VersionTuple(1, 3)))
addAvailableCaps({Capability::GroupNonUniform,
Capability::GroupNonUniformVote,
Capability::GroupNonUniformArithmetic,
Capability::GroupNonUniformBallot,
Capability::GroupNonUniformClustered,
Capability::GroupNonUniformShuffle,
Capability::GroupNonUniformShuffleRelative});
if (ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
addAvailableCaps({Capability::DotProduct, Capability::DotProductInputAll,
Capability::DotProductInput4x8Bit,
Capability::DotProductInput4x8BitPacked,
Capability::DemoteToHelperInvocation});
// Add capabilities enabled by extensions.
for (auto Extension : ST.getAllAvailableExtensions()) {
CapabilityList EnabledCapabilities =
getCapabilitiesEnabledByExtension(Extension);
addAvailableCaps(EnabledCapabilities);
}
if (!ST.isShader()) {
initAvailableCapabilitiesForOpenCL(ST);
return;
}
if (ST.isShader()) {
initAvailableCapabilitiesForVulkan(ST);
return;
}
report_fatal_error("Unimplemented environment for SPIR-V generation.");
}
void RequirementHandler::initAvailableCapabilitiesForOpenCL(
const SPIRVSubtarget &ST) {
// Add the min requirements for different OpenCL and SPIR-V versions.
addAvailableCaps({Capability::Addresses, Capability::Float16Buffer,
Capability::Kernel, Capability::Vector16,
Capability::Groups, Capability::GenericPointer,
Capability::StorageImageWriteWithoutFormat,
Capability::StorageImageReadWithoutFormat});
if (ST.hasOpenCLFullProfile())
addAvailableCaps({Capability::Int64, Capability::Int64Atomics});
if (ST.hasOpenCLImageSupport()) {
addAvailableCaps({Capability::ImageBasic, Capability::LiteralSampler,
Capability::Image1D, Capability::SampledBuffer,
Capability::ImageBuffer});
if (ST.isAtLeastOpenCLVer(VersionTuple(2, 0)))
addAvailableCaps({Capability::ImageReadWrite});
}
if (ST.isAtLeastSPIRVVer(VersionTuple(1, 1)) &&
ST.isAtLeastOpenCLVer(VersionTuple(2, 2)))
addAvailableCaps({Capability::SubgroupDispatch, Capability::PipeStorage});
if (ST.isAtLeastSPIRVVer(VersionTuple(1, 4)))
addAvailableCaps({Capability::DenormPreserve, Capability::DenormFlushToZero,
Capability::SignedZeroInfNanPreserve,
Capability::RoundingModeRTE,
Capability::RoundingModeRTZ});
// TODO: verify if this needs some checks.
addAvailableCaps({Capability::Float16, Capability::Float64});
// TODO: add OpenCL extensions.
}
void RequirementHandler::initAvailableCapabilitiesForVulkan(
const SPIRVSubtarget &ST) {
// Core in Vulkan 1.1 and earlier.
addAvailableCaps({Capability::Int64, Capability::Float16, Capability::Float64,
Capability::GroupNonUniform, Capability::Image1D,
Capability::SampledBuffer, Capability::ImageBuffer,
Capability::UniformBufferArrayDynamicIndexing,
Capability::SampledImageArrayDynamicIndexing,
Capability::StorageBufferArrayDynamicIndexing,
Capability::StorageImageArrayDynamicIndexing});
// Became core in Vulkan 1.2
if (ST.isAtLeastSPIRVVer(VersionTuple(1, 5))) {
addAvailableCaps(
{Capability::ShaderNonUniformEXT, Capability::RuntimeDescriptorArrayEXT,
Capability::InputAttachmentArrayDynamicIndexingEXT,
Capability::UniformTexelBufferArrayDynamicIndexingEXT,
Capability::StorageTexelBufferArrayDynamicIndexingEXT,
Capability::UniformBufferArrayNonUniformIndexingEXT,
Capability::SampledImageArrayNonUniformIndexingEXT,
Capability::StorageBufferArrayNonUniformIndexingEXT,
Capability::StorageImageArrayNonUniformIndexingEXT,
Capability::InputAttachmentArrayNonUniformIndexingEXT,
Capability::UniformTexelBufferArrayNonUniformIndexingEXT,
Capability::StorageTexelBufferArrayNonUniformIndexingEXT});
}
// Became core in Vulkan 1.3
if (ST.isAtLeastSPIRVVer(VersionTuple(1, 6)))
addAvailableCaps({Capability::StorageImageWriteWithoutFormat,
Capability::StorageImageReadWithoutFormat});
}
} // namespace SPIRV
} // namespace llvm
// Add the required capabilities from a decoration instruction (including
// BuiltIns).
static void addOpDecorateReqs(const MachineInstr &MI, unsigned DecIndex,
SPIRV::RequirementHandler &Reqs,
const SPIRVSubtarget &ST) {
int64_t DecOp = MI.getOperand(DecIndex).getImm();
auto Dec = static_cast<SPIRV::Decoration::Decoration>(DecOp);
Reqs.addRequirements(getSymbolicOperandRequirements(
SPIRV::OperandCategory::DecorationOperand, Dec, ST, Reqs));
if (Dec == SPIRV::Decoration::BuiltIn) {
int64_t BuiltInOp = MI.getOperand(DecIndex + 1).getImm();
auto BuiltIn = static_cast<SPIRV::BuiltIn::BuiltIn>(BuiltInOp);
Reqs.addRequirements(getSymbolicOperandRequirements(
SPIRV::OperandCategory::BuiltInOperand, BuiltIn, ST, Reqs));
} else if (Dec == SPIRV::Decoration::LinkageAttributes) {
int64_t LinkageOp = MI.getOperand(MI.getNumOperands() - 1).getImm();
SPIRV::LinkageType::LinkageType LnkType =
static_cast<SPIRV::LinkageType::LinkageType>(LinkageOp);
if (LnkType == SPIRV::LinkageType::LinkOnceODR)
Reqs.addExtension(SPIRV::Extension::SPV_KHR_linkonce_odr);
} else if (Dec == SPIRV::Decoration::CacheControlLoadINTEL ||
Dec == SPIRV::Decoration::CacheControlStoreINTEL) {
Reqs.addExtension(SPIRV::Extension::SPV_INTEL_cache_controls);
} else if (Dec == SPIRV::Decoration::HostAccessINTEL) {
Reqs.addExtension(SPIRV::Extension::SPV_INTEL_global_variable_host_access);
} else if (Dec == SPIRV::Decoration::InitModeINTEL ||
Dec == SPIRV::Decoration::ImplementInRegisterMapINTEL) {
Reqs.addExtension(
SPIRV::Extension::SPV_INTEL_global_variable_fpga_decorations);
} else if (Dec == SPIRV::Decoration::NonUniformEXT) {
Reqs.addRequirements(SPIRV::Capability::ShaderNonUniformEXT);
} else if (Dec == SPIRV::Decoration::FPMaxErrorDecorationINTEL) {
Reqs.addRequirements(SPIRV::Capability::FPMaxErrorINTEL);
Reqs.addExtension(SPIRV::Extension::SPV_INTEL_fp_max_error);
}
}
// Add requirements for image handling.
static void addOpTypeImageReqs(const MachineInstr &MI,
SPIRV::RequirementHandler &Reqs,
const SPIRVSubtarget &ST) {
assert(MI.getNumOperands() >= 8 && "Insufficient operands for OpTypeImage");
// The operand indices used here are based on the OpTypeImage layout, which
// the MachineInstr follows as well.
int64_t ImgFormatOp = MI.getOperand(7).getImm();
auto ImgFormat = static_cast<SPIRV::ImageFormat::ImageFormat>(ImgFormatOp);
Reqs.getAndAddRequirements(SPIRV::OperandCategory::ImageFormatOperand,
ImgFormat, ST);
bool IsArrayed = MI.getOperand(4).getImm() == 1;
bool IsMultisampled = MI.getOperand(5).getImm() == 1;
bool NoSampler = MI.getOperand(6).getImm() == 2;
// Add dimension requirements.
assert(MI.getOperand(2).isImm());
switch (MI.getOperand(2).getImm()) {
case SPIRV::Dim::DIM_1D:
Reqs.addRequirements(NoSampler ? SPIRV::Capability::Image1D
: SPIRV::Capability::Sampled1D);
break;
case SPIRV::Dim::DIM_2D:
if (IsMultisampled && NoSampler)
Reqs.addRequirements(SPIRV::Capability::ImageMSArray);
break;
case SPIRV::Dim::DIM_Cube:
Reqs.addRequirements(SPIRV::Capability::Shader);
if (IsArrayed)
Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageCubeArray
: SPIRV::Capability::SampledCubeArray);
break;
case SPIRV::Dim::DIM_Rect:
Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageRect
: SPIRV::Capability::SampledRect);
break;
case SPIRV::Dim::DIM_Buffer:
Reqs.addRequirements(NoSampler ? SPIRV::Capability::ImageBuffer
: SPIRV::Capability::SampledBuffer);
break;
case SPIRV::Dim::DIM_SubpassData:
Reqs.addRequirements(SPIRV::Capability::InputAttachment);
break;
}
// Has optional access qualifier.
if (!ST.isShader()) {
if (MI.getNumOperands() > 8 &&
MI.getOperand(8).getImm() == SPIRV::AccessQualifier::ReadWrite)
Reqs.addRequirements(SPIRV::Capability::ImageReadWrite);
else
Reqs.addRequirements(SPIRV::Capability::ImageBasic);
}
}
// Add requirements for handling atomic float instructions
#define ATOM_FLT_REQ_EXT_MSG(ExtName) \
"The atomic float instruction requires the following SPIR-V " \
"extension: SPV_EXT_shader_atomic_float" ExtName
static void AddAtomicFloatRequirements(const MachineInstr &MI,
SPIRV::RequirementHandler &Reqs,
const SPIRVSubtarget &ST) {
assert(MI.getOperand(1).isReg() &&
"Expect register operand in atomic float instruction");
Register TypeReg = MI.getOperand(1).getReg();
SPIRVType *TypeDef = MI.getMF()->getRegInfo().getVRegDef(TypeReg);
if (TypeDef->getOpcode() != SPIRV::OpTypeFloat)
report_fatal_error("Result type of an atomic float instruction must be a "
"floating-point type scalar");
unsigned BitWidth = TypeDef->getOperand(1).getImm();
unsigned Op = MI.getOpcode();
if (Op == SPIRV::OpAtomicFAddEXT) {
if (!ST.canUseExtension(SPIRV::Extension::SPV_EXT_shader_atomic_float_add))
report_fatal_error(ATOM_FLT_REQ_EXT_MSG("_add"), false);