Debian Codegraph @

llvm/unittests/Analysis/IR2VecTest.cpp

raw
1 //===- IR2VecTest.cpp - Unit tests for IR2Vec -----------------------------==//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "llvm/Analysis/IR2Vec.h"
10 #include "llvm/IR/Constants.h"
11 #include "llvm/IR/Instruction.h"
12 #include "llvm/IR/Instructions.h"
13 #include "llvm/IR/LLVMContext.h"
14 #include "llvm/IR/Module.h"
15 #include "llvm/IR/Type.h"
16 #include "llvm/Support/Error.h"
17 #include "llvm/Support/JSON.h"
18
19 #include "gmock/gmock.h"
20 #include "gtest/gtest.h"
21 #include <map>
22 #include <vector>
23
24 using namespace llvm;
25 using namespace ir2vec;
26 using namespace ::testing;
27
28 namespace {
29
30 class TestableEmbedder : public Embedder {
31 public:
32 TestableEmbedder(const Function &F, const Vocabulary &V) : Embedder(F, V) {}
33 void computeEmbeddings() const override {}
34 void computeEmbeddings(const BasicBlock &BB) const override {}
35 };
36
37 TEST(EmbeddingTest, ConstructorsAndAccessors) {
38 // Default constructor
39 {
40 Embedding E;
41 EXPECT_TRUE(E.empty());
42 EXPECT_EQ(E.size(), 0u);
43 }
44
45 // Constructor with const std::vector<double>&
46 {
47 std::vector<double> Data = {1.0, 2.0, 3.0};
48 Embedding E(Data);
49 EXPECT_FALSE(E.empty());
50 ASSERT_THAT(E, SizeIs(3u));
51 EXPECT_THAT(E.getData(), ElementsAre(1.0, 2.0, 3.0));
52 EXPECT_EQ(E[0], 1.0);
53 EXPECT_EQ(E[1], 2.0);
54 EXPECT_EQ(E[2], 3.0);
55 }
56
57 // Constructor with std::vector<double>&&
58 {
59 Embedding E(std::vector<double>({4.0, 5.0}));
60 ASSERT_THAT(E, SizeIs(2u));
61 EXPECT_THAT(E.getData(), ElementsAre(4.0, 5.0));
62 }
63
64 // Constructor with std::initializer_list<double>
65 {
66 Embedding E({6.0, 7.0, 8.0, 9.0});
67 ASSERT_THAT(E, SizeIs(4u));
68 EXPECT_THAT(E.getData(), ElementsAre(6.0, 7.0, 8.0, 9.0));
69 EXPECT_EQ(E[0], 6.0);
70 E[0] = 6.5;
71 EXPECT_EQ(E[0], 6.5);
72 }
73
74 // Constructor with size_t
75 {
76 Embedding E(5);
77 ASSERT_THAT(E, SizeIs(5u));
78 EXPECT_THAT(E.getData(), ElementsAre(0.0, 0.0, 0.0, 0.0, 0.0));
79 }
80
81 // Constructor with size_t and double
82 {
83 Embedding E(5, 1.5);
84 ASSERT_THAT(E, SizeIs(5u));
85 EXPECT_THAT(E.getData(), ElementsAre(1.5, 1.5, 1.5, 1.5, 1.5));
86 }
87
88 // Test iterators
89 {
90 Embedding E({6.5, 7.0, 8.0, 9.0});
91 std::vector<double> VecE;
92 for (double Val : E) {
93 VecE.push_back(Val);
94 }
95 EXPECT_THAT(VecE, ElementsAre(6.5, 7.0, 8.0, 9.0));
96
97 const Embedding CE = E;
98 std::vector<double> VecCE;
99 for (const double &Val : CE) {
100 VecCE.push_back(Val);
101 }
102 EXPECT_THAT(VecCE, ElementsAre(6.5, 7.0, 8.0, 9.0));
103
104 EXPECT_EQ(*E.begin(), 6.5);
105 EXPECT_EQ(*(E.end() - 1), 9.0);
106 EXPECT_EQ(*CE.cbegin(), 6.5);
107 EXPECT_EQ(*(CE.cend() - 1), 9.0);
108 }
109 }
110
111 TEST(EmbeddingTest, AddVectorsOutOfPlace) {
112 Embedding E1 = {1.0, 2.0, 3.0};
113 Embedding E2 = {0.5, 1.5, -1.0};
114
115 Embedding E3 = E1 + E2;
116 EXPECT_THAT(E3, ElementsAre(1.5, 3.5, 2.0));
117
118 // Check that E1 and E2 are unchanged
119 EXPECT_THAT(E1, ElementsAre(1.0, 2.0, 3.0));
120 EXPECT_THAT(E2, ElementsAre(0.5, 1.5, -1.0));
121 }
122
123 TEST(EmbeddingTest, AddVectors) {
124 Embedding E1 = {1.0, 2.0, 3.0};
125 Embedding E2 = {0.5, 1.5, -1.0};
126
127 E1 += E2;
128 EXPECT_THAT(E1, ElementsAre(1.5, 3.5, 2.0));
129
130 // Check that E2 is unchanged
131 EXPECT_THAT(E2, ElementsAre(0.5, 1.5, -1.0));
132 }
133
134 TEST(EmbeddingTest, SubtractVectorsOutOfPlace) {
135 Embedding E1 = {1.0, 2.0, 3.0};
136 Embedding E2 = {0.5, 1.5, -1.0};
137
138 Embedding E3 = E1 - E2;
139 EXPECT_THAT(E3, ElementsAre(0.5, 0.5, 4.0));
140
141 // Check that E1 and E2 are unchanged
142 EXPECT_THAT(E1, ElementsAre(1.0, 2.0, 3.0));
143 EXPECT_THAT(E2, ElementsAre(0.5, 1.5, -1.0));
144 }
145
146 TEST(EmbeddingTest, SubtractVectors) {
147 Embedding E1 = {1.0, 2.0, 3.0};
148 Embedding E2 = {0.5, 1.5, -1.0};
149
150 E1 -= E2;
151 EXPECT_THAT(E1, ElementsAre(0.5, 0.5, 4.0));
152
153 // Check that E2 is unchanged
154 EXPECT_THAT(E2, ElementsAre(0.5, 1.5, -1.0));
155 }
156
157 TEST(EmbeddingTest, ScaleVector) {
158 Embedding E1 = {1.0, 2.0, 3.0};
159 E1 *= 0.5f;
160 EXPECT_THAT(E1, ElementsAre(0.5, 1.0, 1.5));
161 }
162
163 TEST(EmbeddingTest, ScaleVectorOutOfPlace) {
164 Embedding E1 = {1.0, 2.0, 3.0};
165 Embedding E2 = E1 * 0.5f;
166 EXPECT_THAT(E2, ElementsAre(0.5, 1.0, 1.5));
167
168 // Check that E1 is unchanged
169 EXPECT_THAT(E1, ElementsAre(1.0, 2.0, 3.0));
170 }
171
172 TEST(EmbeddingTest, AddScaledVector) {
173 Embedding E1 = {1.0, 2.0, 3.0};
174 Embedding E2 = {2.0, 0.5, -1.0};
175
176 E1.scaleAndAdd(E2, 0.5f);
177 EXPECT_THAT(E1, ElementsAre(2.0, 2.25, 2.5));
178
179 // Check that E2 is unchanged
180 EXPECT_THAT(E2, ElementsAre(2.0, 0.5, -1.0));
181 }
182
183 TEST(EmbeddingTest, ApproximatelyEqual) {
184 Embedding E1 = {1.0, 2.0, 3.0};
185 Embedding E2 = {1.0000001, 2.0000001, 3.0000001};
186 EXPECT_TRUE(E1.approximatelyEquals(E2)); // Diff = 1e-7
187
188 Embedding E3 = {1.00002, 2.00002, 3.00002}; // Diff = 2e-5
189 EXPECT_FALSE(E1.approximatelyEquals(E3, 1e-6));
190 EXPECT_TRUE(E1.approximatelyEquals(E3, 3e-5));
191
192 Embedding E_clearly_within = {1.0000005, 2.0000005, 3.0000005}; // Diff = 5e-7
193 EXPECT_TRUE(E1.approximatelyEquals(E_clearly_within));
194
195 Embedding E_clearly_outside = {1.00001, 2.00001, 3.00001}; // Diff = 1e-5
196 EXPECT_FALSE(E1.approximatelyEquals(E_clearly_outside, 1e-6));
197
198 Embedding E4 = {1.0, 2.0, 3.5}; // Large diff
199 EXPECT_FALSE(E1.approximatelyEquals(E4, 0.01));
200
201 Embedding E5 = {1.0, 2.0, 3.0};
202 EXPECT_TRUE(E1.approximatelyEquals(E5, 0.0));
203 EXPECT_TRUE(E1.approximatelyEquals(E5));
204 }
205
206 #if GTEST_HAS_DEATH_TEST
207 #ifndef NDEBUG
208 TEST(EmbeddingTest, AccessOutOfBounds) {
209 Embedding E = {1.0, 2.0, 3.0};
210 EXPECT_DEATH(E[3], "Index out of bounds");
211 EXPECT_DEATH(E[-1], "Index out of bounds");
212 EXPECT_DEATH(E[4] = 4.0, "Index out of bounds");
213 }
214
215 TEST(EmbeddingTest, MismatchedDimensionsAddVectorsOutOfPlace) {
216 Embedding E1 = {1.0, 2.0};
217 Embedding E2 = {1.0};
218 EXPECT_DEATH(E1 + E2, "Vectors must have the same dimension");
219 }
220
221 TEST(EmbeddingTest, MismatchedDimensionsAddVectors) {
222 Embedding E1 = {1.0, 2.0};
223 Embedding E2 = {1.0};
224 EXPECT_DEATH(E1 += E2, "Vectors must have the same dimension");
225 }
226
227 TEST(EmbeddingTest, MismatchedDimensionsSubtractVectors) {
228 Embedding E1 = {1.0, 2.0};
229 Embedding E2 = {1.0};
230 EXPECT_DEATH(E1 -= E2, "Vectors must have the same dimension");
231 }
232
233 TEST(EmbeddingTest, MismatchedDimensionsAddScaledVector) {
234 Embedding E1 = {1.0, 2.0};
235 Embedding E2 = {1.0};
236 EXPECT_DEATH(E1.scaleAndAdd(E2, 1.0f),
237 "Vectors must have the same dimension");
238 }
239
240 TEST(EmbeddingTest, MismatchedDimensionsApproximatelyEqual) {
241 Embedding E1 = {1.0, 2.0};
242 Embedding E2 = {1.010};
243 EXPECT_DEATH(E1.approximatelyEquals(E2),
244 "Vectors must have the same dimension");
245 }
246 #endif // NDEBUG
247 #endif // GTEST_HAS_DEATH_TEST
248
249 TEST(IR2VecTest, CreateSymbolicEmbedder) {
250 Vocabulary V = Vocabulary(Vocabulary::createDummyVocabForTest());
251
252 LLVMContext Ctx;
253 Module M("M", Ctx);
254 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), false);
255 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
256
257 auto Emb = Embedder::create(IR2VecKind::Symbolic, *F, V);
258 EXPECT_NE(Emb, nullptr);
259 }
260
261 TEST(IR2VecTest, CreateInvalidMode) {
262 Vocabulary V = Vocabulary(Vocabulary::createDummyVocabForTest());
263
264 LLVMContext Ctx;
265 Module M("M", Ctx);
266 FunctionType *FTy = FunctionType::get(Type::getVoidTy(Ctx), false);
267 Function *F = Function::Create(FTy, Function::ExternalLinkage, "f", M);
268
269 // static_cast an invalid int to IR2VecKind
270 auto Result = Embedder::create(static_cast<IR2VecKind>(-1), *F, V);
271 EXPECT_FALSE(static_cast<bool>(Result));
272 }
273
274 TEST(IR2VecTest, ZeroDimensionEmbedding) {
275 Embedding E1;
276 Embedding E2;
277 // Should be no-op, but not crash
278 E1 += E2;
279 E1 -= E2;
280 E1.scaleAndAdd(E2, 1.0f);
281 EXPECT_TRUE(E1.empty());
282 }
283
284 // Fixture for IR2Vec tests requiring IR setup.
285 class IR2VecTestFixture : public ::testing::Test {
286 protected:
287 Vocabulary V;
288 LLVMContext Ctx;
289 std::unique_ptr<Module> M;
290 Function *F = nullptr;
291 BasicBlock *BB = nullptr;
292 Instruction *AddInst = nullptr;
293 Instruction *RetInst = nullptr;
294
295 void SetUp() override {
296 V = Vocabulary(Vocabulary::createDummyVocabForTest(2));
297
298 // Setup IR
299 M = std::make_unique<Module>("TestM", Ctx);
300 FunctionType *FTy = FunctionType::get(
301 Type::getInt32Ty(Ctx), {Type::getInt32Ty(Ctx), Type::getInt32Ty(Ctx)},
302 false);
303 F = Function::Create(FTy, Function::ExternalLinkage, "f", M.get());
304 BB = BasicBlock::Create(Ctx, "entry", F);
305 Argument *Arg = F->getArg(0);
306 llvm::Value *Const = ConstantInt::get(Type::getInt32Ty(Ctx), 42);
307
308 AddInst = BinaryOperator::CreateAdd(Arg, Const, "add", BB);
309 RetInst = ReturnInst::Create(Ctx, AddInst, BB);
310 }
311 };
312
313 TEST_F(IR2VecTestFixture, GetInstVecMap) {
314 auto Emb = Embedder::create(IR2VecKind::Symbolic, *F, V);
315 ASSERT_TRUE(static_cast<bool>(Emb));
316
317 const auto &InstMap = Emb->getInstVecMap();
318
319 EXPECT_EQ(InstMap.size(), 2u);
320 EXPECT_TRUE(InstMap.count(AddInst));
321 EXPECT_TRUE(InstMap.count(RetInst));
322
323 EXPECT_EQ(InstMap.at(AddInst).size(), 2u);
324 EXPECT_EQ(InstMap.at(RetInst).size(), 2u);
325
326 EXPECT_TRUE(InstMap.at(AddInst).approximatelyEquals(Embedding(2, 27.6)));
327 EXPECT_TRUE(InstMap.at(RetInst).approximatelyEquals(Embedding(2, 16.8)));
328 }
329
330 TEST_F(IR2VecTestFixture, GetBBVecMap) {
331 auto Emb = Embedder::create(IR2VecKind::Symbolic, *F, V);
332 ASSERT_TRUE(static_cast<bool>(Emb));
333
334 const auto &BBMap = Emb->getBBVecMap();
335
336 EXPECT_EQ(BBMap.size(), 1u);
337 EXPECT_TRUE(BBMap.count(BB));
338 EXPECT_EQ(BBMap.at(BB).size(), 2u);
339
340 // BB vector should be sum of add and ret: {27.6, 27.6} + {16.8, 16.8} =
341 // {44.4, 44.4}
342 EXPECT_TRUE(BBMap.at(BB).approximatelyEquals(Embedding(2, 44.4)));
343 }
344
345 TEST_F(IR2VecTestFixture, GetBBVector) {
346 auto Emb = Embedder::create(IR2VecKind::Symbolic, *F, V);
347 ASSERT_TRUE(static_cast<bool>(Emb));
348
349 const auto &BBVec = Emb->getBBVector(*BB);
350
351 EXPECT_EQ(BBVec.size(), 2u);
352 EXPECT_TRUE(BBVec.approximatelyEquals(Embedding(2, 44.4)));
353 }
354
355 TEST_F(IR2VecTestFixture, GetFunctionVector) {
356 auto Emb = Embedder::create(IR2VecKind::Symbolic, *F, V);
357 ASSERT_TRUE(static_cast<bool>(Emb));
358
359 const auto &FuncVec = Emb->getFunctionVector();
360
361 EXPECT_EQ(FuncVec.size(), 2u);
362
363 // Function vector should match BB vector (only one BB): {44.4, 44.4}
364 EXPECT_TRUE(FuncVec.approximatelyEquals(Embedding(2, 44.4)));
365 }
366
367 static constexpr unsigned MaxOpcodes = 67;
368 static constexpr unsigned MaxTypeIDs = 21;
369 static constexpr unsigned MaxOperands = 4;
370
371 TEST(IR2VecVocabularyTest, DummyVocabTest) {
372 for (unsigned Dim = 1; Dim <= 10; ++Dim) {
373 auto VocabVec = Vocabulary::createDummyVocabForTest(Dim);
374
375 // All embeddings should have the same dimension
376 for (const auto &Emb : VocabVec)
377 EXPECT_EQ(Emb.size(), Dim);
378
379 // Should have the correct total number of embeddings
380 EXPECT_EQ(VocabVec.size(), MaxOpcodes + MaxTypeIDs + MaxOperands);
381
382 auto ExpectedVocab = VocabVec;
383
384 IR2VecVocabAnalysis VocabAnalysis(std::move(VocabVec));
385 LLVMContext TestCtx;
386 Module TestMod("TestModuleForVocabAnalysis", TestCtx);
387 ModuleAnalysisManager MAM;
388 Vocabulary Result = VocabAnalysis.run(TestMod, MAM);
389 EXPECT_TRUE(Result.isValid());
390 EXPECT_EQ(Result.getDimension(), Dim);
391 EXPECT_EQ(Result.size(), MaxOpcodes + MaxTypeIDs + MaxOperands);
392
393 unsigned CurPos = 0;
394 for (const auto &Entry : Result)
395 EXPECT_TRUE(Entry.approximatelyEquals(ExpectedVocab[CurPos++], 0.01));
396 }
397 }
398
399 TEST(IR2VecVocabularyTest, StringKeyGeneration) {
400 EXPECT_EQ(Vocabulary::getStringKey(0), "Ret");
401 EXPECT_EQ(Vocabulary::getStringKey(12), "Add");
402
403 StringRef HalfTypeKey = Vocabulary::getStringKey(MaxOpcodes + 0);
404 StringRef FloatTypeKey = Vocabulary::getStringKey(MaxOpcodes + 2);
405 StringRef VoidTypeKey = Vocabulary::getStringKey(MaxOpcodes + 7);
406 StringRef IntTypeKey = Vocabulary::getStringKey(MaxOpcodes + 12);
407
408 EXPECT_EQ(HalfTypeKey, "FloatTy");
409 EXPECT_EQ(FloatTypeKey, "FloatTy");
410 EXPECT_EQ(VoidTypeKey, "VoidTy");
411 EXPECT_EQ(IntTypeKey, "IntegerTy");
412
413 StringRef FuncArgKey = Vocabulary::getStringKey(MaxOpcodes + MaxTypeIDs + 0);
414 StringRef PtrArgKey = Vocabulary::getStringKey(MaxOpcodes + MaxTypeIDs + 1);
415 EXPECT_EQ(FuncArgKey, "Function");
416 EXPECT_EQ(PtrArgKey, "Pointer");
417 }
418
419 TEST(IR2VecVocabularyTest, VocabularyDimensions) {
420 {
421 Vocabulary V(Vocabulary::createDummyVocabForTest(1));
422 EXPECT_TRUE(V.isValid());
423 EXPECT_EQ(V.getDimension(), 1u);
424 }
425
426 {
427 Vocabulary V(Vocabulary::createDummyVocabForTest(5));
428 EXPECT_TRUE(V.isValid());
429 EXPECT_EQ(V.getDimension(), 5u);
430 }
431
432 {
433 Vocabulary V(Vocabulary::createDummyVocabForTest(10));
434 EXPECT_TRUE(V.isValid());
435 EXPECT_EQ(V.getDimension(), 10u);
436 }
437 }
438
439 #if GTEST_HAS_DEATH_TEST
440 #ifndef NDEBUG
441 TEST(IR2VecVocabularyTest, InvalidAccess) {
442 Vocabulary V(Vocabulary::createDummyVocabForTest(2));
443
444 EXPECT_DEATH(V[0u], "Invalid opcode");
445
446 EXPECT_DEATH(V[100u], "Invalid opcode");
447 }
448 #endif // NDEBUG
449 #endif // GTEST_HAS_DEATH_TEST
450
451 TEST(IR2VecVocabularyTest, TypeIDStringKeyMapping) {
452 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
453 static_cast<unsigned>(Type::VoidTyID)),
454 "VoidTy");
455 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
456 static_cast<unsigned>(Type::IntegerTyID)),
457 "IntegerTy");
458 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
459 static_cast<unsigned>(Type::FloatTyID)),
460 "FloatTy");
461 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
462 static_cast<unsigned>(Type::PointerTyID)),
463 "PointerTy");
464 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
465 static_cast<unsigned>(Type::FunctionTyID)),
466 "FunctionTy");
467 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
468 static_cast<unsigned>(Type::StructTyID)),
469 "StructTy");
470 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
471 static_cast<unsigned>(Type::ArrayTyID)),
472 "ArrayTy");
473 EXPECT_EQ(Vocabulary::getStringKey(
474 MaxOpcodes + static_cast<unsigned>(Type::FixedVectorTyID)),
475 "VectorTy");
476 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
477 static_cast<unsigned>(Type::LabelTyID)),
478 "LabelTy");
479 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
480 static_cast<unsigned>(Type::TokenTyID)),
481 "TokenTy");
482 EXPECT_EQ(Vocabulary::getStringKey(MaxOpcodes +
483 static_cast<unsigned>(Type::MetadataTyID)),
484 "MetadataTy");
485 }
486
487 TEST(IR2VecVocabularyTest, InvalidVocabularyConstruction) {
488 std::vector<Embedding> InvalidVocab;
489 InvalidVocab.push_back(Embedding(2, 1.0));
490 InvalidVocab.push_back(Embedding(2, 2.0));
491
492 Vocabulary V(std::move(InvalidVocab));
493 EXPECT_FALSE(V.isValid());
494
495 {
496 Vocabulary InvalidResult;
497 EXPECT_FALSE(InvalidResult.isValid());
498 #if GTEST_HAS_DEATH_TEST
499 #ifndef NDEBUG
500 EXPECT_DEATH(InvalidResult.getDimension(), "IR2Vec Vocabulary is invalid");
501 #endif // NDEBUG
502 #endif // GTEST_HAS_DEATH_TEST
503 }
504 }
505
506 } // end anonymous namespace