/* * nextpnr -- Next Generation Place and Route * * Copyright (C) 2018 David Shah * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * */ #include "place_common.h" #include #include "log.h" #include "util.h" NEXTPNR_NAMESPACE_BEGIN // Get the total estimated wirelength for a net wirelen_t get_net_metric(const Context *ctx, const NetInfo *net, MetricType type, float &tns) { wirelen_t wirelength = 0; CellInfo *driver_cell = net->driver.cell; if (!driver_cell) return 0; if (driver_cell->bel == BelId()) return 0; bool driver_gb = ctx->getBelGlobalBuf(driver_cell->bel); if (driver_gb) return 0; int clock_count; bool timing_driven = ctx->timing_driven && type == MetricType::COST && ctx->getPortTimingClass(driver_cell, net->driver.port, clock_count) != TMG_IGNORE; delay_t negative_slack = 0; delay_t worst_slack = std::numeric_limits::max(); Loc driver_loc = ctx->getBelLocation(driver_cell->bel); int xmin = driver_loc.x, xmax = driver_loc.x, ymin = driver_loc.y, ymax = driver_loc.y; for (auto load : net->users) { if (load.cell == nullptr) continue; CellInfo *load_cell = load.cell; if (load_cell->bel == BelId()) continue; if (timing_driven) { delay_t net_delay = ctx->predictDelay(net, load); auto slack = load.budget - net_delay; if (slack < 0) negative_slack += slack; worst_slack = std::min(slack, worst_slack); } if (ctx->getBelGlobalBuf(load_cell->bel)) continue; Loc load_loc = ctx->getBelLocation(load_cell->bel); xmin = std::min(xmin, load_loc.x); ymin = std::min(ymin, load_loc.y); xmax = std::max(xmax, load_loc.x); ymax = std::max(ymax, load_loc.y); } if (timing_driven) { wirelength = wirelen_t( (((ymax - ymin) + (xmax - xmin)) * std::min(5.0, (1.0 + std::exp(-ctx->getDelayNS(worst_slack) / 5))))); } else { wirelength = wirelen_t((ymax - ymin) + (xmax - xmin)); } tns += ctx->getDelayNS(negative_slack); return wirelength; } // Get the total wirelength for a cell wirelen_t get_cell_metric(const Context *ctx, const CellInfo *cell, MetricType type) { std::set nets; for (auto p : cell->ports) { if (p.second.net) nets.insert(p.second.net->name); } wirelen_t wirelength = 0; float tns = 0; for (auto n : nets) { wirelength += get_net_metric(ctx, ctx->nets.at(n).get(), type, tns); } return wirelength; } wirelen_t get_cell_metric_at_bel(const Context *ctx, CellInfo *cell, BelId bel, MetricType type) { BelId oldBel = cell->bel; cell->bel = bel; wirelen_t wirelen = get_cell_metric(ctx, cell, type); cell->bel = oldBel; return wirelen; } // Placing a single cell bool place_single_cell(Context *ctx, CellInfo *cell, bool require_legality) { bool all_placed = false; int iters = 25; while (!all_placed) { BelId best_bel = BelId(); wirelen_t best_wirelen = std::numeric_limits::max(), best_ripup_wirelen = std::numeric_limits::max(); CellInfo *ripup_target = nullptr; BelId ripup_bel = BelId(); if (cell->bel != BelId()) { ctx->unbindBel(cell->bel); } IdString targetType = cell->type; for (auto bel : ctx->getBels()) { if (ctx->getBelType(bel) == targetType && (!require_legality || ctx->isValidBelForCell(cell, bel))) { if (ctx->checkBelAvail(bel)) { wirelen_t wirelen = get_cell_metric_at_bel(ctx, cell, bel, MetricType::COST); if (iters >= 4) wirelen += ctx->rng(25); if (wirelen <= best_wirelen) { best_wirelen = wirelen; best_bel = bel; } } else { wirelen_t wirelen = get_cell_metric_at_bel(ctx, cell, bel, MetricType::COST); if (iters >= 4) wirelen += ctx->rng(25); if (wirelen <= best_ripup_wirelen) { CellInfo *curr_cell = ctx->getBoundBelCell(bel); if (curr_cell->belStrength < STRENGTH_STRONG) { best_ripup_wirelen = wirelen; ripup_bel = bel; ripup_target = curr_cell; } } } } } if (best_bel == BelId()) { if (iters == 0) { log_error("failed to place cell '%s' of type '%s' (ripup iteration limit exceeded)\n", cell->name.c_str(ctx), cell->type.c_str(ctx)); } if (ripup_bel == BelId()) { log_error("failed to place cell '%s' of type '%s'\n", cell->name.c_str(ctx), cell->type.c_str(ctx)); } --iters; ctx->unbindBel(ripup_target->bel); best_bel = ripup_bel; } else { all_placed = true; } if (ctx->verbose) log_info(" placed single cell '%s' at '%s'\n", cell->name.c_str(ctx), ctx->getBelName(best_bel).c_str(ctx)); ctx->bindBel(best_bel, cell, STRENGTH_WEAK); cell = ripup_target; } return true; } class ConstraintLegaliseWorker { private: Context *ctx; std::set rippedCells; std::unordered_map oldLocations; class IncreasingDiameterSearch { public: IncreasingDiameterSearch() : start(0), min(0), max(-1){}; IncreasingDiameterSearch(int x) : start(x), min(x), max(x){}; IncreasingDiameterSearch(int start, int min, int max) : start(start), min(min), max(max){}; bool done() const { return (diameter > (max - min)); }; int get() const { int val = start + sign * diameter; val = std::max(val, min); val = std::min(val, max); return val; } void next() { if (sign == 0) { sign = 1; diameter = 1; } else if (sign == -1) { sign = 1; if ((start + sign * diameter) > max) sign = -1; ++diameter; } else { sign = -1; if ((start + sign * diameter) < min) { sign = 1; ++diameter; } } } void reset() { sign = 0; diameter = 0; } private: int start, min, max; int diameter = 0; int sign = 0; }; typedef std::unordered_map CellLocations; // Check if a location would be suitable for a cell and all its constrained children // This also makes a crude attempt to "solve" unconstrained constraints, that is slow and horrible // and will need to be reworked if mixed constrained/unconstrained chains become common bool valid_loc_for(const CellInfo *cell, Loc loc, CellLocations &solution, std::unordered_set &usedLocations) { BelId locBel = ctx->getBelByLocation(loc); if (locBel == BelId()) { return false; } if (ctx->getBelType(locBel) != cell->type) { return false; } if (!ctx->checkBelAvail(locBel)) { CellInfo *confCell = ctx->getConflictingBelCell(locBel); if (confCell->belStrength >= STRENGTH_STRONG) { return false; } } // Don't place at tiles where any strongly bound Bels exist, as we might need to rip them up later for (auto tilebel : ctx->getBelsByTile(loc.x, loc.y)) { CellInfo *tcell = ctx->getBoundBelCell(tilebel); if (tcell && tcell->belStrength >= STRENGTH_STRONG) return false; } usedLocations.insert(loc); for (auto child : cell->constr_children) { IncreasingDiameterSearch xSearch, ySearch, zSearch; if (child->constr_x == child->UNCONSTR) { xSearch = IncreasingDiameterSearch(loc.x, 0, ctx->getGridDimX() - 1); } else { xSearch = IncreasingDiameterSearch(loc.x + child->constr_x); } if (child->constr_y == child->UNCONSTR) { ySearch = IncreasingDiameterSearch(loc.y, 0, ctx->getGridDimY() - 1); } else { ySearch = IncreasingDiameterSearch(loc.y + child->constr_y); } if (child->constr_z == child->UNCONSTR) { zSearch = IncreasingDiameterSearch(loc.z, 0, ctx->getTileBelDimZ(loc.x, loc.y)); } else { if (child->constr_abs_z) { zSearch = IncreasingDiameterSearch(child->constr_z); } else { zSearch = IncreasingDiameterSearch(loc.z + child->constr_z); } } bool success = false;
/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *  
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *  
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 *  ---
 *
 *  The Verilog frontend.
 *
 *  This frontend is using the AST frontend library (see frontends/ast/).
 *  Thus this frontend does not generate RTLIL code directly but creates an
 *  AST directly from the Verilog parse tree and then passes this AST to
 *  the AST frontend library.
 *
 *  ---
 *
 *  This file contains an ad-hoc parser for Verilog constants. The Verilog
 *  lexer does only recognize a constant but does not actually split it to its
 *  components. I.e. it just passes the Verilog code for the constant to the
 *  bison parser. The parser then uses the function const2ast() from this file
 *  to create an AST node for the constant.
 *
 */

