xref: /freebsd/contrib/llvm-project/llvm/lib/ObjectYAML/OffloadEmitter.cpp (revision e32fecd0c2c3ee37c47ee100f169e7eb0282a873)
1 //===- OffloadEmitter.cpp -------------------------------------------------===//
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/Object/OffloadBinary.h"
10 #include "llvm/ObjectYAML/OffloadYAML.h"
11 #include "llvm/ObjectYAML/yaml2obj.h"
12 #include "llvm/Support/Error.h"
13 #include "llvm/Support/raw_ostream.h"
14 
15 using namespace llvm;
16 using namespace OffloadYAML;
17 
18 namespace llvm {
19 namespace yaml {
20 
21 bool yaml2offload(Binary &Doc, raw_ostream &Out, ErrorHandler EH) {
22   for (const auto &Member : Doc.Members) {
23     object::OffloadBinary::OffloadingImage Image{};
24     if (Member.ImageKind)
25       Image.TheImageKind = *Member.ImageKind;
26     if (Member.OffloadKind)
27       Image.TheOffloadKind = *Member.OffloadKind;
28     if (Member.Flags)
29       Image.Flags = *Member.Flags;
30 
31     StringMap<StringRef> &StringData = Image.StringData;
32     if (Member.StringEntries) {
33       for (const auto &Entry : *Member.StringEntries) {
34         StringData[Entry.Key] = Entry.Value;
35       }
36     }
37 
38     SmallVector<char, 1024> Data;
39     raw_svector_ostream OS(Data);
40     if (Member.Content)
41       Member.Content->writeAsBinary(OS);
42     Image.Image = MemoryBuffer::getMemBufferCopy(OS.str());
43 
44     std::unique_ptr<MemoryBuffer> Binary = object::OffloadBinary::write(Image);
45 
46     // Copy the data to a new buffer so we can modify the bytes directly.
47     SmallVector<char> NewBuffer;
48     std::copy(Binary->getBufferStart(), Binary->getBufferEnd(),
49               std::back_inserter(NewBuffer));
50     auto *TheHeader =
51         reinterpret_cast<object::OffloadBinary::Header *>(&NewBuffer[0]);
52     if (Doc.Version)
53       TheHeader->Version = *Doc.Version;
54     if (Doc.Size)
55       TheHeader->Size = *Doc.Size;
56     if (Doc.EntryOffset)
57       TheHeader->EntryOffset = *Doc.EntryOffset;
58     if (Doc.EntrySize)
59       TheHeader->EntrySize = *Doc.EntrySize;
60 
61     Out.write(NewBuffer.begin(), NewBuffer.size());
62   }
63 
64   return true;
65 }
66 
67 } // namespace yaml
68 } // namespace llvm
69