forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMIParser.cpp
3466 lines (3157 loc) · 112 KB
/
MIParser.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
//===- MIParser.cpp - Machine instructions parser implementation ----------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements the parsing of machine instructions.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MIRParser/MIParser.h"
#include "MILexer.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/AsmParser/Parser.h"
#include "llvm/AsmParser/SlotMapping.h"
#include "llvm/CodeGen/GlobalISel/RegisterBank.h"
#include "llvm/CodeGen/GlobalISel/RegisterBankInfo.h"
#include "llvm/CodeGen/MIRFormatter.h"
#include "llvm/CodeGen/MIRPrinter.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineMemOperand.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/ModuleSlotTracker.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/ValueSymbolTable.h"
#include "llvm/MC/LaneBitmask.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDwarf.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/BranchProbability.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LowLevelTypeImpl.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SMLoc.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetIntrinsicInfo.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <string>
#include <utility>
using namespace llvm;
void PerTargetMIParsingState::setTarget(
const TargetSubtargetInfo &NewSubtarget) {
// If the subtarget changed, over conservatively assume everything is invalid.
if (&Subtarget == &NewSubtarget)
return;
Names2InstrOpCodes.clear();
Names2Regs.clear();
Names2RegMasks.clear();
Names2SubRegIndices.clear();
Names2TargetIndices.clear();
Names2DirectTargetFlags.clear();
Names2BitmaskTargetFlags.clear();
Names2MMOTargetFlags.clear();
initNames2RegClasses();
initNames2RegBanks();
}
void PerTargetMIParsingState::initNames2Regs() {
if (!Names2Regs.empty())
return;
// The '%noreg' register is the register 0.
Names2Regs.insert(std::make_pair("noreg", 0));
const auto *TRI = Subtarget.getRegisterInfo();
assert(TRI && "Expected target register info");
for (unsigned I = 0, E = TRI->getNumRegs(); I < E; ++I) {
bool WasInserted =
Names2Regs.insert(std::make_pair(StringRef(TRI->getName(I)).lower(), I))
.second;
(void)WasInserted;
assert(WasInserted && "Expected registers to be unique case-insensitively");
}
}
bool PerTargetMIParsingState::getRegisterByName(StringRef RegName,
Register &Reg) {
initNames2Regs();
auto RegInfo = Names2Regs.find(RegName);
if (RegInfo == Names2Regs.end())
return true;
Reg = RegInfo->getValue();
return false;
}
void PerTargetMIParsingState::initNames2InstrOpCodes() {
if (!Names2InstrOpCodes.empty())
return;
const auto *TII = Subtarget.getInstrInfo();
assert(TII && "Expected target instruction info");
for (unsigned I = 0, E = TII->getNumOpcodes(); I < E; ++I)
Names2InstrOpCodes.insert(std::make_pair(StringRef(TII->getName(I)), I));
}
bool PerTargetMIParsingState::parseInstrName(StringRef InstrName,
unsigned &OpCode) {
initNames2InstrOpCodes();
auto InstrInfo = Names2InstrOpCodes.find(InstrName);
if (InstrInfo == Names2InstrOpCodes.end())
return true;
OpCode = InstrInfo->getValue();
return false;
}
void PerTargetMIParsingState::initNames2RegMasks() {
if (!Names2RegMasks.empty())
return;
const auto *TRI = Subtarget.getRegisterInfo();
assert(TRI && "Expected target register info");
ArrayRef<const uint32_t *> RegMasks = TRI->getRegMasks();
ArrayRef<const char *> RegMaskNames = TRI->getRegMaskNames();
assert(RegMasks.size() == RegMaskNames.size());
for (size_t I = 0, E = RegMasks.size(); I < E; ++I)
Names2RegMasks.insert(
std::make_pair(StringRef(RegMaskNames[I]).lower(), RegMasks[I]));
}
const uint32_t *PerTargetMIParsingState::getRegMask(StringRef Identifier) {
initNames2RegMasks();
auto RegMaskInfo = Names2RegMasks.find(Identifier);
if (RegMaskInfo == Names2RegMasks.end())
return nullptr;
return RegMaskInfo->getValue();
}
void PerTargetMIParsingState::initNames2SubRegIndices() {
if (!Names2SubRegIndices.empty())
return;
const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
for (unsigned I = 1, E = TRI->getNumSubRegIndices(); I < E; ++I)
Names2SubRegIndices.insert(
std::make_pair(TRI->getSubRegIndexName(I), I));
}
unsigned PerTargetMIParsingState::getSubRegIndex(StringRef Name) {
initNames2SubRegIndices();
auto SubRegInfo = Names2SubRegIndices.find(Name);
if (SubRegInfo == Names2SubRegIndices.end())
return 0;
return SubRegInfo->getValue();
}
void PerTargetMIParsingState::initNames2TargetIndices() {
if (!Names2TargetIndices.empty())
return;
const auto *TII = Subtarget.getInstrInfo();
assert(TII && "Expected target instruction info");
auto Indices = TII->getSerializableTargetIndices();
for (const auto &I : Indices)
Names2TargetIndices.insert(std::make_pair(StringRef(I.second), I.first));
}
bool PerTargetMIParsingState::getTargetIndex(StringRef Name, int &Index) {
initNames2TargetIndices();
auto IndexInfo = Names2TargetIndices.find(Name);
if (IndexInfo == Names2TargetIndices.end())
return true;
Index = IndexInfo->second;
return false;
}
void PerTargetMIParsingState::initNames2DirectTargetFlags() {
if (!Names2DirectTargetFlags.empty())
return;
const auto *TII = Subtarget.getInstrInfo();
assert(TII && "Expected target instruction info");
auto Flags = TII->getSerializableDirectMachineOperandTargetFlags();
for (const auto &I : Flags)
Names2DirectTargetFlags.insert(
std::make_pair(StringRef(I.second), I.first));
}
bool PerTargetMIParsingState::getDirectTargetFlag(StringRef Name,
unsigned &Flag) {
initNames2DirectTargetFlags();
auto FlagInfo = Names2DirectTargetFlags.find(Name);
if (FlagInfo == Names2DirectTargetFlags.end())
return true;
Flag = FlagInfo->second;
return false;
}
void PerTargetMIParsingState::initNames2BitmaskTargetFlags() {
if (!Names2BitmaskTargetFlags.empty())
return;
const auto *TII = Subtarget.getInstrInfo();
assert(TII && "Expected target instruction info");
auto Flags = TII->getSerializableBitmaskMachineOperandTargetFlags();
for (const auto &I : Flags)
Names2BitmaskTargetFlags.insert(
std::make_pair(StringRef(I.second), I.first));
}
bool PerTargetMIParsingState::getBitmaskTargetFlag(StringRef Name,
unsigned &Flag) {
initNames2BitmaskTargetFlags();
auto FlagInfo = Names2BitmaskTargetFlags.find(Name);
if (FlagInfo == Names2BitmaskTargetFlags.end())
return true;
Flag = FlagInfo->second;
return false;
}
void PerTargetMIParsingState::initNames2MMOTargetFlags() {
if (!Names2MMOTargetFlags.empty())
return;
const auto *TII = Subtarget.getInstrInfo();
assert(TII && "Expected target instruction info");
auto Flags = TII->getSerializableMachineMemOperandTargetFlags();
for (const auto &I : Flags)
Names2MMOTargetFlags.insert(std::make_pair(StringRef(I.second), I.first));
}
bool PerTargetMIParsingState::getMMOTargetFlag(StringRef Name,
MachineMemOperand::Flags &Flag) {
initNames2MMOTargetFlags();
auto FlagInfo = Names2MMOTargetFlags.find(Name);
if (FlagInfo == Names2MMOTargetFlags.end())
return true;
Flag = FlagInfo->second;
return false;
}
void PerTargetMIParsingState::initNames2RegClasses() {
if (!Names2RegClasses.empty())
return;
const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
for (unsigned I = 0, E = TRI->getNumRegClasses(); I < E; ++I) {
const auto *RC = TRI->getRegClass(I);
Names2RegClasses.insert(
std::make_pair(StringRef(TRI->getRegClassName(RC)).lower(), RC));
}
}
void PerTargetMIParsingState::initNames2RegBanks() {
if (!Names2RegBanks.empty())
return;
const RegisterBankInfo *RBI = Subtarget.getRegBankInfo();
// If the target does not support GlobalISel, we may not have a
// register bank info.
if (!RBI)
return;
for (unsigned I = 0, E = RBI->getNumRegBanks(); I < E; ++I) {
const auto &RegBank = RBI->getRegBank(I);
Names2RegBanks.insert(
std::make_pair(StringRef(RegBank.getName()).lower(), &RegBank));
}
}
const TargetRegisterClass *
PerTargetMIParsingState::getRegClass(StringRef Name) {
auto RegClassInfo = Names2RegClasses.find(Name);
if (RegClassInfo == Names2RegClasses.end())
return nullptr;
return RegClassInfo->getValue();
}
const RegisterBank *PerTargetMIParsingState::getRegBank(StringRef Name) {
auto RegBankInfo = Names2RegBanks.find(Name);
if (RegBankInfo == Names2RegBanks.end())
return nullptr;
return RegBankInfo->getValue();
}
PerFunctionMIParsingState::PerFunctionMIParsingState(MachineFunction &MF,
SourceMgr &SM, const SlotMapping &IRSlots, PerTargetMIParsingState &T)
: MF(MF), SM(&SM), IRSlots(IRSlots), Target(T) {
}
VRegInfo &PerFunctionMIParsingState::getVRegInfo(Register Num) {
auto I = VRegInfos.insert(std::make_pair(Num, nullptr));
if (I.second) {
MachineRegisterInfo &MRI = MF.getRegInfo();
VRegInfo *Info = new (Allocator) VRegInfo;
Info->VReg = MRI.createIncompleteVirtualRegister();
I.first->second = Info;
}
return *I.first->second;
}
VRegInfo &PerFunctionMIParsingState::getVRegInfoNamed(StringRef RegName) {
assert(RegName != "" && "Expected named reg.");
auto I = VRegInfosNamed.insert(std::make_pair(RegName.str(), nullptr));
if (I.second) {
VRegInfo *Info = new (Allocator) VRegInfo;
Info->VReg = MF.getRegInfo().createIncompleteVirtualRegister(RegName);
I.first->second = Info;
}
return *I.first->second;
}
static void mapValueToSlot(const Value *V, ModuleSlotTracker &MST,
DenseMap<unsigned, const Value *> &Slots2Values) {
int Slot = MST.getLocalSlot(V);
if (Slot == -1)
return;
Slots2Values.insert(std::make_pair(unsigned(Slot), V));
}
/// Creates the mapping from slot numbers to function's unnamed IR values.
static void initSlots2Values(const Function &F,
DenseMap<unsigned, const Value *> &Slots2Values) {
ModuleSlotTracker MST(F.getParent(), /*ShouldInitializeAllMetadata=*/false);
MST.incorporateFunction(F);
for (const auto &Arg : F.args())
mapValueToSlot(&Arg, MST, Slots2Values);
for (const auto &BB : F) {
mapValueToSlot(&BB, MST, Slots2Values);
for (const auto &I : BB)
mapValueToSlot(&I, MST, Slots2Values);
}
}
const Value* PerFunctionMIParsingState::getIRValue(unsigned Slot) {
if (Slots2Values.empty())
initSlots2Values(MF.getFunction(), Slots2Values);
return Slots2Values.lookup(Slot);
}
namespace {
/// A wrapper struct around the 'MachineOperand' struct that includes a source
/// range and other attributes.
struct ParsedMachineOperand {
MachineOperand Operand;
StringRef::iterator Begin;
StringRef::iterator End;
Optional<unsigned> TiedDefIdx;
ParsedMachineOperand(const MachineOperand &Operand, StringRef::iterator Begin,
StringRef::iterator End, Optional<unsigned> &TiedDefIdx)
: Operand(Operand), Begin(Begin), End(End), TiedDefIdx(TiedDefIdx) {
if (TiedDefIdx)
assert(Operand.isReg() && Operand.isUse() &&
"Only used register operands can be tied");
}
};
class MIParser {
MachineFunction &MF;
SMDiagnostic &Error;
StringRef Source, CurrentSource;
SMRange SourceRange;
MIToken Token;
PerFunctionMIParsingState &PFS;
/// Maps from slot numbers to function's unnamed basic blocks.
DenseMap<unsigned, const BasicBlock *> Slots2BasicBlocks;
public:
MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
StringRef Source);
MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
StringRef Source, SMRange SourceRange);
/// \p SkipChar gives the number of characters to skip before looking
/// for the next token.
void lex(unsigned SkipChar = 0);
/// Report an error at the current location with the given message.
///
/// This function always return true.
bool error(const Twine &Msg);
/// Report an error at the given location with the given message.
///
/// This function always return true.
bool error(StringRef::iterator Loc, const Twine &Msg);
bool
parseBasicBlockDefinitions(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
bool parseBasicBlocks();
bool parse(MachineInstr *&MI);
bool parseStandaloneMBB(MachineBasicBlock *&MBB);
bool parseStandaloneNamedRegister(Register &Reg);
bool parseStandaloneVirtualRegister(VRegInfo *&Info);
bool parseStandaloneRegister(Register &Reg);
bool parseStandaloneStackObject(int &FI);
bool parseStandaloneMDNode(MDNode *&Node);
bool parseMachineMetadata();
bool parseMDTuple(MDNode *&MD, bool IsDistinct);
bool parseMDNodeVector(SmallVectorImpl<Metadata *> &Elts);
bool parseMetadata(Metadata *&MD);
bool
parseBasicBlockDefinition(DenseMap<unsigned, MachineBasicBlock *> &MBBSlots);
bool parseBasicBlock(MachineBasicBlock &MBB,
MachineBasicBlock *&AddFalthroughFrom);
bool parseBasicBlockLiveins(MachineBasicBlock &MBB);
bool parseBasicBlockSuccessors(MachineBasicBlock &MBB);
bool parseNamedRegister(Register &Reg);
bool parseVirtualRegister(VRegInfo *&Info);
bool parseNamedVirtualRegister(VRegInfo *&Info);
bool parseRegister(Register &Reg, VRegInfo *&VRegInfo);
bool parseRegisterFlag(unsigned &Flags);
bool parseRegisterClassOrBank(VRegInfo &RegInfo);
bool parseSubRegisterIndex(unsigned &SubReg);
bool parseRegisterTiedDefIndex(unsigned &TiedDefIdx);
bool parseRegisterOperand(MachineOperand &Dest,
Optional<unsigned> &TiedDefIdx, bool IsDef = false);
bool parseImmediateOperand(MachineOperand &Dest);
bool parseIRConstant(StringRef::iterator Loc, StringRef StringValue,
const Constant *&C);
bool parseIRConstant(StringRef::iterator Loc, const Constant *&C);
bool parseLowLevelType(StringRef::iterator Loc, LLT &Ty);
bool parseTypedImmediateOperand(MachineOperand &Dest);
bool parseFPImmediateOperand(MachineOperand &Dest);
bool parseMBBReference(MachineBasicBlock *&MBB);
bool parseMBBOperand(MachineOperand &Dest);
bool parseStackFrameIndex(int &FI);
bool parseStackObjectOperand(MachineOperand &Dest);
bool parseFixedStackFrameIndex(int &FI);
bool parseFixedStackObjectOperand(MachineOperand &Dest);
bool parseGlobalValue(GlobalValue *&GV);
bool parseGlobalAddressOperand(MachineOperand &Dest);
bool parseConstantPoolIndexOperand(MachineOperand &Dest);
bool parseSubRegisterIndexOperand(MachineOperand &Dest);
bool parseJumpTableIndexOperand(MachineOperand &Dest);
bool parseExternalSymbolOperand(MachineOperand &Dest);
bool parseMCSymbolOperand(MachineOperand &Dest);
bool parseMDNode(MDNode *&Node);
bool parseDIExpression(MDNode *&Expr);
bool parseDILocation(MDNode *&Expr);
bool parseMetadataOperand(MachineOperand &Dest);
bool parseCFIOffset(int &Offset);
bool parseCFIRegister(Register &Reg);
bool parseCFIAddressSpace(unsigned &AddressSpace);
bool parseCFIEscapeValues(std::string& Values);
bool parseCFIOperand(MachineOperand &Dest);
bool parseIRBlock(BasicBlock *&BB, const Function &F);
bool parseBlockAddressOperand(MachineOperand &Dest);
bool parseIntrinsicOperand(MachineOperand &Dest);
bool parsePredicateOperand(MachineOperand &Dest);
bool parseShuffleMaskOperand(MachineOperand &Dest);
bool parseTargetIndexOperand(MachineOperand &Dest);
bool parseCustomRegisterMaskOperand(MachineOperand &Dest);
bool parseLiveoutRegisterMaskOperand(MachineOperand &Dest);
bool parseMachineOperand(const unsigned OpCode, const unsigned OpIdx,
MachineOperand &Dest,
Optional<unsigned> &TiedDefIdx);
bool parseMachineOperandAndTargetFlags(const unsigned OpCode,
const unsigned OpIdx,
MachineOperand &Dest,
Optional<unsigned> &TiedDefIdx);
bool parseOffset(int64_t &Offset);
bool parseAlignment(uint64_t &Alignment);
bool parseAddrspace(unsigned &Addrspace);
bool parseSectionID(Optional<MBBSectionID> &SID);
bool parseOperandsOffset(MachineOperand &Op);
bool parseIRValue(const Value *&V);
bool parseMemoryOperandFlag(MachineMemOperand::Flags &Flags);
bool parseMemoryPseudoSourceValue(const PseudoSourceValue *&PSV);
bool parseMachinePointerInfo(MachinePointerInfo &Dest);
bool parseOptionalScope(LLVMContext &Context, SyncScope::ID &SSID);
bool parseOptionalAtomicOrdering(AtomicOrdering &Order);
bool parseMachineMemoryOperand(MachineMemOperand *&Dest);
bool parsePreOrPostInstrSymbol(MCSymbol *&Symbol);
bool parseHeapAllocMarker(MDNode *&Node);
bool parseTargetImmMnemonic(const unsigned OpCode, const unsigned OpIdx,
MachineOperand &Dest, const MIRFormatter &MF);
private:
/// Convert the integer literal in the current token into an unsigned integer.
///
/// Return true if an error occurred.
bool getUnsigned(unsigned &Result);
/// Convert the integer literal in the current token into an uint64.
///
/// Return true if an error occurred.
bool getUint64(uint64_t &Result);
/// Convert the hexadecimal literal in the current token into an unsigned
/// APInt with a minimum bitwidth required to represent the value.
///
/// Return true if the literal does not represent an integer value.
bool getHexUint(APInt &Result);
/// If the current token is of the given kind, consume it and return false.
/// Otherwise report an error and return true.
bool expectAndConsume(MIToken::TokenKind TokenKind);
/// If the current token is of the given kind, consume it and return true.
/// Otherwise return false.
bool consumeIfPresent(MIToken::TokenKind TokenKind);
bool parseInstruction(unsigned &OpCode, unsigned &Flags);
bool assignRegisterTies(MachineInstr &MI,
ArrayRef<ParsedMachineOperand> Operands);
bool verifyImplicitOperands(ArrayRef<ParsedMachineOperand> Operands,
const MCInstrDesc &MCID);
const BasicBlock *getIRBlock(unsigned Slot);
const BasicBlock *getIRBlock(unsigned Slot, const Function &F);
/// Get or create an MCSymbol for a given name.
MCSymbol *getOrCreateMCSymbol(StringRef Name);
/// parseStringConstant
/// ::= StringConstant
bool parseStringConstant(std::string &Result);
/// Map the location in the MI string to the corresponding location specified
/// in `SourceRange`.
SMLoc mapSMLoc(StringRef::iterator Loc);
};
} // end anonymous namespace
MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
StringRef Source)
: MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source), PFS(PFS)
{}
MIParser::MIParser(PerFunctionMIParsingState &PFS, SMDiagnostic &Error,
StringRef Source, SMRange SourceRange)
: MF(PFS.MF), Error(Error), Source(Source), CurrentSource(Source),
SourceRange(SourceRange), PFS(PFS) {}
void MIParser::lex(unsigned SkipChar) {
CurrentSource = lexMIToken(
CurrentSource.slice(SkipChar, StringRef::npos), Token,
[this](StringRef::iterator Loc, const Twine &Msg) { error(Loc, Msg); });
}
bool MIParser::error(const Twine &Msg) { return error(Token.location(), Msg); }
bool MIParser::error(StringRef::iterator Loc, const Twine &Msg) {
const SourceMgr &SM = *PFS.SM;
assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
const MemoryBuffer &Buffer = *SM.getMemoryBuffer(SM.getMainFileID());
if (Loc >= Buffer.getBufferStart() && Loc <= Buffer.getBufferEnd()) {
// Create an ordinary diagnostic when the source manager's buffer is the
// source string.
Error = SM.GetMessage(SMLoc::getFromPointer(Loc), SourceMgr::DK_Error, Msg);
return true;
}
// Create a diagnostic for a YAML string literal.
Error = SMDiagnostic(SM, SMLoc(), Buffer.getBufferIdentifier(), 1,
Loc - Source.data(), SourceMgr::DK_Error, Msg.str(),
Source, None, None);
return true;
}
SMLoc MIParser::mapSMLoc(StringRef::iterator Loc) {
assert(SourceRange.isValid() && "Invalid source range");
assert(Loc >= Source.data() && Loc <= (Source.data() + Source.size()));
return SMLoc::getFromPointer(SourceRange.Start.getPointer() +
(Loc - Source.data()));
}
typedef function_ref<bool(StringRef::iterator Loc, const Twine &)>
ErrorCallbackType;
static const char *toString(MIToken::TokenKind TokenKind) {
switch (TokenKind) {
case MIToken::comma:
return "','";
case MIToken::equal:
return "'='";
case MIToken::colon:
return "':'";
case MIToken::lparen:
return "'('";
case MIToken::rparen:
return "')'";
default:
return "<unknown token>";
}
}
bool MIParser::expectAndConsume(MIToken::TokenKind TokenKind) {
if (Token.isNot(TokenKind))
return error(Twine("expected ") + toString(TokenKind));
lex();
return false;
}
bool MIParser::consumeIfPresent(MIToken::TokenKind TokenKind) {
if (Token.isNot(TokenKind))
return false;
lex();
return true;
}
// Parse Machine Basic Block Section ID.
bool MIParser::parseSectionID(Optional<MBBSectionID> &SID) {
assert(Token.is(MIToken::kw_bbsections));
lex();
if (Token.is(MIToken::IntegerLiteral)) {
unsigned Value = 0;
if (getUnsigned(Value))
return error("Unknown Section ID");
SID = MBBSectionID{Value};
} else {
const StringRef &S = Token.stringValue();
if (S == "Exception")
SID = MBBSectionID::ExceptionSectionID;
else if (S == "Cold")
SID = MBBSectionID::ColdSectionID;
else
return error("Unknown Section ID");
}
lex();
return false;
}
bool MIParser::parseBasicBlockDefinition(
DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
assert(Token.is(MIToken::MachineBasicBlockLabel));
unsigned ID = 0;
if (getUnsigned(ID))
return true;
auto Loc = Token.location();
auto Name = Token.stringValue();
lex();
bool HasAddressTaken = false;
bool IsLandingPad = false;
bool IsInlineAsmBrIndirectTarget = false;
bool IsEHFuncletEntry = false;
Optional<MBBSectionID> SectionID;
uint64_t Alignment = 0;
BasicBlock *BB = nullptr;
if (consumeIfPresent(MIToken::lparen)) {
do {
// TODO: Report an error when multiple same attributes are specified.
switch (Token.kind()) {
case MIToken::kw_address_taken:
HasAddressTaken = true;
lex();
break;
case MIToken::kw_landing_pad:
IsLandingPad = true;
lex();
break;
case MIToken::kw_inlineasm_br_indirect_target:
IsInlineAsmBrIndirectTarget = true;
lex();
break;
case MIToken::kw_ehfunclet_entry:
IsEHFuncletEntry = true;
lex();
break;
case MIToken::kw_align:
if (parseAlignment(Alignment))
return true;
break;
case MIToken::IRBlock:
// TODO: Report an error when both name and ir block are specified.
if (parseIRBlock(BB, MF.getFunction()))
return true;
lex();
break;
case MIToken::kw_bbsections:
if (parseSectionID(SectionID))
return true;
break;
default:
break;
}
} while (consumeIfPresent(MIToken::comma));
if (expectAndConsume(MIToken::rparen))
return true;
}
if (expectAndConsume(MIToken::colon))
return true;
if (!Name.empty()) {
BB = dyn_cast_or_null<BasicBlock>(
MF.getFunction().getValueSymbolTable()->lookup(Name));
if (!BB)
return error(Loc, Twine("basic block '") + Name +
"' is not defined in the function '" +
MF.getName() + "'");
}
auto *MBB = MF.CreateMachineBasicBlock(BB);
MF.insert(MF.end(), MBB);
bool WasInserted = MBBSlots.insert(std::make_pair(ID, MBB)).second;
if (!WasInserted)
return error(Loc, Twine("redefinition of machine basic block with id #") +
Twine(ID));
if (Alignment)
MBB->setAlignment(Align(Alignment));
if (HasAddressTaken)
MBB->setHasAddressTaken();
MBB->setIsEHPad(IsLandingPad);
MBB->setIsInlineAsmBrIndirectTarget(IsInlineAsmBrIndirectTarget);
MBB->setIsEHFuncletEntry(IsEHFuncletEntry);
if (SectionID.hasValue()) {
MBB->setSectionID(SectionID.getValue());
MF.setBBSectionsType(BasicBlockSection::List);
}
return false;
}
bool MIParser::parseBasicBlockDefinitions(
DenseMap<unsigned, MachineBasicBlock *> &MBBSlots) {
lex();
// Skip until the first machine basic block.
while (Token.is(MIToken::Newline))
lex();
if (Token.isErrorOrEOF())
return Token.isError();
if (Token.isNot(MIToken::MachineBasicBlockLabel))
return error("expected a basic block definition before instructions");
unsigned BraceDepth = 0;
do {
if (parseBasicBlockDefinition(MBBSlots))
return true;
bool IsAfterNewline = false;
// Skip until the next machine basic block.
while (true) {
if ((Token.is(MIToken::MachineBasicBlockLabel) && IsAfterNewline) ||
Token.isErrorOrEOF())
break;
else if (Token.is(MIToken::MachineBasicBlockLabel))
return error("basic block definition should be located at the start of "
"the line");
else if (consumeIfPresent(MIToken::Newline)) {
IsAfterNewline = true;
continue;
}
IsAfterNewline = false;
if (Token.is(MIToken::lbrace))
++BraceDepth;
if (Token.is(MIToken::rbrace)) {
if (!BraceDepth)
return error("extraneous closing brace ('}')");
--BraceDepth;
}
lex();
}
// Verify that we closed all of the '{' at the end of a file or a block.
if (!Token.isError() && BraceDepth)
return error("expected '}'"); // FIXME: Report a note that shows '{'.
} while (!Token.isErrorOrEOF());
return Token.isError();
}
bool MIParser::parseBasicBlockLiveins(MachineBasicBlock &MBB) {
assert(Token.is(MIToken::kw_liveins));
lex();
if (expectAndConsume(MIToken::colon))
return true;
if (Token.isNewlineOrEOF()) // Allow an empty list of liveins.
return false;
do {
if (Token.isNot(MIToken::NamedRegister))
return error("expected a named register");
Register Reg;
if (parseNamedRegister(Reg))
return true;
lex();
LaneBitmask Mask = LaneBitmask::getAll();
if (consumeIfPresent(MIToken::colon)) {
// Parse lane mask.
if (Token.isNot(MIToken::IntegerLiteral) &&
Token.isNot(MIToken::HexLiteral))
return error("expected a lane mask");
static_assert(sizeof(LaneBitmask::Type) == sizeof(uint64_t),
"Use correct get-function for lane mask");
LaneBitmask::Type V;
if (getUint64(V))
return error("invalid lane mask value");
Mask = LaneBitmask(V);
lex();
}
MBB.addLiveIn(Reg, Mask);
} while (consumeIfPresent(MIToken::comma));
return false;
}
bool MIParser::parseBasicBlockSuccessors(MachineBasicBlock &MBB) {
assert(Token.is(MIToken::kw_successors));
lex();
if (expectAndConsume(MIToken::colon))
return true;
if (Token.isNewlineOrEOF()) // Allow an empty list of successors.
return false;
do {
if (Token.isNot(MIToken::MachineBasicBlock))
return error("expected a machine basic block reference");
MachineBasicBlock *SuccMBB = nullptr;
if (parseMBBReference(SuccMBB))
return true;
lex();
unsigned Weight = 0;
if (consumeIfPresent(MIToken::lparen)) {
if (Token.isNot(MIToken::IntegerLiteral) &&
Token.isNot(MIToken::HexLiteral))
return error("expected an integer literal after '('");
if (getUnsigned(Weight))
return true;
lex();
if (expectAndConsume(MIToken::rparen))
return true;
}
MBB.addSuccessor(SuccMBB, BranchProbability::getRaw(Weight));
} while (consumeIfPresent(MIToken::comma));
MBB.normalizeSuccProbs();
return false;
}
bool MIParser::parseBasicBlock(MachineBasicBlock &MBB,
MachineBasicBlock *&AddFalthroughFrom) {
// Skip the definition.
assert(Token.is(MIToken::MachineBasicBlockLabel));
lex();
if (consumeIfPresent(MIToken::lparen)) {
while (Token.isNot(MIToken::rparen) && !Token.isErrorOrEOF())
lex();
consumeIfPresent(MIToken::rparen);
}
consumeIfPresent(MIToken::colon);
// Parse the liveins and successors.
// N.B: Multiple lists of successors and liveins are allowed and they're
// merged into one.
// Example:
// liveins: $edi
// liveins: $esi
//
// is equivalent to
// liveins: $edi, $esi
bool ExplicitSuccessors = false;
while (true) {
if (Token.is(MIToken::kw_successors)) {
if (parseBasicBlockSuccessors(MBB))
return true;
ExplicitSuccessors = true;
} else if (Token.is(MIToken::kw_liveins)) {
if (parseBasicBlockLiveins(MBB))
return true;
} else if (consumeIfPresent(MIToken::Newline)) {
continue;
} else
break;
if (!Token.isNewlineOrEOF())
return error("expected line break at the end of a list");
lex();
}
// Parse the instructions.
bool IsInBundle = false;
MachineInstr *PrevMI = nullptr;
while (!Token.is(MIToken::MachineBasicBlockLabel) &&
!Token.is(MIToken::Eof)) {
if (consumeIfPresent(MIToken::Newline))
continue;
if (consumeIfPresent(MIToken::rbrace)) {
// The first parsing pass should verify that all closing '}' have an
// opening '{'.
assert(IsInBundle);
IsInBundle = false;
continue;
}
MachineInstr *MI = nullptr;
if (parse(MI))
return true;
MBB.insert(MBB.end(), MI);
if (IsInBundle) {
PrevMI->setFlag(MachineInstr::BundledSucc);
MI->setFlag(MachineInstr::BundledPred);
}
PrevMI = MI;
if (Token.is(MIToken::lbrace)) {
if (IsInBundle)
return error("nested instruction bundles are not allowed");
lex();
// This instruction is the start of the bundle.
MI->setFlag(MachineInstr::BundledSucc);
IsInBundle = true;
if (!Token.is(MIToken::Newline))
// The next instruction can be on the same line.
continue;
}
assert(Token.isNewlineOrEOF() && "MI is not fully parsed");
lex();
}
// Construct successor list by searching for basic block machine operands.
if (!ExplicitSuccessors) {
SmallVector<MachineBasicBlock*,4> Successors;
bool IsFallthrough;
guessSuccessors(MBB, Successors, IsFallthrough);
for (MachineBasicBlock *Succ : Successors)
MBB.addSuccessor(Succ);
if (IsFallthrough) {
AddFalthroughFrom = &MBB;
} else {
MBB.normalizeSuccProbs();
}
}
return false;
}
bool MIParser::parseBasicBlocks() {
lex();
// Skip until the first machine basic block.
while (Token.is(MIToken::Newline))
lex();
if (Token.isErrorOrEOF())
return Token.isError();
// The first parsing pass should have verified that this token is a MBB label
// in the 'parseBasicBlockDefinitions' method.
assert(Token.is(MIToken::MachineBasicBlockLabel));
MachineBasicBlock *AddFalthroughFrom = nullptr;
do {
MachineBasicBlock *MBB = nullptr;
if (parseMBBReference(MBB))
return true;
if (AddFalthroughFrom) {
if (!AddFalthroughFrom->isSuccessor(MBB))
AddFalthroughFrom->addSuccessor(MBB);
AddFalthroughFrom->normalizeSuccProbs();
AddFalthroughFrom = nullptr;
}
if (parseBasicBlock(*MBB, AddFalthroughFrom))
return true;
// The method 'parseBasicBlock' should parse the whole block until the next
// block or the end of file.
assert(Token.is(MIToken::MachineBasicBlockLabel) || Token.is(MIToken::Eof));
} while (Token.isNot(MIToken::Eof));
return false;
}
bool MIParser::parse(MachineInstr *&MI) {
// Parse any register operands before '='
MachineOperand MO = MachineOperand::CreateImm(0);
SmallVector<ParsedMachineOperand, 8> Operands;
while (Token.isRegister() || Token.isRegisterFlag()) {
auto Loc = Token.location();
Optional<unsigned> TiedDefIdx;
if (parseRegisterOperand(MO, TiedDefIdx, /*IsDef=*/true))
return true;
Operands.push_back(
ParsedMachineOperand(MO, Loc, Token.location(), TiedDefIdx));
if (Token.isNot(MIToken::comma))
break;
lex();