forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathTargetLoweringObjectFileImpl.cpp
2708 lines (2372 loc) · 103 KB
/
TargetLoweringObjectFileImpl.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
//===- llvm/CodeGen/TargetLoweringObjectFileImpl.cpp - Object File Info ---===//
//
// 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 classes used to handle lowerings specific to common
// object file formats.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/BinaryFormat/COFF.h"
#include "llvm/BinaryFormat/Dwarf.h"
#include "llvm/BinaryFormat/ELF.h"
#include "llvm/BinaryFormat/MachO.h"
#include "llvm/BinaryFormat/Wasm.h"
#include "llvm/CodeGen/BasicBlockSectionUtils.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineModuleInfoImpls.h"
#include "llvm/IR/Comdat.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/GlobalObject.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Mangler.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PseudoProbe.h"
#include "llvm/IR/Type.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCSectionCOFF.h"
#include "llvm/MC/MCSectionELF.h"
#include "llvm/MC/MCSectionGOFF.h"
#include "llvm/MC/MCSectionMachO.h"
#include "llvm/MC/MCSectionWasm.h"
#include "llvm/MC/MCSectionXCOFF.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCSymbol.h"
#include "llvm/MC/MCSymbolELF.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/SectionKind.h"
#include "llvm/ProfileData/InstrProf.h"
#include "llvm/Support/Base64.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CodeGen.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/TargetParser/Triple.h"
#include <cassert>
#include <string>
using namespace llvm;
using namespace dwarf;
static cl::opt<bool> JumpTableInFunctionSection(
"jumptable-in-function-section", cl::Hidden, cl::init(false),
cl::desc("Putting Jump Table in function section"));
static void GetObjCImageInfo(Module &M, unsigned &Version, unsigned &Flags,
StringRef &Section) {
SmallVector<Module::ModuleFlagEntry, 8> ModuleFlags;
M.getModuleFlagsMetadata(ModuleFlags);
for (const auto &MFE: ModuleFlags) {
// Ignore flags with 'Require' behaviour.
if (MFE.Behavior == Module::Require)
continue;
StringRef Key = MFE.Key->getString();
if (Key == "Objective-C Image Info Version") {
Version = mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
} else if (Key == "Objective-C Garbage Collection" ||
Key == "Objective-C GC Only" ||
Key == "Objective-C Is Simulated" ||
Key == "Objective-C Class Properties" ||
Key == "Objective-C Image Swift Version") {
Flags |= mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue();
} else if (Key == "Objective-C Image Info Section") {
Section = cast<MDString>(MFE.Val)->getString();
}
// Backend generates L_OBJC_IMAGE_INFO from Swift ABI version + major + minor +
// "Objective-C Garbage Collection".
else if (Key == "Swift ABI Version") {
Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 8;
} else if (Key == "Swift Major Version") {
Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 24;
} else if (Key == "Swift Minor Version") {
Flags |= (mdconst::extract<ConstantInt>(MFE.Val)->getZExtValue()) << 16;
}
}
}
//===----------------------------------------------------------------------===//
// ELF
//===----------------------------------------------------------------------===//
TargetLoweringObjectFileELF::TargetLoweringObjectFileELF() {
SupportDSOLocalEquivalentLowering = true;
}
void TargetLoweringObjectFileELF::Initialize(MCContext &Ctx,
const TargetMachine &TgtM) {
TargetLoweringObjectFile::Initialize(Ctx, TgtM);
CodeModel::Model CM = TgtM.getCodeModel();
InitializeELF(TgtM.Options.UseInitArray);
switch (TgtM.getTargetTriple().getArch()) {
case Triple::arm:
case Triple::armeb:
case Triple::thumb:
case Triple::thumbeb:
if (Ctx.getAsmInfo()->getExceptionHandlingType() == ExceptionHandling::ARM)
break;
// Fallthrough if not using EHABI
[[fallthrough]];
case Triple::ppc:
case Triple::ppcle:
case Triple::x86:
PersonalityEncoding = isPositionIndependent()
? dwarf::DW_EH_PE_indirect |
dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4
: dwarf::DW_EH_PE_absptr;
LSDAEncoding = isPositionIndependent()
? dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4
: dwarf::DW_EH_PE_absptr;
TTypeEncoding = isPositionIndependent()
? dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4
: dwarf::DW_EH_PE_absptr;
break;
case Triple::x86_64:
if (isPositionIndependent()) {
PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
((CM == CodeModel::Small || CM == CodeModel::Medium)
? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
LSDAEncoding = dwarf::DW_EH_PE_pcrel |
(CM == CodeModel::Small
? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
((CM == CodeModel::Small || CM == CodeModel::Medium)
? dwarf::DW_EH_PE_sdata4 : dwarf::DW_EH_PE_sdata8);
} else {
PersonalityEncoding =
(CM == CodeModel::Small || CM == CodeModel::Medium)
? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
LSDAEncoding = (CM == CodeModel::Small)
? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
TTypeEncoding = (CM == CodeModel::Small)
? dwarf::DW_EH_PE_udata4 : dwarf::DW_EH_PE_absptr;
}
break;
case Triple::hexagon:
PersonalityEncoding = dwarf::DW_EH_PE_absptr;
LSDAEncoding = dwarf::DW_EH_PE_absptr;
TTypeEncoding = dwarf::DW_EH_PE_absptr;
if (isPositionIndependent()) {
PersonalityEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
LSDAEncoding |= dwarf::DW_EH_PE_pcrel;
TTypeEncoding |= dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel;
}
break;
case Triple::aarch64:
case Triple::aarch64_be:
case Triple::aarch64_32:
// The small model guarantees static code/data size < 4GB, but not where it
// will be in memory. Most of these could end up >2GB away so even a signed
// pc-relative 32-bit address is insufficient, theoretically.
//
// Use DW_EH_PE_indirect even for -fno-pic to avoid copy relocations.
LSDAEncoding = dwarf::DW_EH_PE_pcrel |
(TgtM.getTargetTriple().getEnvironment() == Triple::GNUILP32
? dwarf::DW_EH_PE_sdata4
: dwarf::DW_EH_PE_sdata8);
PersonalityEncoding = LSDAEncoding | dwarf::DW_EH_PE_indirect;
TTypeEncoding = LSDAEncoding | dwarf::DW_EH_PE_indirect;
break;
case Triple::lanai:
LSDAEncoding = dwarf::DW_EH_PE_absptr;
PersonalityEncoding = dwarf::DW_EH_PE_absptr;
TTypeEncoding = dwarf::DW_EH_PE_absptr;
break;
case Triple::mips:
case Triple::mipsel:
case Triple::mips64:
case Triple::mips64el:
// MIPS uses indirect pointer to refer personality functions and types, so
// that the eh_frame section can be read-only. DW.ref.personality will be
// generated for relocation.
PersonalityEncoding = dwarf::DW_EH_PE_indirect;
// FIXME: The N64 ABI probably ought to use DW_EH_PE_sdata8 but we can't
// identify N64 from just a triple.
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
// We don't support PC-relative LSDA references in GAS so we use the default
// DW_EH_PE_absptr for those.
// FreeBSD must be explicit about the data size and using pcrel since it's
// assembler/linker won't do the automatic conversion that the Linux tools
// do.
if (TgtM.getTargetTriple().isOSFreeBSD()) {
PersonalityEncoding |= dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
}
break;
case Triple::ppc64:
case Triple::ppc64le:
PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_udata8;
LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_udata8;
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_udata8;
break;
case Triple::sparcel:
case Triple::sparc:
if (isPositionIndependent()) {
LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
} else {
LSDAEncoding = dwarf::DW_EH_PE_absptr;
PersonalityEncoding = dwarf::DW_EH_PE_absptr;
TTypeEncoding = dwarf::DW_EH_PE_absptr;
}
CallSiteEncoding = dwarf::DW_EH_PE_udata4;
break;
case Triple::riscv32:
case Triple::riscv64:
LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
CallSiteEncoding = dwarf::DW_EH_PE_udata4;
break;
case Triple::sparcv9:
LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
if (isPositionIndependent()) {
PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
} else {
PersonalityEncoding = dwarf::DW_EH_PE_absptr;
TTypeEncoding = dwarf::DW_EH_PE_absptr;
}
break;
case Triple::systemz:
// All currently-defined code models guarantee that 4-byte PC-relative
// values will be in range.
if (isPositionIndependent()) {
PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
} else {
PersonalityEncoding = dwarf::DW_EH_PE_absptr;
LSDAEncoding = dwarf::DW_EH_PE_absptr;
TTypeEncoding = dwarf::DW_EH_PE_absptr;
}
break;
case Triple::loongarch32:
case Triple::loongarch64:
LSDAEncoding = dwarf::DW_EH_PE_pcrel | dwarf::DW_EH_PE_sdata4;
PersonalityEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
TTypeEncoding = dwarf::DW_EH_PE_indirect | dwarf::DW_EH_PE_pcrel |
dwarf::DW_EH_PE_sdata4;
break;
default:
break;
}
}
void TargetLoweringObjectFileELF::getModuleMetadata(Module &M) {
SmallVector<GlobalValue *, 4> Vec;
collectUsedGlobalVariables(M, Vec, false);
for (GlobalValue *GV : Vec)
if (auto *GO = dyn_cast<GlobalObject>(GV))
Used.insert(GO);
}
void TargetLoweringObjectFileELF::emitModuleMetadata(MCStreamer &Streamer,
Module &M) const {
auto &C = getContext();
if (NamedMDNode *LinkerOptions = M.getNamedMetadata("llvm.linker.options")) {
auto *S = C.getELFSection(".linker-options", ELF::SHT_LLVM_LINKER_OPTIONS,
ELF::SHF_EXCLUDE);
Streamer.switchSection(S);
for (const auto *Operand : LinkerOptions->operands()) {
if (cast<MDNode>(Operand)->getNumOperands() != 2)
report_fatal_error("invalid llvm.linker.options");
for (const auto &Option : cast<MDNode>(Operand)->operands()) {
Streamer.emitBytes(cast<MDString>(Option)->getString());
Streamer.emitInt8(0);
}
}
}
if (NamedMDNode *DependentLibraries = M.getNamedMetadata("llvm.dependent-libraries")) {
auto *S = C.getELFSection(".deplibs", ELF::SHT_LLVM_DEPENDENT_LIBRARIES,
ELF::SHF_MERGE | ELF::SHF_STRINGS, 1);
Streamer.switchSection(S);
for (const auto *Operand : DependentLibraries->operands()) {
Streamer.emitBytes(
cast<MDString>(cast<MDNode>(Operand)->getOperand(0))->getString());
Streamer.emitInt8(0);
}
}
if (NamedMDNode *FuncInfo = M.getNamedMetadata(PseudoProbeDescMetadataName)) {
// Emit a descriptor for every function including functions that have an
// available external linkage. We may not want this for imported functions
// that has code in another thinLTO module but we don't have a good way to
// tell them apart from inline functions defined in header files. Therefore
// we put each descriptor in a separate comdat section and rely on the
// linker to deduplicate.
for (const auto *Operand : FuncInfo->operands()) {
const auto *MD = cast<MDNode>(Operand);
auto *GUID = mdconst::dyn_extract<ConstantInt>(MD->getOperand(0));
auto *Hash = mdconst::dyn_extract<ConstantInt>(MD->getOperand(1));
auto *Name = cast<MDString>(MD->getOperand(2));
auto *S = C.getObjectFileInfo()->getPseudoProbeDescSection(
TM->getFunctionSections() ? Name->getString() : StringRef());
Streamer.switchSection(S);
Streamer.emitInt64(GUID->getZExtValue());
Streamer.emitInt64(Hash->getZExtValue());
Streamer.emitULEB128IntValue(Name->getString().size());
Streamer.emitBytes(Name->getString());
}
}
if (NamedMDNode *LLVMStats = M.getNamedMetadata("llvm.stats")) {
// Emit the metadata for llvm statistics into .llvm_stats section, which is
// formatted as a list of key/value pair, the value is base64 encoded.
auto *S = C.getObjectFileInfo()->getLLVMStatsSection();
Streamer.switchSection(S);
for (const auto *Operand : LLVMStats->operands()) {
const auto *MD = cast<MDNode>(Operand);
assert(MD->getNumOperands() % 2 == 0 &&
("Operand num should be even for a list of key/value pair"));
for (size_t I = 0; I < MD->getNumOperands(); I += 2) {
// Encode the key string size.
auto *Key = cast<MDString>(MD->getOperand(I));
Streamer.emitULEB128IntValue(Key->getString().size());
Streamer.emitBytes(Key->getString());
// Encode the value into a Base64 string.
std::string Value = encodeBase64(
Twine(mdconst::dyn_extract<ConstantInt>(MD->getOperand(I + 1))
->getZExtValue())
.str());
Streamer.emitULEB128IntValue(Value.size());
Streamer.emitBytes(Value);
}
}
}
unsigned Version = 0;
unsigned Flags = 0;
StringRef Section;
GetObjCImageInfo(M, Version, Flags, Section);
if (!Section.empty()) {
auto *S = C.getELFSection(Section, ELF::SHT_PROGBITS, ELF::SHF_ALLOC);
Streamer.switchSection(S);
Streamer.emitLabel(C.getOrCreateSymbol(StringRef("OBJC_IMAGE_INFO")));
Streamer.emitInt32(Version);
Streamer.emitInt32(Flags);
Streamer.addBlankLine();
}
emitCGProfileMetadata(Streamer, M);
}
MCSymbol *TargetLoweringObjectFileELF::getCFIPersonalitySymbol(
const GlobalValue *GV, const TargetMachine &TM,
MachineModuleInfo *MMI) const {
unsigned Encoding = getPersonalityEncoding();
if ((Encoding & 0x80) == DW_EH_PE_indirect)
return getContext().getOrCreateSymbol(StringRef("DW.ref.") +
TM.getSymbol(GV)->getName());
if ((Encoding & 0x70) == DW_EH_PE_absptr)
return TM.getSymbol(GV);
report_fatal_error("We do not support this DWARF encoding yet!");
}
void TargetLoweringObjectFileELF::emitPersonalityValue(
MCStreamer &Streamer, const DataLayout &DL, const MCSymbol *Sym) const {
SmallString<64> NameData("DW.ref.");
NameData += Sym->getName();
MCSymbolELF *Label =
cast<MCSymbolELF>(getContext().getOrCreateSymbol(NameData));
Streamer.emitSymbolAttribute(Label, MCSA_Hidden);
Streamer.emitSymbolAttribute(Label, MCSA_Weak);
unsigned Flags = ELF::SHF_ALLOC | ELF::SHF_WRITE | ELF::SHF_GROUP;
MCSection *Sec = getContext().getELFNamedSection(".data", Label->getName(),
ELF::SHT_PROGBITS, Flags, 0);
unsigned Size = DL.getPointerSize();
Streamer.switchSection(Sec);
Streamer.emitValueToAlignment(DL.getPointerABIAlignment(0));
Streamer.emitSymbolAttribute(Label, MCSA_ELF_TypeObject);
const MCExpr *E = MCConstantExpr::create(Size, getContext());
Streamer.emitELFSize(Label, E);
Streamer.emitLabel(Label);
Streamer.emitSymbolValue(Sym, Size);
}
const MCExpr *TargetLoweringObjectFileELF::getTTypeGlobalReference(
const GlobalValue *GV, unsigned Encoding, const TargetMachine &TM,
MachineModuleInfo *MMI, MCStreamer &Streamer) const {
if (Encoding & DW_EH_PE_indirect) {
MachineModuleInfoELF &ELFMMI = MMI->getObjFileInfo<MachineModuleInfoELF>();
MCSymbol *SSym = getSymbolWithGlobalValueBase(GV, ".DW.stub", TM);
// Add information about the stub reference to ELFMMI so that the stub
// gets emitted by the asmprinter.
MachineModuleInfoImpl::StubValueTy &StubSym = ELFMMI.getGVStubEntry(SSym);
if (!StubSym.getPointer()) {
MCSymbol *Sym = TM.getSymbol(GV);
StubSym = MachineModuleInfoImpl::StubValueTy(Sym, !GV->hasLocalLinkage());
}
return TargetLoweringObjectFile::
getTTypeReference(MCSymbolRefExpr::create(SSym, getContext()),
Encoding & ~DW_EH_PE_indirect, Streamer);
}
return TargetLoweringObjectFile::getTTypeGlobalReference(GV, Encoding, TM,
MMI, Streamer);
}
static SectionKind getELFKindForNamedSection(StringRef Name, SectionKind K) {
// N.B.: The defaults used in here are not the same ones used in MC.
// We follow gcc, MC follows gas. For example, given ".section .eh_frame",
// both gas and MC will produce a section with no flags. Given
// section(".eh_frame") gcc will produce:
//
// .section .eh_frame,"a",@progbits
if (Name == getInstrProfSectionName(IPSK_covmap, Triple::ELF,
/*AddSegmentInfo=*/false) ||
Name == getInstrProfSectionName(IPSK_covfun, Triple::ELF,
/*AddSegmentInfo=*/false) ||
Name == getInstrProfSectionName(IPSK_covdata, Triple::ELF,
/*AddSegmentInfo=*/false) ||
Name == getInstrProfSectionName(IPSK_covname, Triple::ELF,
/*AddSegmentInfo=*/false) ||
Name == ".llvmbc" || Name == ".llvmcmd")
return SectionKind::getMetadata();
if (Name.empty() || Name[0] != '.') return K;
// Default implementation based on some magic section names.
if (Name == ".bss" || Name.starts_with(".bss.") ||
Name.starts_with(".gnu.linkonce.b.") ||
Name.starts_with(".llvm.linkonce.b.") || Name == ".sbss" ||
Name.starts_with(".sbss.") || Name.starts_with(".gnu.linkonce.sb.") ||
Name.starts_with(".llvm.linkonce.sb."))
return SectionKind::getBSS();
if (Name == ".tdata" || Name.starts_with(".tdata.") ||
Name.starts_with(".gnu.linkonce.td.") ||
Name.starts_with(".llvm.linkonce.td."))
return SectionKind::getThreadData();
if (Name == ".tbss" || Name.starts_with(".tbss.") ||
Name.starts_with(".gnu.linkonce.tb.") ||
Name.starts_with(".llvm.linkonce.tb."))
return SectionKind::getThreadBSS();
return K;
}
static bool hasPrefix(StringRef SectionName, StringRef Prefix) {
return SectionName.consume_front(Prefix) &&
(SectionName.empty() || SectionName[0] == '.');
}
static unsigned getELFSectionType(StringRef Name, SectionKind K) {
// Use SHT_NOTE for section whose name starts with ".note" to allow
// emitting ELF notes from C variable declaration.
// See https://gcc.gnu.org/bugzilla/show_bug.cgi?id=77609
if (Name.starts_with(".note"))
return ELF::SHT_NOTE;
if (hasPrefix(Name, ".init_array"))
return ELF::SHT_INIT_ARRAY;
if (hasPrefix(Name, ".fini_array"))
return ELF::SHT_FINI_ARRAY;
if (hasPrefix(Name, ".preinit_array"))
return ELF::SHT_PREINIT_ARRAY;
if (hasPrefix(Name, ".llvm.offloading"))
return ELF::SHT_LLVM_OFFLOADING;
if (K.isBSS() || K.isThreadBSS())
return ELF::SHT_NOBITS;
return ELF::SHT_PROGBITS;
}
static unsigned getELFSectionFlags(SectionKind K) {
unsigned Flags = 0;
if (!K.isMetadata() && !K.isExclude())
Flags |= ELF::SHF_ALLOC;
if (K.isExclude())
Flags |= ELF::SHF_EXCLUDE;
if (K.isText())
Flags |= ELF::SHF_EXECINSTR;
if (K.isExecuteOnly())
Flags |= ELF::SHF_ARM_PURECODE;
if (K.isWriteable())
Flags |= ELF::SHF_WRITE;
if (K.isThreadLocal())
Flags |= ELF::SHF_TLS;
if (K.isMergeableCString() || K.isMergeableConst())
Flags |= ELF::SHF_MERGE;
if (K.isMergeableCString())
Flags |= ELF::SHF_STRINGS;
return Flags;
}
static const Comdat *getELFComdat(const GlobalValue *GV) {
const Comdat *C = GV->getComdat();
if (!C)
return nullptr;
if (C->getSelectionKind() != Comdat::Any &&
C->getSelectionKind() != Comdat::NoDeduplicate)
report_fatal_error("ELF COMDATs only support SelectionKind::Any and "
"SelectionKind::NoDeduplicate, '" +
C->getName() + "' cannot be lowered.");
return C;
}
static const MCSymbolELF *getLinkedToSymbol(const GlobalObject *GO,
const TargetMachine &TM) {
MDNode *MD = GO->getMetadata(LLVMContext::MD_associated);
if (!MD)
return nullptr;
auto *VM = cast<ValueAsMetadata>(MD->getOperand(0).get());
auto *OtherGV = dyn_cast<GlobalValue>(VM->getValue());
return OtherGV ? dyn_cast<MCSymbolELF>(TM.getSymbol(OtherGV)) : nullptr;
}
static unsigned getEntrySizeForKind(SectionKind Kind) {
if (Kind.isMergeable1ByteCString())
return 1;
else if (Kind.isMergeable2ByteCString())
return 2;
else if (Kind.isMergeable4ByteCString())
return 4;
else if (Kind.isMergeableConst4())
return 4;
else if (Kind.isMergeableConst8())
return 8;
else if (Kind.isMergeableConst16())
return 16;
else if (Kind.isMergeableConst32())
return 32;
else {
// We shouldn't have mergeable C strings or mergeable constants that we
// didn't handle above.
assert(!Kind.isMergeableCString() && "unknown string width");
assert(!Kind.isMergeableConst() && "unknown data width");
return 0;
}
}
/// Return the section prefix name used by options FunctionsSections and
/// DataSections.
static StringRef getSectionPrefixForGlobal(SectionKind Kind, bool IsLarge) {
if (Kind.isText())
return IsLarge ? ".ltext" : ".text";
if (Kind.isReadOnly())
return IsLarge ? ".lrodata" : ".rodata";
if (Kind.isBSS())
return IsLarge ? ".lbss" : ".bss";
if (Kind.isThreadData())
return ".tdata";
if (Kind.isThreadBSS())
return ".tbss";
if (Kind.isData())
return IsLarge ? ".ldata" : ".data";
if (Kind.isReadOnlyWithRel())
return IsLarge ? ".ldata.rel.ro" : ".data.rel.ro";
llvm_unreachable("Unknown section kind");
}
static SmallString<128>
getELFSectionNameForGlobal(const GlobalObject *GO, SectionKind Kind,
Mangler &Mang, const TargetMachine &TM,
unsigned EntrySize, bool UniqueSectionName) {
SmallString<128> Name;
if (Kind.isMergeableCString()) {
// We also need alignment here.
// FIXME: this is getting the alignment of the character, not the
// alignment of the global!
Align Alignment = GO->getParent()->getDataLayout().getPreferredAlign(
cast<GlobalVariable>(GO));
std::string SizeSpec = ".rodata.str" + utostr(EntrySize) + ".";
Name = SizeSpec + utostr(Alignment.value());
} else if (Kind.isMergeableConst()) {
Name = ".rodata.cst";
Name += utostr(EntrySize);
} else {
Name = getSectionPrefixForGlobal(Kind, TM.isLargeGlobalValue(GO));
}
bool HasPrefix = false;
if (const auto *F = dyn_cast<Function>(GO)) {
if (std::optional<StringRef> Prefix = F->getSectionPrefix()) {
raw_svector_ostream(Name) << '.' << *Prefix;
HasPrefix = true;
}
}
if (UniqueSectionName) {
Name.push_back('.');
TM.getNameWithPrefix(Name, GO, Mang, /*MayAlwaysUsePrivate*/true);
} else if (HasPrefix)
// For distinguishing between .text.${text-section-prefix}. (with trailing
// dot) and .text.${function-name}
Name.push_back('.');
return Name;
}
namespace {
class LoweringDiagnosticInfo : public DiagnosticInfo {
const Twine &Msg;
public:
LoweringDiagnosticInfo(const Twine &DiagMsg,
DiagnosticSeverity Severity = DS_Error)
: DiagnosticInfo(DK_Lowering, Severity), Msg(DiagMsg) {}
void print(DiagnosticPrinter &DP) const override { DP << Msg; }
};
}
/// Calculate an appropriate unique ID for a section, and update Flags,
/// EntrySize and NextUniqueID where appropriate.
static unsigned
calcUniqueIDUpdateFlagsAndSize(const GlobalObject *GO, StringRef SectionName,
SectionKind Kind, const TargetMachine &TM,
MCContext &Ctx, Mangler &Mang, unsigned &Flags,
unsigned &EntrySize, unsigned &NextUniqueID,
const bool Retain, const bool ForceUnique) {
// Increment uniqueID if we are forced to emit a unique section.
// This works perfectly fine with section attribute or pragma section as the
// sections with the same name are grouped together by the assembler.
if (ForceUnique)
return NextUniqueID++;
// A section can have at most one associated section. Put each global with
// MD_associated in a unique section.
const bool Associated = GO->getMetadata(LLVMContext::MD_associated);
if (Associated) {
Flags |= ELF::SHF_LINK_ORDER;
return NextUniqueID++;
}
if (Retain) {
if (TM.getTargetTriple().isOSSolaris())
Flags |= ELF::SHF_SUNW_NODISCARD;
else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36))
Flags |= ELF::SHF_GNU_RETAIN;
return NextUniqueID++;
}
// If two symbols with differing sizes end up in the same mergeable section
// that section can be assigned an incorrect entry size. To avoid this we
// usually put symbols of the same size into distinct mergeable sections with
// the same name. Doing so relies on the ",unique ," assembly feature. This
// feature is not avalible until bintuils version 2.35
// (https://sourceware.org/bugzilla/show_bug.cgi?id=25380).
const bool SupportsUnique = Ctx.getAsmInfo()->useIntegratedAssembler() ||
Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35);
if (!SupportsUnique) {
Flags &= ~ELF::SHF_MERGE;
EntrySize = 0;
return MCContext::GenericSectionID;
}
const bool SymbolMergeable = Flags & ELF::SHF_MERGE;
const bool SeenSectionNameBefore =
Ctx.isELFGenericMergeableSection(SectionName);
// If this is the first ocurrence of this section name, treat it as the
// generic section
if (!SymbolMergeable && !SeenSectionNameBefore)
return MCContext::GenericSectionID;
// Symbols must be placed into sections with compatible entry sizes. Generate
// unique sections for symbols that have not been assigned to compatible
// sections.
const auto PreviousID =
Ctx.getELFUniqueIDForEntsize(SectionName, Flags, EntrySize);
if (PreviousID)
return *PreviousID;
// If the user has specified the same section name as would be created
// implicitly for this symbol e.g. .rodata.str1.1, then we don't need
// to unique the section as the entry size for this symbol will be
// compatible with implicitly created sections.
SmallString<128> ImplicitSectionNameStem =
getELFSectionNameForGlobal(GO, Kind, Mang, TM, EntrySize, false);
if (SymbolMergeable &&
Ctx.isELFImplicitMergeableSectionNamePrefix(SectionName) &&
SectionName.starts_with(ImplicitSectionNameStem))
return MCContext::GenericSectionID;
// We have seen this section name before, but with different flags or entity
// size. Create a new unique ID.
return NextUniqueID++;
}
static std::tuple<StringRef, bool, unsigned>
getGlobalObjectInfo(const GlobalObject *GO, const TargetMachine &TM) {
StringRef Group = "";
bool IsComdat = false;
unsigned Flags = 0;
if (const Comdat *C = getELFComdat(GO)) {
Flags |= ELF::SHF_GROUP;
Group = C->getName();
IsComdat = C->getSelectionKind() == Comdat::Any;
}
if (TM.isLargeGlobalValue(GO))
Flags |= ELF::SHF_X86_64_LARGE;
return {Group, IsComdat, Flags};
}
static MCSection *selectExplicitSectionGlobal(
const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM,
MCContext &Ctx, Mangler &Mang, unsigned &NextUniqueID,
bool Retain, bool ForceUnique) {
StringRef SectionName = GO->getSection();
// Check if '#pragma clang section' name is applicable.
// Note that pragma directive overrides -ffunction-section, -fdata-section
// and so section name is exactly as user specified and not uniqued.
const GlobalVariable *GV = dyn_cast<GlobalVariable>(GO);
if (GV && GV->hasImplicitSection()) {
auto Attrs = GV->getAttributes();
if (Attrs.hasAttribute("bss-section") && Kind.isBSS()) {
SectionName = Attrs.getAttribute("bss-section").getValueAsString();
} else if (Attrs.hasAttribute("rodata-section") && Kind.isReadOnly()) {
SectionName = Attrs.getAttribute("rodata-section").getValueAsString();
} else if (Attrs.hasAttribute("relro-section") && Kind.isReadOnlyWithRel()) {
SectionName = Attrs.getAttribute("relro-section").getValueAsString();
} else if (Attrs.hasAttribute("data-section") && Kind.isData()) {
SectionName = Attrs.getAttribute("data-section").getValueAsString();
}
}
const Function *F = dyn_cast<Function>(GO);
if (F && F->hasFnAttribute("implicit-section-name")) {
SectionName = F->getFnAttribute("implicit-section-name").getValueAsString();
}
// Infer section flags from the section name if we can.
Kind = getELFKindForNamedSection(SectionName, Kind);
unsigned Flags = getELFSectionFlags(Kind);
auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
Flags |= ExtraFlags;
unsigned EntrySize = getEntrySizeForKind(Kind);
const unsigned UniqueID = calcUniqueIDUpdateFlagsAndSize(
GO, SectionName, Kind, TM, Ctx, Mang, Flags, EntrySize, NextUniqueID,
Retain, ForceUnique);
const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
MCSectionELF *Section = Ctx.getELFSection(
SectionName, getELFSectionType(SectionName, Kind), Flags, EntrySize,
Group, IsComdat, UniqueID, LinkedToSym);
// Make sure that we did not get some other section with incompatible sh_link.
// This should not be possible due to UniqueID code above.
assert(Section->getLinkedToSymbol() == LinkedToSym &&
"Associated symbol mismatch between sections");
if (!(Ctx.getAsmInfo()->useIntegratedAssembler() ||
Ctx.getAsmInfo()->binutilsIsAtLeast(2, 35))) {
// If we are using GNU as before 2.35, then this symbol might have
// been placed in an incompatible mergeable section. Emit an error if this
// is the case to avoid creating broken output.
if ((Section->getFlags() & ELF::SHF_MERGE) &&
(Section->getEntrySize() != getEntrySizeForKind(Kind)))
GO->getContext().diagnose(LoweringDiagnosticInfo(
"Symbol '" + GO->getName() + "' from module '" +
(GO->getParent() ? GO->getParent()->getSourceFileName() : "unknown") +
"' required a section with entry-size=" +
Twine(getEntrySizeForKind(Kind)) + " but was placed in section '" +
SectionName + "' with entry-size=" + Twine(Section->getEntrySize()) +
": Explicit assignment by pragma or attribute of an incompatible "
"symbol to this section?"));
}
return Section;
}
MCSection *TargetLoweringObjectFileELF::getExplicitSectionGlobal(
const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
return selectExplicitSectionGlobal(GO, Kind, TM, getContext(), getMangler(),
NextUniqueID, Used.count(GO),
/* ForceUnique = */false);
}
static MCSectionELF *selectELFSectionForGlobal(
MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
const TargetMachine &TM, bool EmitUniqueSection, unsigned Flags,
unsigned *NextUniqueID, const MCSymbolELF *AssociatedSymbol) {
auto [Group, IsComdat, ExtraFlags] = getGlobalObjectInfo(GO, TM);
Flags |= ExtraFlags;
// Get the section entry size based on the kind.
unsigned EntrySize = getEntrySizeForKind(Kind);
bool UniqueSectionName = false;
unsigned UniqueID = MCContext::GenericSectionID;
if (EmitUniqueSection) {
if (TM.getUniqueSectionNames()) {
UniqueSectionName = true;
} else {
UniqueID = *NextUniqueID;
(*NextUniqueID)++;
}
}
SmallString<128> Name = getELFSectionNameForGlobal(
GO, Kind, Mang, TM, EntrySize, UniqueSectionName);
// Use 0 as the unique ID for execute-only text.
if (Kind.isExecuteOnly())
UniqueID = 0;
return Ctx.getELFSection(Name, getELFSectionType(Name, Kind), Flags,
EntrySize, Group, IsComdat, UniqueID,
AssociatedSymbol);
}
static MCSection *selectELFSectionForGlobal(
MCContext &Ctx, const GlobalObject *GO, SectionKind Kind, Mangler &Mang,
const TargetMachine &TM, bool Retain, bool EmitUniqueSection,
unsigned Flags, unsigned *NextUniqueID) {
const MCSymbolELF *LinkedToSym = getLinkedToSymbol(GO, TM);
if (LinkedToSym) {
EmitUniqueSection = true;
Flags |= ELF::SHF_LINK_ORDER;
}
if (Retain) {
if (TM.getTargetTriple().isOSSolaris()) {
EmitUniqueSection = true;
Flags |= ELF::SHF_SUNW_NODISCARD;
} else if (Ctx.getAsmInfo()->useIntegratedAssembler() ||
Ctx.getAsmInfo()->binutilsIsAtLeast(2, 36)) {
EmitUniqueSection = true;
Flags |= ELF::SHF_GNU_RETAIN;
}
}
MCSectionELF *Section = selectELFSectionForGlobal(
Ctx, GO, Kind, Mang, TM, EmitUniqueSection, Flags,
NextUniqueID, LinkedToSym);
assert(Section->getLinkedToSymbol() == LinkedToSym);
return Section;
}
MCSection *TargetLoweringObjectFileELF::SelectSectionForGlobal(
const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const {
unsigned Flags = getELFSectionFlags(Kind);
// If we have -ffunction-section or -fdata-section then we should emit the
// global value to a uniqued section specifically for it.
bool EmitUniqueSection = false;
if (!(Flags & ELF::SHF_MERGE) && !Kind.isCommon()) {
if (Kind.isText())
EmitUniqueSection = TM.getFunctionSections();
else
EmitUniqueSection = TM.getDataSections();
}
EmitUniqueSection |= GO->hasComdat();
return selectELFSectionForGlobal(getContext(), GO, Kind, getMangler(), TM,
Used.count(GO), EmitUniqueSection, Flags,
&NextUniqueID);
}
MCSection *TargetLoweringObjectFileELF::getUniqueSectionForFunction(
const Function &F, const TargetMachine &TM) const {
SectionKind Kind = SectionKind::getText();
unsigned Flags = getELFSectionFlags(Kind);
// If the function's section names is pre-determined via pragma or a
// section attribute, call selectExplicitSectionGlobal.
if (F.hasSection() || F.hasFnAttribute("implicit-section-name"))
return selectExplicitSectionGlobal(
&F, Kind, TM, getContext(), getMangler(), NextUniqueID,
Used.count(&F), /* ForceUnique = */true);
else
return selectELFSectionForGlobal(
getContext(), &F, Kind, getMangler(), TM, Used.count(&F),
/*EmitUniqueSection=*/true, Flags, &NextUniqueID);
}
MCSection *TargetLoweringObjectFileELF::getSectionForJumpTable(
const Function &F, const TargetMachine &TM) const {
// If the function can be removed, produce a unique section so that
// the table doesn't prevent the removal.
const Comdat *C = F.getComdat();
bool EmitUniqueSection = TM.getFunctionSections() || C;
if (!EmitUniqueSection)
return ReadOnlySection;
return selectELFSectionForGlobal(getContext(), &F, SectionKind::getReadOnly(),
getMangler(), TM, EmitUniqueSection,
ELF::SHF_ALLOC, &NextUniqueID,
/* AssociatedSymbol */ nullptr);
}
MCSection *TargetLoweringObjectFileELF::getSectionForLSDA(
const Function &F, const MCSymbol &FnSym, const TargetMachine &TM) const {
// If neither COMDAT nor function sections, use the monolithic LSDA section.
// Re-use this path if LSDASection is null as in the Arm EHABI.
if (!LSDASection || (!F.hasComdat() && !TM.getFunctionSections()))
return LSDASection;
const auto *LSDA = cast<MCSectionELF>(LSDASection);
unsigned Flags = LSDA->getFlags();
const MCSymbolELF *LinkedToSym = nullptr;
StringRef Group;
bool IsComdat = false;
if (const Comdat *C = getELFComdat(&F)) {
Flags |= ELF::SHF_GROUP;
Group = C->getName();
IsComdat = C->getSelectionKind() == Comdat::Any;
}
// Use SHF_LINK_ORDER to facilitate --gc-sections if we can use GNU ld>=2.36
// or LLD, which support mixed SHF_LINK_ORDER & non-SHF_LINK_ORDER.
if (TM.getFunctionSections() &&
(getContext().getAsmInfo()->useIntegratedAssembler() &&
getContext().getAsmInfo()->binutilsIsAtLeast(2, 36))) {
Flags |= ELF::SHF_LINK_ORDER;
LinkedToSym = cast<MCSymbolELF>(&FnSym);
}
// Append the function name as the suffix like GCC, assuming
// -funique-section-names applies to .gcc_except_table sections.
return getContext().getELFSection(
(TM.getUniqueSectionNames() ? LSDA->getName() + "." + F.getName()
: LSDA->getName()),
LSDA->getType(), Flags, 0, Group, IsComdat, MCSection::NonUniqueID,
LinkedToSym);
}
bool TargetLoweringObjectFileELF::shouldPutJumpTableInFunctionSection(
bool UsesLabelDifference, const Function &F) const {
// We can always create relative relocations, so use another section
// that can be marked non-executable.
return false;