-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathGenDecl.cpp
6435 lines (5587 loc) · 245 KB
/
GenDecl.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
//===--- GenDecl.cpp - IR Generation for Declarations ---------------------===//
//
// 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 local and global
// declarations in Swift.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleDependencies.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeMemberVisitor.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Mangler.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/IRGen/Linking.h"
#include "swift/Runtime/HeapObject.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "swift/Subsystems.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/GlobalDecl.h"
#include "clang/CodeGen/CodeGenABITypes.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalAlias.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"
#include "Callee.h"
#include "ClassTypeInfo.h"
#include "ConformanceDescription.h"
#include "ConstantBuilder.h"
#include "Explosion.h"
#include "FixedTypeInfo.h"
#include "GenCall.h"
#include "GenConstant.h"
#include "GenClass.h"
#include "GenDecl.h"
#include "GenMeta.h"
#include "GenObjC.h"
#include "GenOpaque.h"
#include "GenPointerAuth.h"
#include "GenProto.h"
#include "GenType.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "LoadableTypeInfo.h"
#include "MetadataRequest.h"
#include "ProtocolInfo.h"
#include "Signature.h"
#include "StructLayout.h"
using namespace swift;
using namespace irgen;
llvm::cl::opt<bool> UseBasicDynamicReplacement(
"basic-dynamic-replacement", llvm::cl::init(false),
llvm::cl::desc("Basic implementation of dynamic replacement"));
namespace {
/// Add methods, properties, and protocol conformances from a JITed extension
/// to an ObjC class using the ObjC runtime.
///
/// This must happen after ObjCProtocolInitializerVisitor if any @objc protocols
/// were defined in the TU.
class CategoryInitializerVisitor
: public ClassMemberVisitor<CategoryInitializerVisitor>
{
IRGenFunction &IGF;
IRGenModule &IGM = IGF.IGM;
IRBuilder &Builder = IGF.Builder;
FunctionPointer class_replaceMethod;
FunctionPointer class_addProtocol;
llvm::Value *classMetadata;
llvm::Constant *metaclassMetadata;
public:
CategoryInitializerVisitor(IRGenFunction &IGF, ExtensionDecl *ext)
: IGF(IGF)
{
class_replaceMethod = IGM.getClassReplaceMethodFunctionPointer();
class_addProtocol = IGM.getClassAddProtocolFunctionPointer();
CanType origTy = ext->getSelfNominalTypeDecl()
->getDeclaredType()->getCanonicalType();
classMetadata = emitClassHeapMetadataRef(IGF, origTy,
MetadataValueType::ObjCClass,
MetadataState::Complete,
/*allow uninitialized*/ false);
classMetadata = Builder.CreateBitCast(classMetadata, IGM.ObjCClassPtrTy);
metaclassMetadata = IGM.getAddrOfMetaclassObject(
dyn_cast_or_null<ClassDecl>(origTy->getAnyNominal()),
NotForDefinition);
metaclassMetadata = llvm::ConstantExpr::getBitCast(metaclassMetadata,
IGM.ObjCClassPtrTy);
// Register ObjC protocol conformances.
for (auto *p : ext->getLocalProtocols()) {
if (!p->isObjC())
continue;
auto protoRefAddr = IGM.getAddrOfObjCProtocolRef(p, NotForDefinition);
auto proto = Builder.CreateLoad(protoRefAddr);
Builder.CreateCall(class_addProtocol, {classMetadata, proto});
}
}
void visitMembers(ExtensionDecl *ext) {
for (Decl *member : ext->getMembers())
visit(member);
}
void visitTypeDecl(TypeDecl *type) {
// We'll visit nested types separately if necessary.
}
void visitMissingDecl(MissingDecl *missing) {
llvm_unreachable("missing decl in IRGen");
}
void visitMissingMemberDecl(MissingMemberDecl *placeholder) {}
void visitFuncDecl(FuncDecl *method) {
if (!requiresObjCMethodDescriptor(method)) return;
// Don't emit getters/setters for @NSManaged methods.
if (method->getAttrs().hasAttribute<NSManagedAttr>())
return;
auto descriptor = emitObjCMethodDescriptorParts(IGM, method,
/*concrete*/true);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *args[] = {
method->isStatic() ? metaclassMetadata : classMetadata,
sel,
descriptor.impl,
descriptor.typeEncoding
};
Builder.CreateCall(class_replaceMethod, args);
}
// Can't be added in an extension.
void visitDestructorDecl(DestructorDecl *dtor) {}
void visitConstructorDecl(ConstructorDecl *constructor) {
if (!requiresObjCMethodDescriptor(constructor)) return;
auto descriptor = emitObjCMethodDescriptorParts(IGM, constructor,
/*concrete*/true);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *args[] = {
classMetadata,
sel,
descriptor.impl,
descriptor.typeEncoding
};
Builder.CreateCall(class_replaceMethod, args);
}
void visitPatternBindingDecl(PatternBindingDecl *binding) {
// Ignore the PBD and just handle the individual vars.
}
void visitVarDecl(VarDecl *prop) {
if (!requiresObjCPropertyDescriptor(IGM, prop)) return;
// FIXME: register property metadata in addition to the methods.
// ObjC doesn't have a notion of class properties, so we'd only do this
// for instance properties.
// Don't emit getters/setters for @NSManaged properties.
if (prop->getAttrs().hasAttribute<NSManagedAttr>())
return;
auto descriptor = emitObjCGetterDescriptorParts(IGM, prop);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
auto theClass = prop->isStatic() ? metaclassMetadata : classMetadata;
llvm::Value *getterArgs[] =
{theClass, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, getterArgs);
if (prop->isSettable(prop->getDeclContext())) {
auto descriptor = emitObjCSetterDescriptorParts(IGM, prop);
sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFunctionPointer(),
descriptor.selectorRef);
llvm::Value *setterArgs[] =
{theClass, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, setterArgs);
}
}
void visitSubscriptDecl(SubscriptDecl *subscript) {
assert(!subscript->isStatic() && "objc doesn't support class subscripts");
if (!requiresObjCSubscriptDescriptor(IGM, subscript)) return;
auto descriptor = emitObjCGetterDescriptorParts(IGM, subscript);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *getterArgs[] =
{classMetadata, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, getterArgs);
if (subscript->supportsMutation()) {
auto descriptor = emitObjCSetterDescriptorParts(IGM, subscript);
sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFunctionPointer(),
descriptor.selectorRef);
llvm::Value *setterArgs[] =
{classMetadata, sel, descriptor.impl, descriptor.typeEncoding};
Builder.CreateCall(class_replaceMethod, setterArgs);
}
}
};
/// Create a descriptor for JITed @objc protocol using the ObjC runtime.
class ObjCProtocolInitializerVisitor
: public ClassMemberVisitor<ObjCProtocolInitializerVisitor>
{
IRGenFunction &IGF;
IRGenModule &IGM = IGF.IGM;
IRBuilder &Builder = IGF.Builder;
FunctionPointer objc_getProtocol, objc_allocateProtocol,
objc_registerProtocol, protocol_addMethodDescription,
protocol_addProtocol;
llvm::Value *NewProto = nullptr;
public:
ObjCProtocolInitializerVisitor(IRGenFunction &IGF)
: IGF(IGF)
{
objc_getProtocol = IGM.getGetObjCProtocolFunctionPointer();
objc_allocateProtocol = IGM.getAllocateObjCProtocolFunctionPointer();
objc_registerProtocol = IGM.getRegisterObjCProtocolFunctionPointer();
protocol_addMethodDescription =
IGM.getProtocolAddMethodDescriptionFunctionPointer();
protocol_addProtocol = IGM.getProtocolAddProtocolFunctionPointer();
}
void visitMembers(ProtocolDecl *proto) {
// Check if the ObjC runtime already has a descriptor for this
// protocol. If so, use it.
SmallString<32> buf;
auto protocolName
= IGM.getAddrOfGlobalString(proto->getObjCRuntimeName(buf));
auto existing = Builder.CreateCall(objc_getProtocol, protocolName);
auto isNull = Builder.CreateICmpEQ(existing,
llvm::ConstantPointerNull::get(IGM.ProtocolDescriptorPtrTy));
auto existingBB = IGF.createBasicBlock("existing_protocol");
auto newBB = IGF.createBasicBlock("new_protocol");
auto contBB = IGF.createBasicBlock("cont");
Builder.CreateCondBr(isNull, newBB, existingBB);
// Nothing to do if there's already a descriptor.
Builder.emitBlock(existingBB);
Builder.CreateBr(contBB);
Builder.emitBlock(newBB);
// Allocate the protocol descriptor.
NewProto = Builder.CreateCall(objc_allocateProtocol, protocolName);
// Add the parent protocols.
for (auto parentProto : proto->getInheritedProtocols()) {
if (!parentProto->isObjC())
continue;
auto parentAddr =
IGM.getAddrOfObjCProtocolRef(parentProto, NotForDefinition);
llvm::Value *parent = Builder.CreateLoad(parentAddr);
parent = IGF.Builder.CreateBitCast(parent, IGM.ProtocolDescriptorPtrTy);
Builder.CreateCall(protocol_addProtocol, {NewProto, parent});
}
// Add the members.
for (Decl *member : proto->getMembers())
visit(member);
// Register it.
Builder.CreateCall(objc_registerProtocol, NewProto);
Builder.CreateBr(contBB);
// Store the reference to the runtime's idea of the protocol descriptor.
Builder.emitBlock(contBB);
auto result = Builder.CreatePHI(IGM.ProtocolDescriptorPtrTy, 2);
result->addIncoming(existing, existingBB);
result->addIncoming(NewProto, newBB);
llvm::Value *ref =
IGM.getAddrOfObjCProtocolRef(proto, NotForDefinition).getAddress();
ref = IGF.Builder.CreateBitCast(ref,
IGM.ProtocolDescriptorPtrTy->getPointerTo());
Builder.CreateStore(result, ref, IGM.getPointerAlignment());
}
void visitTypeDecl(TypeDecl *type) {
// We'll visit nested types separately if necessary.
}
void visitMissingDecl(MissingDecl *missing) {
llvm_unreachable("missing decl in IRGen");
}
void visitMissingMemberDecl(MissingMemberDecl *placeholder) {}
void visitAbstractFunctionDecl(AbstractFunctionDecl *method) {
if (isa<AccessorDecl>(method)) {
// Accessors are handled as part of their AbstractStorageDecls.
return;
}
auto descriptor = emitObjCMethodDescriptorParts(IGM, method,
/*concrete*/false);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *args[] = {
NewProto, sel, descriptor.typeEncoding,
// required?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
!method->getAttrs().hasAttribute<OptionalAttr>()),
// instance?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
isa<ConstructorDecl>(method) || method->isInstanceMember()),
};
Builder.CreateCall(protocol_addMethodDescription, args);
}
void visitPatternBindingDecl(PatternBindingDecl *binding) {
// Ignore the PBD and just handle the individual vars.
}
void visitAbstractStorageDecl(AbstractStorageDecl *prop) {
// TODO: Add properties to protocol.
auto descriptor = emitObjCGetterDescriptorParts(IGM, prop);
// When generating JIT'd code, we need to call sel_registerName() to force
// the runtime to unique the selector.
llvm::Value *sel = Builder.CreateCall(
IGM.getObjCSelRegisterNameFunctionPointer(), descriptor.selectorRef);
llvm::Value *getterArgs[] = {
NewProto, sel, descriptor.typeEncoding,
// required?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
!prop->getAttrs().hasAttribute<OptionalAttr>()),
// instance?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
prop->isInstanceMember()),
};
Builder.CreateCall(protocol_addMethodDescription, getterArgs);
if (prop->isSettable(nullptr)) {
auto descriptor = emitObjCSetterDescriptorParts(IGM, prop);
sel = Builder.CreateCall(IGM.getObjCSelRegisterNameFunctionPointer(),
descriptor.selectorRef);
llvm::Value *setterArgs[] = {
NewProto, sel, descriptor.typeEncoding,
// required?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
!prop->getAttrs().hasAttribute<OptionalAttr>()),
// instance?
llvm::ConstantInt::get(IGM.ObjCBoolTy,
prop->isInstanceMember()),
};
Builder.CreateCall(protocol_addMethodDescription, setterArgs);
}
}
};
} // end anonymous namespace
namespace {
class PrettySourceFileEmission : public llvm::PrettyStackTraceEntry {
const SourceFile &SF;
public:
explicit PrettySourceFileEmission(const SourceFile &SF) : SF(SF) {}
void print(raw_ostream &os) const override {
os << "While emitting IR for source file " << SF.getFilename() << '\n';
}
};
class PrettySynthesizedFileUnitEmission : public llvm::PrettyStackTraceEntry {
const SynthesizedFileUnit &SFU;
public:
explicit PrettySynthesizedFileUnitEmission(const SynthesizedFileUnit &SFU)
: SFU(SFU) {}
void print(raw_ostream &os) const override {
os << "While emitting IR for synthesized file" << &SFU << "\n";
}
};
} // end anonymous namespace
/// Emit all the top-level code in the source file.
void IRGenModule::emitSourceFile(SourceFile &SF) {
if (getSILModule().getOptions().StopOptimizationAfterSerialization) {
// We're asked to emit an empty IR module
return;
}
// Type-check the file if we haven't already (this may be necessary for .sil
// files, which don't get fully type-checked by parsing).
performTypeChecking(SF);
PrettySourceFileEmission StackEntry(SF);
// Emit types and other global decls.
for (auto *decl : SF.getTopLevelDecls())
emitGlobalDecl(decl);
for (auto *decl : SF.getHoistedDecls())
emitGlobalDecl(decl);
for (auto *localDecl : SF.getLocalTypeDecls())
emitGlobalDecl(localDecl);
for (auto *opaqueDecl : SF.getOpaqueReturnTypeDecls())
maybeEmitOpaqueTypeDecl(opaqueDecl);
}
/// Emit all the top-level code in the synthesized file unit.
void IRGenModule::emitSynthesizedFileUnit(SynthesizedFileUnit &SFU) {
PrettySynthesizedFileUnitEmission StackEntry(SFU);
for (auto *decl : SFU.getTopLevelDecls())
emitGlobalDecl(decl);
}
/// Collect elements of an already-existing global list with the given
/// \c name into \c list.
///
/// We use this when Clang code generation might populate the list.
static void collectGlobalList(IRGenModule &IGM,
SmallVectorImpl<llvm::WeakTrackingVH> &list,
StringRef name) {
if (auto *existing = IGM.Module.getGlobalVariable(name)) {
auto *globals = cast<llvm::ConstantArray>(existing->getInitializer());
for (auto &use : globals->operands()) {
auto *global = use.get();
list.push_back(global);
}
existing->eraseFromParent();
}
std::for_each(list.begin(), list.end(),
[](const llvm::WeakTrackingVH &global) {
assert(!isa<llvm::GlobalValue>(global) ||
!cast<llvm::GlobalValue>(global)->isDeclaration() &&
"all globals in the 'used' list must be definitions");
});
}
/// Emit a global list, i.e. a global constant array holding all of a
/// list of values. Generally these lists are for various LLVM
/// metadata or runtime purposes.
static llvm::GlobalVariable *
emitGlobalList(IRGenModule &IGM, ArrayRef<llvm::WeakTrackingVH> handles,
StringRef name, StringRef section,
llvm::GlobalValue::LinkageTypes linkage, llvm::Type *eltTy,
bool isConstant, bool asContiguousArray, bool canBeStrippedByLinker = false) {
// Do nothing if the list is empty.
if (handles.empty()) return nullptr;
// For global lists that actually get linked (as opposed to notional
// ones like @llvm.used), it's important to set an explicit alignment
// so that the linker doesn't accidentally put padding in the list.
Alignment alignment = IGM.getPointerAlignment();
if (!asContiguousArray) {
// Emit as individual globals, which is required for conditional runtime
// records to work.
for (auto &handle : handles) {
llvm::Constant *elt = cast<llvm::Constant>(&*handle);
std::string eltName = name.str() + "_" + elt->getName().str();
if (elt->getType() != eltTy)
elt = llvm::ConstantExpr::getBitCast(elt, eltTy);
auto var = new llvm::GlobalVariable(IGM.Module, eltTy, isConstant,
linkage, elt, eltName);
var->setSection(section);
var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
disableAddressSanitizer(IGM, var);
if (llvm::GlobalValue::isLocalLinkage(linkage)) {
if (canBeStrippedByLinker)
IGM.addCompilerUsedGlobal(var);
else
IGM.addUsedGlobal(var);
}
if (IGM.IRGen.Opts.ConditionalRuntimeRecords) {
// Allow dead-stripping `var` (the runtime record from the global list)
// when `handle` / `elt` (the underlaying entity) is not referenced.
IGM.appendLLVMUsedConditionalEntry(var, elt->stripPointerCasts());
}
}
return nullptr;
}
// We have an array of value handles, but we need an array of constants.
SmallVector<llvm::Constant*, 8> elts;
elts.reserve(handles.size());
for (auto &handle : handles) {
auto elt = cast<llvm::Constant>(&*handle);
if (elt->getType() != eltTy)
elt = llvm::ConstantExpr::getBitCast(elt, eltTy);
elts.push_back(elt);
}
auto varTy = llvm::ArrayType::get(eltTy, elts.size());
auto init = llvm::ConstantArray::get(varTy, elts);
auto var = new llvm::GlobalVariable(IGM.Module, varTy, isConstant, linkage,
init, name);
var->setSection(section);
// Do not set alignment and don't set disableAddressSanitizer on @llvm.used
// and @llvm.compiler.used. Doing so confuses LTO (merging) and they're not
// going to end up as real global symbols in the binary anyways.
if (name != "llvm.used" && name != "llvm.compiler.used") {
var->setAlignment(llvm::MaybeAlign(alignment.getValue()));
disableAddressSanitizer(IGM, var);
}
// Mark the variable as used if doesn't have external linkage.
// (Note that we'd specifically like to not put @llvm.used in itself.)
if (llvm::GlobalValue::isLocalLinkage(linkage)) {
if (canBeStrippedByLinker)
IGM.addCompilerUsedGlobal(var);
else
IGM.addUsedGlobal(var);
}
return var;
}
void IRGenModule::emitRuntimeRegistration() {
// Duck out early if we have nothing to register.
// Note that we don't consider `RuntimeResolvableTypes2` here because the
// current Swift runtime is unable to handle move-only types at runtime, and
// we only use this runtime registration path in JIT mode, so there are no
// ABI forward compatibility concerns.
//
// We should incorporate the types from
// `RuntimeResolvableTypes2` into the list of types to register when we do
// have runtime support in place.
if (SwiftProtocols.empty() && ProtocolConformances.empty() &&
RuntimeResolvableTypes.empty() &&
(!ObjCInterop || (ObjCProtocols.empty() && ObjCClasses.empty() &&
ObjCCategoryDecls.empty())))
return;
// Find the entry point.
SILFunction *EntryPoint = getSILModule().lookUpFunction(
getSILModule().getASTContext().getEntryPointFunctionName());
// If we're debugging (and not in the REPL), we don't have a
// main. Find a function marked with the LLDBDebuggerFunction
// attribute instead.
if (!EntryPoint && Context.LangOpts.DebuggerSupport) {
for (SILFunction &SF : getSILModule()) {
if (SF.hasLocation()) {
if (Decl* D = SF.getLocation().getAsASTNode<Decl>()) {
if (auto *FD = dyn_cast<FuncDecl>(D)) {
if (FD->getAttrs().hasAttribute<LLDBDebuggerFunctionAttr>()) {
EntryPoint = &SF;
break;
}
}
}
}
}
}
if (!EntryPoint)
return;
llvm::Function *EntryFunction = Module.getFunction(EntryPoint->getName());
if (!EntryFunction)
return;
// Create a new function to contain our logic.
auto fnTy = llvm::FunctionType::get(VoidTy, /*varArg*/ false);
auto RegistrationFunction = llvm::Function::Create(fnTy,
llvm::GlobalValue::PrivateLinkage,
"runtime_registration",
getModule());
RegistrationFunction->setAttributes(constructInitialAttributes());
// Insert a call into the entry function.
{
llvm::BasicBlock *EntryBB = &EntryFunction->getEntryBlock();
llvm::BasicBlock::iterator IP = EntryBB->getFirstInsertionPt();
IRBuilder Builder(getLLVMContext(),
DebugInfo && !Context.LangOpts.DebuggerSupport);
Builder.llvm::IRBuilderBase::SetInsertPoint(EntryBB, IP);
if (DebugInfo && !Context.LangOpts.DebuggerSupport)
DebugInfo->setEntryPointLoc(Builder);
Builder.CreateCall(fnTy, RegistrationFunction, {});
}
IRGenFunction RegIGF(*this, RegistrationFunction);
if (DebugInfo && !Context.LangOpts.DebuggerSupport)
DebugInfo->emitArtificialFunction(RegIGF, RegistrationFunction);
// Register ObjC protocols we added.
if (ObjCInterop) {
if (!ObjCProtocols.empty()) {
// We need to initialize ObjC protocols in inheritance order, parents
// first.
llvm::DenseSet<ProtocolDecl*> protos;
for (auto &proto : ObjCProtocols)
protos.insert(proto.first);
llvm::SmallVector<ProtocolDecl*, 4> protoInitOrder;
std::function<void(ProtocolDecl*)> orderProtocol
= [&](ProtocolDecl *proto) {
// Recursively put parents first.
for (auto parent : proto->getInheritedProtocols())
orderProtocol(parent);
// Skip if we don't need to reify this protocol.
auto found = protos.find(proto);
if (found == protos.end())
return;
protos.erase(found);
protoInitOrder.push_back(proto);
};
while (!protos.empty()) {
orderProtocol(*protos.begin());
}
// Visit the protocols in the order we established.
for (auto *proto : protoInitOrder) {
ObjCProtocolInitializerVisitor(RegIGF)
.visitMembers(proto);
}
}
}
// Register Swift protocols if we added any.
if (!SwiftProtocols.empty()) {
llvm::Constant *protocols = emitSwiftProtocols(/*asContiguousArray*/ true);
llvm::Constant *beginIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0),
};
auto protocolRecordsTy =
llvm::ArrayType::get(ProtocolRecordTy, SwiftProtocols.size());
auto begin = llvm::ConstantExpr::getGetElementPtr(protocolRecordsTy,
protocols, beginIndices);
llvm::Constant *endIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, SwiftProtocols.size()),
};
auto end = llvm::ConstantExpr::getGetElementPtr(protocolRecordsTy,
protocols, endIndices);
RegIGF.Builder.CreateCall(getRegisterProtocolsFunctionPointer(),
{begin, end});
}
// Register Swift protocol conformances if we added any.
if (llvm::Constant *conformances =
emitProtocolConformances(/*asContiguousArray*/ true)) {
llvm::Constant *beginIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0),
};
auto protocolRecordsTy =
llvm::ArrayType::get(RelativeAddressTy, ProtocolConformances.size());
auto begin = llvm::ConstantExpr::getGetElementPtr(
protocolRecordsTy, conformances, beginIndices);
llvm::Constant *endIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, ProtocolConformances.size()),
};
auto end = llvm::ConstantExpr::getGetElementPtr(protocolRecordsTy,
conformances, endIndices);
RegIGF.Builder.CreateCall(getRegisterProtocolConformancesFunctionPointer(),
{begin, end});
}
if (!RuntimeResolvableTypes.empty()) {
llvm::Constant *records =
emitTypeMetadataRecords(/*asContiguousArray*/ true);
llvm::Constant *beginIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, 0),
};
auto typemetadataRecordsTy = llvm::ArrayType::get(
TypeMetadataRecordTy, RuntimeResolvableTypes.size());
auto begin = llvm::ConstantExpr::getGetElementPtr(typemetadataRecordsTy,
records, beginIndices);
llvm::Constant *endIndices[] = {
llvm::ConstantInt::get(Int32Ty, 0),
llvm::ConstantInt::get(Int32Ty, RuntimeResolvableTypes.size()),
};
auto end = llvm::ConstantExpr::getGetElementPtr(typemetadataRecordsTy,
records, endIndices);
RegIGF.Builder.CreateCall(getRegisterTypeMetadataRecordsFunctionPointer(),
{begin, end});
}
// Register Objective-C classes and extensions we added.
if (ObjCInterop) {
for (llvm::WeakTrackingVH &ObjCClass : ObjCClasses) {
RegIGF.Builder.CreateCall(getInstantiateObjCClassFunctionPointer(),
{ObjCClass});
}
for (ExtensionDecl *ext : ObjCCategoryDecls) {
CategoryInitializerVisitor(RegIGF, ext).visitMembers(ext);
}
}
RegIGF.Builder.CreateRetVoid();
}
/// Return the address of the context descriptor representing the given
/// decl context, used as a parent reference for another decl.
///
/// For a nominal type context, this returns the address of the nominal type
/// descriptor.
/// For an extension context, this returns the address of the extension
/// context descriptor.
/// For a module or file unit context, this returns the address of the module
/// context descriptor.
/// For any other kind of context, this returns an anonymous context descriptor
/// for the context.
ConstantReference
IRGenModule::getAddrOfContextDescriptorForParent(DeclContext *parent,
DeclContext *ofChild,
bool fromAnonymousContext) {
switch (parent->getContextKind()) {
case DeclContextKind::AbstractClosureExpr:
case DeclContextKind::SerializedAbstractClosure:
case DeclContextKind::AbstractFunctionDecl:
case DeclContextKind::SubscriptDecl:
case DeclContextKind::EnumElementDecl:
case DeclContextKind::TopLevelCodeDecl:
case DeclContextKind::SerializedTopLevelCodeDecl:
case DeclContextKind::Initializer:
return {getAddrOfAnonymousContextDescriptor(
fromAnonymousContext ? parent : ofChild),
ConstantReference::Direct};
case DeclContextKind::GenericTypeDecl:
if (auto nomTy = dyn_cast<NominalTypeDecl>(parent)) {
if (nomTy->getDeclContext()->getParentModule() != getSwiftModule() &&
fromAnonymousContext) {
// Can't emit a direct reference.
auto entity = LinkEntity::forNominalTypeDescriptor(nomTy);
return getAddrOfLLVMVariableOrGOTEquivalent(entity);
}
return {getAddrOfTypeContextDescriptor(nomTy, DontRequireMetadata),
ConstantReference::Direct};
}
return {getAddrOfAnonymousContextDescriptor(
fromAnonymousContext ? parent : ofChild),
ConstantReference::Direct};
case DeclContextKind::ExtensionDecl: {
auto ext = cast<ExtensionDecl>(parent);
// If the extension is equivalent to its extended context (that is, it's
// in the same module as the original non-protocol type and
// has no constraints), then we can use the original nominal type context
// (assuming there is one).
if (ext->isEquivalentToExtendedContext()) {
auto nominal = ext->getExtendedNominal();
// If the extended type is an ObjC class, it won't have a nominal type
// descriptor, so we'll just emit an extension context.
auto clazz = dyn_cast<ClassDecl>(nominal);
if (!clazz || clazz->isForeign() || hasKnownSwiftMetadata(*this, clazz)) {
IRGen.noteUseOfTypeContextDescriptor(nominal, DontRequireMetadata);
return getAddrOfLLVMVariableOrGOTEquivalent(
LinkEntity::forNominalTypeDescriptor(nominal));
}
}
return {getAddrOfExtensionContextDescriptor(ext),
ConstantReference::Direct};
}
case DeclContextKind::Package:
assert(false && "package decl context kind should not have been reached");
case DeclContextKind::FileUnit:
case DeclContextKind::MacroDecl:
parent = parent->getParentModule();
LLVM_FALLTHROUGH;
case DeclContextKind::Module:
if (auto *D = ofChild->getAsDecl()) {
// If the top-level decl has been marked as moved from another module,
// using @_originallyDefinedIn, we should emit the original module as
// the context because all run-time names of this decl are based on the
// original module name.
auto OriginalModule = D->getAlternateModuleName();
if (!OriginalModule.empty()) {
return {getAddrOfOriginalModuleContextDescriptor(OriginalModule),
ConstantReference::Direct};
}
}
return {getAddrOfModuleContextDescriptor(cast<ModuleDecl>(parent)),
ConstantReference::Direct};
}
llvm_unreachable("unhandled kind");
}
/// Return the address of the context descriptor representing the parent of
/// the given decl context.
///
/// For a nominal type context, this returns the address of the nominal type
/// descriptor.
/// For an extension context, this returns the address of the extension
/// context descriptor.
/// For a module or file unit context, this returns the address of the module
/// context descriptor.
/// For any other kind of context, this returns an anonymous context descriptor
/// for the context.
ConstantReference
IRGenModule::getAddrOfParentContextDescriptor(DeclContext *from,
bool fromAnonymousContext) {
// Some types get special treatment.
if (auto Type = dyn_cast<NominalTypeDecl>(from)) {
// Use a special module context if we have one.
if (auto context =
Mangle::ASTMangler::getSpecialManglingContext(
Type, /*UseObjCProtocolNames=*/false)) {
switch (*context) {
case Mangle::ASTMangler::ObjCContext:
return {getAddrOfObjCModuleContextDescriptor(),
ConstantReference::Direct};
case Mangle::ASTMangler::ClangImporterContext:
return {getAddrOfClangImporterModuleContextDescriptor(),
ConstantReference::Direct};
}
}
// Wrap up private types in an anonymous context for the containing file
// unit so that the runtime knows they have unstable identity.
if (!fromAnonymousContext && Type->isOutermostPrivateOrFilePrivateScope()
&& !Type->isUsableFromInline())
return {getAddrOfAnonymousContextDescriptor(Type),
ConstantReference::Direct};
}
return getAddrOfContextDescriptorForParent(from->getParent(), from,
fromAnonymousContext);
}
static void markGlobalAsUsedBasedOnLinkage(IRGenModule &IGM, LinkInfo &link,
llvm::GlobalValue *global) {
// If we're internalizing public symbols at link time, don't make globals
// unconditionally externally visible.
if (IGM.getOptions().InternalizeAtLink)
return;
// Everything externally visible is considered used in Swift.
// That mostly means we need to be good at not marking things external.
if (link.isUsed())
IGM.addUsedGlobal(global);
else if (!IGM.IRGen.Opts.shouldOptimize() &&
!IGM.IRGen.Opts.ConditionalRuntimeRecords &&
!IGM.IRGen.Opts.VirtualFunctionElimination &&
!IGM.IRGen.Opts.WitnessMethodElimination &&
!global->isDeclaration()) {
// llvm's pipeline has decide to run GlobalDCE as part of the O0 pipeline.
// Mark non public symbols as compiler used to counter act this.
IGM.addCompilerUsedGlobal(global);
}
}
bool LinkInfo::isUsed(IRLinkage IRL) {
// Everything externally visible is considered used in Swift.
// That mostly means we need to be good at not marking things external.
return IRL.Linkage == llvm::GlobalValue::ExternalLinkage &&
(IRL.Visibility == llvm::GlobalValue::DefaultVisibility ||
IRL.Visibility == llvm::GlobalValue::ProtectedVisibility) &&
(IRL.DLLStorage == llvm::GlobalValue::DefaultStorageClass ||
IRL.DLLStorage == llvm::GlobalValue::DLLExportStorageClass);
}
/// Add the given global value to @llvm.used.
///
/// This value must have a definition by the time the module is finalized.
void IRGenModule::addUsedGlobal(llvm::GlobalValue *global) {
LLVMUsed.push_back(global);
}
/// Add the given global value to @llvm.compiler.used.
///
/// This value must have a definition by the time the module is finalized.
void IRGenModule::addCompilerUsedGlobal(llvm::GlobalValue *global) {
LLVMCompilerUsed.push_back(global);
}
void IRGenModule::addGenericROData(llvm::Constant *RODataAddr) {
GenericRODatas.push_back(RODataAddr);
}
/// Add the given global value to the Objective-C class list.
void IRGenModule::addObjCClass(llvm::Constant *classPtr, bool nonlazy) {
ObjCClasses.push_back(classPtr);
if (nonlazy)
ObjCNonLazyClasses.push_back(classPtr);
}
/// Add the given global value to the Objective-C resilient class stub list.
void IRGenModule::addObjCClassStub(llvm::Constant *classPtr) {
ObjCClassStubs.push_back(classPtr);
}
void IRGenModule::addRuntimeResolvableType(GenericTypeDecl *type) {
// Collect the nominal type records we emit into a special section.
if (isa<NominalTypeDecl>(type) &&
!cast<NominalTypeDecl>(type)->canBeCopyable()) {
// Older runtimes should not be allowed to discover noncopyable types, since
// they will try to expose them dynamically as copyable types. Record
// noncopyable type descriptors in a separate vector so that future
// noncopyable-type-aware runtimes and reflection libraries can still find
// them.
RuntimeResolvableTypes2.push_back(type);
} else {
RuntimeResolvableTypes.push_back(type);
}
if (auto nominal = dyn_cast<NominalTypeDecl>(type)) {
// As soon as the type metadata is available, all the type's conformances
// must be available, too. The reason is that a type (with the help of its
// metadata) can be checked at runtime if it conforms to a protocol.
addLazyConformances(nominal);
}
}
ConstantReference
IRGenModule::getConstantReferenceForProtocolDescriptor(ProtocolDecl *proto) {