linker.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. // Copyright (c) 2017 Pierre Moreau
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "spirv-tools/linker.hpp"
  15. #include <algorithm>
  16. #include <cstdio>
  17. #include <cstring>
  18. #include <iostream>
  19. #include <memory>
  20. #include <string>
  21. #include <unordered_map>
  22. #include <unordered_set>
  23. #include <utility>
  24. #include <vector>
  25. #include "source/assembly_grammar.h"
  26. #include "source/diagnostic.h"
  27. #include "source/opt/build_module.h"
  28. #include "source/opt/compact_ids_pass.h"
  29. #include "source/opt/decoration_manager.h"
  30. #include "source/opt/ir_loader.h"
  31. #include "source/opt/pass_manager.h"
  32. #include "source/opt/remove_duplicates_pass.h"
  33. #include "source/spirv_target_env.h"
  34. #include "source/util/make_unique.h"
  35. #include "spirv-tools/libspirv.hpp"
  36. namespace spvtools {
  37. namespace {
  38. using opt::IRContext;
  39. using opt::Instruction;
  40. using opt::Module;
  41. using opt::Operand;
  42. using opt::PassManager;
  43. using opt::RemoveDuplicatesPass;
  44. using opt::analysis::DecorationManager;
  45. using opt::analysis::DefUseManager;
  46. // Stores various information about an imported or exported symbol.
  47. struct LinkageSymbolInfo {
  48. SpvId id; // ID of the symbol
  49. SpvId type_id; // ID of the type of the symbol
  50. std::string name; // unique name defining the symbol and used for matching
  51. // imports and exports together
  52. std::vector<SpvId> parameter_ids; // ID of the parameters of the symbol, if
  53. // it is a function
  54. };
  55. struct LinkageEntry {
  56. LinkageSymbolInfo imported_symbol;
  57. LinkageSymbolInfo exported_symbol;
  58. LinkageEntry(const LinkageSymbolInfo& import_info,
  59. const LinkageSymbolInfo& export_info)
  60. : imported_symbol(import_info), exported_symbol(export_info) {}
  61. };
  62. using LinkageTable = std::vector<LinkageEntry>;
  63. // Shifts the IDs used in each binary of |modules| so that they occupy a
  64. // disjoint range from the other binaries, and compute the new ID bound which
  65. // is returned in |max_id_bound|.
  66. //
  67. // Both |modules| and |max_id_bound| should not be null, and |modules| should
  68. // not be empty either. Furthermore |modules| should not contain any null
  69. // pointers.
  70. spv_result_t ShiftIdsInModules(const MessageConsumer& consumer,
  71. std::vector<opt::Module*>* modules,
  72. uint32_t* max_id_bound);
  73. // Generates the header for the linked module and returns it in |header|.
  74. //
  75. // |header| should not be null, |modules| should not be empty and pointers
  76. // should be non-null. |max_id_bound| should be strictly greater than 0.
  77. //
  78. // TODO(pierremoreau): What to do when binaries use different versions of
  79. // SPIR-V? For now, use the max of all versions found in
  80. // the input modules.
  81. spv_result_t GenerateHeader(const MessageConsumer& consumer,
  82. const std::vector<opt::Module*>& modules,
  83. uint32_t max_id_bound, opt::ModuleHeader* header);
  84. // Merge all the modules from |in_modules| into a single module owned by
  85. // |linked_context|.
  86. //
  87. // |linked_context| should not be null.
  88. spv_result_t MergeModules(const MessageConsumer& consumer,
  89. const std::vector<Module*>& in_modules,
  90. const AssemblyGrammar& grammar,
  91. IRContext* linked_context);
  92. // Compute all pairs of import and export and return it in |linkings_to_do|.
  93. //
  94. // |linkings_to_do should not be null. Built-in symbols will be ignored.
  95. //
  96. // TODO(pierremoreau): Linkage attributes applied by a group decoration are
  97. // currently not handled. (You could have a group being
  98. // applied to a single ID.)
  99. // TODO(pierremoreau): What should be the proper behaviour with built-in
  100. // symbols?
  101. spv_result_t GetImportExportPairs(const MessageConsumer& consumer,
  102. const opt::IRContext& linked_context,
  103. const DefUseManager& def_use_manager,
  104. const DecorationManager& decoration_manager,
  105. bool allow_partial_linkage,
  106. LinkageTable* linkings_to_do);
  107. // Checks that for each pair of import and export, the import and export have
  108. // the same type as well as the same decorations.
  109. //
  110. // TODO(pierremoreau): Decorations on functions parameters are currently not
  111. // checked.
  112. spv_result_t CheckImportExportCompatibility(const MessageConsumer& consumer,
  113. const LinkageTable& linkings_to_do,
  114. opt::IRContext* context);
  115. // Remove linkage specific instructions, such as prototypes of imported
  116. // functions, declarations of imported variables, import (and export if
  117. // necessary) linkage attribtes.
  118. //
  119. // |linked_context| and |decoration_manager| should not be null, and the
  120. // 'RemoveDuplicatePass' should be run first.
  121. //
  122. // TODO(pierremoreau): Linkage attributes applied by a group decoration are
  123. // currently not handled. (You could have a group being
  124. // applied to a single ID.)
  125. // TODO(pierremoreau): Run a pass for removing dead instructions, for example
  126. // OpName for prototypes of imported funcions.
  127. spv_result_t RemoveLinkageSpecificInstructions(
  128. const MessageConsumer& consumer, const LinkerOptions& options,
  129. const LinkageTable& linkings_to_do, DecorationManager* decoration_manager,
  130. opt::IRContext* linked_context);
  131. // Verify that the unique ids of each instruction in |linked_context| (i.e. the
  132. // merged module) are truly unique. Does not check the validity of other ids
  133. spv_result_t VerifyIds(const MessageConsumer& consumer,
  134. opt::IRContext* linked_context);
  135. spv_result_t ShiftIdsInModules(const MessageConsumer& consumer,
  136. std::vector<opt::Module*>* modules,
  137. uint32_t* max_id_bound) {
  138. spv_position_t position = {};
  139. if (modules == nullptr)
  140. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  141. << "|modules| of ShiftIdsInModules should not be null.";
  142. if (modules->empty())
  143. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  144. << "|modules| of ShiftIdsInModules should not be empty.";
  145. if (max_id_bound == nullptr)
  146. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  147. << "|max_id_bound| of ShiftIdsInModules should not be null.";
  148. uint32_t id_bound = modules->front()->IdBound() - 1u;
  149. for (auto module_iter = modules->begin() + 1; module_iter != modules->end();
  150. ++module_iter) {
  151. Module* module = *module_iter;
  152. module->ForEachInst([&id_bound](Instruction* insn) {
  153. insn->ForEachId([&id_bound](uint32_t* id) { *id += id_bound; });
  154. });
  155. id_bound += module->IdBound() - 1u;
  156. if (id_bound > 0x3FFFFF)
  157. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_ID)
  158. << "The limit of IDs, 4194303, was exceeded:"
  159. << " " << id_bound << " is the current ID bound.";
  160. // Invalidate the DefUseManager
  161. module->context()->InvalidateAnalyses(opt::IRContext::kAnalysisDefUse);
  162. }
  163. ++id_bound;
  164. if (id_bound > 0x3FFFFF)
  165. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_ID)
  166. << "The limit of IDs, 4194303, was exceeded:"
  167. << " " << id_bound << " is the current ID bound.";
  168. *max_id_bound = id_bound;
  169. return SPV_SUCCESS;
  170. }
  171. spv_result_t GenerateHeader(const MessageConsumer& consumer,
  172. const std::vector<opt::Module*>& modules,
  173. uint32_t max_id_bound, opt::ModuleHeader* header) {
  174. spv_position_t position = {};
  175. if (modules.empty())
  176. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  177. << "|modules| of GenerateHeader should not be empty.";
  178. if (max_id_bound == 0u)
  179. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  180. << "|max_id_bound| of GenerateHeader should not be null.";
  181. uint32_t version = 0u;
  182. for (const auto& module : modules)
  183. version = std::max(version, module->version());
  184. header->magic_number = SpvMagicNumber;
  185. header->version = version;
  186. header->generator = 17u;
  187. header->bound = max_id_bound;
  188. header->reserved = 0u;
  189. return SPV_SUCCESS;
  190. }
  191. spv_result_t MergeModules(const MessageConsumer& consumer,
  192. const std::vector<Module*>& input_modules,
  193. const AssemblyGrammar& grammar,
  194. IRContext* linked_context) {
  195. spv_position_t position = {};
  196. if (linked_context == nullptr)
  197. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  198. << "|linked_module| of MergeModules should not be null.";
  199. Module* linked_module = linked_context->module();
  200. if (input_modules.empty()) return SPV_SUCCESS;
  201. for (const auto& module : input_modules)
  202. for (const auto& inst : module->capabilities())
  203. linked_module->AddCapability(
  204. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  205. for (const auto& module : input_modules)
  206. for (const auto& inst : module->extensions())
  207. linked_module->AddExtension(
  208. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  209. for (const auto& module : input_modules)
  210. for (const auto& inst : module->ext_inst_imports())
  211. linked_module->AddExtInstImport(
  212. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  213. do {
  214. const Instruction* memory_model_inst = input_modules[0]->GetMemoryModel();
  215. if (memory_model_inst == nullptr) break;
  216. uint32_t addressing_model = memory_model_inst->GetSingleWordOperand(0u);
  217. uint32_t memory_model = memory_model_inst->GetSingleWordOperand(1u);
  218. for (const auto& module : input_modules) {
  219. memory_model_inst = module->GetMemoryModel();
  220. if (memory_model_inst == nullptr) continue;
  221. if (addressing_model != memory_model_inst->GetSingleWordOperand(0u)) {
  222. spv_operand_desc initial_desc = nullptr, current_desc = nullptr;
  223. grammar.lookupOperand(SPV_OPERAND_TYPE_ADDRESSING_MODEL,
  224. addressing_model, &initial_desc);
  225. grammar.lookupOperand(SPV_OPERAND_TYPE_ADDRESSING_MODEL,
  226. memory_model_inst->GetSingleWordOperand(0u),
  227. &current_desc);
  228. return DiagnosticStream(position, consumer, "", SPV_ERROR_INTERNAL)
  229. << "Conflicting addressing models: " << initial_desc->name
  230. << " vs " << current_desc->name << ".";
  231. }
  232. if (memory_model != memory_model_inst->GetSingleWordOperand(1u)) {
  233. spv_operand_desc initial_desc = nullptr, current_desc = nullptr;
  234. grammar.lookupOperand(SPV_OPERAND_TYPE_MEMORY_MODEL, memory_model,
  235. &initial_desc);
  236. grammar.lookupOperand(SPV_OPERAND_TYPE_MEMORY_MODEL,
  237. memory_model_inst->GetSingleWordOperand(1u),
  238. &current_desc);
  239. return DiagnosticStream(position, consumer, "", SPV_ERROR_INTERNAL)
  240. << "Conflicting memory models: " << initial_desc->name << " vs "
  241. << current_desc->name << ".";
  242. }
  243. }
  244. if (memory_model_inst != nullptr)
  245. linked_module->SetMemoryModel(std::unique_ptr<Instruction>(
  246. memory_model_inst->Clone(linked_context)));
  247. } while (false);
  248. std::vector<std::pair<uint32_t, const char*>> entry_points;
  249. for (const auto& module : input_modules)
  250. for (const auto& inst : module->entry_points()) {
  251. const uint32_t model = inst.GetSingleWordInOperand(0);
  252. const char* const name =
  253. reinterpret_cast<const char*>(inst.GetInOperand(2).words.data());
  254. const auto i = std::find_if(
  255. entry_points.begin(), entry_points.end(),
  256. [model, name](const std::pair<uint32_t, const char*>& v) {
  257. return v.first == model && strcmp(name, v.second) == 0;
  258. });
  259. if (i != entry_points.end()) {
  260. spv_operand_desc desc = nullptr;
  261. grammar.lookupOperand(SPV_OPERAND_TYPE_EXECUTION_MODEL, model, &desc);
  262. return DiagnosticStream(position, consumer, "", SPV_ERROR_INTERNAL)
  263. << "The entry point \"" << name << "\", with execution model "
  264. << desc->name << ", was already defined.";
  265. }
  266. linked_module->AddEntryPoint(
  267. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  268. entry_points.emplace_back(model, name);
  269. }
  270. for (const auto& module : input_modules)
  271. for (const auto& inst : module->execution_modes())
  272. linked_module->AddExecutionMode(
  273. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  274. for (const auto& module : input_modules)
  275. for (const auto& inst : module->debugs1())
  276. linked_module->AddDebug1Inst(
  277. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  278. for (const auto& module : input_modules)
  279. for (const auto& inst : module->debugs2())
  280. linked_module->AddDebug2Inst(
  281. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  282. for (const auto& module : input_modules)
  283. for (const auto& inst : module->debugs3())
  284. linked_module->AddDebug3Inst(
  285. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  286. // If the generated module uses SPIR-V 1.1 or higher, add an
  287. // OpModuleProcessed instruction about the linking step.
  288. if (linked_module->version() >= 0x10100) {
  289. const std::string processed_string("Linked by SPIR-V Tools Linker");
  290. const auto num_chars = processed_string.size();
  291. // Compute num words, accommodate the terminating null character.
  292. const auto num_words = (num_chars + 1 + 3) / 4;
  293. std::vector<uint32_t> processed_words(num_words, 0u);
  294. std::memcpy(processed_words.data(), processed_string.data(), num_chars);
  295. linked_module->AddDebug3Inst(std::unique_ptr<Instruction>(
  296. new Instruction(linked_context, SpvOpModuleProcessed, 0u, 0u,
  297. {{SPV_OPERAND_TYPE_LITERAL_STRING, processed_words}})));
  298. }
  299. for (const auto& module : input_modules)
  300. for (const auto& inst : module->annotations())
  301. linked_module->AddAnnotationInst(
  302. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  303. // TODO(pierremoreau): Since the modules have not been validate, should we
  304. // expect SpvStorageClassFunction variables outside
  305. // functions?
  306. uint32_t num_global_values = 0u;
  307. for (const auto& module : input_modules) {
  308. for (const auto& inst : module->types_values()) {
  309. linked_module->AddType(
  310. std::unique_ptr<Instruction>(inst.Clone(linked_context)));
  311. num_global_values += inst.opcode() == SpvOpVariable;
  312. }
  313. }
  314. if (num_global_values > 0xFFFF)
  315. return DiagnosticStream(position, consumer, "", SPV_ERROR_INTERNAL)
  316. << "The limit of global values, 65535, was exceeded;"
  317. << " " << num_global_values << " global values were found.";
  318. // Process functions and their basic blocks
  319. for (const auto& module : input_modules) {
  320. for (const auto& func : *module) {
  321. std::unique_ptr<opt::Function> cloned_func(func.Clone(linked_context));
  322. linked_module->AddFunction(std::move(cloned_func));
  323. }
  324. }
  325. return SPV_SUCCESS;
  326. }
  327. spv_result_t GetImportExportPairs(const MessageConsumer& consumer,
  328. const opt::IRContext& linked_context,
  329. const DefUseManager& def_use_manager,
  330. const DecorationManager& decoration_manager,
  331. bool allow_partial_linkage,
  332. LinkageTable* linkings_to_do) {
  333. spv_position_t position = {};
  334. if (linkings_to_do == nullptr)
  335. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  336. << "|linkings_to_do| of GetImportExportPairs should not be empty.";
  337. std::vector<LinkageSymbolInfo> imports;
  338. std::unordered_map<std::string, std::vector<LinkageSymbolInfo>> exports;
  339. // Figure out the imports and exports
  340. for (const auto& decoration : linked_context.annotations()) {
  341. if (decoration.opcode() != SpvOpDecorate ||
  342. decoration.GetSingleWordInOperand(1u) != SpvDecorationLinkageAttributes)
  343. continue;
  344. const SpvId id = decoration.GetSingleWordInOperand(0u);
  345. // Ignore if the targeted symbol is a built-in
  346. bool is_built_in = false;
  347. for (const auto& id_decoration :
  348. decoration_manager.GetDecorationsFor(id, false)) {
  349. if (id_decoration->GetSingleWordInOperand(1u) == SpvDecorationBuiltIn) {
  350. is_built_in = true;
  351. break;
  352. }
  353. }
  354. if (is_built_in) {
  355. continue;
  356. }
  357. const uint32_t type = decoration.GetSingleWordInOperand(3u);
  358. LinkageSymbolInfo symbol_info;
  359. symbol_info.name =
  360. reinterpret_cast<const char*>(decoration.GetInOperand(2u).words.data());
  361. symbol_info.id = id;
  362. symbol_info.type_id = 0u;
  363. // Retrieve the type of the current symbol. This information will be used
  364. // when checking that the imported and exported symbols have the same
  365. // types.
  366. const Instruction* def_inst = def_use_manager.GetDef(id);
  367. if (def_inst == nullptr)
  368. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  369. << "ID " << id << " is never defined:\n";
  370. if (def_inst->opcode() == SpvOpVariable) {
  371. symbol_info.type_id = def_inst->type_id();
  372. } else if (def_inst->opcode() == SpvOpFunction) {
  373. symbol_info.type_id = def_inst->GetSingleWordInOperand(1u);
  374. // range-based for loop calls begin()/end(), but never cbegin()/cend(),
  375. // which will not work here.
  376. for (auto func_iter = linked_context.module()->cbegin();
  377. func_iter != linked_context.module()->cend(); ++func_iter) {
  378. if (func_iter->result_id() != id) continue;
  379. func_iter->ForEachParam([&symbol_info](const Instruction* inst) {
  380. symbol_info.parameter_ids.push_back(inst->result_id());
  381. });
  382. }
  383. } else {
  384. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  385. << "Only global variables and functions can be decorated using"
  386. << " LinkageAttributes; " << id << " is neither of them.\n";
  387. }
  388. if (type == SpvLinkageTypeImport)
  389. imports.push_back(symbol_info);
  390. else if (type == SpvLinkageTypeExport)
  391. exports[symbol_info.name].push_back(symbol_info);
  392. }
  393. // Find the import/export pairs
  394. for (const auto& import : imports) {
  395. std::vector<LinkageSymbolInfo> possible_exports;
  396. const auto& exp = exports.find(import.name);
  397. if (exp != exports.end()) possible_exports = exp->second;
  398. if (possible_exports.empty() && !allow_partial_linkage)
  399. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  400. << "Unresolved external reference to \"" << import.name << "\".";
  401. else if (possible_exports.size() > 1u)
  402. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  403. << "Too many external references, " << possible_exports.size()
  404. << ", were found for \"" << import.name << "\".";
  405. if (!possible_exports.empty())
  406. linkings_to_do->emplace_back(import, possible_exports.front());
  407. }
  408. return SPV_SUCCESS;
  409. }
  410. spv_result_t CheckImportExportCompatibility(const MessageConsumer& consumer,
  411. const LinkageTable& linkings_to_do,
  412. opt::IRContext* context) {
  413. spv_position_t position = {};
  414. // Ensure th import and export types are the same.
  415. const DefUseManager& def_use_manager = *context->get_def_use_mgr();
  416. const DecorationManager& decoration_manager = *context->get_decoration_mgr();
  417. for (const auto& linking_entry : linkings_to_do) {
  418. if (!RemoveDuplicatesPass::AreTypesEqual(
  419. *def_use_manager.GetDef(linking_entry.imported_symbol.type_id),
  420. *def_use_manager.GetDef(linking_entry.exported_symbol.type_id),
  421. context))
  422. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  423. << "Type mismatch on symbol \""
  424. << linking_entry.imported_symbol.name
  425. << "\" between imported variable/function %"
  426. << linking_entry.imported_symbol.id
  427. << " and exported variable/function %"
  428. << linking_entry.exported_symbol.id << ".";
  429. }
  430. // Ensure the import and export decorations are similar
  431. for (const auto& linking_entry : linkings_to_do) {
  432. if (!decoration_manager.HaveTheSameDecorations(
  433. linking_entry.imported_symbol.id, linking_entry.exported_symbol.id))
  434. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  435. << "Decorations mismatch on symbol \""
  436. << linking_entry.imported_symbol.name
  437. << "\" between imported variable/function %"
  438. << linking_entry.imported_symbol.id
  439. << " and exported variable/function %"
  440. << linking_entry.exported_symbol.id << ".";
  441. // TODO(pierremoreau): Decorations on function parameters should probably
  442. // match, except for FuncParamAttr if I understand the
  443. // spec correctly.
  444. // TODO(pierremoreau): Decorations on the function return type should
  445. // match, except for FuncParamAttr.
  446. }
  447. return SPV_SUCCESS;
  448. }
  449. spv_result_t RemoveLinkageSpecificInstructions(
  450. const MessageConsumer& consumer, const LinkerOptions& options,
  451. const LinkageTable& linkings_to_do, DecorationManager* decoration_manager,
  452. opt::IRContext* linked_context) {
  453. spv_position_t position = {};
  454. if (decoration_manager == nullptr)
  455. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  456. << "|decoration_manager| of RemoveLinkageSpecificInstructions "
  457. "should not be empty.";
  458. if (linked_context == nullptr)
  459. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_DATA)
  460. << "|linked_module| of RemoveLinkageSpecificInstructions should not "
  461. "be empty.";
  462. // TODO(pierremoreau): Remove FuncParamAttr decorations of imported
  463. // functions' return type.
  464. // Remove FuncParamAttr decorations of imported functions' parameters.
  465. // From the SPIR-V specification, Sec. 2.13:
  466. // When resolving imported functions, the Function Control and all Function
  467. // Parameter Attributes are taken from the function definition, and not
  468. // from the function declaration.
  469. for (const auto& linking_entry : linkings_to_do) {
  470. for (const auto parameter_id :
  471. linking_entry.imported_symbol.parameter_ids) {
  472. decoration_manager->RemoveDecorationsFrom(
  473. parameter_id, [](const Instruction& inst) {
  474. return (inst.opcode() == SpvOpDecorate ||
  475. inst.opcode() == SpvOpMemberDecorate) &&
  476. inst.GetSingleWordInOperand(1u) ==
  477. SpvDecorationFuncParamAttr;
  478. });
  479. }
  480. }
  481. // Remove prototypes of imported functions
  482. for (const auto& linking_entry : linkings_to_do) {
  483. for (auto func_iter = linked_context->module()->begin();
  484. func_iter != linked_context->module()->end();) {
  485. if (func_iter->result_id() == linking_entry.imported_symbol.id)
  486. func_iter = func_iter.Erase();
  487. else
  488. ++func_iter;
  489. }
  490. }
  491. // Remove declarations of imported variables
  492. for (const auto& linking_entry : linkings_to_do) {
  493. auto next = linked_context->types_values_begin();
  494. for (auto inst = next; inst != linked_context->types_values_end();
  495. inst = next) {
  496. ++next;
  497. if (inst->result_id() == linking_entry.imported_symbol.id) {
  498. linked_context->KillInst(&*inst);
  499. }
  500. }
  501. }
  502. // If partial linkage is allowed, we need an efficient way to check whether
  503. // an imported ID had a corresponding export symbol. As uses of the imported
  504. // symbol have already been replaced by the exported symbol, use the exported
  505. // symbol ID.
  506. // TODO(pierremoreau): This will not work if the decoration is applied
  507. // through a group, but the linker does not support that
  508. // either.
  509. std::unordered_set<SpvId> imports;
  510. if (options.GetAllowPartialLinkage()) {
  511. imports.reserve(linkings_to_do.size());
  512. for (const auto& linking_entry : linkings_to_do)
  513. imports.emplace(linking_entry.exported_symbol.id);
  514. }
  515. // Remove import linkage attributes
  516. auto next = linked_context->annotation_begin();
  517. for (auto inst = next; inst != linked_context->annotation_end();
  518. inst = next) {
  519. ++next;
  520. // If this is an import annotation:
  521. // * if we do not allow partial linkage, remove all import annotations;
  522. // * otherwise, remove the annotation only if there was a corresponding
  523. // export.
  524. if (inst->opcode() == SpvOpDecorate &&
  525. inst->GetSingleWordOperand(1u) == SpvDecorationLinkageAttributes &&
  526. inst->GetSingleWordOperand(3u) == SpvLinkageTypeImport &&
  527. (!options.GetAllowPartialLinkage() ||
  528. imports.find(inst->GetSingleWordOperand(0u)) != imports.end())) {
  529. linked_context->KillInst(&*inst);
  530. }
  531. }
  532. // Remove export linkage attributes if making an executable
  533. if (!options.GetCreateLibrary()) {
  534. next = linked_context->annotation_begin();
  535. for (auto inst = next; inst != linked_context->annotation_end();
  536. inst = next) {
  537. ++next;
  538. if (inst->opcode() == SpvOpDecorate &&
  539. inst->GetSingleWordOperand(1u) == SpvDecorationLinkageAttributes &&
  540. inst->GetSingleWordOperand(3u) == SpvLinkageTypeExport) {
  541. linked_context->KillInst(&*inst);
  542. }
  543. }
  544. }
  545. // Remove Linkage capability if making an executable and partial linkage is
  546. // not allowed
  547. if (!options.GetCreateLibrary() && !options.GetAllowPartialLinkage()) {
  548. for (auto& inst : linked_context->capabilities())
  549. if (inst.GetSingleWordInOperand(0u) == SpvCapabilityLinkage) {
  550. linked_context->KillInst(&inst);
  551. // The RemoveDuplicatesPass did remove duplicated capabilities, so we
  552. // now there aren’t more SpvCapabilityLinkage further down.
  553. break;
  554. }
  555. }
  556. return SPV_SUCCESS;
  557. }
  558. spv_result_t VerifyIds(const MessageConsumer& consumer,
  559. opt::IRContext* linked_context) {
  560. std::unordered_set<uint32_t> ids;
  561. bool ok = true;
  562. linked_context->module()->ForEachInst(
  563. [&ids, &ok](const opt::Instruction* inst) {
  564. ok &= ids.insert(inst->unique_id()).second;
  565. });
  566. if (!ok) {
  567. consumer(SPV_MSG_INTERNAL_ERROR, "", {}, "Non-unique id in merged module");
  568. return SPV_ERROR_INVALID_ID;
  569. }
  570. return SPV_SUCCESS;
  571. }
  572. } // namespace
  573. spv_result_t Link(const Context& context,
  574. const std::vector<std::vector<uint32_t>>& binaries,
  575. std::vector<uint32_t>* linked_binary,
  576. const LinkerOptions& options) {
  577. std::vector<const uint32_t*> binary_ptrs;
  578. binary_ptrs.reserve(binaries.size());
  579. std::vector<size_t> binary_sizes;
  580. binary_sizes.reserve(binaries.size());
  581. for (const auto& binary : binaries) {
  582. binary_ptrs.push_back(binary.data());
  583. binary_sizes.push_back(binary.size());
  584. }
  585. return Link(context, binary_ptrs.data(), binary_sizes.data(), binaries.size(),
  586. linked_binary, options);
  587. }
  588. spv_result_t Link(const Context& context, const uint32_t* const* binaries,
  589. const size_t* binary_sizes, size_t num_binaries,
  590. std::vector<uint32_t>* linked_binary,
  591. const LinkerOptions& options) {
  592. spv_position_t position = {};
  593. const spv_context& c_context = context.CContext();
  594. const MessageConsumer& consumer = c_context->consumer;
  595. linked_binary->clear();
  596. if (num_binaries == 0u)
  597. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  598. << "No modules were given.";
  599. std::vector<std::unique_ptr<IRContext>> ir_contexts;
  600. std::vector<Module*> modules;
  601. modules.reserve(num_binaries);
  602. for (size_t i = 0u; i < num_binaries; ++i) {
  603. const uint32_t schema = binaries[i][4u];
  604. if (schema != 0u) {
  605. position.index = 4u;
  606. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  607. << "Schema is non-zero for module " << i << ".";
  608. }
  609. std::unique_ptr<IRContext> ir_context = BuildModule(
  610. c_context->target_env, consumer, binaries[i], binary_sizes[i]);
  611. if (ir_context == nullptr)
  612. return DiagnosticStream(position, consumer, "", SPV_ERROR_INVALID_BINARY)
  613. << "Failed to build a module out of " << ir_contexts.size() << ".";
  614. modules.push_back(ir_context->module());
  615. ir_contexts.push_back(std::move(ir_context));
  616. }
  617. // Phase 1: Shift the IDs used in each binary so that they occupy a disjoint
  618. // range from the other binaries, and compute the new ID bound.
  619. uint32_t max_id_bound = 0u;
  620. spv_result_t res = ShiftIdsInModules(consumer, &modules, &max_id_bound);
  621. if (res != SPV_SUCCESS) return res;
  622. // Phase 2: Generate the header
  623. opt::ModuleHeader header;
  624. res = GenerateHeader(consumer, modules, max_id_bound, &header);
  625. if (res != SPV_SUCCESS) return res;
  626. IRContext linked_context(c_context->target_env, consumer);
  627. linked_context.module()->SetHeader(header);
  628. // Phase 3: Merge all the binaries into a single one.
  629. AssemblyGrammar grammar(c_context);
  630. res = MergeModules(consumer, modules, grammar, &linked_context);
  631. if (res != SPV_SUCCESS) return res;
  632. if (options.GetVerifyIds()) {
  633. res = VerifyIds(consumer, &linked_context);
  634. if (res != SPV_SUCCESS) return res;
  635. }
  636. // Phase 4: Find the import/export pairs
  637. LinkageTable linkings_to_do;
  638. res = GetImportExportPairs(consumer, linked_context,
  639. *linked_context.get_def_use_mgr(),
  640. *linked_context.get_decoration_mgr(),
  641. options.GetAllowPartialLinkage(), &linkings_to_do);
  642. if (res != SPV_SUCCESS) return res;
  643. // Phase 5: Ensure the import and export have the same types and decorations.
  644. res =
  645. CheckImportExportCompatibility(consumer, linkings_to_do, &linked_context);
  646. if (res != SPV_SUCCESS) return res;
  647. // Phase 6: Remove duplicates
  648. PassManager manager;
  649. manager.SetMessageConsumer(consumer);
  650. manager.AddPass<RemoveDuplicatesPass>();
  651. opt::Pass::Status pass_res = manager.Run(&linked_context);
  652. if (pass_res == opt::Pass::Status::Failure) return SPV_ERROR_INVALID_DATA;
  653. // Phase 7: Rematch import variables/functions to export variables/functions
  654. for (const auto& linking_entry : linkings_to_do)
  655. linked_context.ReplaceAllUsesWith(linking_entry.imported_symbol.id,
  656. linking_entry.exported_symbol.id);
  657. // Phase 8: Remove linkage specific instructions, such as import/export
  658. // attributes, linkage capability, etc. if applicable
  659. res = RemoveLinkageSpecificInstructions(consumer, options, linkings_to_do,
  660. linked_context.get_decoration_mgr(),
  661. &linked_context);
  662. if (res != SPV_SUCCESS) return res;
  663. // Phase 9: Compact the IDs used in the module
  664. manager.AddPass<opt::CompactIdsPass>();
  665. pass_res = manager.Run(&linked_context);
  666. if (pass_res == opt::Pass::Status::Failure) return SPV_ERROR_INVALID_DATA;
  667. // Phase 10: Output the module
  668. linked_context.module()->ToBinary(linked_binary, true);
  669. return SPV_SUCCESS;
  670. }
  671. } // namespace spvtools