-- Copyright (c) 2023 Adrian "asie" Siekierka
--
-- Licensed under the Apache License, Version 2.0 with LLVM Exceptions,                                   
-- See https://github.com/llvm-mos/llvm-mos-sdk/blob/main/LICENSE for license                             
-- information.

local BANK_MAX = 254

function next_power_of_two(i)
	i = i - 1
	i = i | (i >> 1)
	i = i | (i >> 2)
	i = i | (i >> 4)
	i = i | (i >> 8)
	i = i | (i >> 16)
	i = i | (i >> 32)
	return i + 1
end

function printf(...)
	print(string.format(table.unpack({...})))
end

local args = {...}
if args[1] == "output" then
	for i=0,BANK_MAX do
		printf("  FULL(prg_rom_%d)", i)
	end
	return
end

print("/* Automatically generated by generate-rom-banked-sections.lua. */\n")

print("INPUT(reset.o)")

for i=0,BANK_MAX do
	printf("__prg_rom_%d_lma = 0x%02x8000;", i, i)
end
printf("__prg_rom_fixed_lma = 0xc000;\n")

for i=0,BANK_MAX do
	printf("__prg_rom_%d_offset = 0x%06x;", i, i * 0x4000)
end
printf("__prg_rom_fixed_offset = __prg_rom_size * 1024 - 0x4000;\n")

printf("MEMORY {")
printf("  /* PRG-ROM LMAs. */")
for i=0,BANK_MAX do
	local rom_size_kb = next_power_of_two(i + 2) * 16
	printf("  prg_rom_%d : ORIGIN = __prg_rom_%d_lma, LENGTH = __prg_rom_size >= %d ? 0x4000 : 0", i, i, rom_size_kb)
end
print([[  prg_rom_fixed : ORIGIN = __prg_rom_fixed_lma, LENGTH = 0x4000 - 0x6
  vectors : ORIGIN = 0x10000 - 0x6, LENGTH = 6
}

REGION_ALIAS("c_readonly", prg_rom_fixed)

SECTIONS {]])
for i=0,BANK_MAX do
	printf("  .prg_rom_%d : { *(.prg_rom_%d .prg_rom_%d.*) } >prg_rom_%d", i, i, i, i)
end
print([[  .prg_rom_fixed : { *(.prg_rom_fixed .prg_rom_fixed.*) } >prg_rom_fixed
}

INCLUDE rompoke-table.ld
INCLUDE dpcm.ld

SECTIONS {
  .vectors : { KEEP(*(.vectors)) } >vectors
}]])
