-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathTriple.swift
1766 lines (1581 loc) · 50.1 KB
/
Triple.swift
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
//===--------------- Triple.swift - Swift Target Triples ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Helper for working with target triples.
///
/// Target triples are strings in the canonical form:
/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM
/// or
/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM-ENVIRONMENT
///
/// This type is used for clients which want to support arbitrary
/// configuration names, but also want to implement certain special
/// behavior for particular configurations. This class isolates the mapping
/// from the components of the configuration name to well known IDs.
///
/// At its core the Triple class is designed to be a wrapper for a triple
/// string; the constructor does not change or normalize the triple string.
/// Clients that need to handle the non-canonical triples that users often
/// specify should use the normalize method.
///
/// See autoconf/config.guess for a glimpse into what target triples
/// look like in practice.
///
/// This is a port of https://github.com/apple/swift-llvm/blob/stable/include/llvm/ADT/Triple.h
@dynamicMemberLookup
public struct Triple: Sendable {
/// `Triple` proxies predicates from `Triple.OS`, returning `false` for an unknown OS.
public subscript(dynamicMember predicate: KeyPath<OS, Bool>) -> Bool {
os?[keyPath: predicate] ?? false
}
/// The original triple string.
public let triple: String
/// The parsed arch.
public let arch: Arch?
/// The parsed subarchitecture.
public let subArch: SubArch?
/// The parsed vendor.
public let vendor: Vendor?
/// The parsed OS.
public let os: OS?
/// The parsed Environment type.
public let environment: Environment?
/// The object format type.
public let objectFormat: ObjectFormat?
/// Represents a version that may be present in the target triple.
public struct Version: Equatable, Comparable, CustomStringConvertible, Sendable {
public static let zero = Version(0, 0, 0)
public var major: Int
public var minor: Int
public var micro: Int
public init<S: StringProtocol>(parse string: S) {
let components = string.split(separator: ".", maxSplits: 3).map{ Int($0) ?? 0 }
self.major = components.count > 0 ? components[0] : 0
self.minor = components.count > 1 ? components[1] : 0
self.micro = components.count > 2 ? components[2] : 0
}
public init(_ major: Int, _ minor: Int, _ micro: Int) {
self.major = major
self.minor = minor
self.micro = micro
}
public static func <(lhs: Version, rhs: Version) -> Bool {
return (lhs.major, lhs.minor, lhs.micro) < (rhs.major, rhs.minor, rhs.micro)
}
public var description: String {
return "\(major).\(minor).\(micro)"
}
}
public init(_ string: String, normalizing: Bool = false) {
var parser = TripleParser(string, allowMore: normalizing)
// First, see if each component parses at its expected position.
var parsedArch = parser.match(ArchInfo.self, at: 0)
var parsedVendor = parser.match(Vendor.self, at: 1)
var parsedOS = parser.match(OS.self, at: 2)
var parsedEnv = parser.match(EnvInfo.self, at: 3)
if normalizing {
// Next, try to fill in each unmatched field from the rejected components.
parser.rematch(&parsedArch, at: 0)
parser.rematch(&parsedVendor, at: 1)
parser.rematch(&parsedOS, at: 2)
parser.rematch(&parsedEnv, at: 3)
let isCygwin = parser.componentsIndicateCygwin
let isMinGW32 = parser.componentsIndicateMinGW32
if
let parsedEnv = parsedEnv,
parsedEnv.value.environment == .android,
parsedEnv.substring.hasPrefix("androideabi") {
let androidVersion = parsedEnv.substring.dropFirst("androideabi".count)
parser.components[3] = "android\(androidVersion)"
}
// SUSE uses "gnueabi" to mean "gnueabihf"
if parsedVendor?.value == .suse && parsedEnv?.value.environment == .gnueabi {
parser.components[3] = "gnueabihf"
}
if parsedOS?.value == .win32 {
parser.components.resize(toCount: 4, paddingWith: "")
parser.components[2] = "windows"
if parsedEnv?.value.environment == nil {
if let objectFormat = parsedEnv?.value.objectFormat {
parser.components[3] = Substring(objectFormat.name)
} else {
parser.components[3] = "msvc"
}
}
} else if isMinGW32 {
parser.components.resize(toCount: 4, paddingWith: "")
parser.components[2] = "windows"
parser.components[3] = "gnu"
} else if isCygwin {
parser.components.resize(toCount: 4, paddingWith: "")
parser.components[2] = "windows"
parser.components[3] = "cygnus"
}
if isMinGW32 || isCygwin || (parsedOS?.value == .win32 && parsedEnv?.value.environment != nil) {
if let objectFormat = parsedEnv?.value.objectFormat, objectFormat != .coff {
parser.components.resize(toCount: 5, paddingWith: "")
parser.components[4] = Substring(objectFormat.name)
}
}
// Now that we've parsed everything, we construct a normalized form of the
// triple string.
triple = parser.components.map({ $0.isEmpty ? "unknown" : $0 }).joined(separator: "-")
}
else {
triple = string
}
// Unpack the parsed data into the fields. If no environment info was found,
// attempt to infer it from other fields.
self.arch = parsedArch?.value.arch
self.subArch = parsedArch?.value.subArch
self.vendor = parsedVendor?.value
self.os = parsedOS?.value
if let parsedEnv = parsedEnv {
self.environment = parsedEnv.value.environment
self.objectFormat = parsedEnv.value.objectFormat
?? ObjectFormat.infer(arch: parsedArch?.value.arch,
os: parsedOS?.value)
}
else {
self.environment = Environment.infer(archName: parsedArch?.substring)
self.objectFormat = ObjectFormat.infer(arch: parsedArch?.value.arch,
os: parsedOS?.value)
}
}
}
extension Triple: Codable {
public init(from decoder: Decoder) throws {
self.init(try decoder.singleValueContainer().decode(String.self))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(triple)
}
}
// MARK: - Triple component parsing
fileprivate protocol TripleComponent {
static func parse(_ component: Substring) -> Self?
static func valueIsValid(_ value: Substring) -> Bool
}
extension TripleComponent {
static func valueIsValid(_ value: Substring) -> Bool {
parse(value) != nil
}
}
fileprivate struct ParsedComponent<Value: TripleComponent> {
let value: Value
let substring: Substring
/// Attempts to parse `component` with `parser`, placing it in `rejects` if
/// it does not succeed.
///
/// - Returns: `nil` if `type` cannot parse `component`; otherwise, an
/// instance containing the component and its parsed value.
init?(_ component: Substring, as type: Value.Type) {
guard let value = type.parse(component) else {
return nil
}
self.value = value
self.substring = component
}
}
/// Holds the list of components in this string, as well as whether or not we
/// have matched them.
///
/// In normalizing mode, the triple is parsed in two steps:
///
/// 1. Try to match each component against the type of component expected in
/// that position. (`TripleParser.match(_:at:)`.)
/// 2. For each type of component we have not yet matched, try each component
/// we have not yet found a match for, moving the match (if found) to the
/// correct location. (`TripleParser.rematch(_:at:)`.)
///
/// In non-normalizing mode, we simply skip the second step.
fileprivate struct TripleParser {
var components: [Substring]
var isMatched: Set<Int> = []
var componentsIndicateCygwin: Bool {
components.count > 2 ? components[2].hasPrefix("cygwin") : false
}
var componentsIndicateMinGW32: Bool {
components.count > 2 ? components[2].hasPrefix("mingw") : false
}
init(_ string: String, allowMore: Bool) {
components = string.split(
separator: "-", maxSplits: allowMore ? Int.max : 3,
omittingEmptySubsequences: false
)
}
/// Attempt to parse the component at position `i` as a `Value`, marking it as
/// matched if successful.
mutating func match<Value: TripleComponent>(_: Value.Type, at i: Int)
-> ParsedComponent<Value>?
{
guard
i < components.endIndex,
let parsed = ParsedComponent(components[i], as: Value.self)
else {
return nil
}
precondition(!isMatched.contains(i))
isMatched.insert(i)
return parsed
}
/// If `value` has not been filled in, attempt to parse all unmatched
/// components with it, correcting the components list if a match is found.
mutating func rematch<Value: TripleComponent>(
_ value: inout ParsedComponent<Value>?, at correctIndex: Int
) {
guard value == nil else { return }
precondition(!isMatched.contains(correctIndex),
"Lost the parsed component somehow?")
for i in unmatchedIndices {
guard Value.valueIsValid(components[i]) else {
continue
}
value = ParsedComponent(components[i], as: Value.self)
shiftComponent(at: i, to: correctIndex)
isMatched.insert(correctIndex)
return
}
}
/// Returns `component.indices` with matched elements lazily filtered out.
private var unmatchedIndices: LazyFilterSequence<Range<Int>> {
components.indices.lazy.filter { [isMatched] in
!isMatched.contains($0)
}
}
/// Rearrange `components` so that the element at `actualIndex` now appears
/// at `correctIndex`, without moving any components that have already
/// matched.
///
/// The exact transformations performed by this function are difficult to
/// describe concisely, but they work well in practice for the ways people
/// tend to permute triples. Essentially:
///
/// * If a component appears later than it ought to, it is moved to the right
/// location and other unmatched components are shifted later.
/// * If a component appears earlier than it ought to, empty components are
/// either found later in the list and moved before it, or created from
/// whole cloth and inserted before it.
/// * If no movement is necessary, this is a no-op.
///
/// - Parameter actualIndex: The index that the component is currently at.
/// - Parameter correctIndex: The index that the component ought to be at.
///
/// - Precondition: Neither `correctIndex` nor `actualIndex` are matched.
private mutating func shiftComponent(
at actualIndex: Int,
to correctIndex: Int
) {
// Don't mark actualIndex as matched until after you've called this method.
precondition(!isMatched.contains(actualIndex),
"actualIndex was already matched to something else?")
precondition(!isMatched.contains(correctIndex),
"correctIndex already had something match it?")
if correctIndex < actualIndex {
// Repeatedly swap `actualIndex` with its leftward neighbor, skipping
// matched components, until it finds its way to `correctIndex`.
// Compute all of the indices that we'll shift, not including any that
// have matched, and then build a reversed list of adjacent pairs. (That
// is, if the filter returns `[1,2,4]`, the resulting list will be
// `[(4,2),(2,1)]`.)
let swaps = unmatchedIndices[correctIndex...actualIndex]
.zippedPairs().reversed()
// Swap each pair. This has the effect of moving `actualIndex` to
// `correctIndex` and shifting each unmatched element between them to
// take up the space. Swapping instead of assigning ought to avoid retain
// count traffic.
for (earlier, later) in swaps {
components.swapAt(earlier, later)
}
}
// The rest of this method is concerned with shifting components rightward.
// If we don't need to do that, we're done.
guard correctIndex > actualIndex else { return }
// We will essentially insert one empty component in front of `actualIndex`,
// then recurse to shift `actualIndex + 1` if necessary. However, we want to
// avoid shifting matched components and eat empty components, so this is
// all a bit more complicated than just that.
// Create a new empty component. We call it `removed` because for most
// of this variable's lifetime, `removed` is a component that has been
// removed from the list.
var removed: Substring = ""
// This loop has the effect of inserting the empty component and
// shifting other unmatched components rightward until we either remove
// an empty unmatched component, or remove the last element of the list.
for i in unmatchedIndices[actualIndex...] {
swap(&removed, &components[i])
// If the element we removed is empty, consume it rather than reinserting
// it later in the list.
if removed.isEmpty { break }
}
// If we shifted a non-empty component off the end, add it back in.
if !removed.isEmpty {
components.append(removed)
}
// Find the next unmatched index after `actualIndex`; that's where we moved
// the element at `actualIndex` to.
let nextIndex = unmatchedIndices[(actualIndex + 1)..<correctIndex].first ??
correctIndex
// Recurse to move or create another empty component if necessary.
shiftComponent(at: nextIndex, to: correctIndex)
}
}
extension Collection {
fileprivate func zippedPairs() -> Zip2Sequence<SubSequence, SubSequence> {
zip(dropLast(), dropFirst())
}
}
// MARK: - Parse Arch
extension Triple {
fileprivate struct ArchInfo: TripleComponent {
var arch: Triple.Arch
var subArch: Triple.SubArch?
fileprivate static func parse(_ component: Substring) -> ArchInfo? {
// This code assumes that all architectures with a subarch also have an arch.
// This is slightly different from llvm::Triple, whose
// startswith/endswith-based logic might occasionally recognize a subarch
// without an arch, e.g. "xxkalimba5" would have an unknown arch and a
// kalimbav5 subarch. I'm pretty sure that's undesired behavior from LLVM.
guard let arch = Triple.Arch.parse(component) else { return nil }
return ArchInfo(arch: arch, subArch: Triple.SubArch.parse(component))
}
}
public enum Arch: String, CaseIterable, Decodable, Sendable {
/// ARM (little endian): arm, armv.*, xscale
case arm
// ARM (big endian): armeb
case armeb
/// AArch64 (little endian): aarch64
case aarch64
/// AArch64e (little endian): aarch64e
case aarch64e
/// AArch64 (big endian): aarch64_be
case aarch64_be
// AArch64 (little endian) ILP32: aarch64_32
case aarch64_32
/// ARC: Synopsys ARC
case arc
/// AVR: Atmel AVR microcontroller
case avr
/// eBPF or extended BPF or 64-bit BPF (little endian)
case bpfel
/// eBPF or extended BPF or 64-bit BPF (big endian)
case bpfeb
/// Hexagon: hexagon
case hexagon
// M68k: Motorola 680x0 family
case m68k
/// MIPS: mips, mipsallegrex, mipsr6
case mips
/// MIPSEL: mipsel, mipsallegrexe, mipsr6el
case mipsel
// MIPS64: mips64, mips64r6, mipsn32, mipsn32r6
case mips64
// MIPS64EL: mips64el, mips64r6el, mipsn32el, mipsn32r6el
case mips64el
// MSP430: msp430
case msp430
// PPC: powerpc
case ppc
// PPC64: powerpc64, ppu
case ppc64
// PPC64LE: powerpc64le
case ppc64le
// R600: AMD GPUs HD2XXX - HD6XXX
case r600
// AMDGCN: AMD GCN GPUs
case amdgcn
// RISC-V (32-bit): riscv32
case riscv32
// RISC-V (64-bit): riscv64
case riscv64
// Sparc: sparc
case sparc
// Sparcv9: Sparcv9
case sparcv9
// Sparc: (endianness = little). NB: 'Sparcle' is a CPU variant
case sparcel
// SystemZ: s390x
case systemz
// TCE (http://tce.cs.tut.fi/): tce
case tce
// TCE little endian (http://tce.cs.tut.fi/): tcele
case tcele
// Thumb (little endian): thumb, thumbv.*
case thumb
// Thumb (big endian): thumbeb
case thumbeb
// X86: i[3-9]86
case x86 = "i386"
// X86-64: amd64, x86_64
case x86_64
// XCore: xcore
case xcore
// NVPTX: 32-bit
case nvptx
// NVPTX: 64-bit
case nvptx64
// le32: generic little-endian 32-bit CPU (PNaCl)
case le32
// le64: generic little-endian 64-bit CPU (PNaCl)
case le64
// AMDIL
case amdil
// AMDIL with 64-bit pointers
case amdil64
// AMD HSAIL
case hsail
// AMD HSAIL with 64-bit pointers
case hsail64
// SPIR: standard portable IR for OpenCL 32-bit version
case spir
// SPIR: standard portable IR for OpenCL 64-bit version
case spir64
// Kalimba: generic kalimba
case kalimba
// SHAVE: Movidius vector VLIW processors
case shave
// Lanai: Lanai 32-bit
case lanai
// WebAssembly with 32-bit pointers
case wasm32
// WebAssembly with 64-bit pointers
case wasm64
// 32-bit RenderScript
case renderscript32
// 64-bit RenderScript
case renderscript64
// Xtensa instruction set
case xtensa
static func parse(_ archName: Substring) -> Triple.Arch? {
switch archName {
case "i386", "i486", "i586", "i686":
return .x86
case "i786", "i886", "i986":
return .x86
case "amd64", "x86_64", "x86_64h":
return .x86_64
case "powerpc", "ppc", "ppc32":
return .ppc
case "powerpc64", "ppu", "ppc64":
return .ppc64
case "powerpc64le", "ppc64le":
return .ppc64le
case "xscale":
return .arm
case "xscaleeb":
return .armeb
case "aarch64":
return .aarch64
case "aarch64_be":
return .aarch64_be
case "aarch64_32":
return .aarch64_32
case "arc":
return .arc
case "arm64":
return .aarch64
case "arm64e":
return .aarch64e
case "arm64_32":
return .aarch64_32
case "arm":
return .arm
case "armeb":
return .armeb
case "thumb":
return .thumb
case "thumbeb":
return .thumbeb
case "avr":
return .avr
case "m68k":
return .m68k
case "msp430":
return .msp430
case "mips", "mipseb", "mipsallegrex", "mipsisa32r6", "mipsr6":
return .mips
case "mipsel", "mipsallegrexel", "mipsisa32r6el", "mipsr6el":
return .mipsel
case "mips64", "mips64eb", "mipsn32", "mipsisa64r6", "mips64r6", "mipsn32r6":
return .mips64
case "mips64el", "mipsn32el", "mipsisa64r6el", "mips64r6el", "mipsn32r6el":
return .mips64el
case "r600":
return .r600
case "amdgcn":
return .amdgcn
case "riscv32":
return .riscv32
case "riscv64":
return .riscv64
case "hexagon":
return .hexagon
case "s390x", "systemz":
return .systemz
case "sparc":
return .sparc
case "sparcel":
return .sparcel
case "sparcv9", "sparc64":
return .sparcv9
case "tce":
return .tce
case "tcele":
return .tcele
case "xcore":
return .xcore
case "nvptx":
return .nvptx
case "nvptx64":
return .nvptx64
case "le32":
return .le32
case "le64":
return .le64
case "amdil":
return .amdil
case "amdil64":
return .amdil64
case "hsail":
return .hsail
case "hsail64":
return .hsail64
case "spir":
return .spir
case "spir64":
return .spir64
case _ where archName.hasPrefix("kalimba"):
return .kalimba
case "lanai":
return .lanai
case "shave":
return .shave
case "wasm32":
return .wasm32
case "wasm64":
return .wasm64
case "renderscript32":
return .renderscript32
case "renderscript64":
return .renderscript64
case "xtensa":
return .xtensa
case _ where archName.hasPrefix("arm") || archName.hasPrefix("thumb") || archName.hasPrefix("aarch64"):
return parseARMArch(archName)
case _ where archName.hasPrefix("bpf"):
return parseBPFArch(archName)
default:
return nil
}
}
enum Endianness {
case big, little
// Based on LLVM's ARM::parseArchEndian
init?<S: StringProtocol>(armArchName archName: S) {
if archName.starts(with: "armeb") || archName.starts(with: "thumbeb") || archName.starts(with: "aarch64_be") {
self = .big
} else if archName.starts(with: "arm") || archName.starts(with: "thumb") {
self = archName.hasSuffix("eb") ? .big : .little
} else if archName.starts(with: "aarch64") || archName.starts(with: "aarch64_32") {
self = .little
} else {
return nil
}
}
}
enum ARMISA {
case aarch64, thumb, arm
// Based on LLVM's ARM::parseArchISA
init?<S: StringProtocol>(archName: S) {
if archName.starts(with: "aarch64") || archName.starts(with: "arm64") {
self = .aarch64
} else if archName.starts(with: "thumb") {
self = .thumb
} else if archName.starts(with: "arm") {
self = .arm
} else {
return nil
}
}
}
// Parse ARM architectures not handled by `parse`. On its own, this is not
// enough to correctly parse an ARM architecture.
private static func parseARMArch<S: StringProtocol>(_ archName: S) -> Triple.Arch? {
let ISA = ARMISA(archName: archName)
let endianness = Endianness(armArchName: archName)
let arch: Triple.Arch?
switch (endianness, ISA) {
case (.little, .arm):
arch = .arm
case (.little, .thumb):
arch = .thumb
case (.little, .aarch64):
arch = .aarch64
case (.big, .arm):
arch = .armeb
case (.big, .thumb):
arch = .thumbeb
case (.big, .aarch64):
arch = .aarch64_be
case (nil, _), (_, nil):
arch = nil
}
let canonicalArchName = canonicalARMArchName(from: archName)
if canonicalArchName.isEmpty {
return nil
}
// Thumb only exists in v4+
if ISA == .thumb && (canonicalArchName.hasPrefix("v2") || canonicalArchName.hasPrefix("v3")) {
return nil
}
// Thumb only for v6m
if case .arm(let subArch) = Triple.SubArch.parse(archName), subArch.profile == .m && subArch.version == 6 {
if endianness == .big {
return .thumbeb
} else {
return .thumb
}
}
return arch
}
// Based on LLVM's ARM::getCanonicalArchName
//
// MArch is expected to be of the form (arm|thumb)?(eb)?(v.+)?(eb)?, but
// (iwmmxt|xscale)(eb)? is also permitted. If the former, return
// "v.+", if the latter, return unmodified string, minus 'eb'.
// If invalid, return empty string.
fileprivate static func canonicalARMArchName<S: StringProtocol>(from arch: S) -> String {
var name = Substring(arch)
func dropPrefix(_ prefix: String) {
if name.hasPrefix(prefix) {
name = name.dropFirst(prefix.count)
}
}
let possiblePrefixes = ["arm64_32", "arm64", "aarch64_32", "arm", "thumb", "aarch64"]
if let prefix = possiblePrefixes.first(where: name.hasPrefix) {
dropPrefix(prefix)
if prefix == "aarch64" {
// AArch64 uses "_be", not "eb" suffix.
if name.contains("eb") {
return ""
}
dropPrefix("_be")
}
}
// Ex. "armebv7", move past the "eb".
if name != arch {
dropPrefix("eb")
}
// Or, if it ends with eb ("armv7eb"), chop it off.
else if name.hasSuffix("eb") {
name = name.dropLast(2)
}
// Reached the end - arch is valid.
if name.isEmpty {
return String(arch)
}
// Only match non-marketing names
if name != arch {
// Must start with 'vN'.
if name.count >= 2 && (name.first != "v" || !name.dropFirst().first!.isNumber) {
return ""
}
// Can't have an extra 'eb'.
if name.hasPrefix("eb") {
return ""
}
}
// Arch will either be a 'v' name (v7a) or a marketing name (xscale).
return String(name)
}
private static func parseBPFArch<S: StringProtocol>(_ archName: S) -> Triple.Arch? {
let isLittleEndianHost = 1.littleEndian == 1
switch archName {
case "bpf":
return isLittleEndianHost ? .bpfel : .bpfeb
case "bpf_be", "bpfeb":
return .bpfeb
case "bpf_le", "bpfel":
return .bpfel
default:
return nil
}
}
/// Whether or not this architecture has 64-bit pointers
public var is64Bit: Bool { pointerBitWidth == 64 }
/// Whether or not this architecture has 32-bit pointers
public var is32Bit: Bool { pointerBitWidth == 32 }
/// Whether or not this architecture has 16-bit pointers
public var is16Bit: Bool { pointerBitWidth == 16 }
/// The width in bits of pointers on this architecture.
var pointerBitWidth: Int {
switch self {
case .avr, .msp430:
return 16
case .arc, .arm, .armeb, .hexagon, .le32, .mips, .mipsel, .nvptx,
.ppc, .r600, .riscv32, .sparc, .sparcel, .tce, .tcele, .thumb,
.thumbeb, .x86, .xcore, .amdil, .hsail, .spir, .kalimba,.lanai,
.shave, .wasm32, .renderscript32, .aarch64_32, .m68k, .xtensa:
return 32
case .aarch64, .aarch64e, .aarch64_be, .amdgcn, .bpfel, .bpfeb, .le64, .mips64,
.mips64el, .nvptx64, .ppc64, .ppc64le, .riscv64, .sparcv9, .systemz,
.x86_64, .amdil64, .hsail64, .spir64, .wasm64, .renderscript64:
return 64
}
}
}
}
// MARK: - Parse SubArch
extension Triple {
public enum SubArch: Hashable, Sendable {
public enum ARM: Sendable {
public enum Profile: Sendable {
case a, r, m
}
case v2
case v2a
case v3
case v3m
case v4
case v4t
case v5
case v5e
case v6
case v6k
case v6kz
case v6m
case v6t2
case v7
case v7em
case v7k
case v7m
case v7r
case v7s
case v7ve
case v8
case v8_1a
case v8_1m_mainline
case v8_2a
case v8_3a
case v8_4a
case v8_5a
case v8m_baseline
case v8m_mainline
case v8r
var profile: Triple.SubArch.ARM.Profile? {
switch self {
case .v6m, .v7m, .v7em, .v8m_mainline, .v8m_baseline, .v8_1m_mainline:
return .m
case .v7r, .v8r:
return .r
case .v7, .v7ve, .v7k, .v8, .v8_1a, .v8_2a, .v8_3a, .v8_4a, .v8_5a:
return .a
case .v2, .v2a, .v3, .v3m, .v4, .v4t, .v5, .v5e, .v6, .v6k, .v6kz, .v6t2, .v7s:
return nil
}
}
var version: Int {
switch self {
case .v2, .v2a:
return 2
case .v3, .v3m:
return 3
case .v4, .v4t:
return 4
case .v5, .v5e:
return 5
case .v6, .v6k, .v6kz, .v6m, .v6t2:
return 6
case .v7, .v7em, .v7k, .v7m, .v7r, .v7s, .v7ve:
return 7
case .v8, .v8_1a, .v8_1m_mainline, .v8_2a, .v8_3a, .v8_4a, .v8_5a, .v8m_baseline, .v8m_mainline, .v8r:
return 8
}
}
}
public enum Kalimba: Sendable {
case v3
case v4
case v5
}
public enum MIPS: Sendable {
case r6
}
case arm(ARM)
case kalimba(Kalimba)
case mips(MIPS)
fileprivate static func parse<S: StringProtocol>(_ component: S) -> Triple.SubArch? {
if component.hasPrefix("mips") && (component.hasSuffix("r6el") || component.hasSuffix("r6")) {
return .mips(.r6)
}
let armSubArch = Triple.Arch.canonicalARMArchName(from: component)
if armSubArch.isEmpty {
switch component {
case _ where component.hasSuffix("kalimba3"):
return .kalimba(.v3)
case _ where component.hasSuffix("kalimba4"):
return .kalimba(.v4)
case _ where component.hasSuffix("kalimba5"):
return .kalimba(.v5)
default:
return nil
}
}
switch armSubArch {
case "v2":
return .arm(.v2)
case "v2a":
return .arm(.v2a)
case "v3":
return .arm(.v3)
case "v3m":
return .arm(.v3m)
case "v4":
return .arm(.v4)
case "v4t":
return .arm(.v4t)
case "v5t":
return .arm(.v5)
case "v5te", "v5tej", "xscale":
return .arm(.v5e)
case "v6":
return .arm(.v6)
case "v6k":
return .arm(.v6k)
case "v6kz":
return .arm(.v6kz)
case "v6m", "v6-m":
return .arm(.v6m)
case "v6t2":
return .arm(.v6t2)
case "v7a", "v7-a":
return .arm(.v7)
case "v7k":
return .arm(.v7k)
case "v7m", "v7-m":
return .arm(.v7m)
case "v7em", "v7e-m":
return .arm(.v7em)
case "v7r", "v7-r":
return .arm(.v7r)
case "v7s":
return .arm(.v7s)
case "v7ve":
return .arm(.v7ve)
case "v8-a":
return .arm(.v8)
case "v8-m.main":
return .arm(.v8m_mainline)
case "v8-m.base":
return .arm(.v8m_baseline)
case "v8-r":
return .arm(.v8r)
case "v8.1-m.main":