forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathModuleImport.cpp
More file actions
2745 lines (2419 loc) · 107 KB
/
ModuleImport.cpp
File metadata and controls
2745 lines (2419 loc) · 107 KB
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
//===- ModuleImport.cpp - LLVM to MLIR conversion ---------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the import of an LLVM IR module into an LLVM dialect
// module.
//
//===----------------------------------------------------------------------===//
#include "mlir/Target/LLVMIR/ModuleImport.h"
#include "mlir/IR/BuiltinAttributes.h"
#include "mlir/Target/LLVMIR/Import.h"
#include "AttrKindDetail.h"
#include "DataLayoutImporter.h"
#include "DebugImporter.h"
#include "LoopAnnotationImporter.h"
#include "mlir/Dialect/DLTI/DLTI.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Matchers.h"
#include "mlir/Interfaces/DataLayoutInterfaces.h"
#include "mlir/Tools/mlir-translate/Translation.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/TypeSwitch.h"
#include "llvm/IR/Comdat.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Operator.h"
#include "llvm/Support/ModRef.h"
using namespace mlir;
using namespace mlir::LLVM;
using namespace mlir::LLVM::detail;
#include "mlir/Dialect/LLVMIR/LLVMConversionEnumsFromLLVM.inc"
// Utility to print an LLVM value as a string for passing to emitError().
// FIXME: Diagnostic should be able to natively handle types that have
// operator << (raw_ostream&) defined.
static std::string diag(const llvm::Value &value) {
std::string str;
llvm::raw_string_ostream os(str);
os << value;
return str;
}
// Utility to print an LLVM metadata node as a string for passing
// to emitError(). The module argument is needed to print the nodes
// canonically numbered.
static std::string diagMD(const llvm::Metadata *node,
const llvm::Module *module) {
std::string str;
llvm::raw_string_ostream os(str);
node->print(os, module, /*IsForDebug=*/true);
return str;
}
/// Returns the name of the global_ctors global variables.
static constexpr StringRef getGlobalCtorsVarName() {
return "llvm.global_ctors";
}
/// Prefix used for symbols of nameless llvm globals.
static constexpr StringRef getNamelessGlobalPrefix() {
return "mlir.llvm.nameless_global";
}
/// Returns the name of the global_dtors global variables.
static constexpr StringRef getGlobalDtorsVarName() {
return "llvm.global_dtors";
}
/// Returns the symbol name for the module-level comdat operation. It must not
/// conflict with the user namespace.
static constexpr StringRef getGlobalComdatOpName() {
return "__llvm_global_comdat";
}
/// Converts the sync scope identifier of `inst` to the string representation
/// necessary to build an atomic LLVM dialect operation. Returns the empty
/// string if the operation has either no sync scope or the default system-level
/// sync scope attached. The atomic operations only set their sync scope
/// attribute if they have a non-default sync scope attached.
static StringRef getLLVMSyncScope(llvm::Instruction *inst) {
std::optional<llvm::SyncScope::ID> syncScopeID =
llvm::getAtomicSyncScopeID(inst);
if (!syncScopeID)
return "";
// Search the sync scope name for the given identifier. The default
// system-level sync scope thereby maps to the empty string.
SmallVector<StringRef> syncScopeName;
llvm::LLVMContext &llvmContext = inst->getContext();
llvmContext.getSyncScopeNames(syncScopeName);
auto *it = llvm::find_if(syncScopeName, [&](StringRef name) {
return *syncScopeID == llvmContext.getOrInsertSyncScopeID(name);
});
if (it != syncScopeName.end())
return *it;
llvm_unreachable("incorrect sync scope identifier");
}
/// Converts an array of unsigned indices to a signed integer position array.
static SmallVector<int64_t> getPositionFromIndices(ArrayRef<unsigned> indices) {
SmallVector<int64_t> position;
llvm::append_range(position, indices);
return position;
}
/// Converts the LLVM instructions that have a generated MLIR builder. Using a
/// static implementation method called from the module import ensures the
/// builders have to use the `moduleImport` argument and cannot directly call
/// import methods. As a result, both the intrinsic and the instruction MLIR
/// builders have to use the `moduleImport` argument and none of them has direct
/// access to the private module import methods.
static LogicalResult convertInstructionImpl(OpBuilder &odsBuilder,
llvm::Instruction *inst,
ModuleImport &moduleImport,
LLVMImportInterface &iface) {
// Copy the operands to an LLVM operands array reference for conversion.
SmallVector<llvm::Value *> operands(inst->operands());
ArrayRef<llvm::Value *> llvmOperands(operands);
// Convert all instructions that provide an MLIR builder.
if (iface.isConvertibleInstruction(inst->getOpcode()))
return iface.convertInstruction(odsBuilder, inst, llvmOperands,
moduleImport);
// TODO: Implement the `convertInstruction` hooks in the
// `LLVMDialectLLVMIRImportInterface` and move the following include there.
#include "mlir/Dialect/LLVMIR/LLVMOpFromLLVMIRConversions.inc"
return failure();
}
/// Get a topologically sorted list of blocks for the given basic blocks.
static SetVector<llvm::BasicBlock *>
getTopologicallySortedBlocks(ArrayRef<llvm::BasicBlock *> basicBlocks) {
SetVector<llvm::BasicBlock *> blocks;
for (llvm::BasicBlock *basicBlock : basicBlocks) {
if (!blocks.contains(basicBlock)) {
llvm::ReversePostOrderTraversal<llvm::BasicBlock *> traversal(basicBlock);
blocks.insert_range(traversal);
}
}
assert(blocks.size() == basicBlocks.size() && "some blocks are not sorted");
return blocks;
}
ModuleImport::ModuleImport(ModuleOp mlirModule,
std::unique_ptr<llvm::Module> llvmModule,
bool emitExpensiveWarnings,
bool importEmptyDICompositeTypes,
bool preferUnregisteredIntrinsics)
: builder(mlirModule->getContext()), context(mlirModule->getContext()),
mlirModule(mlirModule), llvmModule(std::move(llvmModule)),
iface(mlirModule->getContext()),
typeTranslator(*mlirModule->getContext()),
debugImporter(std::make_unique<DebugImporter>(
mlirModule, importEmptyDICompositeTypes)),
loopAnnotationImporter(
std::make_unique<LoopAnnotationImporter>(*this, builder)),
emitExpensiveWarnings(emitExpensiveWarnings),
preferUnregisteredIntrinsics(preferUnregisteredIntrinsics) {
builder.setInsertionPointToStart(mlirModule.getBody());
}
ComdatOp ModuleImport::getGlobalComdatOp() {
if (globalComdatOp)
return globalComdatOp;
OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToEnd(mlirModule.getBody());
globalComdatOp =
builder.create<ComdatOp>(mlirModule.getLoc(), getGlobalComdatOpName());
globalInsertionOp = globalComdatOp;
return globalComdatOp;
}
LogicalResult ModuleImport::processTBAAMetadata(const llvm::MDNode *node) {
Location loc = mlirModule.getLoc();
// If `node` is a valid TBAA root node, then return its optional identity
// string, otherwise return failure.
auto getIdentityIfRootNode =
[&](const llvm::MDNode *node) -> FailureOr<std::optional<StringRef>> {
// Root node, e.g.:
// !0 = !{!"Simple C/C++ TBAA"}
// !1 = !{}
if (node->getNumOperands() > 1)
return failure();
// If the operand is MDString, then assume that this is a root node.
if (node->getNumOperands() == 1)
if (const auto *op0 = dyn_cast<const llvm::MDString>(node->getOperand(0)))
return std::optional<StringRef>{op0->getString()};
return std::optional<StringRef>{};
};
// If `node` looks like a TBAA type descriptor metadata,
// then return true, if it is a valid node, and false otherwise.
// If it does not look like a TBAA type descriptor metadata, then
// return std::nullopt.
// If `identity` and `memberTypes/Offsets` are non-null, then they will
// contain the converted metadata operands for a valid TBAA node (i.e. when
// true is returned).
auto isTypeDescriptorNode = [&](const llvm::MDNode *node,
StringRef *identity = nullptr,
SmallVectorImpl<TBAAMemberAttr> *members =
nullptr) -> std::optional<bool> {
unsigned numOperands = node->getNumOperands();
// Type descriptor, e.g.:
// !1 = !{!"int", !0, /*optional*/i64 0} /* scalar int type */
// !2 = !{!"agg_t", !1, i64 0} /* struct agg_t { int x; } */
if (numOperands < 2)
return std::nullopt;
// TODO: support "new" format (D41501) for type descriptors,
// where the first operand is an MDNode.
const auto *identityNode =
dyn_cast<const llvm::MDString>(node->getOperand(0));
if (!identityNode)
return std::nullopt;
// This should be a type descriptor node.
if (identity)
*identity = identityNode->getString();
for (unsigned pairNum = 0, e = numOperands / 2; pairNum < e; ++pairNum) {
const auto *memberNode =
dyn_cast<const llvm::MDNode>(node->getOperand(2 * pairNum + 1));
if (!memberNode) {
emitError(loc) << "operand '" << 2 * pairNum + 1 << "' must be MDNode: "
<< diagMD(node, llvmModule.get());
return false;
}
int64_t offset = 0;
if (2 * pairNum + 2 >= numOperands) {
// Allow for optional 0 offset in 2-operand nodes.
if (numOperands != 2) {
emitError(loc) << "missing member offset: "
<< diagMD(node, llvmModule.get());
return false;
}
} else {
auto *offsetCI = llvm::mdconst::dyn_extract<llvm::ConstantInt>(
node->getOperand(2 * pairNum + 2));
if (!offsetCI) {
emitError(loc) << "operand '" << 2 * pairNum + 2
<< "' must be ConstantInt: "
<< diagMD(node, llvmModule.get());
return false;
}
offset = offsetCI->getZExtValue();
}
if (members)
members->push_back(TBAAMemberAttr::get(
cast<TBAANodeAttr>(tbaaMapping.lookup(memberNode)), offset));
}
return true;
};
// If `node` looks like a TBAA access tag metadata,
// then return true, if it is a valid node, and false otherwise.
// If it does not look like a TBAA access tag metadata, then
// return std::nullopt.
// If the other arguments are non-null, then they will contain
// the converted metadata operands for a valid TBAA node (i.e. when true is
// returned).
auto isTagNode = [&](const llvm::MDNode *node,
TBAATypeDescriptorAttr *baseAttr = nullptr,
TBAATypeDescriptorAttr *accessAttr = nullptr,
int64_t *offset = nullptr,
bool *isConstant = nullptr) -> std::optional<bool> {
// Access tag, e.g.:
// !3 = !{!1, !1, i64 0} /* scalar int access */
// !4 = !{!2, !1, i64 0} /* agg_t::x access */
//
// Optional 4th argument is ConstantInt 0/1 identifying whether
// the location being accessed is "constant" (see for details:
// https://llvm.org/docs/LangRef.html#representation).
unsigned numOperands = node->getNumOperands();
if (numOperands != 3 && numOperands != 4)
return std::nullopt;
const auto *baseMD = dyn_cast<const llvm::MDNode>(node->getOperand(0));
const auto *accessMD = dyn_cast<const llvm::MDNode>(node->getOperand(1));
auto *offsetCI =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(2));
if (!baseMD || !accessMD || !offsetCI)
return std::nullopt;
// TODO: support "new" TBAA format, if needed (see D41501).
// In the "old" format the first operand of the access type
// metadata is MDString. We have to distinguish the formats,
// because access tags have the same structure, but different
// meaning for the operands.
if (accessMD->getNumOperands() < 1 ||
!isa<llvm::MDString>(accessMD->getOperand(0)))
return std::nullopt;
bool isConst = false;
if (numOperands == 4) {
auto *isConstantCI =
llvm::mdconst::dyn_extract<llvm::ConstantInt>(node->getOperand(3));
if (!isConstantCI) {
emitError(loc) << "operand '3' must be ConstantInt: "
<< diagMD(node, llvmModule.get());
return false;
}
isConst = isConstantCI->getValue()[0];
}
if (baseAttr)
*baseAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(baseMD));
if (accessAttr)
*accessAttr = cast<TBAATypeDescriptorAttr>(tbaaMapping.lookup(accessMD));
if (offset)
*offset = offsetCI->getZExtValue();
if (isConstant)
*isConstant = isConst;
return true;
};
// Do a post-order walk over the TBAA Graph. Since a correct TBAA Graph is a
// DAG, a post-order walk guarantees that we convert any metadata node we
// depend on, prior to converting the current node.
DenseSet<const llvm::MDNode *> seen;
SmallVector<const llvm::MDNode *> workList;
workList.push_back(node);
while (!workList.empty()) {
const llvm::MDNode *current = workList.back();
if (tbaaMapping.contains(current)) {
// Already converted. Just pop from the worklist.
workList.pop_back();
continue;
}
// If any child of this node is not yet converted, don't pop the current
// node from the worklist but push the not-yet-converted children in the
// front of the worklist.
bool anyChildNotConverted = false;
for (const llvm::MDOperand &operand : current->operands())
if (auto *childNode = dyn_cast_or_null<const llvm::MDNode>(operand.get()))
if (!tbaaMapping.contains(childNode)) {
workList.push_back(childNode);
anyChildNotConverted = true;
}
if (anyChildNotConverted) {
// If this is the second time we failed to convert an element in the
// worklist it must be because a child is dependent on it being converted
// and we have a cycle in the graph. Cycles are not allowed in TBAA
// graphs.
if (!seen.insert(current).second)
return emitError(loc) << "has cycle in TBAA graph: "
<< diagMD(current, llvmModule.get());
continue;
}
// Otherwise simply import the current node.
workList.pop_back();
FailureOr<std::optional<StringRef>> rootNodeIdentity =
getIdentityIfRootNode(current);
if (succeeded(rootNodeIdentity)) {
StringAttr stringAttr = *rootNodeIdentity
? builder.getStringAttr(**rootNodeIdentity)
: nullptr;
// The root nodes do not have operands, so we can create
// the TBAARootAttr on the first walk.
tbaaMapping.insert({current, builder.getAttr<TBAARootAttr>(stringAttr)});
continue;
}
StringRef identity;
SmallVector<TBAAMemberAttr> members;
if (std::optional<bool> isValid =
isTypeDescriptorNode(current, &identity, &members)) {
assert(isValid.value() && "type descriptor node must be valid");
tbaaMapping.insert({current, builder.getAttr<TBAATypeDescriptorAttr>(
identity, members)});
continue;
}
TBAATypeDescriptorAttr baseAttr, accessAttr;
int64_t offset;
bool isConstant;
if (std::optional<bool> isValid =
isTagNode(current, &baseAttr, &accessAttr, &offset, &isConstant)) {
assert(isValid.value() && "access tag node must be valid");
tbaaMapping.insert(
{current, builder.getAttr<TBAATagAttr>(baseAttr, accessAttr, offset,
isConstant)});
continue;
}
return emitError(loc) << "unsupported TBAA node format: "
<< diagMD(current, llvmModule.get());
}
return success();
}
LogicalResult
ModuleImport::processAccessGroupMetadata(const llvm::MDNode *node) {
Location loc = mlirModule.getLoc();
if (failed(loopAnnotationImporter->translateAccessGroup(node, loc)))
return emitError(loc) << "unsupported access group node: "
<< diagMD(node, llvmModule.get());
return success();
}
LogicalResult
ModuleImport::processAliasScopeMetadata(const llvm::MDNode *node) {
Location loc = mlirModule.getLoc();
// Helper that verifies the node has a self reference operand.
auto verifySelfRef = [](const llvm::MDNode *node) {
return node->getNumOperands() != 0 &&
node == dyn_cast<llvm::MDNode>(node->getOperand(0));
};
auto verifySelfRefOrString = [](const llvm::MDNode *node) {
return node->getNumOperands() != 0 &&
(node == dyn_cast<llvm::MDNode>(node->getOperand(0)) ||
isa<llvm::MDString>(node->getOperand(0)));
};
// Helper that verifies the given operand is a string or does not exist.
auto verifyDescription = [](const llvm::MDNode *node, unsigned idx) {
return idx >= node->getNumOperands() ||
isa<llvm::MDString>(node->getOperand(idx));
};
auto getIdAttr = [&](const llvm::MDNode *node) -> Attribute {
if (verifySelfRef(node))
return DistinctAttr::create(builder.getUnitAttr());
auto name = cast<llvm::MDString>(node->getOperand(0));
return builder.getStringAttr(name->getString());
};
// Helper that creates an alias scope domain attribute.
auto createAliasScopeDomainOp = [&](const llvm::MDNode *aliasDomain) {
StringAttr description = nullptr;
if (aliasDomain->getNumOperands() >= 2)
if (auto *operand = dyn_cast<llvm::MDString>(aliasDomain->getOperand(1)))
description = builder.getStringAttr(operand->getString());
Attribute idAttr = getIdAttr(aliasDomain);
return builder.getAttr<AliasScopeDomainAttr>(idAttr, description);
};
// Collect the alias scopes and domains to translate them.
for (const llvm::MDOperand &operand : node->operands()) {
if (const auto *scope = dyn_cast<llvm::MDNode>(operand)) {
llvm::AliasScopeNode aliasScope(scope);
const llvm::MDNode *domain = aliasScope.getDomain();
// Verify the scope node points to valid scope metadata which includes
// verifying its domain. Perform the verification before looking it up in
// the alias scope mapping since it could have been inserted as a domain
// node before.
if (!verifySelfRefOrString(scope) || !domain ||
!verifyDescription(scope, 2))
return emitError(loc) << "unsupported alias scope node: "
<< diagMD(scope, llvmModule.get());
if (!verifySelfRefOrString(domain) || !verifyDescription(domain, 1))
return emitError(loc) << "unsupported alias domain node: "
<< diagMD(domain, llvmModule.get());
if (aliasScopeMapping.contains(scope))
continue;
// Convert the domain metadata node if it has not been translated before.
auto it = aliasScopeMapping.find(aliasScope.getDomain());
if (it == aliasScopeMapping.end()) {
auto aliasScopeDomainOp = createAliasScopeDomainOp(domain);
it = aliasScopeMapping.try_emplace(domain, aliasScopeDomainOp).first;
}
// Convert the scope metadata node if it has not been converted before.
StringAttr description = nullptr;
if (!aliasScope.getName().empty())
description = builder.getStringAttr(aliasScope.getName());
Attribute idAttr = getIdAttr(scope);
auto aliasScopeOp = builder.getAttr<AliasScopeAttr>(
idAttr, cast<AliasScopeDomainAttr>(it->second), description);
aliasScopeMapping.try_emplace(aliasScope.getNode(), aliasScopeOp);
}
}
return success();
}
FailureOr<SmallVector<AliasScopeAttr>>
ModuleImport::lookupAliasScopeAttrs(const llvm::MDNode *node) const {
SmallVector<AliasScopeAttr> aliasScopes;
aliasScopes.reserve(node->getNumOperands());
for (const llvm::MDOperand &operand : node->operands()) {
auto *node = cast<llvm::MDNode>(operand.get());
aliasScopes.push_back(
dyn_cast_or_null<AliasScopeAttr>(aliasScopeMapping.lookup(node)));
}
// Return failure if one of the alias scope lookups failed.
if (llvm::is_contained(aliasScopes, nullptr))
return failure();
return aliasScopes;
}
void ModuleImport::addDebugIntrinsic(llvm::CallInst *intrinsic) {
debugIntrinsics.insert(intrinsic);
}
LogicalResult ModuleImport::convertModuleFlagsMetadata() {
SmallVector<llvm::Module::ModuleFlagEntry> llvmModuleFlags;
llvmModule->getModuleFlagsMetadata(llvmModuleFlags);
SmallVector<Attribute> moduleFlags;
for (const auto [behavior, key, val] : llvmModuleFlags) {
Attribute valAttr = nullptr;
if (auto *constInt = llvm::mdconst::dyn_extract<llvm::ConstantInt>(val)) {
valAttr = builder.getI32IntegerAttr(constInt->getZExtValue());
} else if (auto *mdString = dyn_cast<llvm::MDString>(val)) {
valAttr = builder.getStringAttr(mdString->getString());
} else {
emitWarning(mlirModule.getLoc())
<< "unsupported module flag value: " << diagMD(val, llvmModule.get());
continue;
}
moduleFlags.push_back(builder.getAttr<ModuleFlagAttr>(
convertModFlagBehaviorFromLLVM(behavior),
builder.getStringAttr(key->getString()), valAttr));
}
if (!moduleFlags.empty())
builder.create<LLVM::ModuleFlagsOp>(mlirModule.getLoc(),
builder.getArrayAttr(moduleFlags));
return success();
}
LogicalResult ModuleImport::convertLinkerOptionsMetadata() {
for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
if (named.getName() != "llvm.linker.options")
continue;
// llvm.linker.options operands are lists of strings.
for (const llvm::MDNode *node : named.operands()) {
SmallVector<StringRef> options;
options.reserve(node->getNumOperands());
for (const llvm::MDOperand &option : node->operands())
options.push_back(cast<llvm::MDString>(option)->getString());
builder.create<LLVM::LinkerOptionsOp>(mlirModule.getLoc(),
builder.getStrArrayAttr(options));
}
}
return success();
}
LogicalResult ModuleImport::convertDependentLibrariesMetadata() {
for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
if (named.getName() != "llvm.dependent-libraries")
continue;
SmallVector<StringRef> libraries;
for (const llvm::MDNode *node : named.operands()) {
if (node->getNumOperands() == 1)
if (auto *mdString = dyn_cast<llvm::MDString>(node->getOperand(0)))
libraries.push_back(mdString->getString());
}
if (!libraries.empty())
mlirModule->setAttr(LLVM::LLVMDialect::getDependentLibrariesAttrName(),
builder.getStrArrayAttr(libraries));
}
return success();
}
LogicalResult ModuleImport::convertIdentMetadata() {
for (const llvm::NamedMDNode &named : llvmModule->named_metadata()) {
// llvm.ident should have a single operand. That operand is itself an
// MDNode with a single string operand.
if (named.getName() != LLVMDialect::getIdentAttrName())
continue;
if (named.getNumOperands() == 1)
if (auto *md = dyn_cast<llvm::MDNode>(named.getOperand(0)))
if (md->getNumOperands() == 1)
if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
mlirModule->setAttr(LLVMDialect::getIdentAttrName(),
builder.getStringAttr(mdStr->getString()));
}
return success();
}
LogicalResult ModuleImport::convertCommandlineMetadata() {
for (const llvm::NamedMDNode &nmd : llvmModule->named_metadata()) {
// llvm.commandline should have a single operand. That operand is itself an
// MDNode with a single string operand.
if (nmd.getName() != LLVMDialect::getCommandlineAttrName())
continue;
if (nmd.getNumOperands() == 1)
if (auto *md = dyn_cast<llvm::MDNode>(nmd.getOperand(0)))
if (md->getNumOperands() == 1)
if (auto *mdStr = dyn_cast<llvm::MDString>(md->getOperand(0)))
mlirModule->setAttr(LLVMDialect::getCommandlineAttrName(),
builder.getStringAttr(mdStr->getString()));
}
return success();
}
LogicalResult ModuleImport::convertMetadata() {
OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToEnd(mlirModule.getBody());
for (const llvm::Function &func : llvmModule->functions()) {
for (const llvm::Instruction &inst : llvm::instructions(func)) {
// Convert access group metadata nodes.
if (llvm::MDNode *node =
inst.getMetadata(llvm::LLVMContext::MD_access_group))
if (failed(processAccessGroupMetadata(node)))
return failure();
// Convert alias analysis metadata nodes.
llvm::AAMDNodes aliasAnalysisNodes = inst.getAAMetadata();
if (!aliasAnalysisNodes)
continue;
if (aliasAnalysisNodes.TBAA)
if (failed(processTBAAMetadata(aliasAnalysisNodes.TBAA)))
return failure();
if (aliasAnalysisNodes.Scope)
if (failed(processAliasScopeMetadata(aliasAnalysisNodes.Scope)))
return failure();
if (aliasAnalysisNodes.NoAlias)
if (failed(processAliasScopeMetadata(aliasAnalysisNodes.NoAlias)))
return failure();
}
}
if (failed(convertLinkerOptionsMetadata()))
return failure();
if (failed(convertDependentLibrariesMetadata()))
return failure();
if (failed(convertModuleFlagsMetadata()))
return failure();
if (failed(convertIdentMetadata()))
return failure();
if (failed(convertCommandlineMetadata()))
return failure();
return success();
}
void ModuleImport::processComdat(const llvm::Comdat *comdat) {
if (comdatMapping.contains(comdat))
return;
ComdatOp comdatOp = getGlobalComdatOp();
OpBuilder::InsertionGuard guard(builder);
builder.setInsertionPointToEnd(&comdatOp.getBody().back());
auto selectorOp = builder.create<ComdatSelectorOp>(
mlirModule.getLoc(), comdat->getName(),
convertComdatFromLLVM(comdat->getSelectionKind()));
auto symbolRef =
SymbolRefAttr::get(builder.getContext(), getGlobalComdatOpName(),
FlatSymbolRefAttr::get(selectorOp.getSymNameAttr()));
comdatMapping.try_emplace(comdat, symbolRef);
}
LogicalResult ModuleImport::convertComdats() {
for (llvm::GlobalVariable &globalVar : llvmModule->globals())
if (globalVar.hasComdat())
processComdat(globalVar.getComdat());
for (llvm::Function &func : llvmModule->functions())
if (func.hasComdat())
processComdat(func.getComdat());
return success();
}
LogicalResult ModuleImport::convertGlobals() {
for (llvm::GlobalVariable &globalVar : llvmModule->globals()) {
if (globalVar.getName() == getGlobalCtorsVarName() ||
globalVar.getName() == getGlobalDtorsVarName()) {
if (failed(convertGlobalCtorsAndDtors(&globalVar))) {
return emitError(UnknownLoc::get(context))
<< "unhandled global variable: " << diag(globalVar);
}
continue;
}
if (failed(convertGlobal(&globalVar))) {
return emitError(UnknownLoc::get(context))
<< "unhandled global variable: " << diag(globalVar);
}
}
return success();
}
LogicalResult ModuleImport::convertAliases() {
for (llvm::GlobalAlias &alias : llvmModule->aliases()) {
if (failed(convertAlias(&alias))) {
return emitError(UnknownLoc::get(context))
<< "unhandled global alias: " << diag(alias);
}
}
return success();
}
LogicalResult ModuleImport::convertDataLayout() {
Location loc = mlirModule.getLoc();
DataLayoutImporter dataLayoutImporter(context, llvmModule->getDataLayout());
if (!dataLayoutImporter.getDataLayout())
return emitError(loc, "cannot translate data layout: ")
<< dataLayoutImporter.getLastToken();
for (StringRef token : dataLayoutImporter.getUnhandledTokens())
emitWarning(loc, "unhandled data layout token: ") << token;
mlirModule->setAttr(DLTIDialect::kDataLayoutAttrName,
dataLayoutImporter.getDataLayout());
return success();
}
void ModuleImport::convertTargetTriple() {
mlirModule->setAttr(
LLVM::LLVMDialect::getTargetTripleAttrName(),
builder.getStringAttr(llvmModule->getTargetTriple().str()));
}
LogicalResult ModuleImport::convertFunctions() {
for (llvm::Function &func : llvmModule->functions())
if (failed(processFunction(&func)))
return failure();
return success();
}
void ModuleImport::setNonDebugMetadataAttrs(llvm::Instruction *inst,
Operation *op) {
SmallVector<std::pair<unsigned, llvm::MDNode *>> allMetadata;
inst->getAllMetadataOtherThanDebugLoc(allMetadata);
for (auto &[kind, node] : allMetadata) {
if (!iface.isConvertibleMetadata(kind))
continue;
if (failed(iface.setMetadataAttrs(builder, kind, node, op, *this))) {
if (emitExpensiveWarnings) {
Location loc = debugImporter->translateLoc(inst->getDebugLoc());
emitWarning(loc) << "unhandled metadata: "
<< diagMD(node, llvmModule.get()) << " on "
<< diag(*inst);
}
}
}
}
void ModuleImport::setIntegerOverflowFlags(llvm::Instruction *inst,
Operation *op) const {
auto iface = cast<IntegerOverflowFlagsInterface>(op);
IntegerOverflowFlags value = {};
value = bitEnumSet(value, IntegerOverflowFlags::nsw, inst->hasNoSignedWrap());
value =
bitEnumSet(value, IntegerOverflowFlags::nuw, inst->hasNoUnsignedWrap());
iface.setOverflowFlags(value);
}
void ModuleImport::setExactFlag(llvm::Instruction *inst, Operation *op) const {
auto iface = cast<ExactFlagInterface>(op);
iface.setIsExact(inst->isExact());
}
void ModuleImport::setDisjointFlag(llvm::Instruction *inst,
Operation *op) const {
auto iface = cast<DisjointFlagInterface>(op);
auto instDisjoint = cast<llvm::PossiblyDisjointInst>(inst);
iface.setIsDisjoint(instDisjoint->isDisjoint());
}
void ModuleImport::setNonNegFlag(llvm::Instruction *inst, Operation *op) const {
auto iface = cast<NonNegFlagInterface>(op);
iface.setNonNeg(inst->hasNonNeg());
}
void ModuleImport::setFastmathFlagsAttr(llvm::Instruction *inst,
Operation *op) const {
auto iface = cast<FastmathFlagsInterface>(op);
// Even if the imported operation implements the fastmath interface, the
// original instruction may not have fastmath flags set. Exit if an
// instruction, such as a non floating-point function call, does not have
// fastmath flags.
if (!isa<llvm::FPMathOperator>(inst))
return;
llvm::FastMathFlags flags = inst->getFastMathFlags();
// Set the fastmath bits flag-by-flag.
FastmathFlags value = {};
value = bitEnumSet(value, FastmathFlags::nnan, flags.noNaNs());
value = bitEnumSet(value, FastmathFlags::ninf, flags.noInfs());
value = bitEnumSet(value, FastmathFlags::nsz, flags.noSignedZeros());
value = bitEnumSet(value, FastmathFlags::arcp, flags.allowReciprocal());
value = bitEnumSet(value, FastmathFlags::contract, flags.allowContract());
value = bitEnumSet(value, FastmathFlags::afn, flags.approxFunc());
value = bitEnumSet(value, FastmathFlags::reassoc, flags.allowReassoc());
FastmathFlagsAttr attr = FastmathFlagsAttr::get(builder.getContext(), value);
iface->setAttr(iface.getFastmathAttrName(), attr);
}
/// Returns `type` if it is a builtin integer or floating-point vector type that
/// can be used to create an attribute or nullptr otherwise. If provided,
/// `arrayShape` is added to the shape of the vector to create an attribute that
/// matches an array of vectors.
static Type getVectorTypeForAttr(Type type, ArrayRef<int64_t> arrayShape = {}) {
if (!LLVM::isCompatibleVectorType(type))
return {};
llvm::ElementCount numElements = LLVM::getVectorNumElements(type);
if (numElements.isScalable()) {
emitError(UnknownLoc::get(type.getContext()))
<< "scalable vectors not supported";
return {};
}
// An LLVM dialect vector can only contain scalars.
Type elementType = cast<VectorType>(type).getElementType();
if (!elementType.isIntOrFloat())
return {};
SmallVector<int64_t> shape(arrayShape);
shape.push_back(numElements.getKnownMinValue());
return VectorType::get(shape, elementType);
}
Type ModuleImport::getBuiltinTypeForAttr(Type type) {
if (!type)
return {};
// Return builtin integer and floating-point types as is.
if (type.isIntOrFloat())
return type;
// Return builtin vectors of integer and floating-point types as is.
if (Type vectorType = getVectorTypeForAttr(type))
return vectorType;
// Multi-dimensional array types are converted to tensors or vectors,
// depending on the innermost type being a scalar or a vector.
SmallVector<int64_t> arrayShape;
while (auto arrayType = dyn_cast<LLVMArrayType>(type)) {
arrayShape.push_back(arrayType.getNumElements());
type = arrayType.getElementType();
}
if (type.isIntOrFloat())
return RankedTensorType::get(arrayShape, type);
return getVectorTypeForAttr(type, arrayShape);
}
/// Returns an integer or float attribute for the provided scalar constant
/// `constScalar` or nullptr if the conversion fails.
static TypedAttr getScalarConstantAsAttr(OpBuilder &builder,
llvm::Constant *constScalar) {
MLIRContext *context = builder.getContext();
// Convert scalar intergers.
if (auto *constInt = dyn_cast<llvm::ConstantInt>(constScalar)) {
return builder.getIntegerAttr(
IntegerType::get(context, constInt->getBitWidth()),
constInt->getValue());
}
// Convert scalar floats.
if (auto *constFloat = dyn_cast<llvm::ConstantFP>(constScalar)) {
llvm::Type *type = constFloat->getType();
FloatType floatType =
type->isBFloatTy()
? BFloat16Type::get(context)
: LLVM::detail::getFloatType(context, type->getScalarSizeInBits());
if (!floatType) {
emitError(UnknownLoc::get(builder.getContext()))
<< "unexpected floating-point type";
return {};
}
return builder.getFloatAttr(floatType, constFloat->getValueAPF());
}
return {};
}
/// Returns an integer or float attribute array for the provided constant
/// sequence `constSequence` or nullptr if the conversion fails.
static SmallVector<Attribute>
getSequenceConstantAsAttrs(OpBuilder &builder,
llvm::ConstantDataSequential *constSequence) {
SmallVector<Attribute> elementAttrs;
elementAttrs.reserve(constSequence->getNumElements());
for (auto idx : llvm::seq<int64_t>(0, constSequence->getNumElements())) {
llvm::Constant *constElement = constSequence->getElementAsConstant(idx);
elementAttrs.push_back(getScalarConstantAsAttr(builder, constElement));
}
return elementAttrs;
}
Attribute ModuleImport::getConstantAsAttr(llvm::Constant *constant) {
// Convert scalar constants.
if (Attribute scalarAttr = getScalarConstantAsAttr(builder, constant))
return scalarAttr;
// Returns the static shape of the provided type if possible.
auto getConstantShape = [&](llvm::Type *type) {
return llvm::dyn_cast_if_present<ShapedType>(
getBuiltinTypeForAttr(convertType(type)));
};
// Convert one-dimensional constant arrays or vectors that store 1/2/4/8-byte
// integer or half/bfloat/float/double values.
if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(constant)) {
if (constArray->isString())
return builder.getStringAttr(constArray->getAsString());
auto shape = getConstantShape(constArray->getType());
if (!shape)
return {};
// Convert splat constants to splat elements attributes.
auto *constVector = dyn_cast<llvm::ConstantDataVector>(constant);
if (constVector && constVector->isSplat()) {
// A vector is guaranteed to have at least size one.
Attribute splatAttr = getScalarConstantAsAttr(
builder, constVector->getElementAsConstant(0));
return SplatElementsAttr::get(shape, splatAttr);
}
// Convert non-splat constants to dense elements attributes.
SmallVector<Attribute> elementAttrs =
getSequenceConstantAsAttrs(builder, constArray);
return DenseElementsAttr::get(shape, elementAttrs);
}
// Convert multi-dimensional constant aggregates that store all kinds of
// integer and floating-point types.
if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(constant)) {
auto shape = getConstantShape(constAggregate->getType());
if (!shape)
return {};
// Collect the aggregate elements in depths first order.
SmallVector<Attribute> elementAttrs;
SmallVector<llvm::Constant *> workList = {constAggregate};
while (!workList.empty()) {
llvm::Constant *current = workList.pop_back_val();
// Append any nested aggregates in reverse order to ensure the head
// element of the nested aggregates is at the back of the work list.
if (auto *constAggregate = dyn_cast<llvm::ConstantAggregate>(current)) {
for (auto idx :
reverse(llvm::seq<int64_t>(0, constAggregate->getNumOperands())))
workList.push_back(constAggregate->getAggregateElement(idx));
continue;
}
// Append the elements of nested constant arrays or vectors that store
// 1/2/4/8-byte integer or half/bfloat/float/double values.
if (auto *constArray = dyn_cast<llvm::ConstantDataSequential>(current)) {
SmallVector<Attribute> attrs =
getSequenceConstantAsAttrs(builder, constArray);
elementAttrs.append(attrs.begin(), attrs.end());
continue;
}
// Append nested scalar constants that store all kinds of integer and
// floating-point types.
if (Attribute scalarAttr = getScalarConstantAsAttr(builder, current)) {
elementAttrs.push_back(scalarAttr);
continue;
}
// Bail if the aggregate contains a unsupported constant type such as a
// constant expression.
return {};
}
return DenseElementsAttr::get(shape, elementAttrs);
}
// Convert zero aggregates.
if (auto *constZero = dyn_cast<llvm::ConstantAggregateZero>(constant)) {
auto shape = llvm::dyn_cast_if_present<ShapedType>(
getBuiltinTypeForAttr(convertType(constZero->getType())));
if (!shape)
return {};
// Convert zero aggregates with a static shape to splat elements attributes.
Attribute splatAttr = builder.getZeroAttr(shape.getElementType());
assert(splatAttr && "expected non-null zero attribute for scalar types");
return SplatElementsAttr::get(shape, splatAttr);
}
return {};
}
FlatSymbolRefAttr
ModuleImport::getOrCreateNamelessSymbolName(llvm::GlobalVariable *globalVar) {
assert(globalVar->getName().empty() &&
"expected to work with a nameless global");
auto [it, success] = namelessGlobals.try_emplace(globalVar);
if (!success)