forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathIRGenDebugInfo.cpp
1788 lines (1573 loc) · 67.4 KB
/
IRGenDebugInfo.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
//===--- IRGenDebugInfo.cpp - Debug Info Support --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements IR debug info generation for Swift.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "debug-info"
#include "IRGenDebugInfo.h"
#include "GenOpaque.h"
#include "GenType.h"
#include "Linking.h"
#include "swift/AST/Expr.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/Mangle.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/AST/Pattern.h"
#include "swift/Basic/Dwarf.h"
#include "swift/Basic/Punycode.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/Version.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILBasicBlock.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILModule.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/Config/config.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/Local.h"
using namespace swift;
using namespace irgen;
/// Strdup a raw char array using the bump pointer.
StringRef IRGenDebugInfo::BumpAllocatedString(const char *Data, size_t Length) {
char *Ptr = DebugInfoNames.Allocate<char>(Length+1);
memcpy(Ptr, Data, Length);
*(Ptr+Length) = 0;
return StringRef(Ptr, Length);
}
/// Strdup S using the bump pointer.
StringRef IRGenDebugInfo::BumpAllocatedString(std::string S) {
return BumpAllocatedString(S.c_str(), S.length());
}
/// Strdup StringRef S using the bump pointer.
StringRef IRGenDebugInfo::BumpAllocatedString(StringRef S) {
return BumpAllocatedString(S.data(), S.size());
}
/// Return the size reported by a type.
static unsigned getSizeInBits(llvm::DIType *Ty, const TrackingDIRefMap &Map) {
// Follow derived types until we reach a type that
// reports back a size.
while (isa<llvm::DIDerivedType>(Ty) && !Ty->getSizeInBits()) {
auto *DT = cast<llvm::DIDerivedType>(Ty);
Ty = DT->getBaseType().resolve(Map);
if (!Ty)
return 0;
}
return Ty->getSizeInBits();
}
/// Return the size reported by the variable's type.
static unsigned getSizeInBits(const llvm::DILocalVariable *Var,
const TrackingDIRefMap &Map) {
llvm::DIType *Ty = Var->getType().resolve(Map);
return getSizeInBits(Ty, Map);
}
IRGenDebugInfo::IRGenDebugInfo(const IRGenOptions &Opts,
ClangImporter &CI,
IRGenModule &IGM,
llvm::Module &M,
SourceFile *SF)
: Opts(Opts),
CI(CI),
SM(IGM.Context.SourceMgr),
M(M),
DBuilder(M),
IGM(IGM),
EntryPointFn(nullptr),
MetadataTypeDecl(nullptr),
InternalType(nullptr),
LastDebugLoc({}),
LastScope(nullptr)
{
assert(Opts.DebugInfoKind > IRGenDebugInfoKind::None
&& "no debug info should be generated");
StringRef SourceFileName = SF ? SF->getFilename() :
StringRef(Opts.MainInputFilename);
StringRef Dir;
llvm::SmallString<256> AbsMainFile;
if (SourceFileName.empty())
AbsMainFile = "<unknown>";
else {
AbsMainFile = SourceFileName;
llvm::sys::fs::make_absolute(AbsMainFile);
}
unsigned Lang = llvm::dwarf::DW_LANG_Swift;
std::string Producer = version::getSwiftFullVersion();
bool IsOptimized = Opts.Optimize;
StringRef Flags = Opts.DWARFDebugFlags;
unsigned Major, Minor;
std::tie(Major, Minor) = version::getSwiftNumericVersion();
unsigned MajorRuntimeVersion = Major;
// No split DWARF on Darwin.
StringRef SplitName = StringRef();
// Note that File + Dir need not result in a valid path.
// Clang is doing the same thing here.
TheCU = DBuilder.createCompileUnit(
Lang, AbsMainFile, Opts.DebugCompilationDir, Producer, IsOptimized,
Flags, MajorRuntimeVersion, SplitName,
Opts.DebugInfoKind == IRGenDebugInfoKind::LineTables
? llvm::DIBuilder::LineTablesOnly
: llvm::DIBuilder::FullDebug);
MainFile = getOrCreateFile(BumpAllocatedString(AbsMainFile).data());
if (auto *MainFunc = IGM.SILMod->lookUpFunction(SWIFT_ENTRY_POINT_FUNCTION)) {
IsLibrary = false;
auto *MainIGM = IGM.dispatcher.getGenModule(MainFunc->getDeclContext());
// Don't create the function type if we are in a different llvm module than
// the module where @main is defined. This is the case for non-primary
// modules when doing multi-threaded whole-module compilation.
if (MainIGM == &IGM) {
EntryPointFn = DBuilder.createReplaceableCompositeType(
llvm::dwarf::DW_TAG_subroutine_type, SWIFT_ENTRY_POINT_FUNCTION,
MainFile, MainFile, 0);
}
}
// Because the swift compiler relies on Clang to setup the Module,
// the clang CU is always created first. Several dwarf-reading
// tools (older versions of ld64, and lldb) can get confused if the
// first CU in an object is empty, so ensure that the Swift CU comes
// first by rearranging the list of CUs in the LLVM module.
llvm::NamedMDNode *CU_Nodes = M.getNamedMetadata("llvm.dbg.cu");
SmallVector<llvm::DICompileUnit *, 2> CUs;
for (auto *N : CU_Nodes->operands())
CUs.push_back(cast<llvm::DICompileUnit>(N));
CU_Nodes->dropAllReferences();
for (auto CU = CUs.rbegin(), CE = CUs.rend(); CU != CE; ++CU)
CU_Nodes->addOperand(*CU);
// Create a module for the current compile unit.
llvm::sys::path::remove_filename(AbsMainFile);
MainModule =
getOrCreateModule(Opts.ModuleName, TheCU, Opts.ModuleName, AbsMainFile);
DBuilder.createImportedModule(MainFile, MainModule, 1);
}
static const char *getFilenameFromDC(const DeclContext *DC) {
if (auto LF = dyn_cast<LoadedFile>(DC)) {
// FIXME: Today, the subclasses of LoadedFile happen to return StringRefs
// that are backed by null-terminated strings, but that's certainly not
// guaranteed in the future.
StringRef Fn = LF->getFilename();
assert(((Fn.size() == 0) ||
(Fn.data()[Fn.size()] == '\0')) && "not a C string");
return Fn.data();
}
if (auto SF = dyn_cast<SourceFile>(DC))
return SF->getFilename().data();
else if (auto M = dyn_cast<Module>(DC))
return M->getModuleFilename().data();
else
return nullptr;
}
SILLocation::DebugLoc getDeserializedLoc(Pattern *) { return {}; }
SILLocation::DebugLoc getDeserializedLoc(Expr *) { return {}; }
SILLocation::DebugLoc getDeserializedLoc(Stmt *) { return {}; }
SILLocation::DebugLoc getDeserializedLoc(Decl *D) {
SILLocation::DebugLoc L;
const DeclContext *DC = D->getDeclContext()->getModuleScopeContext();
if (const char *Filename = getFilenameFromDC(DC))
L.Filename = Filename;
return L;
}
/// Use the SM to figure out the actual line/column of a SourceLoc.
template <typename WithLoc>
SILLocation::DebugLoc getDebugLoc(SourceManager &SM, WithLoc *S,
bool End = false) {
SILLocation::DebugLoc L;
if (S == nullptr)
return L;
SourceLoc Loc = End ? S->getEndLoc() : S->getStartLoc();
if (Loc.isInvalid())
// This may be a deserialized or clang-imported decl. And modules
// don't come with SourceLocs right now. Get at least the name of
// the module.
return getDeserializedLoc(S);
return SILLocation::decode(Loc, SM);
}
/// Return the start of the location's source range.
static SILLocation::DebugLoc getStartLocation(Optional<SILLocation> OptLoc,
SourceManager &SM) {
if (!OptLoc) return {};
return SILLocation::decode(OptLoc->getStartSourceLoc(), SM);
}
/// Return the debug location from a SILLocation.
static SILLocation::DebugLoc getDebugLocation(Optional<SILLocation> OptLoc,
SourceManager &SM) {
if (!OptLoc || OptLoc->isInPrologue())
return {};
return OptLoc->decodeDebugLoc(SM);
}
/// Determine whether this debug scope belongs to an explicit closure.
static bool isExplicitClosure(const SILDebugScope *DS) {
if (DS) {
auto *SILFn = DS->getInlinedFunction();
if (SILFn && SILFn->hasLocation())
if (Expr *E = SILFn->getLocation().getAsASTNode<Expr>())
if (isa<ClosureExpr>(E))
return true;
}
return false;
}
/// Determine whether this location is some kind of closure.
static bool isAbstractClosure(const SILLocation &Loc) {
if (Expr *E = Loc.getAsASTNode<Expr>())
if (isa<AbstractClosureExpr>(E))
return true;
return false;
}
llvm::MDNode *IRGenDebugInfo::createInlinedAt(const SILDebugScope *DS) {
llvm::MDNode *InlinedAt = nullptr;
if (DS) {
for (auto *CS : DS->flattenedInlineTree()) {
// In SIL the inlined-at information is part of the scopes, in
// LLVM IR it is part of the location. Transforming the inlined-at
// SIL scope to a location means skipping the inlined-at scope.
auto *Parent = CS->Parent.get<const SILDebugScope *>();
auto *ParentScope = getOrCreateScope(Parent);
auto L = CS->Loc.decodeDebugLoc(SM);
InlinedAt = llvm::DebugLoc::get(L.Line, L.Column, ParentScope, InlinedAt);
}
}
return InlinedAt;
}
#ifndef NDEBUG
/// Perform a couple of sanity checks on scopes.
static bool parentScopesAreSane(const SILDebugScope *DS) {
auto *Parent = DS;
while ((Parent = Parent->Parent.dyn_cast<const SILDebugScope *>())) {
if (!DS->InlinedCallSite)
assert(!Parent->InlinedCallSite &&
"non-inlined scope has an inlined parent");
}
return true;
}
bool IRGenDebugInfo::lineNumberIsSane(IRBuilder &Builder, unsigned Line) {
if (IGM.Opts.Optimize)
return true;
// Assert monotonically increasing line numbers within the same basic block;
llvm::BasicBlock *CurBasicBlock = Builder.GetInsertBlock();
if (CurBasicBlock == LastBasicBlock) {
return Line >= LastDebugLoc.Line;
}
LastBasicBlock = CurBasicBlock;
return true;
}
#endif
void IRGenDebugInfo::setCurrentLoc(IRBuilder &Builder, const SILDebugScope *DS,
Optional<SILLocation> Loc) {
assert(DS && "empty scope");
// Inline info is emitted as part of the location below; extract the
// original scope here.
auto *Scope = getOrCreateScope(DS->getInlinedScope());
if (!Scope)
return;
auto L = getDebugLocation(Loc, SM);
auto *File = getOrCreateFile(L.Filename);
if (File->getFilename() != Scope->getFilename()) {
// We changed files in the middle of a scope. This happens, for
// example, when constructors are inlined. Create a new scope to
// reflect this.
auto File = getOrCreateFile(L.Filename);
Scope = DBuilder.createLexicalBlockFile(Scope, File);
}
// Both the code that is used to set up a closure object and the
// (beginning of) the closure itself has the AbstractClosureExpr as
// location. We are only interested in the latter case and want to
// ignore the setup code.
//
// callWithClosure(
// { // <-- a breakpoint here should only stop inside of the closure.
// foo();
// })
//
// The actual closure has a closure expression as scope.
if (Loc && isAbstractClosure(*Loc) && DS && !isAbstractClosure(DS->Loc)
&& !Loc->is<ImplicitReturnLocation>())
return;
if (L.Line == 0 && DS == LastScope) {
// Reuse the last source location if we are still in the same
// scope to get a more contiguous line table.
L = LastDebugLoc;
}
// FIXME: Enable this assertion.
//assert(lineNumberIsSane(Builder, L.Line) &&
// "-Onone, but line numbers are not monotonically increasing within bb");
LastDebugLoc = L;
LastScope = DS;
auto *InlinedAt = createInlinedAt(DS);
assert(((!InlinedAt) || (InlinedAt && Scope)) && "inlined w/o scope");
assert(parentScopesAreSane(DS) && "parent scope sanity check failed");
auto DL = llvm::DebugLoc::get(L.Line, L.Column, Scope, InlinedAt);
// TODO: Write a strongly-worded letter to the person that came up
// with a pair of functions spelled "get" and "Set".
Builder.SetCurrentDebugLocation(DL);
}
llvm::DIScope *IRGenDebugInfo::getOrCreateScope(const SILDebugScope *DS) {
if (DS == 0)
return MainFile;
// Try to find it in the cache first.
auto CachedScope = ScopeCache.find(DS);
if (CachedScope != ScopeCache.end())
return cast<llvm::DIScope>(CachedScope->second);
// If this is an (inlined) function scope, the function may
// not have been created yet.
if (auto *SILFn = DS->Parent.dyn_cast<SILFunction *>()) {
auto *FnScope = SILFn->getDebugScope();
// FIXME: This is a bug in the SIL deserialization.
if (!FnScope)
SILFn->setDebugScope(DS);
auto CachedScope = ScopeCache.find(FnScope);
if (CachedScope != ScopeCache.end())
return cast<llvm::DIScope>(CachedScope->second);
// Force the debug info for the function to be emitted, even if it
// is external or has been inlined.
llvm::Function *Fn = nullptr;
if (!SILFn->getName().empty() && !SILFn->isZombie())
Fn = IGM.getAddrOfSILFunction(SILFn, NotForDefinition);
auto *SP = emitFunction(*SILFn, Fn);
// Cache it.
ScopeCache[DS] = llvm::TrackingMDNodeRef(SP);
return SP;
}
auto *ParentScope = DS->Parent.get<const SILDebugScope *>();
llvm::DIScope *Parent = getOrCreateScope(ParentScope);
assert(isa<llvm::DILocalScope>(Parent) && "not a local scope");
if (Opts.DebugInfoKind == IRGenDebugInfoKind::LineTables)
return Parent;
assert(DS->Parent && "lexical block must have a parent subprogram");
auto L = getStartLocation(DS->Loc, SM);
llvm::DIFile *File = getOrCreateFile(L.Filename);
auto *DScope = DBuilder.createLexicalBlock(Parent, File, L.Line, L.Column);
// Cache it.
ScopeCache[DS] = llvm::TrackingMDNodeRef(DScope);
return DScope;
}
llvm::DIFile *IRGenDebugInfo::getOrCreateFile(const char *Filename) {
if (!Filename)
return MainFile;
if (MainFile) {
SmallString<256> AbsMainFile, ThisFile;
AbsMainFile = Filename;
llvm::sys::fs::make_absolute(AbsMainFile);
llvm::sys::path::append(ThisFile, MainFile->getDirectory(),
MainFile->getFilename());
if (ThisFile == AbsMainFile) {
DIFileCache[Filename] = llvm::TrackingMDNodeRef(MainFile);
return MainFile;
}
}
// Look in the cache first.
auto CachedFile = DIFileCache.find(Filename);
if (CachedFile != DIFileCache.end()) {
// Verify that the information still exists.
if (llvm::Metadata *V = CachedFile->second)
return cast<llvm::DIFile>(V);
}
// Create a new one.
StringRef File = llvm::sys::path::filename(Filename);
llvm::SmallString<512> Path(Filename);
llvm::sys::path::remove_filename(Path);
llvm::DIFile *F = DBuilder.createFile(File, Path);
// Cache it.
DIFileCache[Filename] = llvm::TrackingMDNodeRef(F);
return F;
}
StringRef IRGenDebugInfo::getName(const FuncDecl &FD) {
// Getters and Setters are anonymous functions, so we forge a name
// using its parent declaration.
if (FD.isAccessor())
if (ValueDecl *VD = FD.getAccessorStorageDecl()) {
const char *Kind;
switch (FD.getAccessorKind()) {
case AccessorKind::NotAccessor: llvm_unreachable("this is an accessor");
case AccessorKind::IsGetter: Kind = ".get"; break;
case AccessorKind::IsSetter: Kind = ".set"; break;
case AccessorKind::IsWillSet: Kind = ".willset"; break;
case AccessorKind::IsDidSet: Kind = ".didset"; break;
case AccessorKind::IsMaterializeForSet: Kind = ".materialize"; break;
case AccessorKind::IsAddressor: Kind = ".addressor"; break;
case AccessorKind::IsMutableAddressor: Kind = ".mutableAddressor"; break;
}
SmallVector<char, 64> Buf;
StringRef Name = (VD->getName().str() + Twine(Kind)).toStringRef(Buf);
return BumpAllocatedString(Name);
}
if (FD.hasName())
return FD.getName().str();
return StringRef();
}
StringRef IRGenDebugInfo::getName(SILLocation L) {
if (L.isNull())
return StringRef();
if (FuncDecl *FD = L.getAsASTNode<FuncDecl>())
return getName(*FD);
if (L.isASTNode<ConstructorDecl>())
return "init";
if (L.isASTNode<DestructorDecl>())
return "deinit";
return StringRef();
}
static CanSILFunctionType getFunctionType(SILType SILTy) {
if (!SILTy)
return CanSILFunctionType();
auto FnTy = SILTy.getAs<SILFunctionType>();
if (!FnTy) {
DEBUG(llvm::dbgs() << "Unexpected function type: "; SILTy.dump();
llvm::dbgs() << "\n");
return CanSILFunctionType();
}
return FnTy;
}
llvm::DIScope *IRGenDebugInfo::getOrCreateContext(DeclContext *DC) {
if (!DC)
return TheCU;
if (isa<FuncDecl>(DC))
if (auto *Decl = IGM.SILMod->lookUpFunction(
SILDeclRef(cast<AbstractFunctionDecl>(DC), SILDeclRef::Kind::Func)))
return getOrCreateScope(Decl->getDebugScope());
switch (DC->getContextKind()) {
// The interesting cases are already handled above.
case DeclContextKind::AbstractFunctionDecl:
case DeclContextKind::AbstractClosureExpr:
// We don't model these in DWARF.
case DeclContextKind::SerializedLocal:
case DeclContextKind::Initializer:
case DeclContextKind::ExtensionDecl:
case DeclContextKind::SubscriptDecl:
return getOrCreateContext(DC->getParent());
case DeclContextKind::TopLevelCodeDecl:
return cast<llvm::DIScope>(EntryPointFn);
case DeclContextKind::Module:
return getOrCreateModule({Module::AccessPathTy(), cast<ModuleDecl>(DC)});
case DeclContextKind::FileUnit:
// A module may contain multiple files.
return getOrCreateContext(DC->getParent());
case DeclContextKind::GenericTypeDecl: {
auto CachedType = DITypeCache.find(
cast<GenericTypeDecl>(DC)->getDeclaredType().getPointer());
if (CachedType != DITypeCache.end()) {
// Verify that the information still exists.
if (llvm::Metadata *Val = CachedType->second)
return cast<llvm::DIType>(Val);
}
// Create a Forward-declared type.
auto *TyDecl = cast<NominalTypeDecl>(DC);
auto Loc = getDebugLoc(SM, TyDecl);
auto File = getOrCreateFile(Loc.Filename);
auto Line = Loc.Line;
auto FwdDecl = DBuilder.createForwardDecl(
llvm::dwarf::DW_TAG_structure_type, TyDecl->getName().str(),
getOrCreateContext(DC->getParent()), File, Line,
llvm::dwarf::DW_LANG_Swift, 0, 0);
return FwdDecl;
}
}
return TheCU;
}
void IRGenDebugInfo::createParameterType(
llvm::SmallVectorImpl<llvm::Metadata *> &Parameters, SILType type,
DeclContext *DeclCtx) {
// FIXME: This use of getSwiftType() is extremely suspect.
DebugTypeInfo DbgTy(type.getSwiftType(), IGM.getTypeInfo(type), DeclCtx);
Parameters.push_back(getOrCreateType(DbgTy));
}
llvm::DITypeRefArray
IRGenDebugInfo::createParameterTypes(SILType SILTy, DeclContext *DeclCtx) {
if (!SILTy)
return nullptr;
return createParameterTypes(SILTy.castTo<SILFunctionType>(), DeclCtx);
}
static SILType getResultTypeForDebugInfo(CanSILFunctionType fnTy) {
if (fnTy->getNumAllResults() == 1) {
return fnTy->getAllResults()[0].getSILType();
} else if (!fnTy->getNumIndirectResults()) {
return fnTy->getSILResult();
} else {
SmallVector<TupleTypeElt, 4> eltTys;
for (auto &result : fnTy->getAllResults()) {
eltTys.push_back(result.getType());
}
return SILType::getPrimitiveAddressType(
CanType(TupleType::get(eltTys, fnTy->getASTContext())));
}
}
llvm::DITypeRefArray
IRGenDebugInfo::createParameterTypes(CanSILFunctionType FnTy,
DeclContext *DeclCtx) {
SmallVector<llvm::Metadata *, 16> Parameters;
GenericContextScope scope(IGM, FnTy->getGenericSignature());
// The function return type is the first element in the list.
createParameterType(Parameters, getResultTypeForDebugInfo(FnTy), DeclCtx);
// Actually, the input type is either a single type or a tuple
// type. We currently represent a function with one n-tuple argument
// as an n-ary function.
for (auto Param : FnTy->getParameters())
createParameterType(Parameters, Param.getSILType(), DeclCtx);
return DBuilder.getOrCreateTypeArray(Parameters);
}
/// FIXME: replace this condition with something more sane.
static bool isAllocatingConstructor(SILFunctionTypeRepresentation Rep,
DeclContext *DeclCtx) {
return Rep != SILFunctionTypeRepresentation::Method
&& DeclCtx && isa<ConstructorDecl>(DeclCtx);
}
llvm::DISubprogram *IRGenDebugInfo::emitFunction(
SILModule &SILMod, const SILDebugScope *DS, llvm::Function *Fn,
SILFunctionTypeRepresentation Rep, SILType SILTy, DeclContext *DeclCtx) {
auto Cached = ScopeCache.find(DS);
if (Cached != ScopeCache.end()) {
auto SP = cast<llvm::DISubprogram>(Cached->second);
// If we created the DISubprogram for a forward declaration,
// attach it to the function now.
if (!Fn->getSubprogram() && !Fn->isDeclaration())
Fn->setSubprogram(SP);
return SP;
}
// Some IRGen-generated helper functions don't have a corresponding
// SIL function, hence the dyn_cast.
SILFunction *SILFn = DS ? DS->Parent.dyn_cast<SILFunction *>() : nullptr;
StringRef LinkageName;
if (Fn)
LinkageName = Fn->getName();
else if (DS)
LinkageName = SILFn->getName();
else
llvm_unreachable("function has no mangled name");
StringRef Name;
if (DS) {
if (DS->Loc.isSILFile())
Name = SILFn->getName();
else
Name = getName(DS->Loc);
}
SILLocation::DebugLoc L;
unsigned ScopeLine = 0; /// The source line used for the function prologue.
// Bare functions and thunks should not have any line numbers. This
// is especially important for shared functions like reabstraction
// thunk helpers, where DS->Loc is an arbitrary location of whichever use
// was emitted first.
if (DS && (!SILFn || (!SILFn->isBare() && !SILFn->isThunk()))) {
L = DS->Loc.decodeDebugLoc(SM);
ScopeLine = L.Line;
if (!DS->Loc.isDebugInfoLoc())
L = SILLocation::decode(DS->Loc.getSourceLoc(), SM);
}
auto Line = L.Line;
auto File = getOrCreateFile(L.Filename);
llvm::DIScope *Scope = MainModule;
if (SILFn && SILFn->getDeclContext())
Scope = getOrCreateContext(SILFn->getDeclContext()->getParent());
// We know that main always comes from MainFile.
if (LinkageName == SWIFT_ENTRY_POINT_FUNCTION) {
if (!L.Filename)
File = MainFile;
Line = 1;
Name = LinkageName;
}
CanSILFunctionType FnTy = getFunctionType(SILTy);
auto Params = Opts.DebugInfoKind == IRGenDebugInfoKind::LineTables
? nullptr
: createParameterTypes(SILTy, DeclCtx);
llvm::DISubroutineType *DIFnTy = DBuilder.createSubroutineType(Params);
llvm::DITemplateParameterArray TemplateParameters = nullptr;
llvm::DISubprogram *Decl = nullptr;
// Various flags
bool IsLocalToUnit = Fn ? Fn->hasInternalLinkage() : true;
bool IsDefinition = true;
bool IsOptimized = Opts.Optimize;
unsigned Flags = 0;
// Mark everything that is not visible from the source code (i.e.,
// does not have a Swift name) as artificial, so the debugger can
// ignore it. Explicit closures are exempt from this rule. We also
// make an exception for main, which, albeit it does not
// have a Swift name, does appear prominently in the source code.
if ((Name.empty() && LinkageName != SWIFT_ENTRY_POINT_FUNCTION &&
!isExplicitClosure(DS)) ||
// ObjC thunks should also not show up in the linetable, because we
// never want to set a breakpoint there.
(Rep == SILFunctionTypeRepresentation::ObjCMethod) ||
isAllocatingConstructor(Rep, DeclCtx)) {
Flags |= llvm::DINode::FlagArtificial;
ScopeLine = 0;
}
if (FnTy && FnTy->getRepresentation()
== SILFunctionType::Representation::Block)
Flags |= llvm::DINode::FlagAppleBlock;
llvm::DISubprogram *SP = DBuilder.createFunction(
Scope, Name, LinkageName, File, Line, DIFnTy, IsLocalToUnit, IsDefinition,
ScopeLine, Flags, IsOptimized, TemplateParameters, Decl);
if (Fn && !Fn->isDeclaration())
Fn->setSubprogram(SP);
// RAUW the entry point function forward declaration with the real thing.
if (LinkageName == SWIFT_ENTRY_POINT_FUNCTION) {
assert(EntryPointFn->isTemporary() &&
"more than one entry point function");
EntryPointFn->replaceAllUsesWith(SP);
llvm::MDNode::deleteTemporary(EntryPointFn);
EntryPointFn = SP;
}
if (!DS)
return nullptr;
ScopeCache[DS] = llvm::TrackingMDNodeRef(SP);
return SP;
}
void IRGenDebugInfo::emitImport(ImportDecl *D) {
if (Opts.DebugInfoKind == IRGenDebugInfoKind::LineTables)
return;
swift::Module *M = IGM.Context.getModule(D->getModulePath());
if (!M &&
D->getModulePath()[0].first == IGM.Context.TheBuiltinModule->getName())
M = IGM.Context.TheBuiltinModule;
if (!M) {
assert(M && "Could not find module for import decl.");
return;
}
auto DIMod = getOrCreateModule({D->getModulePath(), M});
auto L = getDebugLoc(SM, D);
DBuilder.createImportedModule(getOrCreateFile(L.Filename), DIMod, L.Line);
}
llvm::DIModule *
IRGenDebugInfo::getOrCreateModule(ModuleDecl::ImportedModule M) {
const char *fn = getFilenameFromDC(M.second);
StringRef Path(fn ? fn : "");
if (M.first.empty()) {
StringRef Name = M.second->getName().str();
return getOrCreateModule(Name, TheCU, Name, Path);
}
unsigned I = 0;
SmallString<128> AccessPath;
llvm::DIScope *Scope = TheCU;
llvm::raw_svector_ostream OS(AccessPath);
for (auto elt : M.first) {
auto Component = elt.first.str();
if (++I > 1)
OS << '.';
OS << Component;
Scope = getOrCreateModule(AccessPath, Scope, Component, Path);
}
return cast<llvm::DIModule>(Scope);
}
llvm::DIModule *IRGenDebugInfo::getOrCreateModule(StringRef Key,
llvm::DIScope *Parent,
StringRef Name,
StringRef IncludePath) {
// Look in the cache first.
auto Val = DIModuleCache.find(Key);
if (Val != DIModuleCache.end())
return cast<llvm::DIModule>(Val->second);
StringRef ConfigMacros;
StringRef Sysroot = IGM.Context.SearchPathOpts.SDKPath;
auto M =
DBuilder.createModule(Parent, Name, ConfigMacros, IncludePath, Sysroot);
DIModuleCache.insert({Key, llvm::TrackingMDNodeRef(M)});
return M;
}
llvm::DISubprogram *IRGenDebugInfo::emitFunction(SILFunction &SILFn,
llvm::Function *Fn) {
auto *DS = SILFn.getDebugScope();
assert(DS && "SIL function has no debug scope");
(void) DS;
return emitFunction(SILFn.getModule(), SILFn.getDebugScope(), Fn,
SILFn.getRepresentation(), SILFn.getLoweredType(),
SILFn.getDeclContext());
}
void IRGenDebugInfo::emitArtificialFunction(SILModule &SILMod,
IRBuilder &Builder,
llvm::Function *Fn, SILType SILTy) {
RegularLocation ALoc = RegularLocation::getAutoGeneratedLocation();
const SILDebugScope *Scope = new (SILMod) SILDebugScope(ALoc);
emitFunction(SILMod, Scope, Fn, SILFunctionTypeRepresentation::Thin, SILTy);
setCurrentLoc(Builder, Scope);
}
TypeAliasDecl *IRGenDebugInfo::getMetadataType() {
if (!MetadataTypeDecl) {
MetadataTypeDecl = new (IGM.Context) TypeAliasDecl(
SourceLoc(), IGM.Context.getIdentifier("$swift.type"), SourceLoc(),
TypeLoc::withoutLoc(IGM.Context.TheRawPointerType),
/*genericparams*/nullptr, IGM.Context.TheBuiltinModule);
MetadataTypeDecl->computeType();
}
return MetadataTypeDecl;
}
void IRGenDebugInfo::emitTypeMetadata(IRGenFunction &IGF,
llvm::Value *Metadata,
StringRef Name) {
if (Opts.DebugInfoKind == IRGenDebugInfoKind::LineTables)
return;
auto TName = BumpAllocatedString(("$swift.type." + Name).str());
DebugTypeInfo DbgTy(getMetadataType(), Metadata->getType(),
(Size)CI.getTargetInfo().getPointerWidth(0),
(Alignment)CI.getTargetInfo().getPointerAlign(0));
emitVariableDeclaration(IGF.Builder, Metadata, DbgTy, IGF.getDebugScope(),
TName, 0,
// swift.type is already a pointer type,
// having a shadow copy doesn't add another
// layer of indirection.
DirectValue, ArtificialValue);
}
/// Return the DIFile that is the ancestor of Scope.
llvm::DIFile *IRGenDebugInfo::getFile(llvm::DIScope *Scope) {
while (!isa<llvm::DIFile>(Scope)) {
switch (Scope->getTag()) {
case llvm::dwarf::DW_TAG_lexical_block:
Scope = cast<llvm::DILexicalBlock>(Scope)->getScope();
break;
case llvm::dwarf::DW_TAG_subprogram:
Scope = cast<llvm::DISubprogram>(Scope)->getFile();
break;
default:
return MainFile;
}
if (Scope)
return MainFile;
}
return cast<llvm::DIFile>(Scope);
}
static Size
getStorageSize(const llvm::DataLayout &DL, ArrayRef<llvm::Value *> Storage) {
unsigned size = 0;
for (llvm::Value *Piece : Storage)
size += DL.getTypeSizeInBits(Piece->getType());
return Size(size);
}
void IRGenDebugInfo::emitVariableDeclaration(
IRBuilder &Builder, ArrayRef<llvm::Value *> Storage, DebugTypeInfo DbgTy,
const SILDebugScope *DS, StringRef Name, unsigned ArgNo,
IndirectionKind Indirection, ArtificialKind Artificial) {
// Self is always an artificial argument.
if (ArgNo > 0 && Name == IGM.Context.Id_self.str())
Artificial = ArtificialValue;
// FIXME: Make this an assertion.
// assert(DS && "variable has no scope");
if (!DS)
return;
if (Opts.DebugInfoKind == IRGenDebugInfoKind::LineTables)
return;
if (!DbgTy.size)
DbgTy.size = getStorageSize(IGM.DataLayout, Storage);
auto *Scope = dyn_cast<llvm::DILocalScope>(getOrCreateScope(DS));
assert(Scope && "variable has no local scope");
auto Loc = getDebugLoc(SM, DbgTy.getDecl());
// FIXME: this should be the scope of the type's declaration.
// If this is an argument, attach it to the current function scope.
if (ArgNo > 0) {
while (isa<llvm::DILexicalBlock>(Scope))
Scope = cast<llvm::DILexicalBlock>(Scope)->getScope();
}
assert(Scope && isa<llvm::DIScope>(Scope) && "variable has no scope");
llvm::DIFile *Unit = getFile(Scope);
llvm::DIType *DITy = getOrCreateType(DbgTy);
assert(DITy && "could not determine debug type of variable");
unsigned Line = Loc.Line;
unsigned Flags = 0;
if (Artificial || DITy->isArtificial() || DITy == InternalType)
Flags |= llvm::DINode::FlagArtificial;
// Create the descriptor for the variable.
llvm::DILocalVariable *Var = nullptr;
/// This could be Opts.Optimize if we would also unique DIVariables here.
bool Optimized = false;
Var = (ArgNo > 0)
? DBuilder.createParameterVariable(Scope, Name, ArgNo, Unit, Line, DITy,
Optimized, Flags)
: DBuilder.createAutoVariable(Scope, Name, Unit, Line, DITy,
Optimized, Flags);
// Insert a debug intrinsic into the current block.
auto *BB = Builder.GetInsertBlock();
bool IsPiece = Storage.size() > 1;
uint64_t SizeOfByte = CI.getTargetInfo().getCharWidth();
unsigned VarSizeInBits = getSizeInBits(Var, DIRefMap);
// Running variables for the current/previous piece.
unsigned SizeInBits = 0;
unsigned AlignInBits = SizeOfByte;
unsigned OffsetInBits = 0;
for (llvm::Value *Piece : Storage) {
SmallVector<uint64_t, 3> Operands;
if (Indirection)
Operands.push_back(llvm::dwarf::DW_OP_deref);
// There are variables without storage, such as "struct { func foo() {} }".
// Emit them as constant 0.
if (isa<llvm::UndefValue>(Piece))
Piece = llvm::ConstantInt::get(llvm::Type::getInt64Ty(M.getContext()), 0);
if (IsPiece) {
// Advance the offset and align it for the next piece.
OffsetInBits += llvm::alignTo(SizeInBits, AlignInBits);
SizeInBits = IGM.DataLayout.getTypeSizeInBits(Piece->getType());
AlignInBits = IGM.DataLayout.getABITypeAlignment(Piece->getType());
if (!AlignInBits)
AlignInBits = SizeOfByte;
// Sanity checks.
assert(SizeInBits && "zero-sized piece");
assert(SizeInBits < VarSizeInBits && "piece covers entire var");
assert(OffsetInBits+SizeInBits <= VarSizeInBits && "pars > totum");
(void) VarSizeInBits;
// Add the piece DWARF expression.
Operands.push_back(llvm::dwarf::DW_OP_bit_piece);
Operands.push_back(OffsetInBits);
Operands.push_back(SizeInBits);
}
emitDbgIntrinsic(BB, Piece, Var, DBuilder.createExpression(Operands), Line,
Loc.Column, Scope, DS);
}
// Emit locationless intrinsic for variables that were optimized away.
if (Storage.size() == 0) {
auto *undef = llvm::UndefValue::get(DbgTy.StorageType);
emitDbgIntrinsic(BB, undef, Var, DBuilder.createExpression(), Line,
Loc.Column, Scope, DS);
}
}
void IRGenDebugInfo::emitDbgIntrinsic(llvm::BasicBlock *BB,
llvm::Value *Storage,
llvm::DILocalVariable *Var,
llvm::DIExpression *Expr, unsigned Line,
unsigned Col, llvm::DILocalScope *Scope,
const SILDebugScope *DS) {
// Set the location/scope of the intrinsic.
auto *InlinedAt = createInlinedAt(DS);
auto DL = llvm::DebugLoc::get(Line, Col, Scope, InlinedAt);
// An alloca may only be described by exactly one dbg.declare.
if (isa<llvm::AllocaInst>(Storage) && llvm::FindAllocaDbgDeclare(Storage))
return;
// A dbg.declare is only meaningful if there is a single alloca for
// the variable that is live throughout the function. With SIL
// optimizations this is not guaranteed and a variable can end up in
// two allocas (for example, one function inlined twice).
if (!Opts.Optimize &&
(isa<llvm::AllocaInst>(Storage) ||
isa<llvm::UndefValue>(Storage)))
DBuilder.insertDeclare(Storage, Var, Expr, DL, BB);
else
DBuilder.insertDbgValueIntrinsic(Storage, 0, Var, Expr, DL, BB);
}
void IRGenDebugInfo::emitGlobalVariableDeclaration(llvm::GlobalValue *Var,
StringRef Name,
StringRef LinkageName,
DebugTypeInfo DbgTy,
Optional<SILLocation> Loc) {
if (Opts.DebugInfoKind == IRGenDebugInfoKind::LineTables)
return;
llvm::DIType *Ty = getOrCreateType(DbgTy);
if (Ty->isArtificial() || Ty == InternalType || !Loc)
// FIXME: Really these should be marked as artificial, but LLVM
// currently has no support for flags to be put on global