forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIRGenModule.cpp
1370 lines (1172 loc) · 49.6 KB
/
IRGenModule.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
//===--- IRGenModule.cpp - Swift Global LLVM IR Generation ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// This file implements IR generation for global declarations in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/Availability.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/DiagnosticsIRGen.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/IRGen/Linking.h"
#include "swift/Runtime/RuntimeFnWrappersGen.h"
#include "swift/Runtime/Config.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/CodeGen/SwiftCallingConv.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/HeaderSearchOptions.h"
#include "clang/Basic/CodeGenOptions.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/MDBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/ADT/PointerUnion.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/MD5.h"
#include "ConformanceDescription.h"
#include "GenEnum.h"
#include "GenIntegerLiteral.h"
#include "GenType.h"
#include "IRGenModule.h"
#include "IRGenDebugInfo.h"
#include "ProtocolInfo.h"
#include "StructLayout.h"
#include <initializer_list>
using namespace swift;
using namespace irgen;
using llvm::Attribute;
const unsigned DefaultAS = 0;
/// A helper for creating LLVM struct types.
static llvm::StructType *createStructType(IRGenModule &IGM,
StringRef name,
std::initializer_list<llvm::Type*> types,
bool packed = false) {
return llvm::StructType::create(IGM.getLLVMContext(),
ArrayRef<llvm::Type*>(types.begin(),
types.size()),
name, packed);
};
/// A helper for creating pointer-to-struct types.
static llvm::PointerType *createStructPointerType(IRGenModule &IGM,
StringRef name,
std::initializer_list<llvm::Type*> types) {
return createStructType(IGM, name, types)->getPointerTo(DefaultAS);
};
static clang::CodeGenerator *createClangCodeGenerator(ASTContext &Context,
llvm::LLVMContext &LLVMContext,
IRGenOptions &Opts,
StringRef ModuleName) {
auto Loader = Context.getClangModuleLoader();
auto *Importer = static_cast<ClangImporter*>(&*Loader);
assert(Importer && "No clang module loader!");
auto &ClangContext = Importer->getClangASTContext();
auto &CGO = Importer->getClangCodeGenOpts();
CGO.OptimizationLevel = Opts.shouldOptimize() ? 3 : 0;
CGO.DisableFPElim = Opts.DisableFPElim;
CGO.DiscardValueNames = !Opts.shouldProvideValueNames();
switch (Opts.DebugInfoLevel) {
case IRGenDebugInfoLevel::None:
CGO.setDebugInfo(clang::codegenoptions::DebugInfoKind::NoDebugInfo);
break;
case IRGenDebugInfoLevel::LineTables:
CGO.setDebugInfo(clang::codegenoptions::DebugInfoKind::DebugLineTablesOnly);
break;
case IRGenDebugInfoLevel::ASTTypes:
case IRGenDebugInfoLevel::DwarfTypes:
CGO.DebugTypeExtRefs = true;
CGO.setDebugInfo(clang::codegenoptions::DebugInfoKind::FullDebugInfo);
break;
}
switch (Opts.DebugInfoFormat) {
case IRGenDebugInfoFormat::None:
break;
case IRGenDebugInfoFormat::DWARF:
CGO.DebugCompilationDir = Opts.DebugCompilationDir;
CGO.DwarfVersion = Opts.DWARFVersion;
CGO.DwarfDebugFlags = Opts.DebugFlags;
break;
case IRGenDebugInfoFormat::CodeView:
CGO.EmitCodeView = true;
CGO.DebugCompilationDir = Opts.DebugCompilationDir;
// This actually contains the debug flags for codeview.
CGO.DwarfDebugFlags = Opts.DebugFlags;
break;
}
auto &HSI = Importer->getClangPreprocessor()
.getHeaderSearchInfo()
.getHeaderSearchOpts();
auto &PPO = Importer->getClangPreprocessor().getPreprocessorOpts();
auto *ClangCodeGen = clang::CreateLLVMCodeGen(ClangContext.getDiagnostics(),
ModuleName, HSI, PPO, CGO,
LLVMContext);
ClangCodeGen->Initialize(ClangContext);
return ClangCodeGen;
}
IRGenModule::IRGenModule(IRGenerator &irgen,
std::unique_ptr<llvm::TargetMachine> &&target,
SourceFile *SF, llvm::LLVMContext &LLVMContext,
StringRef ModuleName, StringRef OutputFilename,
StringRef MainInputFilenameForDebugInfo)
: IRGen(irgen), Context(irgen.SIL.getASTContext()),
ClangCodeGen(createClangCodeGenerator(Context, LLVMContext, irgen.Opts,
ModuleName)),
Module(*ClangCodeGen->GetModule()), LLVMContext(Module.getContext()),
DataLayout(irgen.getClangDataLayout()),
Triple(irgen.getEffectiveClangTriple()), TargetMachine(std::move(target)),
silConv(irgen.SIL), OutputFilename(OutputFilename),
MainInputFilenameForDebugInfo(MainInputFilenameForDebugInfo),
TargetInfo(SwiftTargetInfo::get(*this)), DebugInfo(nullptr),
ModuleHash(nullptr), ObjCInterop(Context.LangOpts.EnableObjCInterop),
UseDarwinPreStableABIBit(Context.LangOpts.UseDarwinPreStableABIBit),
Types(*new TypeConverter(*this)) {
irgen.addGenModule(SF, this);
auto &opts = irgen.Opts;
EnableValueNames = opts.shouldProvideValueNames();
VoidTy = llvm::Type::getVoidTy(getLLVMContext());
Int1Ty = llvm::Type::getInt1Ty(getLLVMContext());
Int8Ty = llvm::Type::getInt8Ty(getLLVMContext());
Int16Ty = llvm::Type::getInt16Ty(getLLVMContext());
Int32Ty = llvm::Type::getInt32Ty(getLLVMContext());
Int32PtrTy = Int32Ty->getPointerTo();
Int64Ty = llvm::Type::getInt64Ty(getLLVMContext());
Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
SizeTy = DataLayout.getIntPtrType(getLLVMContext(), /*addrspace*/ 0);
// For the relative address type, we want to use the int32 bit type
// on most architectures, e.g. x86_64, because it produces valid
// fixups/relocations. The exception is 16-bit architectures,
// so we shorten the relative address type there.
if (SizeTy->getBitWidth()<32) {
RelativeAddressTy = SizeTy;
} else {
RelativeAddressTy = Int32Ty;
}
RelativeAddressPtrTy = RelativeAddressTy->getPointerTo();
FloatTy = llvm::Type::getFloatTy(getLLVMContext());
DoubleTy = llvm::Type::getDoubleTy(getLLVMContext());
auto CI = static_cast<ClangImporter*>(&*Context.getClangModuleLoader());
assert(CI && "no clang module loader");
auto &clangASTContext = CI->getClangASTContext();
ObjCBoolTy = Int1Ty;
if (clangASTContext.getTargetInfo().useSignedCharForObjCBool())
ObjCBoolTy = Int8Ty;
RefCountedStructTy =
llvm::StructType::create(getLLVMContext(), "swift.refcounted");
RefCountedPtrTy = RefCountedStructTy->getPointerTo(/*addrspace*/ 0);
RefCountedNull = llvm::ConstantPointerNull::get(RefCountedPtrTy);
// For now, references storage types are just pointers.
#define CHECKED_REF_STORAGE(Name, name, ...) \
Name##ReferencePtrTy = \
createStructPointerType(*this, "swift." #name, { RefCountedPtrTy });
#include "swift/AST/ReferenceStorage.def"
// A type metadata record is the structure pointed to by the canonical
// address point of a type metadata. This is at least one word, and
// potentially more than that, past the start of the actual global
// structure.
TypeMetadataStructTy = createStructType(*this, "swift.type", {
MetadataKindTy // MetadataKind Kind;
});
TypeMetadataPtrTy = TypeMetadataStructTy->getPointerTo(DefaultAS);
TypeMetadataResponseTy = createStructType(*this, "swift.metadata_response", {
TypeMetadataPtrTy,
SizeTy
});
OffsetPairTy = llvm::StructType::get(getLLVMContext(), { SizeTy, SizeTy });
// The TypeLayout structure, including all possible trailing components.
FullTypeLayoutTy = createStructType(*this, "swift.full_type_layout", {
SizeTy, // size
SizeTy, // flags
SizeTy, // alignment
SizeTy // extra inhabitant flags (optional)
});
TypeLayoutTy = createStructType(*this, "swift.type_layout", {
SizeTy, // size
SizeTy, // stride
Int32Ty, // flags
Int32Ty // extra inhabitant count
});
// A protocol descriptor describes a protocol. It is not type metadata in
// and of itself, but is referenced in the structure of existential type
// metadata records.
ProtocolDescriptorStructTy = createStructType(*this, "swift.protocol", {
Int8PtrTy, // objc isa
Int8PtrTy, // name
Int8PtrTy, // inherited protocols
Int8PtrTy, // required objc instance methods
Int8PtrTy, // required objc class methods
Int8PtrTy, // optional objc instance methods
Int8PtrTy, // optional objc class methods
Int8PtrTy, // objc properties
Int32Ty, // size
Int32Ty, // flags
Int32Ty, // total requirement count
Int32Ty, // requirements array
RelativeAddressTy, // superclass
RelativeAddressTy // associated type names
});
ProtocolDescriptorPtrTy = ProtocolDescriptorStructTy->getPointerTo();
ProtocolRequirementStructTy =
createStructType(*this, "swift.protocol_requirement", {
Int32Ty, // flags
RelativeAddressTy, // default implementation
});
// A tuple type metadata record has a couple extra fields.
auto tupleElementTy = createStructType(*this, "swift.tuple_element_type", {
TypeMetadataPtrTy, // Metadata *Type;
Int32Ty // int32_t Offset;
});
TupleTypeMetadataPtrTy = createStructPointerType(*this, "swift.tuple_type", {
TypeMetadataStructTy, // (base)
SizeTy, // size_t NumElements;
Int8PtrTy, // const char *Labels;
llvm::ArrayType::get(tupleElementTy, 0) // Element Elements[];
});
// A full type metadata record is basically just an adjustment to the
// address point of a type metadata. Resilience may cause
// additional data to be laid out prior to this address point.
FullTypeMetadataStructTy = createStructType(*this, "swift.full_type", {
WitnessTablePtrTy,
TypeMetadataStructTy
});
FullTypeMetadataPtrTy = FullTypeMetadataStructTy->getPointerTo(DefaultAS);
DeallocatingDtorTy = llvm::FunctionType::get(VoidTy, RefCountedPtrTy, false);
llvm::Type *dtorPtrTy = DeallocatingDtorTy->getPointerTo();
// A full heap metadata is basically just an additional small prefix
// on a full metadata, used for metadata corresponding to heap
// allocations.
FullHeapMetadataStructTy =
createStructType(*this, "swift.full_heapmetadata", {
dtorPtrTy,
WitnessTablePtrTy,
TypeMetadataStructTy
});
FullHeapMetadataPtrTy = FullHeapMetadataStructTy->getPointerTo(DefaultAS);
// A full box metadata is non-type heap metadata for a heap allocation of a
// single value. The box tracks the offset to the value inside the box.
FullBoxMetadataStructTy =
createStructType(*this, "swift.full_boxmetadata", {
dtorPtrTy,
WitnessTablePtrTy,
TypeMetadataStructTy,
Int32Ty,
CaptureDescriptorPtrTy,
});
FullBoxMetadataPtrTy = FullBoxMetadataStructTy->getPointerTo(DefaultAS);
// This must match struct HeapObject in the runtime.
llvm::Type *refCountedElts[] = {TypeMetadataPtrTy, IntPtrTy};
RefCountedStructTy->setBody(refCountedElts);
RefCountedStructSize =
Size(DataLayout.getStructLayout(RefCountedStructTy)->getSizeInBytes());
PtrSize = Size(DataLayout.getPointerSize(DefaultAS));
FunctionPairTy = createStructType(*this, "swift.function", {
FunctionPtrTy,
RefCountedPtrTy,
});
OpaqueTy = llvm::StructType::create(LLVMContext, "swift.opaque");
OpaquePtrTy = OpaqueTy->getPointerTo(DefaultAS);
NoEscapeFunctionPairTy = createStructType(*this, "swift.noescape.function", {
FunctionPtrTy,
OpaquePtrTy,
});
ProtocolRecordTy =
createStructType(*this, "swift.protocolref", {
RelativeAddressTy
});
ProtocolRecordPtrTy = ProtocolRecordTy->getPointerTo();
ProtocolConformanceDescriptorTy
= createStructType(*this, "swift.protocol_conformance_descriptor", {
RelativeAddressTy,
RelativeAddressTy,
RelativeAddressTy,
Int32Ty
});
ProtocolConformanceDescriptorPtrTy
= ProtocolConformanceDescriptorTy->getPointerTo(DefaultAS);
TypeContextDescriptorTy
= llvm::StructType::create(LLVMContext, "swift.type_descriptor");
TypeContextDescriptorPtrTy
= TypeContextDescriptorTy->getPointerTo(DefaultAS);
ClassContextDescriptorTy =
llvm::StructType::get(LLVMContext, {
Int32Ty, // context flags
Int32Ty, // parent
Int32Ty, // name
Int32Ty, // kind
Int32Ty, // accessor function
Int32Ty, // num fields
Int32Ty, // field offset vector
Int32Ty, // is_reflectable flag
Int32Ty, // (Generics Descriptor) argument offset
Int32Ty, // (Generics Descriptor) num params
Int32Ty, // (Generics Descriptor) num requirements
Int32Ty, // (Generics Descriptor) num key arguments
Int32Ty, // (Generics Descriptor) num extra arguments
Int32Ty, // (VTable Descriptor) offset
Int32Ty, // (VTable Descriptor) size
Int32Ty, // (Methods Descriptor) accessor
Int32Ty, // (Methods Descriptor) flags
}, /*packed=*/true);
MethodDescriptorStructTy
= createStructType(*this, "swift.method_descriptor", {
Int32Ty,
RelativeAddressTy,
});
MethodOverrideDescriptorStructTy
= createStructType(*this, "swift.method_override_descriptor", {
RelativeAddressTy,
RelativeAddressTy,
RelativeAddressTy
});
TypeMetadataRecordTy
= createStructType(*this, "swift.type_metadata_record", {
RelativeAddressTy
});
TypeMetadataRecordPtrTy
= TypeMetadataRecordTy->getPointerTo(DefaultAS);
FieldDescriptorTy
= llvm::StructType::create(LLVMContext, "swift.field_descriptor");
FieldDescriptorPtrTy = FieldDescriptorTy->getPointerTo(DefaultAS);
FieldDescriptorPtrPtrTy = FieldDescriptorPtrTy->getPointerTo(DefaultAS);
FixedBufferTy = nullptr;
for (unsigned i = 0; i != MaxNumValueWitnesses; ++i)
ValueWitnessTys[i] = nullptr;
ObjCPtrTy = llvm::StructType::create(getLLVMContext(), "objc_object")
->getPointerTo(DefaultAS);
BridgeObjectPtrTy = llvm::StructType::create(getLLVMContext(), "swift.bridge")
->getPointerTo(DefaultAS);
ObjCClassStructTy = llvm::StructType::create(LLVMContext, "objc_class");
ObjCClassPtrTy = ObjCClassStructTy->getPointerTo(DefaultAS);
llvm::Type *objcClassElts[] = {
ObjCClassPtrTy,
ObjCClassPtrTy,
OpaquePtrTy,
OpaquePtrTy,
IntPtrTy
};
ObjCClassStructTy->setBody(objcClassElts);
ObjCSuperStructTy = llvm::StructType::create(LLVMContext, "objc_super");
ObjCSuperPtrTy = ObjCSuperStructTy->getPointerTo(DefaultAS);
llvm::Type *objcSuperElts[] = {
ObjCPtrTy,
ObjCClassPtrTy
};
ObjCSuperStructTy->setBody(objcSuperElts);
ObjCBlockStructTy = llvm::StructType::create(LLVMContext, "objc_block");
ObjCBlockPtrTy = ObjCBlockStructTy->getPointerTo(DefaultAS);
llvm::Type *objcBlockElts[] = {
ObjCClassPtrTy, // isa
Int32Ty, // flags
Int32Ty, // reserved
FunctionPtrTy, // invoke function pointer
Int8PtrTy, // TODO: block descriptor pointer.
// We will probably need a struct type for that at some
// point too.
};
ObjCBlockStructTy->setBody(objcBlockElts);
// Class _Nullable callback(Class _Nonnull cls, void * _Nullable arg);
llvm::Type *params[] = { ObjCClassPtrTy, Int8PtrTy };
ObjCUpdateCallbackTy = llvm::FunctionType::get(ObjCClassPtrTy, params, false);
// The full class stub structure, including a word before the address point.
ObjCFullResilientClassStubTy = createStructType(*this, "objc_full_class_stub", {
SizeTy, // zero padding to appease the linker
SizeTy, // isa pointer -- always 1
ObjCUpdateCallbackTy->getPointerTo() // the update callback
});
// What we actually export.
ObjCResilientClassStubTy = createStructType(*this, "objc_class_stub", {
SizeTy, // isa pointer -- always 1
ObjCUpdateCallbackTy->getPointerTo() // the update callback
});
auto ErrorStructTy = llvm::StructType::create(LLVMContext, "swift.error");
// ErrorStruct is currently opaque to the compiler.
ErrorPtrTy = ErrorStructTy->getPointerTo(DefaultAS);
llvm::Type *openedErrorTriple[] = {
OpaquePtrTy,
TypeMetadataPtrTy,
WitnessTablePtrTy,
};
OpenedErrorTripleTy = llvm::StructType::get(getLLVMContext(),
openedErrorTriple,
/*packed*/ false);
OpenedErrorTriplePtrTy = OpenedErrorTripleTy->getPointerTo(DefaultAS);
WitnessTablePtrPtrTy = WitnessTablePtrTy->getPointerTo(DefaultAS);
// todo
OpaqueTypeDescriptorTy = TypeContextDescriptorTy;
OpaqueTypeDescriptorPtrTy = OpaqueTypeDescriptorTy->getPointerTo();
InvariantMetadataID = LLVMContext.getMDKindID("invariant.load");
InvariantNode = llvm::MDNode::get(LLVMContext, {});
DereferenceableID = LLVMContext.getMDKindID("dereferenceable");
C_CC = llvm::CallingConv::C;
// TODO: use "tinycc" on platforms that support it
DefaultCC = SWIFT_DEFAULT_LLVM_CC;
SwiftCC = llvm::CallingConv::Swift;
if (opts.DebugInfoLevel > IRGenDebugInfoLevel::None)
DebugInfo = IRGenDebugInfo::createIRGenDebugInfo(IRGen.Opts, *CI, *this,
Module,
MainInputFilenameForDebugInfo);
initClangTypeConverter();
if (ClangASTContext) {
auto atomicBoolTy = ClangASTContext->getAtomicType(ClangASTContext->BoolTy);
AtomicBoolSize = Size(ClangASTContext->getTypeSize(atomicBoolTy));
AtomicBoolAlign = Alignment(ClangASTContext->getTypeSize(atomicBoolTy));
}
IsSwiftErrorInRegister =
clang::CodeGen::swiftcall::isSwiftErrorLoweredInRegister(
ClangCodeGen->CGM());
DynamicReplacementsTy =
llvm::StructType::get(getLLVMContext(), {Int8PtrPtrTy, Int8PtrTy});
DynamicReplacementsPtrTy = DynamicReplacementsTy->getPointerTo(DefaultAS);
DynamicReplacementLinkEntryTy =
llvm::StructType::create(getLLVMContext(), "swift.dyn_repl_link_entry");
DynamicReplacementLinkEntryPtrTy =
DynamicReplacementLinkEntryTy->getPointerTo(DefaultAS);
llvm::Type *linkEntryFields[] = {
Int8PtrTy, // function pointer.
DynamicReplacementLinkEntryPtrTy // next.
};
DynamicReplacementLinkEntryTy->setBody(linkEntryFields);
DynamicReplacementKeyTy = createStructType(*this, "swift.dyn_repl_key",
{RelativeAddressTy, Int32Ty});
}
IRGenModule::~IRGenModule() {
destroyClangTypeConverter();
destroyMetadataLayoutMap();
delete &Types;
}
static bool isReturnAttribute(llvm::Attribute::AttrKind Attr);
// Explicitly listing these constants is an unfortunate compromise for
// making the database file much more compact.
//
// They have to be non-local because otherwise we'll get warnings when
// a particular x-macro expansion doesn't use one.
namespace RuntimeConstants {
const auto ReadNone = llvm::Attribute::ReadNone;
const auto ReadOnly = llvm::Attribute::ReadOnly;
const auto ArgMemOnly = llvm::Attribute::ArgMemOnly;
const auto NoReturn = llvm::Attribute::NoReturn;
const auto NoUnwind = llvm::Attribute::NoUnwind;
const auto ZExt = llvm::Attribute::ZExt;
const auto FirstParamReturned = llvm::Attribute::Returned;
RuntimeAvailability AlwaysAvailable(ASTContext &Context) {
return RuntimeAvailability::AlwaysAvailable;
}
bool
isDeploymentAvailabilityContainedIn(ASTContext &Context,
AvailabilityContext featureAvailability) {
auto deploymentAvailability =
AvailabilityContext::forDeploymentTarget(Context);
return deploymentAvailability.isContainedIn(featureAvailability);
}
RuntimeAvailability OpaqueTypeAvailability(ASTContext &Context) {
auto featureAvailability = Context.getOpaqueTypeAvailability();
if (!isDeploymentAvailabilityContainedIn(Context, featureAvailability)) {
return RuntimeAvailability::ConditionallyAvailable;
}
return RuntimeAvailability::AlwaysAvailable;
}
RuntimeAvailability DynamicReplacementAvailability(ASTContext &Context) {
auto featureAvailability = Context.getSwift51Availability();
if (!isDeploymentAvailabilityContainedIn(Context, featureAvailability)) {
return RuntimeAvailability::AvailableByCompatibilityLibrary;
}
return RuntimeAvailability::AlwaysAvailable;
}
} // namespace RuntimeConstants
// We don't use enough attributes to justify generalizing the
// RuntimeFunctions.def FUNCTION macro. Instead, special case the one attribute
// associated with the return type not the function type.
static bool isReturnAttribute(llvm::Attribute::AttrKind Attr) {
return Attr == llvm::Attribute::ZExt;
}
// Similar to the 'return' attribute we assume that the 'returned' attributed is
// associated with the first function parameter.
static bool isReturnedAttribute(llvm::Attribute::AttrKind Attr) {
return Attr == llvm::Attribute::Returned;
}
namespace {
bool isStandardLibrary(const llvm::Module &M) {
if (auto *Flags = M.getNamedMetadata("swift.module.flags")) {
for (const auto *F : Flags->operands()) {
const auto *Key = dyn_cast_or_null<llvm::MDString>(F->getOperand(0));
if (!Key)
continue;
const auto *Value =
dyn_cast_or_null<llvm::ConstantAsMetadata>(F->getOperand(1));
if (!Value)
continue;
if (Key->getString() == "standard-library")
return cast<llvm::ConstantInt>(Value->getValue())->isOne();
}
}
return false;
}
}
bool IRGenModule::isStandardLibrary() const {
return ::isStandardLibrary(Module);
}
llvm::Constant *swift::getRuntimeFn(llvm::Module &Module,
llvm::Constant *&cache,
const char *name,
llvm::CallingConv::ID cc,
RuntimeAvailability availability,
llvm::ArrayRef<llvm::Type*> retTypes,
llvm::ArrayRef<llvm::Type*> argTypes,
ArrayRef<Attribute::AttrKind> attrs) {
if (cache)
return cache;
bool isWeakLinked = false;
std::string functionName(name);
switch (availability) {
case RuntimeAvailability::AlwaysAvailable:
// Nothing to do.
break;
case RuntimeAvailability::ConditionallyAvailable: {
isWeakLinked = true;
break;
}
case RuntimeAvailability::AvailableByCompatibilityLibrary: {
functionName.append("50");
break;
}
}
llvm::Type *retTy;
if (retTypes.size() == 1)
retTy = *retTypes.begin();
else
retTy = llvm::StructType::get(Module.getContext(),
{retTypes.begin(), retTypes.end()},
/*packed*/ false);
auto fnTy = llvm::FunctionType::get(retTy,
{argTypes.begin(), argTypes.end()},
/*isVararg*/ false);
cache = Module.getOrInsertFunction(functionName.c_str(), fnTy);
// Add any function attributes and set the calling convention.
if (auto fn = dyn_cast<llvm::Function>(cache)) {
fn->setCallingConv(cc);
bool IsExternal =
fn->getLinkage() == llvm::GlobalValue::AvailableExternallyLinkage ||
(fn->getLinkage() == llvm::GlobalValue::ExternalLinkage &&
fn->isDeclaration());
if (!isStandardLibrary(Module) && IsExternal &&
::useDllStorage(llvm::Triple(Module.getTargetTriple())))
fn->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
if (IsExternal && isWeakLinked
&& !::useDllStorage(llvm::Triple(Module.getTargetTriple())))
fn->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
llvm::AttrBuilder buildFnAttr;
llvm::AttrBuilder buildRetAttr;
llvm::AttrBuilder buildFirstParamAttr;
for (auto Attr : attrs) {
if (isReturnAttribute(Attr))
buildRetAttr.addAttribute(Attr);
else if (isReturnedAttribute(Attr))
buildFirstParamAttr.addAttribute(Attr);
else
buildFnAttr.addAttribute(Attr);
}
fn->addAttributes(llvm::AttributeList::FunctionIndex, buildFnAttr);
fn->addAttributes(llvm::AttributeList::ReturnIndex, buildRetAttr);
fn->addParamAttrs(0, buildFirstParamAttr);
}
return cache;
}
#define QUOTE(...) __VA_ARGS__
#define STR(X) #X
#define FUNCTION(ID, NAME, CC, AVAILABILITY, RETURNS, ARGS, ATTRS) \
FUNCTION_IMPL(ID, NAME, CC, AVAILABILITY, QUOTE(RETURNS), QUOTE(ARGS), QUOTE(ATTRS))
#define RETURNS(...) { __VA_ARGS__ }
#define ARGS(...) { __VA_ARGS__ }
#define NO_ARGS {}
#define ATTRS(...) { __VA_ARGS__ }
#define NO_ATTRS {}
#define FUNCTION_IMPL(ID, NAME, CC, AVAILABILITY, RETURNS, ARGS, ATTRS) \
llvm::Constant *IRGenModule::get##ID##Fn() { \
using namespace RuntimeConstants; \
return getRuntimeFn(Module, ID##Fn, #NAME, CC, \
AVAILABILITY(this->Context), \
RETURNS, ARGS, ATTRS); \
}
#include "swift/Runtime/RuntimeFunctions.def"
std::pair<llvm::GlobalVariable *, llvm::Constant *>
IRGenModule::createStringConstant(StringRef Str,
bool willBeRelativelyAddressed, StringRef sectionName) {
// If not, create it. This implicitly adds a trailing null.
auto init = llvm::ConstantDataArray::getString(LLVMContext, Str);
auto global = new llvm::GlobalVariable(Module, init->getType(), true,
llvm::GlobalValue::PrivateLinkage,
init);
// FIXME: ld64 crashes resolving relative references to coalesceable symbols.
// rdar://problem/22674524
// If we intend to relatively address this string, don't mark it with
// unnamed_addr to prevent it from going into the cstrings section and getting
// coalesced.
if (!willBeRelativelyAddressed)
global->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
if (!sectionName.empty())
global->setSection(sectionName);
// Drill down to make an i8*.
auto zero = llvm::ConstantInt::get(SizeTy, 0);
llvm::Constant *indices[] = { zero, zero };
auto address = llvm::ConstantExpr::getInBoundsGetElementPtr(
global->getValueType(), global, indices);
return { global, address };
}
#define KNOWN_METADATA_ACCESSOR(NAME, SYM) \
llvm::Constant *IRGenModule::get##NAME() { \
if (NAME) \
return NAME; \
NAME = Module.getOrInsertGlobal(SYM, FullTypeMetadataStructTy); \
if (useDllStorage() && !isStandardLibrary()) \
ApplyIRLinkage(IRLinkage::ExternalImport) \
.to(cast<llvm::GlobalVariable>(NAME)); \
return NAME; \
}
KNOWN_METADATA_ACCESSOR(EmptyTupleMetadata,
MANGLE_AS_STRING(METADATA_SYM(EMPTY_TUPLE_MANGLING)))
KNOWN_METADATA_ACCESSOR(AnyExistentialMetadata,
MANGLE_AS_STRING(METADATA_SYM(ANY_MANGLING)))
KNOWN_METADATA_ACCESSOR(AnyObjectExistentialMetadata,
MANGLE_AS_STRING(METADATA_SYM(ANYOBJECT_MANGLING)))
#undef KNOWN_METADATA_ACCESSOR
llvm::Constant *IRGenModule::getObjCEmptyCachePtr() {
if (ObjCEmptyCachePtr)
return ObjCEmptyCachePtr;
if (ObjCInterop) {
// struct objc_cache _objc_empty_cache;
ObjCEmptyCachePtr = Module.getOrInsertGlobal("_objc_empty_cache",
OpaquePtrTy->getElementType());
ApplyIRLinkage(IRLinkage::ExternalImport)
.to(cast<llvm::GlobalVariable>(ObjCEmptyCachePtr));
} else {
// FIXME: Remove even the null value per rdar://problem/18801263
ObjCEmptyCachePtr = llvm::ConstantPointerNull::get(OpaquePtrTy);
}
return ObjCEmptyCachePtr;
}
llvm::Constant *IRGenModule::getObjCEmptyVTablePtr() {
// IMP _objc_empty_vtable;
// On recent Darwin platforms, this symbol is defined at
// runtime as an absolute symbol with the value of null. Older ObjCs
// didn't guarantee _objc_empty_vtable to be nil, but Swift doesn't
// deploy far enough back for that to be a concern.
// FIXME: When !ObjCInterop, we should remove even the null value per
// rdar://problem/18801263
if (!ObjCEmptyVTablePtr)
ObjCEmptyVTablePtr = llvm::ConstantPointerNull::get(OpaquePtrTy);
return ObjCEmptyVTablePtr;
}
Address IRGenModule::getAddrOfObjCISAMask() {
// This symbol is only exported by the runtime if the platform uses
// isa masking.
assert(TargetInfo.hasISAMasking());
if (!ObjCISAMaskPtr) {
ObjCISAMaskPtr = Module.getOrInsertGlobal("swift_isaMask", IntPtrTy);
ApplyIRLinkage(IRLinkage::ExternalImport)
.to(cast<llvm::GlobalVariable>(ObjCISAMaskPtr));
}
return Address(ObjCISAMaskPtr, getPointerAlignment());
}
ModuleDecl *IRGenModule::getSwiftModule() const {
return IRGen.SIL.getSwiftModule();
}
AvailabilityContext IRGenModule::getAvailabilityContext() const {
return AvailabilityContext::forDeploymentTarget(Context);
}
Lowering::TypeConverter &IRGenModule::getSILTypes() const {
return IRGen.SIL.Types;
}
clang::CodeGen::CodeGenModule &IRGenModule::getClangCGM() const {
return ClangCodeGen->CGM();
}
llvm::Module *IRGenModule::getModule() const {
return ClangCodeGen->GetModule();
}
llvm::Module *IRGenModule::releaseModule() {
return ClangCodeGen->ReleaseModule();
}
bool IRGenerator::canEmitWitnessTableLazily(SILWitnessTable *wt) {
if (Opts.UseJIT)
return false;
// Regardless of the access level, if the witness table is shared it means
// we can safely not emit it. Every other module which needs it will generate
// its own shared copy of it.
if (wt->getLinkage() == SILLinkage::Shared)
return true;
NominalTypeDecl *ConformingTy =
wt->getConformingType()->getNominalOrBoundGenericNominal();
switch (ConformingTy->getEffectiveAccess()) {
case AccessLevel::Private:
case AccessLevel::FilePrivate:
return true;
case AccessLevel::Internal:
return PrimaryIGM->getSILModule().isWholeModule();
default:
return false;
}
llvm_unreachable("switch does not handle all cases");
}
void IRGenerator::addLazyWitnessTable(const ProtocolConformance *Conf) {
if (auto *wt = SIL.lookUpWitnessTable(Conf, /*deserializeLazily=*/false)) {
// Add it to the queue if it hasn't already been put there.
if (canEmitWitnessTableLazily(wt) &&
LazilyEmittedWitnessTables.insert(wt).second) {
assert(!FinishedEmittingLazyDefinitions);
LazyWitnessTables.push_back(wt);
}
}
}
void IRGenerator::addClassForEagerInitialization(ClassDecl *ClassDecl) {
if (!ClassDecl->getAttrs().hasAttribute<StaticInitializeObjCMetadataAttr>())
return;
assert(!ClassDecl->isGenericContext());
assert(!ClassDecl->hasClangNode());
ClassesForEagerInitialization.push_back(ClassDecl);
}
llvm::AttributeList IRGenModule::getAllocAttrs() {
if (AllocAttrs.isEmpty()) {
AllocAttrs =
llvm::AttributeList::get(LLVMContext, llvm::AttributeList::ReturnIndex,
llvm::Attribute::NoAlias);
AllocAttrs =
AllocAttrs.addAttribute(LLVMContext, llvm::AttributeList::FunctionIndex,
llvm::Attribute::NoUnwind);
}
return AllocAttrs;
}
/// Disable thumb-mode until debugger support is there.
bool swift::irgen::shouldRemoveTargetFeature(StringRef feature) {
return feature == "+thumb-mode";
}
void IRGenModule::setHasFramePointer(llvm::AttrBuilder &Attrs,
bool HasFramePointer) {
if (HasFramePointer) {
Attrs.addAttribute("no-frame-pointer-elim", "true");
Attrs.addAttribute("no-frame-pointer-elim-non-leaf");
} else {
Attrs.addAttribute("no-frame-pointer-elim", "false");
Attrs.removeAttribute("no-frame-pointer-elim-non-leaf");
}
}
void IRGenModule::setHasFramePointer(llvm::Function *F,
bool HasFramePointer) {
llvm::AttrBuilder b;
setHasFramePointer(b, HasFramePointer);
F->addAttributes(llvm::AttributeList::FunctionIndex, b);
}
/// Construct initial function attributes from options.
void IRGenModule::constructInitialFnAttributes(llvm::AttrBuilder &Attrs,
OptimizationMode FuncOptMode) {
// Add frame pointer attributes.
setHasFramePointer(Attrs, IRGen.Opts.DisableFPElim);
// Add target-cpu and target-features if they are non-null.
auto *Clang = static_cast<ClangImporter *>(Context.getClangModuleLoader());
clang::TargetOptions &ClangOpts = Clang->getTargetInfo().getTargetOpts();
std::string &CPU = ClangOpts.CPU;
if (CPU != "")
Attrs.addAttribute("target-cpu", CPU);
std::vector<std::string> Features;
for (auto &F : ClangOpts.Features)
if (!shouldRemoveTargetFeature(F))
Features.push_back(F);
if (!Features.empty()) {
SmallString<64> allFeatures;
// Sort so that the target features string is canonical.
std::sort(Features.begin(), Features.end());
interleave(Features, [&](const std::string &s) {
allFeatures.append(s);
}, [&]{
allFeatures.push_back(',');
});
Attrs.addAttribute("target-features", allFeatures);
}
if (FuncOptMode == OptimizationMode::NotSet)
FuncOptMode = IRGen.Opts.OptMode;
if (FuncOptMode == OptimizationMode::ForSize)
Attrs.addAttribute(llvm::Attribute::MinSize);
}
llvm::AttributeList IRGenModule::constructInitialAttributes() {
llvm::AttrBuilder b;
constructInitialFnAttributes(b);
return llvm::AttributeList::get(LLVMContext,
llvm::AttributeList::FunctionIndex, b);
}
llvm::Constant *IRGenModule::getInt32(uint32_t value) {
return llvm::ConstantInt::get(Int32Ty, value);
}
llvm::Constant *IRGenModule::getSize(Size size) {
return llvm::ConstantInt::get(SizeTy, size.getValue());
}
llvm::Constant *IRGenModule::getOpaquePtr(llvm::Constant *ptr) {
return llvm::ConstantExpr::getBitCast(ptr, Int8PtrTy);
}
static void appendEncodedName(raw_ostream &os, StringRef name) {
if (clang::isValidIdentifier(name)) {
os << "_" << name;
} else {
for (auto c : name)
os.write_hex(static_cast<uint8_t>(c));
}
}
static void appendEncodedName(llvm::SmallVectorImpl<char> &buf,
StringRef name) {
llvm::raw_svector_ostream os{buf};
appendEncodedName(os, name);
}
StringRef
swift::irgen::encodeForceLoadSymbolName(llvm::SmallVectorImpl<char> &buf,
StringRef name) {
llvm::raw_svector_ostream os{buf};
os << "_swift_FORCE_LOAD_$";
appendEncodedName(os, name);
return os.str();
}
llvm::SmallString<32> getTargetDependentLibraryOption(const llvm::Triple &T,
StringRef library) {
llvm::SmallString<32> buffer;
if (T.isWindowsMSVCEnvironment() || T.isWindowsItaniumEnvironment()) {
bool quote = library.find(' ') != StringRef::npos;
buffer += "/DEFAULTLIB:";
if (quote)
buffer += '"';