-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0058-Xtensa-Implement-Hardware-Loop-optimization-pass.patch
1599 lines (1563 loc) · 55.8 KB
/
0058-Xtensa-Implement-Hardware-Loop-optimization-pass.patch
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
From 3a91ce3786f7cd485113f7f68bce8cace90c2687 Mon Sep 17 00:00:00 2001
From: Andrei Safronov <safronov@espressif.com>
Date: Wed, 5 Apr 2023 00:59:07 +0300
Subject: [PATCH 058/158] [Xtensa] Implement Hardware Loop optimization pass
---
llvm/lib/Target/Xtensa/CMakeLists.txt | 3 +
.../Disassembler/XtensaDisassembler.cpp | 10 +
.../Xtensa/MCTargetDesc/XtensaAsmBackend.cpp | 8 +-
.../Xtensa/MCTargetDesc/XtensaFixupKinds.h | 1 +
.../Xtensa/MCTargetDesc/XtensaInstPrinter.cpp | 15 +
.../Xtensa/MCTargetDesc/XtensaInstPrinter.h | 1 +
.../MCTargetDesc/XtensaMCCodeEmitter.cpp | 21 +
llvm/lib/Target/Xtensa/Xtensa.h | 2 +
llvm/lib/Target/Xtensa/XtensaAsmPrinter.cpp | 2 +
llvm/lib/Target/Xtensa/XtensaFixupHWLoops.cpp | 388 ++++++++++++++++++
.../lib/Target/Xtensa/XtensaHardwareLoops.cpp | 335 +++++++++++++++
llvm/lib/Target/Xtensa/XtensaISelLowering.cpp | 112 ++++-
llvm/lib/Target/Xtensa/XtensaISelLowering.h | 3 +
llvm/lib/Target/Xtensa/XtensaInstrInfo.cpp | 56 +++
llvm/lib/Target/Xtensa/XtensaInstrInfo.h | 4 +
llvm/lib/Target/Xtensa/XtensaInstrInfo.td | 41 +-
llvm/lib/Target/Xtensa/XtensaOperands.td | 9 +-
llvm/lib/Target/Xtensa/XtensaOperators.td | 6 +
.../lib/Target/Xtensa/XtensaTargetMachine.cpp | 21 +
llvm/lib/Target/Xtensa/XtensaTargetMachine.h | 2 +
.../Xtensa/XtensaTargetTransformInfo.cpp | 35 ++
.../Target/Xtensa/XtensaTargetTransformInfo.h | 51 +++
llvm/test/CodeGen/Xtensa/hwloop_inner_loop.ll | 31 ++
.../CodeGen/Xtensa/hwloop_unsuitable_loop.ll | 38 ++
24 files changed, 1164 insertions(+), 31 deletions(-)
create mode 100644 llvm/lib/Target/Xtensa/XtensaFixupHWLoops.cpp
create mode 100644 llvm/lib/Target/Xtensa/XtensaHardwareLoops.cpp
create mode 100644 llvm/lib/Target/Xtensa/XtensaTargetTransformInfo.cpp
create mode 100644 llvm/lib/Target/Xtensa/XtensaTargetTransformInfo.h
create mode 100644 llvm/test/CodeGen/Xtensa/hwloop_inner_loop.ll
create mode 100644 llvm/test/CodeGen/Xtensa/hwloop_unsuitable_loop.ll
diff --git a/llvm/lib/Target/Xtensa/CMakeLists.txt b/llvm/lib/Target/Xtensa/CMakeLists.txt
index 2d27fa78a9b8..6b035e8cb41d 100644
--- a/llvm/lib/Target/Xtensa/CMakeLists.txt
+++ b/llvm/lib/Target/Xtensa/CMakeLists.txt
@@ -17,7 +17,9 @@ add_public_tablegen_target(XtensaCommonTableGen)
add_llvm_target(XtensaCodeGen
XtensaAsmPrinter.cpp
XtensaConstantPoolValue.cpp
+ XtensaFixupHWLoops.cpp
XtensaFrameLowering.cpp
+ XtensaHardwareLoops.cpp
XtensaInstrInfo.cpp
XtensaISelDAGToDAG.cpp
XtensaISelLowering.cpp
@@ -28,6 +30,7 @@ add_llvm_target(XtensaCodeGen
XtensaSubtarget.cpp
XtensaTargetMachine.cpp
XtensaTargetObjectFile.cpp
+ XtensaTargetTransformInfo.cpp
LINK_COMPONENTS
AsmPrinter
diff --git a/llvm/lib/Target/Xtensa/Disassembler/XtensaDisassembler.cpp b/llvm/lib/Target/Xtensa/Disassembler/XtensaDisassembler.cpp
index ae5e8e281253..aa6ac4e38188 100644
--- a/llvm/lib/Target/Xtensa/Disassembler/XtensaDisassembler.cpp
+++ b/llvm/lib/Target/Xtensa/Disassembler/XtensaDisassembler.cpp
@@ -443,6 +443,16 @@ static DecodeStatus decodeBranchOperand(MCInst &Inst, uint64_t Imm,
return MCDisassembler::Success;
}
+static DecodeStatus decodeLoopOperand(MCInst &Inst, uint64_t Imm,
+ int64_t Address, const void *Decoder) {
+
+ assert(isUInt<8>(Imm) && "Invalid immediate");
+ if (!tryAddingSymbolicOperand(Imm + 4 + Address, true, Address, 0, 3, Inst,
+ Decoder))
+ Inst.addOperand(MCOperand::createImm(Imm));
+ return MCDisassembler::Success;
+}
+
static DecodeStatus decodeL32ROperand(MCInst &Inst, uint64_t Imm,
int64_t Address, const void *Decoder) {
diff --git a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaAsmBackend.cpp b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaAsmBackend.cpp
index 61417a2f2455..fc1ad220b8e0 100644
--- a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaAsmBackend.cpp
+++ b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaAsmBackend.cpp
@@ -69,7 +69,8 @@ XtensaMCAsmBackend::getFixupKindInfo(MCFixupKind Kind) const {
MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
{"fixup_xtensa_l32r_16", 8, 16,
MCFixupKindInfo::FKF_IsPCRel |
- MCFixupKindInfo::FKF_IsAlignedDownTo32Bits}};
+ MCFixupKindInfo::FKF_IsAlignedDownTo32Bits},
+ {"fixup_xtensa_loop_8", 16, 8, MCFixupKindInfo::FKF_IsPCRel}};
if (Kind < FirstTargetFixupKind)
return MCAsmBackend::getFixupKindInfo(Kind);
@@ -119,6 +120,11 @@ static uint64_t adjustFixupValue(const MCFixup &Fixup, uint64_t Value,
if (Value & 0x3)
Ctx.reportError(Fixup.getLoc(), "fixup value must be 4-byte aligned");
return (Value & 0xffffc) >> 2;
+ case Xtensa::fixup_xtensa_loop_8:
+ Value -= 4;
+ if (!isUInt<8>(Value))
+ Ctx.reportError(Fixup.getLoc(), "fixup value out of range");
+ return (Value & 0xff);
case Xtensa::fixup_xtensa_l32r_16:
unsigned Offset = Fixup.getOffset();
if (Offset & 0x3)
diff --git a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaFixupKinds.h b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaFixupKinds.h
index 57b114e709a8..f6b1e58adf07 100644
--- a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaFixupKinds.h
+++ b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaFixupKinds.h
@@ -22,6 +22,7 @@ enum FixupKind {
fixup_xtensa_jump_18,
fixup_xtensa_call_18,
fixup_xtensa_l32r_16,
+ fixup_xtensa_loop_8,
fixup_xtensa_invalid,
LastTargetFixupKind,
NumTargetFixupKinds = LastTargetFixupKind - FirstTargetFixupKind
diff --git a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.cpp b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.cpp
index 89343d203e9e..8d5e56b35b51 100644
--- a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.cpp
+++ b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.cpp
@@ -114,6 +114,21 @@ void XtensaInstPrinter::printBranchTarget(const MCInst *MI, int OpNum,
llvm_unreachable("Invalid operand");
}
+void XtensaInstPrinter::printLoopTarget(const MCInst *MI, int OpNum,
+ raw_ostream &OS) {
+ const MCOperand &MC = MI->getOperand(OpNum);
+ if (MI->getOperand(OpNum).isImm()) {
+ int64_t Val = MC.getImm() + 4;
+ OS << ". ";
+ if (Val > 0)
+ OS << '+';
+ OS << Val;
+ } else if (MC.isExpr())
+ MC.getExpr()->print(OS, &MAI, true);
+ else
+ llvm_unreachable("Invalid operand");
+}
+
void XtensaInstPrinter::printJumpTarget(const MCInst *MI, int OpNum,
raw_ostream &OS) {
const MCOperand &MC = MI->getOperand(OpNum);
diff --git a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.h b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.h
index f6858b383cbf..62b080c63570 100644
--- a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.h
+++ b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaInstPrinter.h
@@ -48,6 +48,7 @@ private:
void printOperand(const MCInst *MI, int OpNum, raw_ostream &O);
void printMemOperand(const MCInst *MI, int OpNUm, raw_ostream &O);
void printBranchTarget(const MCInst *MI, int OpNum, raw_ostream &O);
+ void printLoopTarget(const MCInst *MI, int OpNum, raw_ostream &O);
void printJumpTarget(const MCInst *MI, int OpNum, raw_ostream &O);
void printCallOperand(const MCInst *MI, int OpNum, raw_ostream &O);
void printL32RTarget(const MCInst *MI, int OpNum, raw_ostream &O);
diff --git a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaMCCodeEmitter.cpp b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaMCCodeEmitter.cpp
index 8d30edafb54a..96194d4e4aa7 100644
--- a/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaMCCodeEmitter.cpp
+++ b/llvm/lib/Target/Xtensa/MCTargetDesc/XtensaMCCodeEmitter.cpp
@@ -67,6 +67,10 @@ private:
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const;
+ uint32_t getLoopTargetEncoding(const MCInst &MI, unsigned int OpNum,
+ SmallVectorImpl<MCFixup> &Fixups,
+ const MCSubtargetInfo &STI) const;
+
uint32_t getCallEncoding(const MCInst &MI, unsigned int OpNum,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const;
@@ -218,6 +222,23 @@ uint32_t XtensaMCCodeEmitter::getBranchTargetEncoding(
}
}
+uint32_t
+XtensaMCCodeEmitter::getLoopTargetEncoding(const MCInst &MI, unsigned int OpNum,
+ SmallVectorImpl<MCFixup> &Fixups,
+ const MCSubtargetInfo &STI) const {
+ const MCOperand &MO = MI.getOperand(OpNum);
+ if (MO.isImm())
+ return static_cast<uint32_t>(MO.getImm());
+
+ assert((MO.isExpr()) && "Unexpected operand value!");
+
+ const MCExpr *Expr = MO.getExpr();
+
+ Fixups.push_back(MCFixup::create(
+ 0, Expr, MCFixupKind(Xtensa::fixup_xtensa_loop_8), MI.getLoc()));
+ return 0;
+}
+
uint32_t
XtensaMCCodeEmitter::getCallEncoding(const MCInst &MI, unsigned int OpNum,
SmallVectorImpl<MCFixup> &Fixups,
diff --git a/llvm/lib/Target/Xtensa/Xtensa.h b/llvm/lib/Target/Xtensa/Xtensa.h
index ee054d131f35..2966e085634f 100644
--- a/llvm/lib/Target/Xtensa/Xtensa.h
+++ b/llvm/lib/Target/Xtensa/Xtensa.h
@@ -27,5 +27,7 @@ class FunctionPass;
FunctionPass *createXtensaISelDag(XtensaTargetMachine &TM,
CodeGenOpt::Level OptLevel);
FunctionPass *createXtensaSizeReductionPass();
+FunctionPass *createXtensaHardwareLoops();
+FunctionPass *createXtensaFixupHwLoops();
} // namespace llvm
#endif /* LLVM_LIB_TARGET_XTENSA_XTENSA_H */
diff --git a/llvm/lib/Target/Xtensa/XtensaAsmPrinter.cpp b/llvm/lib/Target/Xtensa/XtensaAsmPrinter.cpp
index fb100a734e45..9c483a68f358 100644
--- a/llvm/lib/Target/Xtensa/XtensaAsmPrinter.cpp
+++ b/llvm/lib/Target/Xtensa/XtensaAsmPrinter.cpp
@@ -54,6 +54,8 @@ void XtensaAsmPrinter::emitInstruction(const MachineInstr *MI) {
MCInstBuilder(Xtensa::JX).addReg(MI->getOperand(0).getReg()));
return;
}
+ case Xtensa::LOOPEND:
+ return;
}
Lower.lower(MI, LoweredMI);
EmitToStreamer(*OutStreamer, LoweredMI);
diff --git a/llvm/lib/Target/Xtensa/XtensaFixupHWLoops.cpp b/llvm/lib/Target/Xtensa/XtensaFixupHWLoops.cpp
new file mode 100644
index 000000000000..dc712a913805
--- /dev/null
+++ b/llvm/lib/Target/Xtensa/XtensaFixupHWLoops.cpp
@@ -0,0 +1,388 @@
+//===---- XtensaFixupHWLoops.cpp - Fixup HW loops -------------------------===//
+//
+// 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
+//===----------------------------------------------------------------------===//
+
+#include "Xtensa.h"
+#include "XtensaTargetMachine.h"
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/MachineInstrBuilder.h"
+#include "llvm/CodeGen/MachineLoopInfo.h"
+#include "llvm/CodeGen/Passes.h"
+#include "llvm/CodeGen/TargetInstrInfo.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/MathExtras.h"
+
+using namespace llvm;
+
+namespace llvm {
+FunctionPass *createXtensaFixupHwLoops();
+void initializeXtensaFixupHwLoopsPass(PassRegistry &);
+} // namespace llvm
+
+namespace {
+class XtensaFixupHwLoops : public MachineFunctionPass {
+ // BasicBlockInfo - Information about the offset and size of a single
+ // basic block.
+ struct BasicBlockInfo {
+ // Offset - Distance from the beginning of the function to the beginning
+ // of this basic block.
+ //
+ // The offset is always aligned as required by the basic block.
+ unsigned Offset = 0;
+
+ // Size - Size of the basic block in bytes. If the block contains
+ // inline assembly, this is a worst case estimate.
+ //
+ // The size does not include any alignment padding whether from the
+ // beginning of the block, or from an aligned jump table at the end.
+ unsigned Size = 0;
+
+ BasicBlockInfo() = default;
+
+ // Compute the offset immediately following this block. \p MBB is the next
+ // block.
+ unsigned postOffset(const MachineBasicBlock &MBB) const {
+ const unsigned PO = Offset + Size;
+ const Align Alignment = MBB.getAlignment();
+ if (Alignment == 1)
+ return PO;
+
+ const Align ParentAlign = MBB.getParent()->getAlignment();
+ if (Alignment <= ParentAlign)
+ return PO + offsetToAlignment(PO, Alignment);
+
+ // The alignment of this MBB is larger than the function's alignment, so
+ // we can't tell whether or not it will insert nops. Assume that it will.
+ return PO + Alignment.value() + offsetToAlignment(PO, Alignment);
+ }
+ };
+
+ SmallVector<BasicBlockInfo, 16> BlockInfo;
+ SmallPtrSet<MachineBasicBlock *, 1> AnalyzedMBBs;
+
+ MachineFunction *MF;
+ MachineLoopInfo *MLI;
+ const TargetRegisterInfo *TRI;
+ const TargetInstrInfo *TII;
+
+ bool processLoop(MachineLoop *L);
+
+ bool fixupLoopInstrs(MachineLoop *L);
+
+ void scanFunction();
+
+ uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
+
+ void adjustBlockOffsets(MachineBasicBlock &Start);
+
+public:
+ static char ID;
+
+ XtensaFixupHwLoops() : MachineFunctionPass(ID) {
+ initializeXtensaFixupHwLoopsPass(*PassRegistry::getPassRegistry());
+ }
+
+ bool runOnMachineFunction(MachineFunction &MF) override;
+
+ MachineFunctionProperties getRequiredProperties() const override {
+ return MachineFunctionProperties().set(
+ MachineFunctionProperties::Property::NoVRegs);
+ }
+
+ StringRef getPassName() const override {
+ return "Xtensa Hardware Loop Fixup";
+ }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.setPreservesCFG();
+ AU.addRequired<MachineLoopInfo>();
+ MachineFunctionPass::getAnalysisUsage(AU);
+ }
+};
+
+char XtensaFixupHwLoops::ID = 0;
+} // namespace
+
+INITIALIZE_PASS(XtensaFixupHwLoops, "hwloopsfixup",
+ "Xtensa Hardware Loops Fixup", false, false)
+
+FunctionPass *llvm::createXtensaFixupHwLoops() {
+ return new XtensaFixupHwLoops();
+}
+
+// Returns true if the instruction is a hardware loop instruction.
+static bool isHardwareLoop(const MachineInstr &MI) {
+ return (MI.getOpcode() == Xtensa::LOOPSTART);
+}
+
+bool XtensaFixupHwLoops::runOnMachineFunction(MachineFunction &mf) {
+ if (skipFunction(mf.getFunction()))
+ return false;
+
+ MF = &mf;
+ MLI = &getAnalysis<MachineLoopInfo>();
+ const TargetSubtargetInfo &ST = mf.getSubtarget();
+ TII = ST.getInstrInfo();
+ TRI = ST.getRegisterInfo();
+
+ // Renumber all of the machine basic blocks in the function, guaranteeing that
+ // the numbers agree with the position of the block in the function.
+ mf.RenumberBlocks();
+
+ // Do the initial scan of the function, building up information about the
+ // sizes of each block.
+ scanFunction();
+
+ AnalyzedMBBs.clear();
+
+ bool Changed = false;
+
+ for (auto &L : *MLI)
+ if (!L->getParentLoop()) {
+ Changed |= processLoop(L);
+ }
+
+ return Changed;
+}
+
+// Scan loop and find hardware loop pseudo instructions LOOPSTART and LOOPEND.
+// Transform LOOPSTART to Xtensa instructions and remove LOOPEND.
+bool XtensaFixupHwLoops::fixupLoopInstrs(MachineLoop *L) {
+ // const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
+ MachineBasicBlock &MBB = *(L->getHeader());
+ bool Changed = false;
+ unsigned Num = MBB.getNumber();
+ unsigned Offset = BlockInfo[Num].Offset;
+ MachineBasicBlock *LastBlock = nullptr;
+ unsigned LHOffset = Offset;
+ unsigned LastBlockOffset = 0;
+
+ // Loop over all the instructions.
+ MachineBasicBlock::iterator MII = MBB.begin();
+ MachineBasicBlock::iterator MIE = MBB.end();
+ MachineInstr *PredI1 = nullptr;
+ MachineInstr *FirstMI = nullptr;
+
+ for (auto MBI = L->block_begin(), MBIE = L->block_end(); MBI != MBIE; ++MBI) {
+ if (LastBlockOffset < BlockInfo[(*MBI)->getNumber()].Offset) {
+ LastBlockOffset = BlockInfo[(*MBI)->getNumber()].Offset;
+ LastBlock = (*MBI);
+ }
+ }
+
+ while (MII != MIE) {
+ if (MII->isMetaInstruction()) {
+ ++MII;
+ continue;
+ }
+
+ MachineInstr &MI = *MII;
+
+ if (FirstMI == nullptr)
+ FirstMI = &MI;
+
+ if (isHardwareLoop(*MII)) {
+ MachineBasicBlock *LoopEnd = nullptr;
+
+ MII->getNextNode();
+
+ MachineBasicBlock::iterator NextMII = std::next(MII);
+
+ // Check whether loop is empty and remove if true
+ if (NextMII != MIE) {
+ if ((*NextMII).getOpcode() == Xtensa::LOOPEND) {
+ MBB.erase(*NextMII);
+ MBB.erase(*MII);
+ MBB.removeSuccessor(&MBB, true);
+ return true;
+ }
+ }
+
+ for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),
+ PE = MBB.pred_end();
+ PI != PE; ++PI) {
+ MachineBasicBlock *PMBB = *PI;
+ MachineBasicBlock::iterator PIB = PMBB->begin();
+ MachineBasicBlock::iterator PII = PMBB->end();
+
+ do {
+ --PII;
+ if (PII->isMetaInstruction()) {
+ continue;
+ }
+
+ if ((*PII).getOpcode() == Xtensa::LOOPEND) {
+ DebugLoc DL = PII->getDebugLoc();
+ unsigned OffsetLE = BlockInfo[PMBB->getNumber()].Offset;
+
+ // Check if loop end is placed before loop header
+ // In such case add special MBB after loop header and create jump
+ // from loop end to it
+ if (OffsetLE < LHOffset) {
+ LoopEnd = MF->CreateMachineBasicBlock();
+ MF->insert(++LastBlock->getIterator(), LoopEnd);
+ LoopEnd->transferSuccessors(PMBB);
+ LoopEnd->splice(LoopEnd->end(), PMBB, PII, PMBB->end());
+
+ MachineBasicBlock::iterator LEI = LoopEnd->end();
+ --LEI;
+
+ // Expect jump instruction
+ assert((LEI->getOpcode() == Xtensa::J) && "Broken hardware loop");
+
+ // Create block and insert it before loop end address as
+ // target for jump instruction to avoid premature exit from loop
+ MachineBasicBlock *BlockForJump = MF->CreateMachineBasicBlock();
+ MF->insert(LoopEnd->getIterator(), BlockForJump);
+ BlockForJump->addSuccessor(LoopEnd);
+ BuildMI(*BlockForJump, BlockForJump->end(), DL,
+ TII->get(Xtensa::NOP));
+ BuildMI(*PMBB, PMBB->end(), DL, TII->get(Xtensa::J))
+ .addMBB(BlockForJump);
+ PMBB->addSuccessor(BlockForJump);
+
+ BuildMI(*LoopEnd, LoopEnd->begin(), DL, TII->get(Xtensa::LOOPEND))
+ .addMBB(LoopEnd);
+ LoopEnd->addSuccessor(LoopEnd);
+ Changed = true;
+ break;
+ }
+
+ if (PII != PIB) {
+ LoopEnd = MF->CreateMachineBasicBlock();
+ MF->insert(++(PMBB->getIterator()), LoopEnd);
+ LoopEnd->transferSuccessors(PMBB);
+ LoopEnd->splice(LoopEnd->end(), PMBB, PII, PMBB->end());
+ PMBB->addSuccessor(LoopEnd);
+
+ BuildMI(*LoopEnd, LoopEnd->begin(), DL, TII->get(Xtensa::LOOPEND))
+ .addMBB(LoopEnd);
+ LoopEnd->addSuccessor(LoopEnd);
+ } else {
+ BuildMI(*PMBB, PII, DL, TII->get(Xtensa::LOOPEND)).addMBB(PMBB);
+ PMBB->addSuccessor(PMBB);
+ BuildMI(*PMBB, PII, DL, TII->get(Xtensa::NOP));
+ LoopEnd = PMBB;
+ }
+
+ Changed = true;
+ break;
+ }
+ } while (PII != PIB);
+ if (Changed)
+ break;
+ }
+
+ assert((Changed) && "Broken hardware loop");
+
+ if (MII != FirstMI) {
+ MBB.splice(FirstMI->getIterator(), &MBB, MII);
+ Offset = BlockInfo[Num].Offset;
+ switch (PredI1->getOpcode()) {
+ case Xtensa::L32I_N:
+ if (PredI1->getOperand(0).getReg() == MII->getOperand(0).getReg()) {
+ MBB.splice(MII, &MBB, PredI1);
+ Offset += 2;
+ }
+ break;
+ case Xtensa::L32I:
+ if (PredI1->getOperand(0).getReg() == MII->getOperand(0).getReg()) {
+ MBB.splice(MII, &MBB, PredI1);
+ Offset += 3;
+ }
+ break;
+ }
+ }
+
+ DebugLoc DL = MII->getDebugLoc();
+
+ // Fixup Loop alignment
+ switch (Offset & 0x3) {
+ case 0x0:
+ BuildMI(MBB, MII, DL, TII->get(Xtensa::NOP));
+ BuildMI(MBB, MII, DL, TII->get(Xtensa::NOP));
+ break;
+ case 0x3:
+ BuildMI(MBB, MII, DL, TII->get(Xtensa::NOP));
+ break;
+ }
+
+ BuildMI(MBB, MII, DL, TII->get(Xtensa::LOOP))
+ .addReg(MII->getOperand(0).getReg())
+ .addMBB(LoopEnd);
+ MBB.erase(MII);
+
+ MF->RenumberBlocks();
+ scanFunction();
+ AnalyzedMBBs.insert(&MBB);
+ return true;
+ } else {
+ Offset += TII->getInstSizeInBytes(MI);
+ PredI1 = &MI;
+ ++MII;
+ }
+ }
+
+ return Changed;
+}
+
+bool XtensaFixupHwLoops::processLoop(MachineLoop *L) {
+ bool Changed = false;
+
+ // Process nested loops first.
+ for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
+ Changed |= processLoop(*I);
+ }
+
+ if (Changed)
+ return true;
+
+ return fixupLoopInstrs(L);
+}
+
+// scanFunction - Do the initial scan of the function, building up
+// information about each block.
+void XtensaFixupHwLoops::scanFunction() {
+ BlockInfo.clear();
+ BlockInfo.resize(MF->getNumBlockIDs());
+
+ // First thing, compute the size of all basic blocks, and see if the function
+ // has any inline assembly in it. If so, we have to be conservative about
+ // alignment assumptions, as we don't know for sure the size of any
+ // instructions in the inline assembly.
+ for (MachineBasicBlock &MBB : *MF)
+ BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
+
+ // Compute block offsets and known bits.
+ adjustBlockOffsets(*MF->begin());
+}
+
+// computeBlockSize - Compute the size for MBB.
+uint64_t
+XtensaFixupHwLoops::computeBlockSize(const MachineBasicBlock &MBB) const {
+ uint64_t Size = 0;
+ for (const MachineInstr &MI : MBB)
+ if (MI.getOpcode() != Xtensa::LOOPEND)
+ Size += TII->getInstSizeInBytes(MI);
+ return Size;
+}
+
+void XtensaFixupHwLoops::adjustBlockOffsets(MachineBasicBlock &Start) {
+ unsigned PrevNum = Start.getNumber();
+ for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
+ unsigned Num = MBB.getNumber();
+ if (!Num) // block zero is never changed from offset zero.
+ continue;
+ // Get the offset and known bits at the end of the layout predecessor.
+ // Include the alignment of the current block.
+ BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
+
+ PrevNum = Num;
+ }
+}
+
diff --git a/llvm/lib/Target/Xtensa/XtensaHardwareLoops.cpp b/llvm/lib/Target/Xtensa/XtensaHardwareLoops.cpp
new file mode 100644
index 000000000000..f31d724ebb8f
--- /dev/null
+++ b/llvm/lib/Target/Xtensa/XtensaHardwareLoops.cpp
@@ -0,0 +1,335 @@
+//===- XtensaHardwareLoops.cpp - Idenify and generate hardware Loops ------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// 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 contains implementation of the pass which optimizes loops .
+//
+//===----------------------------------------------------------------------===//
+
+#include "XtensaInstrInfo.h"
+#include "XtensaSubtarget.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Statistic.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/CodeGen/MachineBasicBlock.h"
+#include "llvm/CodeGen/MachineFunction.h"
+#include "llvm/CodeGen/MachineFunctionPass.h"
+#include "llvm/CodeGen/MachineInstr.h"
+#include "llvm/CodeGen/MachineInstrBuilder.h"
+#include "llvm/CodeGen/MachineLoopInfo.h"
+#include "llvm/CodeGen/MachineOperand.h"
+#include "llvm/CodeGen/MachineRegisterInfo.h"
+#include "llvm/CodeGen/TargetRegisterInfo.h"
+#include "llvm/IR/Constants.h"
+#include "llvm/IR/DebugLoc.h"
+#include "llvm/InitializePasses.h"
+#include "llvm/Pass.h"
+#include "llvm/Support/CommandLine.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/raw_ostream.h"
+#include <cassert>
+#include <cstdint>
+#include <cstdlib>
+#include <iterator>
+#include <map>
+#include <set>
+#include <string>
+#include <utility>
+#include <vector>
+
+using namespace llvm;
+
+#define DEBUG_TYPE "xtensa-hwloops"
+#define MAX_LOOP_SIZE 256
+
+namespace llvm {
+
+FunctionPass *createXtensaHardwareLoops();
+void initializeXtensaHardwareLoopsPass(PassRegistry &);
+
+} // end namespace llvm
+
+namespace {
+
+struct XtensaHardwareLoops : public MachineFunctionPass {
+ MachineLoopInfo *MLI;
+ MachineRegisterInfo *MRI;
+ MachineDominatorTree *MDT;
+ const XtensaInstrInfo *TII;
+ const XtensaSubtarget *STI;
+ SmallPtrSet<MachineBasicBlock *, 1> VisitedMBBs;
+
+public:
+ static char ID;
+
+ XtensaHardwareLoops() : MachineFunctionPass(ID) {}
+
+ bool runOnMachineFunction(MachineFunction &MF) override;
+
+ StringRef getPassName() const override { return "Xtensa Hardware Loops"; }
+
+ void getAnalysisUsage(AnalysisUsage &AU) const override {
+ AU.addRequired<MachineLoopInfo>();
+ MachineFunctionPass::getAnalysisUsage(AU);
+ }
+
+private:
+ // Return true if the instruction is not valid within a hardware
+ // loop.
+ bool isInvalidLoopOperation(const MachineInstr *MI) const;
+
+ // Return true if the loop contains an instruction that inhibits
+ // using the hardware loop.
+ bool containsInvalidInstruction(MachineLoop *L) const;
+
+ // Given a loop, check if we can convert it to a hardware loop.
+ // If so, then perform the conversion and return true.
+ bool processLoop(MachineLoop *L);
+
+ bool checkLoopSize(MachineLoop *L);
+
+ bool checkLoopEndDisplacement(MachineFunction &MF, MachineBasicBlock *LH, MachineBasicBlock* LE);
+};
+
+char XtensaHardwareLoops::ID = 0;
+
+} // end anonymous namespace
+
+INITIALIZE_PASS(XtensaHardwareLoops, "hwloops", "Xtensa Hardware Loops", false,
+ false)
+
+FunctionPass *llvm::createXtensaHardwareLoops() {
+ return new XtensaHardwareLoops();
+}
+
+bool XtensaHardwareLoops::runOnMachineFunction(MachineFunction &MF) {
+ LLVM_DEBUG(dbgs() << "********* Xtensa Hardware Loops *********\n");
+ if (skipFunction(MF.getFunction()))
+ return false;
+
+ bool Changed = false;
+
+ MLI = &getAnalysis<MachineLoopInfo>();
+ MRI = &MF.getRegInfo();
+ STI = &MF.getSubtarget<XtensaSubtarget>();
+ TII = STI->getInstrInfo();
+
+ if (!STI->hasLoop())
+ return false;
+
+ VisitedMBBs.clear();
+
+ for (auto &L : *MLI)
+ if (!L->getParentLoop()) {
+ Changed |= processLoop(L);
+ }
+
+ return Changed;
+}
+
+// Return true if the operation is invalid within hardware loop.
+bool XtensaHardwareLoops::isInvalidLoopOperation(const MachineInstr *MI) const {
+
+ // Call is not allowed because the callee may use a hardware loop
+ if (MI->getDesc().isCall())
+ return true;
+
+ if ((MI->getOpcode() == Xtensa::LOOP) ||
+ (MI->getOpcode() == Xtensa::LOOPGTZ) ||
+ (MI->getOpcode() == Xtensa::LOOPNEZ))
+ return true;
+
+ if (MI->isInlineAsm())
+ return true;
+
+ return false;
+}
+
+// Return true if the loop contains an instruction that inhibits
+// the use of the hardware loop instruction.
+bool XtensaHardwareLoops::containsInvalidInstruction(MachineLoop *L) const {
+ LLVM_DEBUG(dbgs() << "\nhw_loop head, "
+ << printMBBReference(**L->block_begin()));
+ for (MachineBasicBlock *MBB : L->getBlocks()) {
+ for (MachineBasicBlock::iterator MII = MBB->begin(), E = MBB->end();
+ MII != E; ++MII) {
+ const MachineInstr *MI = &*MII;
+ if (isInvalidLoopOperation(MI)) {
+ LLVM_DEBUG(dbgs() << "\nCannot convert to hw_loop due to:";
+ MI->dump(););
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+// Check if this loop is suitable for converting to a hardware loop
+bool XtensaHardwareLoops::processLoop(MachineLoop *L) {
+ // This is just for sanity.
+ assert(L->getHeader() && "Loop without a header?");
+
+ bool Changed = false;
+
+ // Process nested loops first.
+ for (MachineLoop::iterator I = L->begin(), E = L->end(); I != E; ++I) {
+ Changed |= processLoop(*I);
+ }
+
+ if (Changed)
+ return true;
+
+ using instr_iterator = MachineBasicBlock::instr_iterator;
+ MachineInstr *LII = nullptr; // LOOPINIT instruction
+ MachineInstr *LEI = nullptr; // LOOPEND instruction
+ MachineBasicBlock *LEMBB = nullptr;
+ MachineBasicBlock *PH = L->getLoopPreheader();
+ MachineBasicBlock *LastMBB = L->getLoopLatch();
+
+ // Try to find LOOPEND instruction in the loop latch
+ for (auto MBI = L->block_begin(), MBIE = L->block_end(); MBI != MBIE; ++MBI) {
+ if (VisitedMBBs.count(*MBI))
+ continue;
+ for (auto MII = (*MBI)->begin(), MIE = (*MBI)->end(); MII != MIE; ++MII) {
+ MachineInstr *LMI = &*MII;
+ if (LMI->getOpcode() == Xtensa::LOOPEND) {
+ LEI = LMI;
+ LEMBB = *MBI;
+ }
+ }
+ VisitedMBBs.insert(*MBI);
+ }
+
+ if (LEI != nullptr) {
+ MachineBasicBlock *LH = L->getHeader();
+ MachineBasicBlock::iterator LHI = LH->getFirstNonPHI();
+
+ if (!PH) {
+ llvm_unreachable("Hardware loop predecessor not found");
+ return false;
+ }
+
+ MachineBasicBlock *LIMBB = PH;
+
+ // Try to find LOOPINIT instruction in predecessors chain
+ while ((LII == nullptr) && (LIMBB != nullptr) &&
+ ((L->getParentLoop() == nullptr) ||
+ (L->getParentLoop()->contains(LIMBB)))) {
+ for (instr_iterator I = LIMBB->instr_begin(), E = LIMBB->instr_end();
+ I != E; ++I) {
+ MachineInstr *MI = &*I;
+ if (MI->getOpcode() == Xtensa::LOOPINIT) {
+ LII = MI;
+ break;
+ }
+ }
+ if (LII == nullptr)
+ LIMBB = *LIMBB->pred_begin();
+ }
+
+ if (LII == nullptr) {
+ llvm_unreachable("Hardware loop init instruction not found");
+ return false;
+ }
+
+ DebugLoc DL = LII->getDebugLoc();
+
+ // If loop is too large or have wrong configuration
+ // then restore branch instruction
+ // sub a, a, 1
+ // bnez a, LH
+ if (!checkLoopSize(L) || containsInvalidInstruction(L) ||
+ (LEMBB != LastMBB) || (!checkLoopEndDisplacement(*LH->getParent(), LH, LEMBB))) {
+ const MCInstrDesc &PD = TII->get(TargetOpcode::PHI);
+ MachineInstr *NewPN = LH->getParent()->CreateMachineInstr(PD, DL);
+ LH->insert(LH->begin(), NewPN);
+ Register PR = MRI->createVirtualRegister(&Xtensa::ARRegClass);
+ NewPN->addOperand(MachineOperand::CreateReg(PR, true));
+
+ MachineOperand MO =
+ MachineOperand::CreateReg(LII->getOperand(0).getReg(), false);
+ NewPN->addOperand(MO);
+ NewPN->addOperand(MachineOperand::CreateMBB(PH));
+
+ Register IndR = MRI->createVirtualRegister(&Xtensa::ARRegClass);
+ MO = MachineOperand::CreateReg(IndR, false);
+ NewPN->addOperand(MO);
+ NewPN->addOperand(MachineOperand::CreateMBB(LastMBB));
+
+ MachineInstrBuilder MIB =
+ BuildMI(*LEMBB, LEI, LEI->getDebugLoc(), TII->get(Xtensa::ADDI), IndR)
+ .addReg(PR)
+ .addImm(-1);
+
+ MIB = BuildMI(*LEMBB, LEI, LEI->getDebugLoc(), TII->get(Xtensa::BNEZ))
+ .addReg(IndR)
+ .addMBB(LEI->getOperand(0).getMBB());
+ LEMBB->erase(LEI);
+ PH->erase(LII);
+ return false;
+ }
+
+ //Place LOOPSTART instruction in loop header
+ BuildMI(*LH, LHI, DL, TII->get(Xtensa::LOOPSTART))
+ .addReg(LII->getOperand(0).getReg())
+ .addMBB(LastMBB);
+ PH->erase(LII);
+ return true;
+ }
+
+ return false;
+}
+
+bool XtensaHardwareLoops::checkLoopSize(MachineLoop *L) {
+ uint64_t LoopSize = 0;
+
+ for (auto *MBB : L->getBlocks()) {
+ uint64_t BlockSize = 0;
+ for (const MachineInstr &MI : *MBB) {
+ uint64_t InstSize = TII->getInstSizeInBytes(MI);
+ if (MI.isPHI())
+ InstSize = 3;
+ BlockSize += InstSize;
+ }
+ LoopSize += BlockSize;
+ }
+
+ if (LoopSize > MAX_LOOP_SIZE)
+ return false;
+
+ return true;
+}
+
+bool XtensaHardwareLoops::checkLoopEndDisplacement(MachineFunction &MF,
+ MachineBasicBlock *LH,
+ MachineBasicBlock *LE) {
+ bool isLHVisited = false;
+
+ if (LH == LE)
+ return true;
+
+ for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
+ MachineBasicBlock *MBB = &*I;
+ if (MBB == LH)
+ isLHVisited = true;
+ else if (MBB == LE) {
+ if (isLHVisited)
+ return true;
+ else
+ return false;
+ }
+ }
+ llvm_unreachable("Wrong hardware loop");
+}
+
diff --git a/llvm/lib/Target/Xtensa/XtensaISelLowering.cpp b/llvm/lib/Target/Xtensa/XtensaISelLowering.cpp
index cdb1dc2bf36e..48f3fed4f909 100644
--- a/llvm/lib/Target/Xtensa/XtensaISelLowering.cpp
+++ b/llvm/lib/Target/Xtensa/XtensaISelLowering.cpp
@@ -513,29 +513,106 @@ static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
return SDValue();
}
+static SDValue SearchLoopIntrinsic(SDValue N, ISD::CondCode &CC, int &Imm,
+ bool &Negate) {
+ switch (N->getOpcode()) {
+ default:
+ break;
+ case ISD::XOR: {
+ if (!isa<ConstantSDNode>(N.getOperand(1)))
+ return SDValue();
+ if (!cast<ConstantSDNode>(N.getOperand(1))->isOne())
+ return SDValue();
+ Negate = !Negate;
+ return SearchLoopIntrinsic(N.getOperand(0), CC, Imm, Negate);
+ }
+ case ISD::SETCC: {
+ auto *Const = dyn_cast<ConstantSDNode>(N.getOperand(1));
+ if (!Const)
+ return SDValue();
+ if (Const->isNullValue())
+ Imm = 0;
+ else if (Const->isOne())
+ Imm = 1;
+ else
+ return SDValue();
+ CC = cast<CondCodeSDNode>(N.getOperand(2))->get();
+ return SearchLoopIntrinsic(N->getOperand(0), CC, Imm, Negate);
+ }
+ case ISD::INTRINSIC_W_CHAIN: {
+ unsigned IntOp = cast<ConstantSDNode>(N.getOperand(1))->getZExtValue();
+ if (IntOp != Intrinsic::loop_decrement)
+ return SDValue();
+ return N;
+ }
+ }
+ return SDValue();
+}
+