#include "verilog_frontend.h"
#include "kernel/log.h"
#include <assert.h>
#include <string.h>
#include <math.h>

using namespace AST;

// divide an arbitrary length decimal number by two and return the rest
static int my_decimal_div_by_two(std::vector<uint8_t> &digits)
{
	int carry = 0;
	for (size_t i = 0; i < digits.size(); i++) {
		assert(digits[i] < 10);
		digits[i] += carry * 10;
		carry = digits[i] % 2;
		digits[i] /= 2;
	}
	while (!digits.empty() && !digits.front())
		digits.erase(digits.begin());
	return carry;
}

// find the number of significant bits in a binary number (not including the sign bit)
static int my_ilog2(int x)
{
	int ret = 0;
	while (x != 0 && x != -1) {
		x = x >> 1;
		ret++;
	}
	return ret;
}

// parse a binary, decimal, hexadecimal or octal number with support for special bits ('x', 'z' and '?')
static void my_strtobin(std::vector<RTLIL::State> &data, const char *str, int len_in_bits, int base, char case_type)
{
	// all digits in string (MSB at index 0)
	std::vector<uint8_t> digits;

	while (*str) {
		if ('0' <= *str && *str <= '9')
			digits.push_back(*str - '0');
		else if ('a' <= *str && *str <= 'f')
			digits.push_back(10 + *str - 'a');
		else if ('A' <= *str && *str <= 'F')
			digits.push_back(10 + *str - 'A');
		else if (*str == 'x' || *str == 'X')
			digits.push_back(0xf0);
		else if (*str == 'z' || *str == 'Z')
			digits.push_back(0xf1);
		else if (*str == '?')
			digits.push_back(0xf2);
		str++;
	}

	if (base == 10) {
		data.clear();
		if (len_in_bits < 0) {
			while (!digits.empty())
				data.push_back(my_decimal_div_by_two(digits) ? RTLIL::S1 : RTLIL::S0);
			while (data.size() < 32)
				data.push_back(RTLIL::S0);
		} else {
			for (int i = 0; i < len_in_bits; i++)
				data.push_back(my_decimal_div_by_two(digits) ? RTLIL::S1 : RTLIL::S0);
		}
		return;
	}

	int bits_per_digit = my_ilog2(base-1);
	if (len_in_bits < 0)
		len_in_bits = std::max<int>(digits.size() * bits_per_digit, 32);

	data.clear();
	data.resize(len_in_bits);

	for (int i = 0; i < len_in_bits; i++) {
		int bitmask = 1 << (i % bits_per_digit);
		int digitidx = digits.size() - (i / bits_per_digit) - 1;
		if (digitidx < 0) {
			if (i > 0 && (data[i-1] == RTLIL::Sz || data[i-1] == RTLIL::Sx || data[i-1] == RTLIL::Sa))
				data[i] = data[i-1];
			else
				data[i] = RTLIL::S0;
		} else if (digits[digitidx] == 0xf0)
			data[i] = case_type == 'x' ? RTLIL::Sa : RTLIL::Sx;
		else if (digits[digitidx] == 0xf1)
			data[i] = case_type == 'x' || case_type == 'z' ? RTLIL::Sa : RTLIL::Sz;
		else if (digits[digitidx] == 0xf2)
			data[i] = RTLIL::Sa;
		else
			data[i] = (digits[digitidx] & bitmask) ? RTLIL::S1 : RTLIL::S0;
	}
}

