Debian Codegraph @

visa/iga/IGALibrary/api/iga.cpp

raw
1 /*========================== begin_copyright_notice ============================
2
3 Copyright (C) 2017-2021 Intel Corporation
4
5 SPDX-License-Identifier: MIT
6
7 ============================= end_copyright_notice ===========================*/
8
9 #include "iga.h"
10 #include "iga.hpp"
11 #include "igad.h"
12 // IGA headers
13 #include "../Backend/GED/Interface.hpp"
14 #include "../Backend/Native/Interface.hpp"
15 #include "../ErrorHandler.hpp"
16 #include "../Frontend/Formatter.hpp"
17 #include "../Frontend/KernelParser.hpp"
18 #include "../IR/Checker/IRChecker.hpp"
19 #include "../IR/DUAnalysis.hpp"
20 #include "../Models/Models.hpp"
21 #include "../strings.hpp"
22 #include "../version.hpp"
23 #include "common/secure_mem.h"
24 #include "common/secure_string.h"
25
26 // external dependencies
27 #include <algorithm>
28 #include <cstring>
29 #include <map>
30 #include <ostream>
31 #include <sstream>
32 #include <unordered_map>
33 #include <vector>
34
35 using namespace iga;
36
37 //
38 // BINARY COMPATIBILITY:
39 // We can add stuff to the assemble/diasseemble options without forcing users
40 // to recompile. E.g. the user compiles with an older header and has:
41 // struct opts {
42 // uint32_t cb; // = sizeof(opts)
43 // uint32_t opt;
44 // };
45 // #define INIT_OPTS(A) {sizeof(struct opts), A}
46 //
47 // Later, we internally add new options (features) and make the structure
48 // struct opts {
49 // uint32_t cb; // = sizeof(opts)
50 // uint32_t opt;
51 // uint32_t newOpt;
52 // uint32_t _reserved; // to pad out the structure on 64-bit compilers
53 // };
54 // #define INIT_OPTS(A1,A2) {sizeof(struct opts), A1, A2, 0}
55 //
56 // WARNING: ensure you pad the structure to 64 bit alignment.
57 // When IGA copies in the user structure it is careful to honor the user's
58 // cb field to determine how much of the structure to read in. We use a memcpy
59 // to copy the structure in safely.
60 //
61 // void iga_api(struct opts *opts)
62 // {
63 // struct opts optsInternal = INIT_OPTS(default1, default2);
64 // memcpy(&optsInternal, opts, opts->cb);
65 // use(optsInternal);
66 // }
67 //
68 // The above strategy allows us to add to the options as long as the new
69 // option has a sensible default.
70
71 const char *iga_status_to_string(iga_status_t st) {
72 switch (st) {
73 case IGA_SUCCESS:
74 return "succeeded";
75 case IGA_ERROR:
76 return "unknown error";
77 case IGA_INVALID_ARG:
78 return "invalid argument";
79 case IGA_OUT_OF_MEM:
80 return "out of memory";
81 case IGA_DECODE_ERROR:
82 return "decode error";
83 case IGA_ENCODE_ERROR:
84 return "encode error";
85 case IGA_PARSE_ERROR:
86 return "parse error";
87 case IGA_VERSION_ERROR:
88 return "version mismatch";
89 case IGA_INVALID_OBJECT:
90 return "invalid object";
91 case IGA_INVALID_STATE:
92 return "invalid state";
93 case IGA_UNSUPPORTED_PLATFORM:
94 return "unsupported platform";
95 case IGA_DIFF_FAILURE:
96 return "differences encountered";
97 default:
98 return "invalid error code";
99 }
100 }
101
102 iga_status_t iga_platforms_list(size_t gens_length_bytes, iga_gen_t *gens,
103 size_t *gens_length_bytes_required) {
104 if (gens_length_bytes != 0 && gens == nullptr)
105 return IGA_INVALID_ARG;
106
107 const size_t MAX_SPACE_NEEDED = ALL_MODELS_LEN * sizeof(iga_gen_t);
108 if (gens_length_bytes_required)
109 *gens_length_bytes_required = MAX_SPACE_NEEDED;
110 if (gens) {
111 for (size_t i = 0;
112 i < std::min(gens_length_bytes, MAX_SPACE_NEEDED) / sizeof(iga_gen_t);
113 i++) {
114 gens[i] = static_cast<iga_gen_t>(ALL_MODELS[i]->platform);
115 }
116 }
117 return IGA_SUCCESS;
118 }
119
120 // We run into a minor annoyance here. We must return IGA memory that
121 // that never gets cleaned up by the user. Thus we use module global
122 // memory. On DLL attach this initializer will run and on DLL detach it
123 // should be cleaned up.
124 //
125 //
126 // c.f. iga_platform_names and iga_platform_symbol_suffix
127 struct PlatformNameMap {
128 std::unordered_map<iga::Platform, std::vector<std::string>> names;
129 std::unordered_map<iga::Platform, std::string> exts;
130
131 PlatformNameMap() {
132 for (size_t i = 0; i < ALL_MODELS_LEN; i++) {
133 const Model &me = *ALL_MODELS[i];
134 std::vector<std::string> nmlist;
135 for (const auto &mn : me.names) {
136 std::string str = mn.str();
137 if (str.empty())
138 break;
139 nmlist.push_back(std::move(str));
140 }
141 names[me.platform] = std::move(nmlist);
142 exts[me.platform] = me.extension.str();
143 }
144 }
145 };
146 //
147 static const PlatformNameMap s_names;
148
149 iga_status_t iga_platform_symbol_suffix(iga_gen_t gen, const char **suffix) {
150 if (suffix == nullptr)
151 return IGA_INVALID_ARG;
152 auto itr = s_names.exts.find(ToPlatform(gen));
153 if (itr == s_names.exts.end()) {
154 *suffix = nullptr;
155 return IGA_INVALID_ARG;
156 }
157 *suffix = itr->second.c_str();
158
159 return IGA_SUCCESS;
160 }
161
162 iga_status_t iga_platform_names(iga_gen_t gen, size_t names_bytes,
163 const char **names,
164 size_t *names_bytes_needed) {
165 if (names_bytes != 0 && names == nullptr)
166 return IGA_INVALID_ARG;
167
168 auto itr = s_names.names.find(ToPlatform(gen));
169 if (itr == s_names.names.end()) {
170 return IGA_INVALID_ARG;
171 }
172 const auto &pltNames = itr->second;
173 if (names_bytes_needed)
174 *names_bytes_needed = pltNames.size() * sizeof(const char *);
175 const int n_copy = std::min<int>((int)pltNames.size(),
176 (int)names_bytes / sizeof(const char *));
177 for (int ni = 0; ni < n_copy; ni++)
178 names[ni] = pltNames[ni].c_str();
179
180 return IGA_SUCCESS;
181 }
182
183 class IGAContext {
184 private:
185 // set to a magic constant when the object is valid (live)
186 // this helps detection such as people passing the wrong context
187 // e.g. iga_release_context(&ctx) instead of iga_release_context(ctx)
188 uint64_t m_validToken;
189 // the options the context was created with
190 iga_context_options_t m_opts;
191 // the model corresponding to the gen options
192 const Model &m_model;
193 // a cached copy of the assembled bits
194 // we free this upon destruction
195 void *m_assemble_bits;
196 // a cached copy of the last disassembled text
197 // we free this upon destruction
198 char *m_disassemble_text;
199 // a reusable empty string to return on errors
200 char m_empty_string[4];
201
202 // diagnostics from the last compile
203 bool m_errorsValid, m_warningsValid;
204 std::vector<iga_diagnostic_t> m_errors, m_warnings;
205
206 public:
207 static void clearDiagnostics(std::vector<iga_diagnostic_t> &api_ds) {
208 for (auto &d : api_ds) {
209 free((void *)d.message);
210 memset(&d, 0xDE, sizeof(d));
211 }
212 api_ds.clear();
213 }
214
215 static iga_status_t
216 translateDiagnosticList(const std::vector<iga::Diagnostic> &ds,
217 std::vector<iga_diagnostic_t> &api_ds) {
218 for (const auto &d : ds) {
219 const char *str = strdup(d.message.c_str());
220 if (!str) {
221 return IGA_OUT_OF_MEM;
222 }
223
224 if (d.at.col != 0 && d.at.line != 0) {
225 // col and line
226 iga_diagnostic_t temp = {d.at.line, d.at.col, (uint32_t)d.at.offset,
227 d.at.extent, str};
228 api_ds.push_back(temp);
229 } else {
230 // pc (offset is in bytes)
231 iga_diagnostic_t temp = {0, 0, (uint32_t)d.at.offset, d.at.extent, str};
232 api_ds.push_back(temp);
233 }
234 }
235 return IGA_SUCCESS;
236 }
237
238 iga_status_t translateDiagnostics(const iga::ErrorHandler &eh) {
239 clearDiagnostics(m_errors);
240 clearDiagnostics(m_warnings);
241 m_warningsValid = m_errorsValid = false;
242
243 iga_status_t s1 = translateDiagnosticList(eh.getErrors(), m_errors);
244 if (s1 != IGA_SUCCESS) {
245 clearDiagnostics(m_errors);
246 return s1;
247 }
248
249 iga_status_t s2 = translateDiagnosticList(eh.getWarnings(), m_warnings);
250 if (s2 != IGA_SUCCESS) {
251 clearDiagnostics(m_warnings);
252 clearDiagnostics(m_errors);
253 return s2;
254 }
255
256 m_warningsValid = m_errorsValid = true;
257 return IGA_SUCCESS;
258 }
259
260 static const Model &convertPlatform(iga_gen_t gen) {
261 const Model *m = Model::LookupModel(ToPlatform(gen));
262 if (!m) {
263 throw FatalError();
264 }
265 return *m;
266 }
267
268 static const uint64_t VALID_COOKIE = 0xFEDCBA9876543210ull;
269
270 public:
271 IGAContext(iga_context_options_t opts)
272 : m_validToken(VALID_COOKIE), m_opts(opts),
273 m_model(convertPlatform(opts.gen)), m_assemble_bits(nullptr),
274 m_disassemble_text(nullptr), m_errorsValid(false),
275 m_warningsValid(false) {
276 memset(m_empty_string, 0, sizeof(m_empty_string));
277 }
278
279 IGAContext(const IGAContext&) = delete;
280 IGAContext& operator=(const IGAContext&) = delete;
281 ~IGAContext() {
282 m_validToken = 0xDEADDEADDEADDEADull;
283 clearDiagnostics(m_warnings);
284 clearDiagnostics(m_errors);
285
286 if (m_disassemble_text) {
287 free(m_disassemble_text);
288 m_disassemble_text = nullptr;
289 }
290 if (m_assemble_bits) {
291 free(m_assemble_bits);
292 m_assemble_bits = nullptr;
293 }
294 }
295
296 bool valid() const { return m_validToken == VALID_COOKIE; }
297
298 iga_status_t assemble(iga_assemble_options_t &aopts, const char *inp,
299 void **bits, uint32_t *bitsLen32) {
300 iga::ErrorHandler errHandler;
301 // compatibility for legacy fields
302 bool used_legacy_fields = false;
303 if (aopts._reserved0) { // used to be error_on_compact_fail
304 aopts.encoder_opts |= IGA_ENCODER_OPT_ERROR_ON_COMPACT_FAIL;
305 used_legacy_fields = true;
306 }
307
308 if (aopts._reserved1) { // used to be error_on_compact_fail
309 aopts.encoder_opts |= IGA_ENCODER_OPT_AUTO_DEPENDENCIES;
310 used_legacy_fields = true;
311 }
312
313 if (used_legacy_fields) {
314 errHandler.reportWarning(
315 Loc(1, 1, 0, 0),
316 "iga_assemble call uses deprecated options "
317 " (error_on_compact_fail or autoset_deps); see newest "
318 "iga.h header file for updated fields");
319 }
320
321 // 1. Parse the kernel text
322 ParseOpts popts(m_model);
323 popts.supportLegacyDirectives =
324 (aopts.syntax_opts & IGA_SYNTAX_OPT_LEGACY_SYNTAX) != 0;
325 Kernel *pKernel = iga::ParseGenKernel(m_model, inp, errHandler, popts);
326 if (pKernel && !errHandler.hasErrors() && aopts.enabled_warnings) {
327 // check semantics if we parsed without error && they haven't
328 // disabled all checking (-Wnone)
329 CheckSemantics(*pKernel, errHandler, aopts.enabled_warnings);
330 }
331 if (errHandler.hasErrors()) {
332 *bits = nullptr;
333 *bitsLen32 = 0;
334 iga_status_t st = translateDiagnostics(errHandler);
335 if (pKernel)
336 delete pKernel;
337 return (st != IGA_SUCCESS) ? st : IGA_PARSE_ERROR;
338 } else if (pKernel == nullptr) {
339 // parser returned nullptr for kernel, but with no errors
340 // shouldn't be reachable; implies we have a missing diagnostic
341 return IGA_ERROR;
342 }
343
344 // 3. Encode the final IR into bits
345 //
346 // clobber the last assembly's bits
347 if (m_assemble_bits) {
348 free(m_assemble_bits);
349 m_assemble_bits = nullptr;
350 }
351 size_t bitsLen = 0;
352 EncoderOpts eopts(
353 (aopts.encoder_opts & IGA_ENCODER_OPT_AUTO_COMPACT) != 0,
354 (aopts.encoder_opts & IGA_ENCODER_OPT_ERROR_ON_COMPACT_FAIL) == 0,
355 (aopts.encoder_opts & IGA_ENCODER_OPT_FORCE_NO_COMPACT) != 0);
356 eopts.autoDepSet =
357 (aopts.encoder_opts & IGA_ENCODER_OPT_AUTO_DEPENDENCIES) != 0;
358 eopts.sbidCount = aopts.sbid_count;
359 eopts.swsbEncodeMode =
360 static_cast<iga::SWSB_ENCODE_MODE>(aopts.swsb_encode_mode);
361 eopts.autoSBIDCounter =
362 (aopts.encoder_opts & IGA_ENCODER_OPT_AUTO_SBID_COUNTER) != 0;
363
364 if ((aopts.encoder_opts & IGA_ENCODER_OPT_USE_NATIVE) == 0) {
365 if (!iga::ged::IsEncodeSupported(m_model, eopts)) {
366 delete pKernel;
367 return IGA_UNSUPPORTED_PLATFORM;
368 }
369 iga::ged::Encode(m_model, eopts, errHandler, *pKernel, *bits, bitsLen);
370 } else {
371 if (!iga::native::IsEncodeSupported(m_model, eopts)) {
372 delete pKernel;
373 return IGA_UNSUPPORTED_PLATFORM;
374 }
375 iga::native::Encode(m_model, eopts, errHandler, *pKernel, *bits, bitsLen);
376 }
377 *bitsLen32 = (uint32_t)bitsLen;
378 if (errHandler.hasErrors()) {
379 // failed encoding
380 delete pKernel;
381 iga_status_t st = translateDiagnostics(errHandler);
382 return st == IGA_SUCCESS ? IGA_ENCODE_ERROR : st;
383 }
384
385 // 4. Copy out the result
386 // encoding succeeded, copy the bits out
387 m_assemble_bits = (void *)malloc(*bitsLen32);
388 if (!m_assemble_bits) {
389 delete pKernel;
390 return IGA_OUT_OF_MEM;
391 }
392 memcpy_s(m_assemble_bits, *bitsLen32, *bits, *bitsLen32);
393 *bits = m_assemble_bits;
394 delete pKernel;
395 return translateDiagnostics(errHandler);
396 }
397
398 FormatOpts formatterOpts(
399 const iga_disassemble_options_t &dopts,
400 const char *(*formatLabel)(int32_t, void *), void *formatLabelEnv,
401 // swsb encoding mode, if not specified, the encoding mode will
402 // be derived from platform by SWSB::getEncdoeMode
403 SWSB_ENCODE_MODE swsbEnMod = SWSB_ENCODE_MODE::SWSBInvalidMode) {
404 FormatOpts fopts(m_model, formatLabel, formatLabelEnv);
405 fopts.addApiOpts(dopts.formatting_opts, dopts.base_pc_offset);
406 if (swsbEnMod == SWSB_ENCODE_MODE::SWSBInvalidMode)
407 fopts.setSWSBEncodingMode(m_model.getSWSBEncodeMode());
408 else
409 fopts.setSWSBEncodingMode(swsbEnMod);
410
411 return fopts;
412 }
413
414 void checkForLegacyFields(iga_disassemble_options_t &dopts,
415 iga::ErrorHandler &errHandler) {
416 // crude compatibility for legacy fields
417 bool used_legacy_fields = false;
418 if (dopts._reserved0) { // used to be hex_floats
419 dopts.formatting_opts |= IGA_FORMATTING_OPT_PRINT_HEX_FLOATS;
420 used_legacy_fields = true;
421 }
422 if (dopts._reserved1) { // used to be hex_floats
423 dopts.formatting_opts |= IGA_FORMATTING_OPT_PRINT_PC;
424 used_legacy_fields = true;
425 }
426 if (used_legacy_fields) {
427 errHandler.reportWarning(Loc(1, 1, 0, 0),
428 "iga_disassemble* call uses deprecated options "
429 " (hex_floats or print_pc); see newest "
430 "iga.h header file for updated fields");
431 }
432 }
433
434 iga_status_t disassembleKernel(iga::ErrorHandler &errHandler,
435 iga_disassemble_options_t &dopts,
436 const void *bits, uint32_t bitsLen,
437 Kernel *&k) {
438 k = nullptr;
439 checkForLegacyFields(dopts, errHandler);
440 DecoderOpts dopts2(
441 (dopts.formatting_opts & IGA_FORMATTING_OPT_NUMERIC_LABELS) != 0);
442
443 if ((dopts.decoder_opts & IGA_DECODING_OPT_NATIVE) == 0) {
444 if (!iga::ged::IsDecodeSupported(m_model, dopts2)) {
445 return IGA_UNSUPPORTED_PLATFORM;
446 }
447 k = iga::ged::Decode(m_model, dopts2, errHandler, bits, (size_t)bitsLen);
448 } else {
449 if (!iga::native::IsDecodeSupported(m_model, dopts2)) {
450 return IGA_UNSUPPORTED_PLATFORM;
451 }
452 k = iga::native::Decode(m_model, dopts2, errHandler, bits,
453 (size_t)bitsLen);
454 }
455 return k == nullptr ? IGA_DECODE_ERROR : IGA_SUCCESS;
456 }
457
458 iga_status_t disassemble(iga_disassemble_options_t &dopts, const void *bits,
459 uint32_t bitsLen,
460 const char *(*formatLbl)(int32_t, void *),
461 void *formatLblEnv, char **output) {
462 if (output)
463 *output = &m_empty_string[0];
464
465 iga::Kernel *k = nullptr;
466 iga::ErrorHandler errHandler;
467 iga_status_t st = IGA_ERROR;
468
469 st = disassembleKernel(errHandler, dopts, bits, bitsLen, k);
470 if (k != nullptr) {
471 // we succeeded in decoding; now format the output to text
472 std::stringstream ss;
473 FormatOpts fopts = formatterOpts(dopts, formatLbl, formatLblEnv);
474 if (dopts.formatting_opts & IGA_FORMATTING_OPT_PRINT_DEFS) {
475 // Set the IDs here (kernel helper function)
476 k->resetIds();
477 // set fopts.printInstDefs
478 fopts.printInstDefs = true;
479 }
480 FormatKernel(errHandler, ss, fopts, *k, bits);
481
482 // copy the text out
483 if (m_disassemble_text) {
484 // previous disassemble clobbers new disassemble
485 free(m_disassemble_text);
486 }
487 size_t slen = (size_t)ss.tellp();
488 m_disassemble_text = (char *)malloc(1 + slen);
489 if (!m_disassemble_text) {
490 // bail out
491 delete k;
492 return IGA_OUT_OF_MEM;
493 }
494 ss.read(m_disassemble_text, slen);
495 m_disassemble_text[slen] = 0;
496 if (output) {
497 *output = m_disassemble_text;
498 }
499
500 delete k;
501 } // k non-null
502
503 st = translateDiagnostics(errHandler);
504 if (errHandler.hasErrors()) {
505 return IGA_DECODE_ERROR;
506 }
507 return st;
508 }
509
510 iga_status_t disassembleInstruction(iga_disassemble_options_t &dopts,
511 const void *bits,
512 const char *(*formatLbl)(int32_t, void *),
513 void *formatLblEnv, char **output) {
514 if (output)
515 *output = &m_empty_string[0];
516
517 // infer the length based on compaction bit
518 size_t bitsLen = ((const MInst *)bits)->isCompact() ? 8 : 16;
519
520 iga::Kernel *k = nullptr;
521 iga::ErrorHandler errHandler;
522 iga_status_t st = IGA_ERROR;
523
524 // force decoding opts to use numeric labels
525 dopts.formatting_opts |= IGA_FORMATTING_OPT_NUMERIC_LABELS;
526
527 st = disassembleKernel(errHandler, dopts, bits, (uint32_t)bitsLen, k);
528 if (k != nullptr) {
529 if (m_disassemble_text) {
530 // previous disassemble clobbers new disassemble
531 free(m_disassemble_text);
532 }
533
534 const Instruction *firstInst = nullptr;
535 const iga::BlockList &bl = k->getBlockList();
536 for (const auto &b : bl) {
537 if (!b->getInstList().empty()) {
538 firstInst = b->getInstList().front();
539 break;
540 }
541 }
542 if (!firstInst) {
543 delete k;
544 return IGA_ERROR; // should be unreachable
545 }
546 std::stringstream ss;
547 FormatOpts fopts = formatterOpts(dopts, formatLbl, formatLblEnv);
548 FormatInstruction(errHandler, ss, fopts, *firstInst);
549
550 size_t slen = (size_t)ss.tellp();
551 m_disassemble_text = (char *)malloc(1 + slen);
552 if (!m_disassemble_text) {
553 delete k;
554 return IGA_OUT_OF_MEM;
555 }
556 ss.read(m_disassemble_text, slen);
557 m_disassemble_text[slen] = 0;
558 if (output) {
559 *output = m_disassemble_text;
560 }
561
562 delete k;
563 } // k non-null
564
565 st = translateDiagnostics(errHandler);
566 if (errHandler.hasErrors()) {
567 return IGA_DECODE_ERROR;
568 }
569 return st;
570 }
571
572 iga_status_t getErrors(const iga_diagnostic_t **ds, uint32_t *ds_len) const {
573 if (!m_errorsValid) {
574 *ds = nullptr;
575 *ds_len = 0;
576 return IGA_INVALID_STATE;
577 }
578 *ds_len = (uint32_t)m_errors.size();
579 *ds = *ds_len ? &m_errors[0] : nullptr;
580 return IGA_SUCCESS;
581 }
582
583 iga_status_t getWarnings(const iga_diagnostic_t **ds,
584 uint32_t *ds_len) const {
585 if (!m_warningsValid) {
586 *ds = nullptr;
587 *ds_len = 0;
588 return IGA_INVALID_STATE;
589 }
590 *ds_len = (uint32_t)m_warnings.size();
591 *ds = *ds_len ? &m_warnings[0] : nullptr;
592 return IGA_SUCCESS;
593 }
594 }; // class IGAContext
595
596 #define RETURN_INVALID_ARG_ON_NULL(X) \
597 do { \
598 if (!(X)) \
599 return IGA_INVALID_ARG; \
600 } while (0)
601
602 #define CAST_CONTEXT(ID, C) \
603 IGAContext *ID = (IGAContext *)(C); \
604 if (!ID->valid()) { \
605 return IGA_INVALID_OBJECT; \
606 }
607
608 const char *iga_version_string() {
609 return IGA_VERSION_PREFIX_STRING IGA_VERSION_SUFFIX;
610 }
611
612 iga_status_t iga_context_create(const iga_context_options_t *opts,
613 iga_context_t *ctx) {
614 RETURN_INVALID_ARG_ON_NULL(ctx);
615 RETURN_INVALID_ARG_ON_NULL(opts);
616
617 iga_context_options_t coptsInternal =
618 IGA_CONTEXT_OPTIONS_INIT(IGA_GEN_INVALID);
619 if (opts->cb > sizeof(iga_context_options_t)) {
620 return IGA_VERSION_ERROR;
621 }
622 memcpy_s(&coptsInternal, opts->cb, opts, opts->cb);
623
624 iga::Platform p = ToPlatform(opts->gen);
625 if (p == iga::Platform::INVALID) {
626 return IGA_UNSUPPORTED_PLATFORM;
627 }
628
629 IGAContext *ctx_obj = nullptr;
630 try {
631 ctx_obj = new IGAContext(*opts);
632 } catch (std::bad_alloc &) {
633 return IGA_OUT_OF_MEM;
634 }
635
636 *ctx = (iga_context_t *)ctx_obj;
637
638 return IGA_SUCCESS;
639 }
640 iga_status_t iga_create_context(const iga_context_options_t *opts,
641 iga_context_t *ctx) {
642 return iga_context_create(opts, ctx);
643 }
644
645 iga_status_t iga_context_release(iga_context_t ctx) {
646 RETURN_INVALID_ARG_ON_NULL(ctx);
647
648 CAST_CONTEXT(ctx_obj, ctx);
649 delete ctx_obj;
650
651 return IGA_SUCCESS;
652 }
653 iga_status_t iga_release_context(iga_context_t ctx) {
654 return iga_context_release(ctx);
655 }
656
657 iga_status_t iga_context_assemble(iga_context_t ctx,
658 const iga_assemble_options_t *aopts,
659 const char *kernel_text, void **output,
660 uint32_t *output_size) {
661 RETURN_INVALID_ARG_ON_NULL(ctx);
662 RETURN_INVALID_ARG_ON_NULL(aopts);
663 RETURN_INVALID_ARG_ON_NULL(kernel_text);
664 RETURN_INVALID_ARG_ON_NULL(output);
665 RETURN_INVALID_ARG_ON_NULL(output_size);
666 // see note at the top of the file about binary compatibility
667 if (aopts->cb > sizeof(*aopts)) {
668 return IGA_VERSION_ERROR;
669 }
670 iga_assemble_options_t aoptsInternal = IGA_ASSEMBLE_OPTIONS_INIT();
671 memcpy_s(&aoptsInternal, aopts->cb, aopts, aopts->cb);
672
673 CAST_CONTEXT(ctx_obj, ctx);
674 return ctx_obj->assemble(aoptsInternal, kernel_text, output, output_size);
675 }
676 IGA_API iga_status_t iga_assemble(iga_context_t ctx,
677 const iga_assemble_options_t *opts,
678 const char *kernel_text, void **output,
679 uint32_t *output_size) {
680 return iga_context_assemble(ctx, opts, kernel_text, output, output_size);
681 }
682
683 iga_status_t iga_context_disassemble(iga_context_t ctx,
684 const iga_disassemble_options_t *dopts,
685 const void *input, uint32_t input_size,
686 const char *(*fmt_label_name)(int32_t,
687 void *),
688 void *fmt_label_ctx, char **kernel_text) {
689 RETURN_INVALID_ARG_ON_NULL(ctx);
690 RETURN_INVALID_ARG_ON_NULL(dopts);
691 if (input == nullptr && input_size != 0)
692 return IGA_INVALID_ARG;
693 RETURN_INVALID_ARG_ON_NULL(kernel_text);
694 if (dopts->cb > sizeof(*dopts)) {
695 return IGA_VERSION_ERROR;
696 }
697 iga_disassemble_options_t doptsInternal = IGA_DISASSEMBLE_OPTIONS_INIT();
698 memcpy_s(&doptsInternal, dopts->cb, dopts, dopts->cb);
699
700 CAST_CONTEXT(ctx_obj, ctx);
701 return ctx_obj->disassemble(doptsInternal, input, input_size, fmt_label_name,
702 fmt_label_ctx, kernel_text);
703 }
704 iga_status_t iga_disassemble(iga_context_t ctx,
705 const iga_disassemble_options_t *dopts,
706 const void *input, uint32_t input_size,
707 const char *(*fmt_label_name)(int32_t, void *),
708 void *fmt_label_ctx, char **kernel_text) {
709 return iga_context_disassemble(ctx, dopts, input, input_size, fmt_label_name,
710 fmt_label_ctx, kernel_text);
711 }
712
713 iga_status_t iga_disassemble_instruction(
714 iga_context_t ctx, const iga_disassemble_options_t *dopts,
715 const void *input, const char *(*fmt_label_name)(int32_t, void *),
716 void *fmt_label_ctx, char **kernel_text) {
717 return iga_context_disassemble_instruction(ctx, dopts, input, fmt_label_name,
718 fmt_label_ctx, kernel_text);
719 }
720 iga_status_t iga_context_disassemble_instruction(
721 iga_context_t ctx, const iga_disassemble_options_t *dopts,
722 const void *input, const char *(*fmt_label_name)(int32_t, void *),
723 void *fmt_label_ctx, char **kernel_text) {
724 RETURN_INVALID_ARG_ON_NULL(ctx);
725 RETURN_INVALID_ARG_ON_NULL(dopts);
726 RETURN_INVALID_ARG_ON_NULL(input);
727 RETURN_INVALID_ARG_ON_NULL(kernel_text);
728 if (dopts->cb > sizeof(*dopts)) {
729 return IGA_VERSION_ERROR;
730 }
731 iga_disassemble_options_t doptsInternal =
732 IGA_DISASSEMBLE_OPTIONS_INIT_NUMERIC_LABELS();
733 memcpy_s(&doptsInternal, dopts->cb, dopts, dopts->cb);
734
735 CAST_CONTEXT(ctx_obj, ctx);
736 return ctx_obj->disassembleInstruction(doptsInternal, input, fmt_label_name,
737 fmt_label_ctx, kernel_text);
738 }
739
740 iga_status_t iga_context_get_errors(iga_context_t ctx,
741 const iga_diagnostic_t **ds,
742 uint32_t *ds_len) {
743 RETURN_INVALID_ARG_ON_NULL(ctx);
744 RETURN_INVALID_ARG_ON_NULL(ds);
745 RETURN_INVALID_ARG_ON_NULL(ds_len);
746
747 CAST_CONTEXT(ctx_obj, ctx);
748 return ctx_obj->getErrors(ds, ds_len);
749 }
750 iga_status_t iga_get_errors(iga_context_t ctx, const iga_diagnostic_t **ds,
751 uint32_t *ds_len) {
752 return iga_context_get_errors(ctx, ds, ds_len);
753 }
754
755 iga_status_t iga_context_get_warnings(iga_context_t ctx,
756 const iga_diagnostic_t **ds,
757 uint32_t *ds_len) {
758 RETURN_INVALID_ARG_ON_NULL(ctx);
759 RETURN_INVALID_ARG_ON_NULL(ds);
760 RETURN_INVALID_ARG_ON_NULL(ds_len);
761
762 CAST_CONTEXT(ctx_obj, ctx);
763 return ctx_obj->getWarnings(ds, ds_len);
764 }
765 iga_status_t iga_get_warnings(iga_context_t ctx, const iga_diagnostic_t **ds,
766 uint32_t *ds_len) {
767 return iga_context_get_warnings(ctx, ds, ds_len);
768 }
769
770 iga_status_t iga_diagnostic_get_message(const iga_diagnostic_t *d,
771 const char **message) {
772 RETURN_INVALID_ARG_ON_NULL(d);
773 RETURN_INVALID_ARG_ON_NULL(message);
774
775 *message = d->message;
776
777 return IGA_SUCCESS;
778 }
779
780 iga_status_t iga_diagnostic_get_offset(const iga_diagnostic_t *d,
781 uint32_t *offset) {
782 RETURN_INVALID_ARG_ON_NULL(d);
783 RETURN_INVALID_ARG_ON_NULL(offset);
784
785 *offset = d->offset;
786
787 return IGA_SUCCESS;
788 }
789
790 // static const uint32_t IGA_DIAGNOSTIC_BINARY_MASK = 0x80000000;
791 /* #define IGA_DIAGNOSTIC_IS_BINARY(D) \
792 ((D)->column & IGA_DIAGNOSTIC_BINARY_MASK)
793 for now we use line == col == 0 to mean binary
794 */
795 #define IGA_DIAGNOSTIC_IS_BINARY(D) ((D)->column == 0 && (D)->line == 0)
796
797 iga_status_t iga_diagnostic_get_type(const iga_diagnostic_t *d,
798 iga_diagnostic_type_t *dt) {
799 RETURN_INVALID_ARG_ON_NULL(d);
800 RETURN_INVALID_ARG_ON_NULL(dt);
801
802 *dt =
803 IGA_DIAGNOSTIC_IS_BINARY(d) ? IGA_DIAGNOSTIC_BINARY : IGA_DIAGNOSTIC_TEXT;
804
805 return IGA_SUCCESS;
806 }
807
808 iga_status_t iga_diagnostic_get_text_line(const iga_diagnostic_t *d,
809 uint32_t *line) {
810 RETURN_INVALID_ARG_ON_NULL(d);
811 RETURN_INVALID_ARG_ON_NULL(line);
812
813 if (IGA_DIAGNOSTIC_IS_BINARY(d))
814 return IGA_INVALID_ARG;
815
816 *line = d->line;
817
818 return IGA_SUCCESS;
819 }
820
821 iga_status_t iga_diagnostic_get_text_column(const iga_diagnostic_t *d,
822 uint32_t *col) {
823 RETURN_INVALID_ARG_ON_NULL(d);
824 RETURN_INVALID_ARG_ON_NULL(col);
825
826 if (IGA_DIAGNOSTIC_IS_BINARY(d))
827 return IGA_INVALID_ARG;
828 *col = d->column; // & ~IGA_DIAGNOSTIC_BINARY_MASK;
829
830 return IGA_SUCCESS;
831 }
832
833 iga_status_t iga_diagnostic_get_text_extent(const iga_diagnostic_t *d,
834 uint32_t *ext) {
835 RETURN_INVALID_ARG_ON_NULL(d);
836 RETURN_INVALID_ARG_ON_NULL(ext);
837
838 if (IGA_DIAGNOSTIC_IS_BINARY(d))
839 return IGA_INVALID_ARG;
840 *ext = d->extent;
841
842 return IGA_SUCCESS;
843 }
844
845 ///////////////////////////////////////////////////////////////////////////////
846 // //
847 // IGA OPSPEC API //
848 // //
849 ///////////////////////////////////////////////////////////////////////////////
850
851 #define IGA_COPY_OUT(DST, DST_LEN_PTR, SRC, SRC_LEN) \
852 do { \
853 if ((DST) != nullptr) { \
854 size_t _CPLEN = *(DST_LEN_PTR) < (SRC_LEN) ? *(DST_LEN_PTR) : (SRC_LEN); \
855 memcpy_s((DST), _CPLEN * sizeof(*(DST)), (SRC), \
856 _CPLEN * sizeof(*(DST))); \
857 } \
858 *(DST_LEN_PTR) = (SRC_LEN); \
859 } while (0)
860
861 // same as above, but for a string
862 #define IGA_COPY_OUT_STR(DST, DST_LEN_PTR, SRC) \
863 do { \
864 size_t SRC_LEN = iga::stringLength(SRC) + 1; \
865 if ((DST) != nullptr) { \
866 size_t _CPLEN = *(DST_LEN_PTR) < (SRC_LEN) ? *(DST_LEN_PTR) : (SRC_LEN); \
867 memcpy_s((DST), _CPLEN * sizeof(*(DST)), (SRC), \
868 _CPLEN * sizeof(*(DST))); \
869 DST[_CPLEN - 1] = 0; \
870 } \
871 *(DST_LEN_PTR) = (SRC_LEN); \
872 } while (0)
873
874 // In the opaque pointer returned, we flip some top bits.
875 // Should the user clobber their stack or accidentially send this pointer
876 // off to be written, this will hopefully trap immediately rather than
877 // internal data structures.
878 static iga_opspec_t opspec_to_handle(const OpSpec *os) {
879 const uintptr_t TOP_BIT =
880 (sizeof(void *) == 4) ? (uintptr_t)0xC0000000 : (uintptr_t)0x8000000000000000;
881 return (iga_opspec_t)((uintptr_t)os ^ TOP_BIT);
882 }
883 static const OpSpec *opspec_from_handle(iga_opspec_t os) {
884 const uintptr_t TOP_BIT =
885 (sizeof(void *) == 4) ? (uintptr_t)0xC0000000 : (uintptr_t)0x8000000000000000;
886 return (const OpSpec *)((uintptr_t)os ^ TOP_BIT);
887 }
888
889 iga_status_t iga_opspec_enumerate(iga_gen_t gen, iga_opspec_t *ops_arr,
890 size_t *ops_arr_len) {
891 RETURN_INVALID_ARG_ON_NULL(ops_arr_len);
892
893 const Model *m = Model::LookupModel(ToPlatform(gen));
894 if (!m) {
895 return IGA_UNSUPPORTED_PLATFORM;
896 }
897 std::vector<iga_opspec_t> ops;
898 ops.reserve(128);
899 for (const OpSpec *os : m->ops()) {
900 ops.emplace_back(opspec_to_handle(os));
901 }
902
903 IGA_COPY_OUT(ops_arr, ops_arr_len, ops.data(), ops.size());
904 return IGA_SUCCESS;
905 }
906
907 iga_status_t iga_opspec_from_op(iga_gen_t gen, uint32_t op_enum,
908 iga_opspec_t *op) {
909 RETURN_INVALID_ARG_ON_NULL(op);
910 const Model *m = Model::LookupModel(ToPlatform(gen));
911 if (!m) {
912 return IGA_UNSUPPORTED_PLATFORM;
913 }
914 const OpSpec *os = &m->lookupOpSpec(static_cast<iga::Op>(op_enum));
915 *op = opspec_to_handle(os);
916 return IGA_SUCCESS;
917 }
918
919 iga_status_t iga_opspec_mnemonic(iga_opspec_t op, char *mnemonic,
920 size_t *mnemonic_len) {
921 RETURN_INVALID_ARG_ON_NULL(op);
922 RETURN_INVALID_ARG_ON_NULL(mnemonic_len);
923
924 const OpSpec *os = opspec_from_handle(op);
925 IGA_COPY_OUT_STR(mnemonic, mnemonic_len, os->mnemonic.str().c_str());
926 return IGA_SUCCESS;
927 }
928
929 iga_status_t iga_opspec_name(iga_opspec_t op, char *name, size_t *name_len) {
930 RETURN_INVALID_ARG_ON_NULL(op);
931 RETURN_INVALID_ARG_ON_NULL(name_len);
932
933 const OpSpec *os = opspec_from_handle(op);
934 IGA_COPY_OUT_STR(name, name_len, os->name.str().c_str());
935 return IGA_SUCCESS;
936 }
937
938 iga_status_t iga_opspec_description(iga_opspec_t op, char *desc,
939 size_t *desc_len) {
940 RETURN_INVALID_ARG_ON_NULL(op);
941 RETURN_INVALID_ARG_ON_NULL(desc_len);
942
943 IGA_COPY_OUT_STR(desc, desc_len, "<description unsupported>");
944 return IGA_SUCCESS;
945 }
946
947 iga_status_t iga_opspec_op(iga_opspec_t op, uint32_t *opcode) {
948 RETURN_INVALID_ARG_ON_NULL(op);
949 RETURN_INVALID_ARG_ON_NULL(opcode);
950
951 *opcode = static_cast<uint32_t>(opspec_from_handle(op)->op);
952 return IGA_SUCCESS;
953 }
954
955 iga_status_t iga_opspec_op_encoding(iga_opspec_t op, uint32_t *opcode) {
956 RETURN_INVALID_ARG_ON_NULL(op);
957 RETURN_INVALID_ARG_ON_NULL(opcode);
958
959 *opcode = static_cast<uint32_t>(opspec_from_handle(op)->opcode);
960 return IGA_SUCCESS;
961 }
962
963 ///////////////////////////////////////////////////////////////////////////////
964 // RETURNS ALL THE FUNCTIONS IN A TABLE
965 ///////////////////////////////////////////////////////////////////////////////
966
967 iga_status_t iga_get_interface(iga_functions_t *funcs) {
968 RETURN_INVALID_ARG_ON_NULL(funcs);
969
970 funcs->iga_version_string = iga_version_string;
971 funcs->iga_status_to_string = iga_status_to_string;
972
973 funcs->iga_context_create = &iga_context_create;
974 funcs->iga_context_release = &iga_context_release;
975 funcs->iga_context_assemble = &iga_context_assemble;
976 funcs->iga_context_disassemble = &iga_context_disassemble;
977 funcs->iga_context_disassemble_instruction =
978 &iga_context_disassemble_instruction;
979 funcs->iga_context_get_errors = &iga_context_get_errors;
980 funcs->iga_context_get_warnings = &iga_context_get_warnings;
981
982 funcs->iga_diagnostic_get_message = &iga_diagnostic_get_message;
983 funcs->iga_diagnostic_get_offset = &iga_diagnostic_get_offset;
984 funcs->iga_diagnostic_get_type = &iga_diagnostic_get_type;
985 funcs->iga_diagnostic_get_text_line = &iga_diagnostic_get_text_line;
986 funcs->iga_diagnostic_get_text_column = &iga_diagnostic_get_text_column;
987 funcs->iga_diagnostic_get_text_extent = &iga_diagnostic_get_text_extent;
988
989 funcs->iga_opspec_enumerate = &iga_opspec_enumerate;
990 funcs->iga_opspec_mnemonic = &iga_opspec_mnemonic;
991 funcs->iga_opspec_name = &iga_opspec_name;
992 funcs->iga_opspec_description = &iga_opspec_description;
993 funcs->iga_opspec_op = &iga_opspec_op;
994
995 return IGA_SUCCESS;
996 }