LLVM 24.0.0git
IR2Vec.cpp
Go to the documentation of this file.
1//===- IR2Vec.cpp - Implementation of IR2Vec -----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM
4// Exceptions. See the LICENSE file for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements the IR2Vec algorithm.
11///
12//===----------------------------------------------------------------------===//
13
15#include "AnalysisOptions.h"
16
18#include "llvm/ADT/Sequence.h"
19#include "llvm/ADT/Statistic.h"
20#include "llvm/IR/CFG.h"
22#include "llvm/IR/Module.h"
23#include "llvm/IR/PassManager.h"
24#include "llvm/Support/Debug.h"
25#include "llvm/Support/Errc.h"
26#include "llvm/Support/Error.h"
28#include "llvm/Support/Format.h"
30
31using namespace llvm;
32using namespace ir2vec;
33
34#define DEBUG_TYPE "ir2vec"
35
36STATISTIC(VocabMissCounter,
37 "Number of lookups to entities not present in the vocabulary");
38
40 return getAnalysisOptions(C).ir2vec_vocab_path;
41}
45
47
48// ==----------------------------------------------------------------------===//
49// Local helper functions
50//===----------------------------------------------------------------------===//
51namespace llvm::json {
52inline bool fromJSON(const llvm::json::Value &E, Embedding &Out,
54 std::vector<double> TempOut;
55 if (!llvm::json::fromJSON(E, TempOut, P))
56 return false;
57 Out = Embedding(std::move(TempOut));
58 return true;
59}
60} // namespace llvm::json
61
62// ==----------------------------------------------------------------------===//
63// Embedding
64//===----------------------------------------------------------------------===//
66 assert(this->size() == RHS.size() && "Vectors must have the same dimension");
67 std::transform(this->begin(), this->end(), RHS.begin(), this->begin(),
68 std::plus<double>());
69 return *this;
70}
71
73 Embedding Result(*this);
74 Result += RHS;
75 return Result;
76}
77
79 assert(this->size() == RHS.size() && "Vectors must have the same dimension");
80 std::transform(this->begin(), this->end(), RHS.begin(), this->begin(),
81 std::minus<double>());
82 return *this;
83}
84
86 Embedding Result(*this);
87 Result -= RHS;
88 return Result;
89}
90
92 std::transform(this->begin(), this->end(), this->begin(),
93 [Factor](double Elem) { return Elem * Factor; });
94 return *this;
95}
96
97Embedding Embedding::operator*(double Factor) const {
98 Embedding Result(*this);
99 Result *= Factor;
100 return Result;
101}
102
103Embedding &Embedding::scaleAndAdd(const Embedding &Src, float Factor) {
104 assert(this->size() == Src.size() && "Vectors must have the same dimension");
105 for (size_t Itr = 0; Itr < this->size(); ++Itr)
106 (*this)[Itr] += Src[Itr] * Factor;
107 return *this;
108}
109
111 double Tolerance) const {
112 assert(this->size() == RHS.size() && "Vectors must have the same dimension");
113 for (size_t Itr = 0; Itr < this->size(); ++Itr)
114 if (std::abs((*this)[Itr] - RHS[Itr]) > Tolerance) {
115 LLVM_DEBUG(errs() << "Embedding mismatch at index " << Itr << ": "
116 << (*this)[Itr] << " vs " << RHS[Itr]
117 << "; Tolerance: " << Tolerance << "\n");
118 return false;
119 }
120 return true;
121}
122
124 OS << " [";
125 for (const auto &Elem : Data)
126 OS << " " << format("%.2f", Elem) << " ";
127 OS << "]\n";
128}
129
130// ==----------------------------------------------------------------------===//
131// Embedder and its subclasses
132//===----------------------------------------------------------------------===//
133
134std::unique_ptr<Embedder> Embedder::create(IR2VecKind Mode, const Function &F,
135 const Vocabulary &Vocab) {
136 switch (Mode) {
138 return std::make_unique<SymbolicEmbedder>(F, Vocab);
140 return std::make_unique<FlowAwareEmbedder>(F, Vocab);
141 }
142 return nullptr;
143}
144
146 Embedding FuncVector(Dimension, 0.0);
147
148 if (F.isDeclaration())
149 return FuncVector;
150
151 // Consider only the basic blocks that are reachable from entry
152 for (const BasicBlock *BB : depth_first(&F))
153 FuncVector += computeEmbeddings(*BB);
154 return FuncVector;
155}
156
158 Embedding BBVector(Dimension, 0);
159
160 // We consider only the non-pseudo instructions
161 for (const auto &I : BB)
163 BBVector += computeEmbeddings(I);
164 return BBVector;
165}
166
168 // Currently, we always (re)compute the embeddings for symbolic embedder.
169 // This is cheaper than caching the vectors.
170 Embedding ArgEmb(Dimension, 0);
171 for (const auto &Op : I.operands()) {
172 // TODO(#247449): Metadata operands are not part of the vocabulary yet;
173 // skip them.
175 continue;
176 ArgEmb += Vocab[*Op];
177 }
178 auto InstVector =
179 Vocab[I.getOpcode()] + Vocab[I.getType()->getTypeID()] + ArgEmb;
180 if (const auto *IC = dyn_cast<CmpInst>(&I))
181 InstVector += Vocab[IC->getPredicate()];
182 return InstVector;
183}
184
186 // If we have already computed the embedding for this instruction, return it
187 auto It = InstVecMap.find(&I);
188 if (It != InstVecMap.end())
189 return It->second;
190
191 // TODO: Handle call instructions differently.
192 // For now, we treat them like other instructions
193 Embedding ArgEmb(Dimension, 0);
194 for (const auto &Op : I.operands()) {
195 // TODO(#247449): Metadata operands are not part of the vocabulary yet;
196 // skip them.
198 continue;
199 // If the operand is defined elsewhere, we use its embedding
200 if (const auto *DefInst = dyn_cast<Instruction>(Op)) {
201 auto DefIt = InstVecMap.find(DefInst);
202 // Fixme (#159171): Ideally we should never miss an instruction
203 // embedding here.
204 // But when we have cyclic dependencies (e.g., phi
205 // nodes), we might miss the embedding. In such cases, we fall back to
206 // using the vocabulary embedding. This can be fixed by iterating to a
207 // fixed-point, or by using a simple solver for the set of simultaneous
208 // equations.
209 // Another case when we might miss an instruction embedding is when
210 // the operand instruction is in a different basic block that has not
211 // been processed yet. This can be fixed by processing the basic blocks
212 // in a topological order.
213 if (DefIt != InstVecMap.end())
214 ArgEmb += DefIt->second;
215 else
216 ArgEmb += Vocab[*Op];
217 }
218 // If the operand is not defined by an instruction, we use the
219 // vocabulary
220 else {
221 LLVM_DEBUG(errs() << "Using embedding from vocabulary for operand: "
222 << *Op << "=" << Vocab[*Op][0] << "\n");
223 ArgEmb += Vocab[*Op];
224 }
225 }
226 // Create the instruction vector by combining opcode, type, and arguments
227 // embeddings
228 auto InstVector =
229 Vocab[I.getOpcode()] + Vocab[I.getType()->getTypeID()] + ArgEmb;
230 if (const auto *IC = dyn_cast<CmpInst>(&I))
231 InstVector += Vocab[IC->getPredicate()];
232 InstVecMap[&I] = InstVector;
233 return InstVector;
234}
235
236// ==----------------------------------------------------------------------===//
237// VocabStorage
238//===----------------------------------------------------------------------===//
239
240VocabStorage::VocabStorage(std::vector<std::vector<Embedding>> &&SectionData)
241 : Sections(std::move(SectionData)), TotalSize([&] {
242 assert(!Sections.empty() && "Vocabulary has no sections");
243 // Compute total size across all sections
244 size_t Size = 0;
245 for (const auto &Section : Sections) {
246 assert(!Section.empty() && "Vocabulary section is empty");
247 Size += Section.size();
248 }
249 return Size;
250 }()),
251 Dimension([&] {
252 // Get dimension from the first embedding in the first section - all
253 // embeddings must have the same dimension
254 assert(!Sections.empty() && "Vocabulary has no sections");
255 assert(!Sections[0].empty() && "First section of vocabulary is empty");
256 unsigned ExpectedDim = static_cast<unsigned>(Sections[0][0].size());
257
258 // Verify that all embeddings across all sections have the same
259 // dimension
260 [[maybe_unused]] auto allSameDim =
261 [ExpectedDim](const std::vector<Embedding> &Section) {
262 return std::all_of(Section.begin(), Section.end(),
263 [ExpectedDim](const Embedding &Emb) {
264 return Emb.size() == ExpectedDim;
265 });
266 };
267 assert(std::all_of(Sections.begin(), Sections.end(), allSameDim) &&
268 "All embeddings must have the same dimension");
269
270 return ExpectedDim;
271 }()) {}
272
274 assert(SectionId < Storage->Sections.size() && "Invalid section ID");
275 assert(LocalIndex < Storage->Sections[SectionId].size() &&
276 "Local index out of range");
277 return Storage->Sections[SectionId][LocalIndex];
278}
279
281 ++LocalIndex;
282 // Check if we need to move to the next section
283 if (SectionId < Storage->getNumSections() &&
284 LocalIndex >= Storage->Sections[SectionId].size()) {
285 assert(LocalIndex == Storage->Sections[SectionId].size() &&
286 "Local index should be at the end of the current section");
287 LocalIndex = 0;
288 ++SectionId;
289 }
290 return *this;
291}
292
294 const const_iterator &Other) const {
295 return Storage == Other.Storage && SectionId == Other.SectionId &&
296 LocalIndex == Other.LocalIndex;
297}
298
300 const const_iterator &Other) const {
301 return !(*this == Other);
302}
303
305 const json::Value &ParsedVocabValue,
306 VocabMap &TargetVocab, unsigned &Dim) {
307 json::Path::Root Path("");
308 const json::Object *RootObj = ParsedVocabValue.getAsObject();
309 if (!RootObj)
311 "JSON root is not an object");
312
313 const json::Value *SectionValue = RootObj->get(Key);
314 if (!SectionValue)
316 "Missing '" + std::string(Key) +
317 "' section in vocabulary file");
318 if (!json::fromJSON(*SectionValue, TargetVocab, Path))
320 "Unable to parse '" + std::string(Key) +
321 "' section from vocabulary");
322
323 Dim = TargetVocab.begin()->second.size();
324 if (Dim == 0)
326 "Dimension of '" + std::string(Key) +
327 "' section of the vocabulary is zero");
328
329 if (!std::all_of(TargetVocab.begin(), TargetVocab.end(),
330 [Dim](const std::pair<StringRef, Embedding> &Entry) {
331 return Entry.second.size() == Dim;
332 }))
333 return createStringError(
335 "All vectors in the '" + std::string(Key) +
336 "' section of the vocabulary are not of the same dimension");
337
338 return Error::success();
339}
340
341// ==----------------------------------------------------------------------===//
342// Vocabulary
343//===----------------------------------------------------------------------===//
344
346 assert(Opcode >= 1 && Opcode <= MaxOpcodes && "Invalid opcode");
347#define HANDLE_INST(NUM, OPCODE, CLASS) \
348 if (Opcode == NUM) { \
349 return #OPCODE; \
350 }
351#include "llvm/IR/Instruction.def"
352#undef HANDLE_INST
353 return "UnknownOpcode";
354}
355
356// Helper function to classify an operand into OperandKind
368
369unsigned Vocabulary::getPredicateLocalIndex(CmpInst::Predicate P) {
372 else
375}
376
377CmpInst::Predicate Vocabulary::getPredicateFromLocalIndex(unsigned LocalIndex) {
378 unsigned fcmpRange =
380 if (LocalIndex < fcmpRange)
382 LocalIndex);
383 else
385 LocalIndex - fcmpRange);
386}
387
389 static SmallString<16> PredNameBuffer;
391 PredNameBuffer = "FCMP_";
392 else
393 PredNameBuffer = "ICMP_";
394 PredNameBuffer += CmpInst::getPredicateName(Pred);
395 return PredNameBuffer;
396}
397
399 assert(Pos < NumCanonicalEntries && "Position out of bounds in vocabulary");
400 // Opcode
401 if (Pos < MaxOpcodes)
402 return getVocabKeyForOpcode(Pos + 1);
403 // Type
404 if (Pos < OperandBaseOffset)
405 return getVocabKeyForCanonicalTypeID(
406 static_cast<CanonicalTypeID>(Pos - MaxOpcodes));
407 // Operand
408 if (Pos < PredicateBaseOffset)
410 static_cast<OperandKind>(Pos - OperandBaseOffset));
411 // Predicates
412 return getVocabKeyForPredicate(getPredicate(Pos - PredicateBaseOffset));
413}
414
415// For now, assume vocabulary is stable unless explicitly invalidated.
417 ModuleAnalysisManager::Invalidator &Inv) const {
418 auto PAC = PA.getChecker<IR2VecVocabAnalysis>();
419 return !(PAC.preservedWhenStateless());
420}
421
423 float DummyVal = 0.1f;
424
425 // Create sections for opcodes, types, operands, and predicates
426 // Order must match Vocabulary::Section enum
427 std::vector<std::vector<Embedding>> Sections;
428 Sections.reserve(static_cast<unsigned>(Section::MaxSections));
429
430 // Opcodes section
431 std::vector<Embedding> OpcodeSec;
432 OpcodeSec.reserve(MaxOpcodes);
433 for (unsigned I = 0; I < MaxOpcodes; ++I) {
434 OpcodeSec.emplace_back(Dim, DummyVal);
435 DummyVal += 0.1f;
436 }
437 Sections.push_back(std::move(OpcodeSec));
438
439 // Types section
440 std::vector<Embedding> TypeSec;
441 TypeSec.reserve(MaxCanonicalTypeIDs);
442 for (unsigned I = 0; I < MaxCanonicalTypeIDs; ++I) {
443 TypeSec.emplace_back(Dim, DummyVal);
444 DummyVal += 0.1f;
445 }
446 Sections.push_back(std::move(TypeSec));
447
448 // Operands section
449 std::vector<Embedding> OperandSec;
450 OperandSec.reserve(MaxOperandKinds);
451 for (unsigned I = 0; I < MaxOperandKinds; ++I) {
452 OperandSec.emplace_back(Dim, DummyVal);
453 DummyVal += 0.1f;
454 }
455 Sections.push_back(std::move(OperandSec));
456
457 // Predicates section
458 std::vector<Embedding> PredicateSec;
459 PredicateSec.reserve(MaxPredicateKinds);
460 for (unsigned I = 0; I < MaxPredicateKinds; ++I) {
461 PredicateSec.emplace_back(Dim, DummyVal);
462 DummyVal += 0.1f;
463 }
464 Sections.push_back(std::move(PredicateSec));
465
466 return VocabStorage(std::move(Sections));
467}
468
469namespace {
470using VocabMap = std::map<std::string, Embedding>;
471
472/// Read vocabulary JSON file and populate the section maps.
473Error readVocabularyFromFile(StringRef VocabFilePath, VocabMap &OpcVocab,
474 VocabMap &TypeVocab, VocabMap &ArgVocab) {
475 auto BufOrError =
476 MemoryBuffer::getFileOrSTDIN(VocabFilePath, /*IsText=*/true);
477 if (!BufOrError)
478 return createFileError(VocabFilePath, BufOrError.getError());
479
480 auto Content = BufOrError.get()->getBuffer();
481
482 Expected<json::Value> ParsedVocabValue = json::parse(Content);
483 if (!ParsedVocabValue)
484 return ParsedVocabValue.takeError();
485
486 unsigned OpcodeDim = 0, TypeDim = 0, ArgDim = 0;
487 if (auto Err = VocabStorage::parseVocabSection("Opcodes", *ParsedVocabValue,
488 OpcVocab, OpcodeDim))
489 return Err;
490
491 if (auto Err = VocabStorage::parseVocabSection("Types", *ParsedVocabValue,
492 TypeVocab, TypeDim))
493 return Err;
494
495 if (auto Err = VocabStorage::parseVocabSection("Arguments", *ParsedVocabValue,
496 ArgVocab, ArgDim))
497 return Err;
498
499 if (!(OpcodeDim == TypeDim && TypeDim == ArgDim))
501 "Vocabulary sections have different dimensions");
502
503 return Error::success();
504}
505} // anonymous namespace
506
507/// Generate VocabStorage from vocabulary maps.
508VocabStorage Vocabulary::buildVocabStorage(const VocabMap &OpcVocab,
509 const VocabMap &TypeVocab,
510 const VocabMap &ArgVocab) {
511
512 // Helper for handling missing entities in the vocabulary.
513 // Currently, we use a zero vector. In the future, we will throw an error to
514 // ensure that *all* known entities are present in the vocabulary.
515 auto handleMissingEntity = [](const std::string &Val) {
516 LLVM_DEBUG(errs() << Val
517 << " is not in vocabulary, using zero vector; This "
518 "would result in an error in future.\n");
519 ++VocabMissCounter;
520 };
521
522 unsigned Dim = OpcVocab.begin()->second.size();
523 assert(Dim > 0 && "Vocabulary dimension must be greater than zero");
524
525 // Handle Opcodes
526 std::vector<Embedding> NumericOpcodeEmbeddings(Vocabulary::MaxOpcodes,
527 Embedding(Dim));
528 for (unsigned Opcode : seq(0u, Vocabulary::MaxOpcodes)) {
529 StringRef VocabKey = Vocabulary::getVocabKeyForOpcode(Opcode + 1);
530 auto It = OpcVocab.find(VocabKey.str());
531 if (It != OpcVocab.end())
532 NumericOpcodeEmbeddings[Opcode] = It->second;
533 else
534 handleMissingEntity(VocabKey.str());
535 }
536
537 // Handle Types - only canonical types are present in vocabulary
538 std::vector<Embedding> NumericTypeEmbeddings(Vocabulary::MaxCanonicalTypeIDs,
539 Embedding(Dim));
540 for (unsigned CTypeID : seq(0u, Vocabulary::MaxCanonicalTypeIDs)) {
541 StringRef VocabKey = Vocabulary::getVocabKeyForCanonicalTypeID(
542 static_cast<Vocabulary::CanonicalTypeID>(CTypeID));
543 if (auto It = TypeVocab.find(VocabKey.str()); It != TypeVocab.end()) {
544 NumericTypeEmbeddings[CTypeID] = It->second;
545 continue;
546 }
547 handleMissingEntity(VocabKey.str());
548 }
549
550 // Handle Arguments/Operands
551 std::vector<Embedding> NumericArgEmbeddings(Vocabulary::MaxOperandKinds,
552 Embedding(Dim));
553 for (unsigned OpKind : seq(0u, Vocabulary::MaxOperandKinds)) {
555 StringRef VocabKey = Vocabulary::getVocabKeyForOperandKind(Kind);
556 auto It = ArgVocab.find(VocabKey.str());
557 if (It != ArgVocab.end()) {
558 NumericArgEmbeddings[OpKind] = It->second;
559 continue;
560 }
561 handleMissingEntity(VocabKey.str());
562 }
563
564 // Handle Predicates: part of Operands section. We look up predicate keys
565 // in ArgVocab.
566 std::vector<Embedding> NumericPredEmbeddings(Vocabulary::MaxPredicateKinds,
567 Embedding(Dim, 0));
568 for (unsigned PK : seq(0u, Vocabulary::MaxPredicateKinds)) {
569 StringRef VocabKey =
570 Vocabulary::getVocabKeyForPredicate(Vocabulary::getPredicate(PK));
571 auto It = ArgVocab.find(VocabKey.str());
572 if (It != ArgVocab.end()) {
573 NumericPredEmbeddings[PK] = It->second;
574 continue;
575 }
576 handleMissingEntity(VocabKey.str());
577 }
578
579 // Create section-based storage instead of flat vocabulary
580 // Order must match Vocabulary::Section enum
581 std::vector<std::vector<Embedding>> Sections(
582 static_cast<unsigned>(Section::MaxSections));
583 Sections[static_cast<unsigned>(Section::Opcodes)] =
584 std::move(NumericOpcodeEmbeddings); // Section::Opcodes
585 Sections[static_cast<unsigned>(Section::CanonicalTypes)] =
586 std::move(NumericTypeEmbeddings); // Section::CanonicalTypes
587 Sections[static_cast<unsigned>(Section::Operands)] =
588 std::move(NumericArgEmbeddings); // Section::Operands
589 Sections[static_cast<unsigned>(Section::Predicates)] =
590 std::move(NumericPredEmbeddings); // Section::Predicates
591
592 // Create VocabStorage from organized sections
593 return VocabStorage(std::move(Sections));
594}
595
596// ==----------------------------------------------------------------------===//
597// Vocabulary
598//===----------------------------------------------------------------------===//
599
601 float OpcWeight, float TypeWeight,
602 float ArgWeight) {
603 VocabMap OpcVocab, TypeVocab, ArgVocab;
604 if (auto Err =
605 readVocabularyFromFile(VocabFilePath, OpcVocab, TypeVocab, ArgVocab))
606 return std::move(Err);
607
608 // Scale the vocabulary sections based on the provided weights
609 auto scaleVocabSection = [](VocabMap &Vocab, float Weight) {
610 for (auto &Entry : Vocab)
611 Entry.second *= Weight;
612 };
613 scaleVocabSection(OpcVocab, OpcWeight);
614 scaleVocabSection(TypeVocab, TypeWeight);
615 scaleVocabSection(ArgVocab, ArgWeight);
616
617 // Generate the numeric lookup vocabulary
618 return Vocabulary(buildVocabStorage(OpcVocab, TypeVocab, ArgVocab));
619}
620
621// ==----------------------------------------------------------------------===//
622// IR2VecVocabAnalysis
623//===----------------------------------------------------------------------===//
624
625void IR2VecVocabAnalysis::emitError(Error Err) {
626 handleAllErrors(std::move(Err), [&](const ErrorInfoBase &EI) {
627 reportFatalUsageError(Twine("error reading vocabulary: ") + EI.message());
628 });
629}
630
633 // If vocabulary is already populated by the constructor, use it.
634 if (Vocab.has_value())
635 return Vocabulary(std::move(Vocab.value()));
636
637 // Otherwise, try to read from the vocabulary file specified via CLI.
638 const AnalysisOptions &Opts = getAnalysisOptions(M);
639 if (Opts.ir2vec_vocab_path.empty())
640 // FIXME: Use default vocabulary
642 "IR2Vec vocabulary file path not specified; You may need to "
643 "set it using --ir2vec-vocab-path");
644
645 // Use the static factory method to load the vocabulary.
646 auto VocabOrErr =
647 Vocabulary::fromFile(Opts.ir2vec_vocab_path, Opts.ir2vec_opc_weight,
648 Opts.ir2vec_type_weight, Opts.ir2vec_arg_weight);
649 if (!VocabOrErr)
650 emitError(VocabOrErr.takeError());
651
652 return std::move(*VocabOrErr);
653}
654
655// ==----------------------------------------------------------------------===//
656// Printer Passes
657//===----------------------------------------------------------------------===//
658
661 auto &Vocabulary = MAM.getResult<IR2VecVocabAnalysis>(M);
662 assert(Vocabulary.isValid() && "IR2Vec Vocabulary is invalid");
663
664 IR2VecKind Kind = getAnalysisOptions(M).ir2vec_kind;
665 for (Function &F : M) {
666 auto Emb = Embedder::create(Kind, F, Vocabulary);
667 if (!Emb) {
668 OS << "Error creating IR2Vec embeddings \n";
669 continue;
670 }
671
672 OS << "IR2Vec embeddings for function " << F.getName() << ":\n";
673 OS << "Function vector: ";
674 Emb->getFunctionVector().print(OS);
675
676 OS << "Basic block vectors:\n";
677 for (const BasicBlock &BB : F) {
678 OS << "Basic block: " << BB.getName() << ":\n";
679 Emb->getBBVector(BB).print(OS);
680 }
681
682 OS << "Instruction vectors:\n";
683 for (const BasicBlock &BB : F) {
684 for (const Instruction &I : BB) {
685 OS << "Instruction: ";
686 I.print(OS);
687 Emb->getInstVector(I).print(OS);
688 }
689 }
690 }
691 return PreservedAnalyses::all();
692}
693
696 auto &IR2VecVocabulary = MAM.getResult<IR2VecVocabAnalysis>(M);
697 assert(IR2VecVocabulary.isValid() && "IR2Vec Vocabulary is invalid");
698
699 // Print each entry
700 unsigned Pos = 0;
701 for (const auto &Entry : IR2VecVocabulary) {
702 OS << "Key: " << IR2VecVocabulary.getStringKey(Pos++) << ": ";
703 Entry.print(OS);
704 }
705 return PreservedAnalyses::all();
706}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
This file builds on the ADT/GraphTraits.h file to build generic depth first graph iterator.
This file defines the IR2Vec vocabulary analysis(IR2VecVocabAnalysis), the core ir2vec::Embedder inte...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Module.h This file contains the declarations for the Module class.
This header defines various interfaces for pass management in LLVM.
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
std::map< std::string, Embedding > VocabMap
Definition MIR2Vec.cpp:473
#define P(N)
ModuleAnalysisManager MAM
Provides some synthesis utilities to produce sequences of values.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:170
#define LLVM_DEBUG(...)
Definition Debug.h:119
LLVM Basic Block Representation.
Definition BasicBlock.h:61
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
static LLVM_ABI StringRef getPredicateName(Predicate P)
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Base class for error info classes.
Definition Error.h:44
virtual std::string message() const
Return the error message as a string.
Definition Error.h:52
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Definition IR2Vec.cpp:659
This analysis provides the vocabulary for IR2Vec.
Definition IR2Vec.h:636
ir2vec::Vocabulary Result
Definition IR2Vec.h:646
LLVM_ABI Result run(Module &M, ModuleAnalysisManager &MAM)
Definition IR2Vec.cpp:632
static LLVM_ABI AnalysisKey Key
Definition IR2Vec.h:642
LLVM_ABI PreservedAnalyses run(Module &M, ModuleAnalysisManager &MAM)
Definition IR2Vec.cpp:694
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalysisChecker getChecker() const
Build a checker for this PreservedAnalyses and the specified analysis type.
Definition Analysis.h:275
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
std::string str() const
Get the contents as an std::string.
Definition StringRef.h:222
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM Value Representation.
Definition Value.h:75
static LLVM_ABI std::unique_ptr< Embedder > create(IR2VecKind Mode, const Function &F, const Vocabulary &Vocab)
Factory method to create an Embedder object.
Definition IR2Vec.cpp:134
const Vocabulary & Vocab
Definition IR2Vec.h:555
const unsigned Dimension
Dimension of the vector representation; captured from the input vocabulary.
Definition IR2Vec.h:558
LLVM_ABI Embedding computeEmbeddings() const
Function to compute embeddings.
Definition IR2Vec.cpp:145
const Function & F
Definition IR2Vec.h:554
Iterator support for section-based access.
Definition IR2Vec.h:200
const_iterator(const VocabStorage *Storage, unsigned SectionId, size_t LocalIndex)
Definition IR2Vec.h:206
LLVM_ABI bool operator!=(const const_iterator &Other) const
Definition IR2Vec.cpp:299
LLVM_ABI const_iterator & operator++()
Definition IR2Vec.cpp:280
LLVM_ABI const Embedding & operator*() const
Definition IR2Vec.cpp:273
LLVM_ABI bool operator==(const const_iterator &Other) const
Definition IR2Vec.cpp:293
Generic storage class for section-based vocabularies.
Definition IR2Vec.h:155
static LLVM_ABI Error parseVocabSection(StringRef Key, const json::Value &ParsedVocabValue, VocabMap &TargetVocab, unsigned &Dim)
Parse a vocabulary section from JSON and populate the target vocabulary map.
Definition IR2Vec.cpp:304
unsigned getNumSections() const
Get number of sections.
Definition IR2Vec.h:183
size_t size() const
Get total number of entries across all sections.
Definition IR2Vec.h:180
VocabStorage()=default
Default constructor creates empty storage (invalid state)
const_iterator begin() const
Definition IR2Vec.h:216
std::map< std::string, Embedding > VocabMap
Definition IR2Vec.h:221
Class for storing and accessing the IR2Vec vocabulary.
Definition IR2Vec.h:246
LLVM_ABI bool invalidate(Module &M, const PreservedAnalyses &PA, ModuleAnalysisManager::Invalidator &Inv) const
Definition IR2Vec.cpp:416
static LLVM_ABI Expected< Vocabulary > fromFile(StringRef VocabFilePath, float OpcWeight=1.0, float TypeWeight=0.5, float ArgWeight=0.2)
Create a Vocabulary by loading embeddings from a JSON file.
Definition IR2Vec.cpp:600
static LLVM_ABI OperandKind getOperandKind(const Value *Op)
Function to classify an operand into OperandKind.
Definition IR2Vec.cpp:357
static StringRef getVocabKeyForOperandKind(OperandKind Kind)
Function to get vocabulary key for a given OperandKind.
Definition IR2Vec.h:366
friend class llvm::IR2VecVocabAnalysis
Definition IR2Vec.h:247
static LLVM_ABI StringRef getStringKey(unsigned Pos)
Returns the string key for a given index position in the vocabulary.
Definition IR2Vec.cpp:398
static constexpr unsigned MaxCanonicalTypeIDs
Definition IR2Vec.h:318
static constexpr unsigned MaxOperandKinds
Definition IR2Vec.h:320
OperandKind
Operand kinds supported by IR2Vec Vocabulary.
Definition IR2Vec.h:303
static LLVM_ABI StringRef getVocabKeyForPredicate(CmpInst::Predicate P)
Function to get vocabulary key for a given predicate.
Definition IR2Vec.cpp:388
static LLVM_ABI StringRef getVocabKeyForOpcode(unsigned Opcode)
Function to get vocabulary key for a given Opcode.
Definition IR2Vec.cpp:345
bool isValid() const
Definition IR2Vec.h:346
static LLVM_ABI VocabStorage createDummyVocabForTest(unsigned Dim=1)
Create a dummy vocabulary for testing purposes.
Definition IR2Vec.cpp:422
static constexpr unsigned MaxPredicateKinds
Definition IR2Vec.h:324
CanonicalTypeID
Canonical type IDs supported by IR2Vec Vocabulary.
Definition IR2Vec.h:285
An Object is a JSON object, which maps strings to heterogenous JSON values.
Definition JSON.h:98
LLVM_ABI Value * get(StringRef K)
Definition JSON.cpp:30
The root is the trivial Path to the root value.
Definition JSON.h:700
A "cursor" marking a position within a Value.
Definition JSON.h:653
A Value is an JSON value of unknown type.
Definition JSON.h:291
const json::Object * getAsObject() const
Definition JSON.h:465
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
LLVM_ABI IR2VecKind getEmbeddingKind(const LLVMContext &C)
Return -ir2vec-kind.
Definition IR2Vec.cpp:42
LLVM_ABI StringRef getVocabFile(const LLVMContext &C)
Return -ir2vec-vocab-path.
Definition IR2Vec.cpp:39
LLVM_ABI llvm::Expected< Value > parse(llvm::StringRef JSON)
Parses the provided JSON source, or returns a ParseError.
Definition JSON.cpp:681
bool fromJSON(const Value &E, std::string &Out, Path P)
Definition JSON.h:729
ir2vec::Embedding Embedding
Definition MIR2Vec.h:78
This is an optimization pass for GlobalISel generic memory operations.
Error createFileError(const Twine &F, Error E)
Concatenate a source file path and/or name with an Error.
Definition Error.h:1415
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
@ illegal_byte_sequence
Definition Errc.h:52
@ invalid_argument
Definition Errc.h:56
const AnalysisOptions & getAnalysisOptions(const LLVMContext &C)
IR2VecKind
IR2Vec computes two kinds of embeddings: Symbolic and Flow-aware.
Definition IR2Vec.h:71
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition Format.h:102
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Other
Any other memory.
Definition ModRef.h:68
DWARFExpression::Operation Op
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
iterator_range< df_iterator< T > > depth_first(const T &G)
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
Embedding is a datatype that wraps std::vector<double>.
Definition IR2Vec.h:86
LLVM_ABI bool approximatelyEquals(const Embedding &RHS, double Tolerance=1e-4) const
Returns true if the embedding is approximately equal to the RHS embedding within the specified tolera...
Definition IR2Vec.cpp:110
LLVM_ABI Embedding & operator+=(const Embedding &RHS)
Arithmetic operators.
Definition IR2Vec.cpp:65
LLVM_ABI Embedding operator-(const Embedding &RHS) const
Definition IR2Vec.cpp:85
LLVM_ABI Embedding & operator-=(const Embedding &RHS)
Definition IR2Vec.cpp:78
LLVM_ABI Embedding operator*(double Factor) const
Definition IR2Vec.cpp:97
size_t size() const
Definition IR2Vec.h:99
LLVM_ABI Embedding & operator*=(double Factor)
Definition IR2Vec.cpp:91
LLVM_ABI Embedding operator+(const Embedding &RHS) const
Definition IR2Vec.cpp:72
LLVM_ABI Embedding & scaleAndAdd(const Embedding &Src, float Factor)
Adds Src Embedding scaled by Factor with the called Embedding.
Definition IR2Vec.cpp:103
LLVM_ABI void print(raw_ostream &OS) const
Definition IR2Vec.cpp:123