// convert the verilog code for a constant to an AST node
AstNode *VERILOG_FRONTEND::const2ast(std::string code, char case_type)
{
	const char *str = code.c_str();

	// Strings
	if (*str == '"') {
		int len = strlen(str) - 2;
		std::vector<RTLIL::State> data;
		data.reserve(len * 8);
		for (int i = 0; i < len; i++) {
			unsigned char ch = str[len - i];
			for (int j = 0; j < 8; j++) {
				data.push_back((ch & 1) ? RTLIL::S1 : RTLIL::S0);
				ch = ch >> 1;
			}
		}
		AstNode *ast = AstNode::mkconst_bits(data, false);
		ast->str = code;
		return ast;
	}

	for (size_t i = 0; i < code.size(); i++)
		if (code[i] == '_' || code[i] == ' ' || code[i] == '\t' || code[i] == '\r' || code[i] == '\n')
			code.erase(code.begin()+(i--));
	str = code.c_str();

	char *endptr;
	long len_in_bits = strtol(str, &endptr, 10);

	// Simple base-10 integer
	if (*endptr == 0) {
		std::vector<RTLIL::State> data;
		my_strtobin(data, str, -1, 10, case_type);
		if (data.back() == RTLIL::S1)
			data.push_back(RTLIL::S0);
		return AstNode::mkconst_bits(data, true);
	}

	// unsized constant
	if (str == endptr)
		len_in_bits = -1;

	// The "<bits>'s?[bodh]<digits>" syntax
	if (*endptr == '\'')
	{
		std::vector<RTLIL::State> data;
		bool is_signed = false;
		if (*(endptr+1) == 's') {
			is_signed = true;
			endptr++;
		}
		switch (*(endptr+1))
		{
		case 'b':
			my_strtobin(data, endptr+2, len_in_bits, 2, case_type);
			break;
		case 'o':
			my_strtobin(data, endptr+2, len_in_bits, 8, case_type);
			break;
		case 'd':
			my_strtobin(data, endptr+2, len_in_bits, 10, case_type);
			break;
		case 'h':
			my_strtobin(data, endptr+2, len_in_bits, 16, case_type);
			break;
		default:
			return NULL;
		}
		if (len_in_bits < 0) {
			if (is_signed && data.back() == RTLIL::S1)
				data.push_back(RTLIL::S0);
			while (data.size() < 32)
				data.push_back(RTLIL::S0);
		}
		return AstNode::mkconst_bits(data, is_signed);
	}

	return NULL;
}