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
|
//===- RemarkTest.cpp - Remark unit tests -------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "mlir/IR/Diagnostics.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/Remarks.h"
#include "mlir/Remark/RemarkStreamer.h"
#include "mlir/Support/TypeID.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/IR/LLVMRemarkStreamer.h"
#include "llvm/Remarks/RemarkFormat.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/LogicalResult.h"
#include "llvm/Support/YAMLParser.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include <optional>
using namespace llvm;
using namespace mlir;
using namespace testing;
namespace {
TEST(Remark, TestOutputOptimizationRemark) {
std::string categoryVectorizer("Vectorizer");
std::string categoryRegister("Register");
std::string categoryUnroll("Unroll");
std::string categoryInliner("Inliner");
std::string categoryReroller("Reroller");
std::string myPassname1("myPass1");
SmallString<64> tmpPathStorage;
sys::fs::createUniquePath("remarks-%%%%%%.yaml", tmpPathStorage,
/*MakeAbsolute=*/true);
std::string yamlFile =
std::string(tmpPathStorage.data(), tmpPathStorage.size());
ASSERT_FALSE(yamlFile.empty());
{
MLIRContext context;
Location loc = UnknownLoc::get(&context);
context.printOpOnDiagnostic(true);
context.printStackTraceOnDiagnostic(true);
// Setup the remark engine
mlir::remark::RemarkCategories cats{/*all=*/"",
/*passed=*/categoryVectorizer,
/*missed=*/categoryUnroll,
/*analysis=*/categoryRegister,
/*failed=*/categoryInliner};
LogicalResult isEnabled =
mlir::remark::enableOptimizationRemarksWithLLVMStreamer(
context, yamlFile, llvm::remarks::Format::YAML, cats);
ASSERT_TRUE(succeeded(isEnabled)) << "Failed to enable remark engine";
// PASS: something succeeded
remark::passed(loc, remark::RemarkOpts::name("Pass1")
.category(categoryVectorizer)
.subCategory(myPassname1)
.function("bar"))
<< "vectorized loop" << remark::metric("tripCount", 128);
// ANALYSIS: neutral insight
remark::analysis(
loc, remark::RemarkOpts::name("Analysis1").category(categoryRegister))
<< "Kernel uses 168 registers";
// MISSED: explain why + suggest a fix
remark::missed(loc, remark::RemarkOpts::name("Miss1")
.category(categoryUnroll)
.subCategory(myPassname1))
<< remark::reason("not profitable at this size")
<< remark::suggest("increase unroll factor to >=4");
// FAILURE: action attempted but failed
remark::failed(loc, remark::RemarkOpts::name("Failed1")
.category(categoryInliner)
.subCategory(myPassname1))
<< remark::reason("failed due to unsupported pattern");
// FAILURE: Won't show up
remark::failed(loc, remark::RemarkOpts::name("Failed2")
.category(categoryReroller)
.subCategory(myPassname1))
<< remark::reason("failed due to rerolling pattern");
}
// Read the file
auto bufferOrErr = MemoryBuffer::getFile(yamlFile);
ASSERT_TRUE(static_cast<bool>(bufferOrErr)) << "Failed to open remarks file";
std::string content = bufferOrErr.get()->getBuffer().str();
EXPECT_THAT(content, HasSubstr("--- !Passed"));
EXPECT_THAT(content, HasSubstr("Name: Pass1"));
EXPECT_THAT(content, HasSubstr("Pass: 'Vectorizer:myPass1'"));
EXPECT_THAT(content, HasSubstr("Function: bar"));
EXPECT_THAT(content, HasSubstr("Remark: vectorized loop"));
EXPECT_THAT(content, HasSubstr("tripCount: '128'"));
EXPECT_THAT(content, HasSubstr("--- !Analysis"));
EXPECT_THAT(content, HasSubstr("Pass: Register"));
EXPECT_THAT(content, HasSubstr("Name: Analysis1"));
EXPECT_THAT(content, HasSubstr("Function: '<unknown function>'"));
EXPECT_THAT(content, HasSubstr("Remark: Kernel uses 168 registers"));
EXPECT_THAT(content, HasSubstr("--- !Missed"));
EXPECT_THAT(content, HasSubstr("Pass: 'Unroll:myPass1'"));
EXPECT_THAT(content, HasSubstr("Name: Miss1"));
EXPECT_THAT(content, HasSubstr("Function: '<unknown function>'"));
EXPECT_THAT(content,
HasSubstr("Reason: not profitable at this size"));
EXPECT_THAT(content,
HasSubstr("Suggestion: 'increase unroll factor to >=4'"));
EXPECT_THAT(content, HasSubstr("--- !Failure"));
EXPECT_THAT(content, HasSubstr("Pass: 'Inliner:myPass1'"));
EXPECT_THAT(content, HasSubstr("Name: Failed1"));
EXPECT_THAT(content, HasSubstr("Function: '<unknown function>'"));
EXPECT_THAT(content,
HasSubstr("Reason: failed due to unsupported pattern"));
EXPECT_THAT(content, Not(HasSubstr("Failed2")));
EXPECT_THAT(content, Not(HasSubstr("Reroller")));
// Also verify document order to avoid false positives.
size_t iPassed = content.find("--- !Passed");
size_t iAnalysis = content.find("--- !Analysis");
size_t iMissed = content.find("--- !Missed");
size_t iFailure = content.find("--- !Failure");
ASSERT_NE(iPassed, std::string::npos);
ASSERT_NE(iAnalysis, std::string::npos);
ASSERT_NE(iMissed, std::string::npos);
ASSERT_NE(iFailure, std::string::npos);
EXPECT_LT(iPassed, iAnalysis);
EXPECT_LT(iAnalysis, iMissed);
EXPECT_LT(iMissed, iFailure);
}
TEST(Remark, TestNoOutputOptimizationRemark) {
const auto *pass1Msg = "My message";
std::string categoryFailName("myImportantCategory");
std::string myPassname1("myPass1");
SmallString<64> tmpPathStorage;
sys::fs::createUniquePath("remarks-%%%%%%.yaml", tmpPathStorage,
/*MakeAbsolute=*/true);
std::string yamlFile =
std::string(tmpPathStorage.data(), tmpPathStorage.size());
ASSERT_FALSE(yamlFile.empty());
std::error_code ec =
llvm::sys::fs::remove(yamlFile, /*IgnoreNonExisting=*/true);
if (ec) {
FAIL() << "Failed to remove file " << yamlFile << ": " << ec.message();
}
{
MLIRContext context;
Location loc = UnknownLoc::get(&context);
remark::failed(loc, remark::RemarkOpts::name("myfail")
.category(categoryFailName)
.subCategory(myPassname1))
<< remark::reason(pass1Msg);
}
// No setup, so no output file should be created
// check!
bool fileExists = llvm::sys::fs::exists(yamlFile);
EXPECT_FALSE(fileExists)
<< "Expected no YAML file to be created without setupOptimizationRemarks";
}
TEST(Remark, TestOutputOptimizationRemarkDiagnostic) {
std::string categoryVectorizer("Vectorizer");
std::string categoryRegister("Register");
std::string categoryUnroll("Unroll");
std::string myPassname1("myPass1");
std::string fName("foo");
llvm::SmallVector<std::string> seenMsg;
{
MLIRContext context;
Location loc = UnknownLoc::get(&context);
context.printOpOnDiagnostic(true);
context.printStackTraceOnDiagnostic(true);
// Register a handler that captures the diagnostic.
ScopedDiagnosticHandler handler(&context, [&](Diagnostic &diag) {
seenMsg.push_back(diag.str());
return success();
});
// Setup the remark engine
mlir::remark::RemarkCategories cats{/*all=*/"",
/*passed=*/categoryVectorizer,
/*missed=*/categoryUnroll,
/*analysis=*/categoryRegister,
/*failed=*/categoryUnroll};
LogicalResult isEnabled =
remark::enableOptimizationRemarks(context, nullptr, cats, true);
ASSERT_TRUE(succeeded(isEnabled)) << "Failed to enable remark engine";
// PASS: something succeeded
remark::passed(loc, remark::RemarkOpts::name("pass1")
.category(categoryVectorizer)
.function(fName)
.subCategory(myPassname1))
<< "vectorized loop" << remark::metric("tripCount", 128);
// ANALYSIS: neutral insight
remark::analysis(loc, remark::RemarkOpts::name("Analysis1")
.category(categoryRegister)
.function(fName))
<< "Kernel uses 168 registers";
// MISSED: explain why + suggest a fix
int target = 128;
int tripBad = 4;
int threshold = 256;
remark::missed(loc, {"", categoryUnroll, "unroller2", ""})
<< remark::reason("tripCount={0} < threshold={1}", tripBad, threshold);
remark::missed(loc, {"", categoryUnroll, "", ""})
<< remark::reason("tripCount={0} < threshold={1}", tripBad, threshold)
<< remark::suggest("increase unroll to {0}", target);
// FAILURE: action attempted but failed
remark::failed(loc, {"", categoryUnroll, "", ""})
<< remark::reason("failed due to unsupported pattern");
}
// clang-format off
unsigned long expectedSize = 5;
ASSERT_EQ(seenMsg.size(), expectedSize);
EXPECT_EQ(seenMsg[0], "[Passed] pass1 | Category:Vectorizer:myPass1 | Function=foo | Remark=\"vectorized loop\", tripCount=128");
EXPECT_EQ(seenMsg[1], "[Analysis] Analysis1 | Category:Register | Function=foo | Remark=\"Kernel uses 168 registers\"");
EXPECT_EQ(seenMsg[2], "[Missed] | Category:Unroll:unroller2 | Reason=\"tripCount=4 < threshold=256\"");
EXPECT_EQ(seenMsg[3], "[Missed] | Category:Unroll | Reason=\"tripCount=4 < threshold=256\", Suggestion=\"increase unroll to 128\"");
EXPECT_EQ(seenMsg[4], "[Failure] | Category:Unroll | Reason=\"failed due to unsupported pattern\"");
// clang-format on
}
/// Custom remark streamer that prints remarks to stderr.
class MyCustomStreamer : public remark::detail::MLIRRemarkStreamerBase {
public:
MyCustomStreamer() = default;
void streamOptimizationRemark(const remark::detail::Remark &remark) override {
llvm::errs() << "Custom remark: ";
remark.print(llvm::errs(), true);
llvm::errs() << "\n";
}
};
TEST(Remark, TestCustomOptimizationRemarkDiagnostic) {
testing::internal::CaptureStderr();
const auto *pass1Msg = "My message";
const auto *pass2Msg = "My another message";
const auto *pass3Msg = "Do not show this message";
std::string categoryLoopunroll("LoopUnroll");
std::string categoryInline("Inliner");
std::string myPassname1("myPass1");
std::string myPassname2("myPass2");
{
MLIRContext context;
Location loc = UnknownLoc::get(&context);
// Setup the remark engine
mlir::remark::RemarkCategories cats{/*all=*/"",
/*passed=*/categoryLoopunroll,
/*missed=*/std::nullopt,
/*analysis=*/std::nullopt,
/*failed=*/categoryLoopunroll};
LogicalResult isEnabled = remark::enableOptimizationRemarks(
context, std::make_unique<MyCustomStreamer>(), cats, true);
ASSERT_TRUE(succeeded(isEnabled)) << "Failed to enable remark engine";
// Remark 1: pass, category LoopUnroll
remark::passed(loc, {"", categoryLoopunroll, myPassname1, ""}) << pass1Msg;
// Remark 2: failure, category LoopUnroll
remark::failed(loc, {"", categoryLoopunroll, myPassname2, ""})
<< remark::reason(pass2Msg);
// Remark 3: pass, category Inline (should not be printed)
remark::passed(loc, {"", categoryInline, myPassname1, ""}) << pass3Msg;
}
llvm::errs().flush();
std::string errOut = ::testing::internal::GetCapturedStderr();
// Expect exactly two "Custom remark:" lines.
auto first = errOut.find("Custom remark:");
EXPECT_NE(first, std::string::npos);
auto second = errOut.find("Custom remark:", first + 1);
EXPECT_NE(second, std::string::npos);
auto third = errOut.find("Custom remark:", second + 1);
EXPECT_EQ(third, std::string::npos);
// Containment checks for messages.
EXPECT_NE(errOut.find(pass1Msg), std::string::npos); // printed
EXPECT_NE(errOut.find(pass2Msg), std::string::npos); // printed
EXPECT_EQ(errOut.find(pass3Msg), std::string::npos); // filtered out
}
} // namespace
|