1 //===- Region.cpp ---------------------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/SandboxIR/Region.h"
10 #include "llvm/SandboxIR/Function.h"
12 namespace llvm::sandboxir
{
14 Region::Region(Context
&Ctx
) : Ctx(Ctx
) {
15 LLVMContext
&LLVMCtx
= Ctx
.LLVMCtx
;
16 auto *RegionStrMD
= MDString::get(LLVMCtx
, RegionStr
);
17 RegionMDN
= MDNode::getDistinct(LLVMCtx
, {RegionStrMD
});
19 CreateInstCB
= Ctx
.registerCreateInstrCallback(
20 [this](Instruction
*NewInst
) { add(NewInst
); });
21 EraseInstCB
= Ctx
.registerEraseInstrCallback(
22 [this](Instruction
*ErasedInst
) { remove(ErasedInst
); });
26 Ctx
.unregisterCreateInstrCallback(CreateInstCB
);
27 Ctx
.unregisterEraseInstrCallback(EraseInstCB
);
30 void Region::add(Instruction
*I
) {
32 // TODO: Consider tagging instructions lazily.
33 cast
<llvm::Instruction
>(I
->Val
)->setMetadata(MDKind
, RegionMDN
);
36 void Region::remove(Instruction
*I
) {
38 cast
<llvm::Instruction
>(I
->Val
)->setMetadata(MDKind
, nullptr);
42 bool Region::operator==(const Region
&Other
) const {
43 if (Insts
.size() != Other
.Insts
.size())
45 if (!std::is_permutation(Insts
.begin(), Insts
.end(), Other
.Insts
.begin()))
50 void Region::dump(raw_ostream
&OS
) const {
55 void Region::dump() const {
61 SmallVector
<std::unique_ptr
<Region
>> Region::createRegionsFromMD(Function
&F
) {
62 SmallVector
<std::unique_ptr
<Region
>> Regions
;
63 DenseMap
<MDNode
*, Region
*> MDNToRegion
;
64 auto &Ctx
= F
.getContext();
65 for (BasicBlock
&BB
: F
) {
66 for (Instruction
&Inst
: BB
) {
67 if (auto *MDN
= cast
<llvm::Instruction
>(Inst
.Val
)->getMetadata(MDKind
)) {
69 auto It
= MDNToRegion
.find(MDN
);
70 if (It
== MDNToRegion
.end()) {
71 Regions
.push_back(std::make_unique
<Region
>(Ctx
));
72 R
= Regions
.back().get();
84 } // namespace llvm::sandboxir