linker.cpp 31 KB

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