Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/adlc/dfa.cpp
32285 views
/*1* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324// DFA.CPP - Method definitions for outputting the matcher DFA from ADLC25#include "adlc.hpp"2627//---------------------------Switches for debugging output---------------------28static bool debug_output = false;29static bool debug_output1 = false; // top level chain rules3031//---------------------------Access to internals of class State----------------32static const char *sLeft = "_kids[0]";33static const char *sRight = "_kids[1]";3435//---------------------------DFA productions-----------------------------------36static const char *dfa_production = "DFA_PRODUCTION";37static const char *dfa_production_set_valid = "DFA_PRODUCTION__SET_VALID";3839//---------------------------Production State----------------------------------40static const char *knownInvalid = "knownInvalid"; // The result does NOT have a rule defined41static const char *knownValid = "knownValid"; // The result must be produced by a rule42static const char *unknownValid = "unknownValid"; // Unknown (probably due to a child or predicate constraint)4344static const char *noConstraint = "noConstraint"; // No constraints seen so far45static const char *hasConstraint = "hasConstraint"; // Within the first constraint464748//------------------------------Production------------------------------------49// Track the status of productions for a particular result50class Production {51public:52const char *_result;53const char *_constraint;54const char *_valid;55Expr *_cost_lb; // Cost lower bound for this production56Expr *_cost_ub; // Cost upper bound for this production5758public:59Production(const char *result, const char *constraint, const char *valid);60~Production() {};6162void initialize(); // reset to be an empty container6364const char *valid() const { return _valid; }65Expr *cost_lb() const { return (Expr *)_cost_lb; }66Expr *cost_ub() const { return (Expr *)_cost_ub; }6768void print();69};707172//------------------------------ProductionState--------------------------------73// Track the status of all production rule results74// Reset for each root opcode (e.g., Op_RegI, Op_AddI, ...)75class ProductionState {76private:77Dict _production; // map result of production, char*, to information or NULL78const char *_constraint;7980public:81// cmpstr does string comparisions. hashstr computes a key.82ProductionState(Arena *arena) : _production(cmpstr, hashstr, arena) { initialize(); };83~ProductionState() { };8485void initialize(); // reset local and dictionary state8687const char *constraint();88void set_constraint(const char *constraint); // currently working inside of constraints8990const char *valid(const char *result); // unknownValid, or status for this production91void set_valid(const char *result); // if not constrained, set status to knownValid9293Expr *cost_lb(const char *result);94Expr *cost_ub(const char *result);95void set_cost_bounds(const char *result, const Expr *cost, bool has_state_check, bool has_cost_check);9697// Return the Production associated with the result,98// or create a new Production and insert it into the dictionary.99Production *getProduction(const char *result);100101void print();102103private:104// Disable public use of constructor, copy-ctor, ...105ProductionState( ) : _production(cmpstr, hashstr, Form::arena) { assert( false, "NotImplemented"); };106ProductionState( const ProductionState & ) : _production(cmpstr, hashstr, Form::arena) { assert( false, "NotImplemented"); }; // Deep-copy107};108109110//---------------------------Helper Functions----------------------------------111// cost_check template:112// 1) if (STATE__NOT_YET_VALID(EBXREGI) || _cost[EBXREGI] > c) {113// 2) DFA_PRODUCTION__SET_VALID(EBXREGI, cmovI_memu_rule, c)114// 3) }115//116static void cost_check(FILE *fp, const char *spaces,117const char *arrayIdx, const Expr *cost, const char *rule, ProductionState &status) {118bool state_check = false; // true if this production needs to check validity119bool cost_check = false; // true if this production needs to check cost120bool cost_is_above_upper_bound = false; // true if this production is unnecessary due to high cost121bool cost_is_below_lower_bound = false; // true if this production replaces a higher cost production122123// Get information about this production124const Expr *previous_ub = status.cost_ub(arrayIdx);125if( !previous_ub->is_unknown() ) {126if( previous_ub->less_than_or_equal(cost) ) {127cost_is_above_upper_bound = true;128if( debug_output ) { fprintf(fp, "// Previous rule with lower cost than: %s === %s_rule costs %s\n", arrayIdx, rule, cost->as_string()); }129}130}131132const Expr *previous_lb = status.cost_lb(arrayIdx);133if( !previous_lb->is_unknown() ) {134if( cost->less_than_or_equal(previous_lb) ) {135cost_is_below_lower_bound = true;136if( debug_output ) { fprintf(fp, "// Previous rule with higher cost\n"); }137}138}139140// line 1)141// Check for validity and compare to other match costs142const char *validity_check = status.valid(arrayIdx);143if( validity_check == unknownValid ) {144fprintf(fp, "%sif (STATE__NOT_YET_VALID(%s) || _cost[%s] > %s) {\n", spaces, arrayIdx, arrayIdx, cost->as_string());145state_check = true;146cost_check = true;147}148else if( validity_check == knownInvalid ) {149if( debug_output ) { fprintf(fp, "%s// %s KNOWN_INVALID \n", spaces, arrayIdx); }150}151else if( validity_check == knownValid ) {152if( cost_is_above_upper_bound ) {153// production cost is known to be too high.154return;155} else if( cost_is_below_lower_bound ) {156// production will unconditionally overwrite a previous production that had higher cost157} else {158fprintf(fp, "%sif ( /* %s KNOWN_VALID || */ _cost[%s] > %s) {\n", spaces, arrayIdx, arrayIdx, cost->as_string());159cost_check = true;160}161}162163// line 2)164// no need to set State vector if our state is knownValid165const char *production = (validity_check == knownValid) ? dfa_production : dfa_production_set_valid;166fprintf(fp, "%s %s(%s, %s_rule, %s)", spaces, production, arrayIdx, rule, cost->as_string() );167if( validity_check == knownValid ) {168if( cost_is_below_lower_bound ) { fprintf(fp, "\t // overwrites higher cost rule"); }169}170fprintf(fp, "\n");171172// line 3)173if( cost_check || state_check ) {174fprintf(fp, "%s}\n", spaces);175}176177status.set_cost_bounds(arrayIdx, cost, state_check, cost_check);178179// Update ProductionState180if( validity_check != knownValid ) {181// set State vector if not previously known182status.set_valid(arrayIdx);183}184}185186187//---------------------------child_test----------------------------------------188// Example:189// STATE__VALID_CHILD(_kids[0], FOO) && STATE__VALID_CHILD(_kids[1], BAR)190// Macro equivalent to: _kids[0]->valid(FOO) && _kids[1]->valid(BAR)191//192static void child_test(FILE *fp, MatchList &mList) {193if (mList._lchild) { // If left child, check it194const char* lchild_to_upper = ArchDesc::getMachOperEnum(mList._lchild);195fprintf(fp, "STATE__VALID_CHILD(_kids[0], %s)", lchild_to_upper);196delete[] lchild_to_upper;197}198if (mList._lchild && mList._rchild) { // If both, add the "&&"199fprintf(fp, " && ");200}201if (mList._rchild) { // If right child, check it202const char* rchild_to_upper = ArchDesc::getMachOperEnum(mList._rchild);203fprintf(fp, "STATE__VALID_CHILD(_kids[1], %s)", rchild_to_upper);204delete[] rchild_to_upper;205}206}207208//---------------------------calc_cost-----------------------------------------209// Example:210// unsigned int c = _kids[0]->_cost[FOO] + _kids[1]->_cost[BAR] + 5;211//212Expr *ArchDesc::calc_cost(FILE *fp, const char *spaces, MatchList &mList, ProductionState &status) {213fprintf(fp, "%sunsigned int c = ", spaces);214Expr *c = new Expr("0");215if (mList._lchild) { // If left child, add it in216const char* lchild_to_upper = ArchDesc::getMachOperEnum(mList._lchild);217sprintf(Expr::buffer(), "_kids[0]->_cost[%s]", lchild_to_upper);218c->add(Expr::buffer());219delete[] lchild_to_upper;220}221if (mList._rchild) { // If right child, add it in222const char* rchild_to_upper = ArchDesc::getMachOperEnum(mList._rchild);223sprintf(Expr::buffer(), "_kids[1]->_cost[%s]", rchild_to_upper);224c->add(Expr::buffer());225delete[] rchild_to_upper;226}227// Add in cost of this rule228const char *mList_cost = mList.get_cost();229c->add(mList_cost, *this);230231fprintf(fp, "%s;\n", c->as_string());232c->set_external_name("c");233return c;234}235236237//---------------------------gen_match-----------------------------------------238void ArchDesc::gen_match(FILE *fp, MatchList &mList, ProductionState &status, Dict &operands_chained_from) {239const char *spaces4 = " ";240const char *spaces6 = " ";241242fprintf(fp, "%s", spaces4);243// Only generate child tests if this is not a leaf node244bool has_child_constraints = mList._lchild || mList._rchild;245const char *predicate_test = mList.get_pred();246if (has_child_constraints || predicate_test) {247// Open the child-and-predicate-test braces248fprintf(fp, "if( ");249status.set_constraint(hasConstraint);250child_test(fp, mList);251// Only generate predicate test if one exists for this match252if (predicate_test) {253if (has_child_constraints) {254fprintf(fp," &&\n");255}256fprintf(fp, "%s %s", spaces6, predicate_test);257}258// End of outer tests259fprintf(fp," ) ");260} else {261// No child or predicate test needed262status.set_constraint(noConstraint);263}264265// End of outer tests266fprintf(fp,"{\n");267268// Calculate cost of this match269const Expr *cost = calc_cost(fp, spaces6, mList, status);270// Check against other match costs, and update cost & rule vectors271cost_check(fp, spaces6, ArchDesc::getMachOperEnum(mList._resultStr), cost, mList._opcode, status);272273// If this is a member of an operand class, update the class cost & rule274expand_opclass( fp, spaces6, cost, mList._resultStr, status);275276// Check if this rule should be used to generate the chains as well.277const char *rule = /* set rule to "Invalid" for internal operands */278strcmp(mList._opcode,mList._resultStr) ? mList._opcode : "Invalid";279280// If this rule produces an operand which has associated chain rules,281// update the operands with the chain rule + this rule cost & this rule.282chain_rule(fp, spaces6, mList._resultStr, cost, rule, operands_chained_from, status);283284// Close the child-and-predicate-test braces285fprintf(fp, " }\n");286287}288289290//---------------------------expand_opclass------------------------------------291// Chain from one result_type to all other members of its operand class292void ArchDesc::expand_opclass(FILE *fp, const char *indent, const Expr *cost,293const char *result_type, ProductionState &status) {294const Form *form = _globalNames[result_type];295OperandForm *op = form ? form->is_operand() : NULL;296if( op && op->_classes.count() > 0 ) {297if( debug_output ) { fprintf(fp, "// expand operand classes for operand: %s \n", (char *)op->_ident ); } // %%%%% Explanation298// Iterate through all operand classes which include this operand299op->_classes.reset();300const char *oclass;301// Expr *cCost = new Expr(cost);302while( (oclass = op->_classes.iter()) != NULL )303// Check against other match costs, and update cost & rule vectors304cost_check(fp, indent, ArchDesc::getMachOperEnum(oclass), cost, result_type, status);305}306}307308//---------------------------chain_rule----------------------------------------309// Starting at 'operand', check if we know how to automatically generate other results310void ArchDesc::chain_rule(FILE *fp, const char *indent, const char *operand,311const Expr *icost, const char *irule, Dict &operands_chained_from, ProductionState &status) {312313// Check if we have already generated chains from this starting point314if( operands_chained_from[operand] != NULL ) {315return;316} else {317operands_chained_from.Insert( operand, operand);318}319if( debug_output ) { fprintf(fp, "// chain rules starting from: %s and %s \n", (char *)operand, (char *)irule); } // %%%%% Explanation320321ChainList *lst = (ChainList *)_chainRules[operand];322if (lst) {323// printf("\nChain from <%s> at cost #%s\n",operand, icost ? icost : "_");324const char *result, *cost, *rule;325for(lst->reset(); (lst->iter(result,cost,rule)) == true; ) {326// Do not generate operands that are already available327if( operands_chained_from[result] != NULL ) {328continue;329} else {330// Compute the cost for previous match + chain_rule_cost331// total_cost = icost + cost;332Expr *total_cost = icost->clone(); // icost + cost333total_cost->add(cost, *this);334335// Check for transitive chain rules336Form *form = (Form *)_globalNames[rule];337if ( ! form->is_instruction()) {338// printf(" result=%s cost=%s rule=%s\n", result, total_cost, rule);339// Check against other match costs, and update cost & rule vectors340const char *reduce_rule = strcmp(irule,"Invalid") ? irule : rule;341cost_check(fp, indent, ArchDesc::getMachOperEnum(result), total_cost, reduce_rule, status);342chain_rule(fp, indent, result, total_cost, irule, operands_chained_from, status);343} else {344// printf(" result=%s cost=%s rule=%s\n", result, total_cost, rule);345// Check against other match costs, and update cost & rule vectors346cost_check(fp, indent, ArchDesc::getMachOperEnum(result), total_cost, rule, status);347chain_rule(fp, indent, result, total_cost, rule, operands_chained_from, status);348}349350// If this is a member of an operand class, update class cost & rule351expand_opclass( fp, indent, total_cost, result, status );352}353}354}355}356357//---------------------------prune_matchlist-----------------------------------358// Check for duplicate entries in a matchlist, and prune out the higher cost359// entry.360void ArchDesc::prune_matchlist(Dict &minimize, MatchList &mlist) {361362}363364//---------------------------buildDFA------------------------------------------365// DFA is a large switch with case statements for each ideal opcode encountered366// in any match rule in the ad file. Each case has a series of if's to handle367// the match or fail decisions. The matches test the cost function of that368// rule, and prune any cases which are higher cost for the same reduction.369// In order to generate the DFA we walk the table of ideal opcode/MatchList370// pairs generated by the ADLC front end to build the contents of the case371// statements (a series of if statements).372void ArchDesc::buildDFA(FILE* fp) {373int i;374// Remember operands that are the starting points for chain rules.375// Prevent cycles by checking if we have already generated chain.376Dict operands_chained_from(cmpstr, hashstr, Form::arena);377378// Hash inputs to match rules so that final DFA contains only one entry for379// each match pattern which is the low cost entry.380Dict minimize(cmpstr, hashstr, Form::arena);381382// Track status of dfa for each resulting production383// reset for each ideal root.384ProductionState status(Form::arena);385386// Output the start of the DFA method into the output file387388fprintf(fp, "\n");389fprintf(fp, "//------------------------- Source -----------------------------------------\n");390// Do not put random source code into the DFA.391// If there are constants which need sharing, put them in "source_hpp" forms.392// _source.output(fp);393fprintf(fp, "\n");394fprintf(fp, "//------------------------- Attributes -------------------------------------\n");395_attributes.output(fp);396fprintf(fp, "\n");397fprintf(fp, "//------------------------- Macros -----------------------------------------\n");398// #define DFA_PRODUCTION(result, rule, cost)\399// _cost[ (result) ] = cost; _rule[ (result) ] = rule;400fprintf(fp, "#define %s(result, rule, cost)\\\n", dfa_production);401fprintf(fp, " _cost[ (result) ] = cost; _rule[ (result) ] = rule;\n");402fprintf(fp, "\n");403404// #define DFA_PRODUCTION__SET_VALID(result, rule, cost)\405// DFA_PRODUCTION( (result), (rule), (cost) ); STATE__SET_VALID( (result) );406fprintf(fp, "#define %s(result, rule, cost)\\\n", dfa_production_set_valid);407fprintf(fp, " %s( (result), (rule), (cost) ); STATE__SET_VALID( (result) );\n", dfa_production);408fprintf(fp, "\n");409410fprintf(fp, "//------------------------- DFA --------------------------------------------\n");411412fprintf(fp,413"// DFA is a large switch with case statements for each ideal opcode encountered\n"414"// in any match rule in the ad file. Each case has a series of if's to handle\n"415"// the match or fail decisions. The matches test the cost function of that\n"416"// rule, and prune any cases which are higher cost for the same reduction.\n"417"// In order to generate the DFA we walk the table of ideal opcode/MatchList\n"418"// pairs generated by the ADLC front end to build the contents of the case\n"419"// statements (a series of if statements).\n"420);421fprintf(fp, "\n");422fprintf(fp, "\n");423if (_dfa_small) {424// Now build the individual routines just like the switch entries in large version425// Iterate over the table of MatchLists, start at first valid opcode of 1426for (i = 1; i < _last_opcode; i++) {427if (_mlistab[i] == NULL) continue;428// Generate the routine header statement for this opcode429fprintf(fp, "void State::_sub_Op_%s(const Node *n){\n", NodeClassNames[i]);430// Generate body. Shared for both inline and out-of-line version431gen_dfa_state_body(fp, minimize, status, operands_chained_from, i);432// End of routine433fprintf(fp, "}\n");434}435}436fprintf(fp, "bool State::DFA");437fprintf(fp, "(int opcode, const Node *n) {\n");438fprintf(fp, " switch(opcode) {\n");439440// Iterate over the table of MatchLists, start at first valid opcode of 1441for (i = 1; i < _last_opcode; i++) {442if (_mlistab[i] == NULL) continue;443// Generate the case statement for this opcode444if (_dfa_small) {445fprintf(fp, " case Op_%s: { _sub_Op_%s(n);\n", NodeClassNames[i], NodeClassNames[i]);446} else {447fprintf(fp, " case Op_%s: {\n", NodeClassNames[i]);448// Walk the list, compacting it449gen_dfa_state_body(fp, minimize, status, operands_chained_from, i);450}451// Print the "break"452fprintf(fp, " break;\n");453fprintf(fp, " }\n");454}455456// Generate the default case for switch(opcode)457fprintf(fp, " \n");458fprintf(fp, " default:\n");459fprintf(fp, " tty->print(\"Default case invoked for: \\n\");\n");460fprintf(fp, " tty->print(\" opcode = %cd, \\\"%cs\\\"\\n\", opcode, NodeClassNames[opcode]);\n", '%', '%');461fprintf(fp, " return false;\n");462fprintf(fp, " }\n");463464// Return status, indicating a successful match.465fprintf(fp, " return true;\n");466// Generate the closing brace for method Matcher::DFA467fprintf(fp, "}\n");468Expr::check_buffers();469}470471472class dfa_shared_preds {473enum { count = 4 };474475static bool _found[count];476static const char* _type [count];477static const char* _var [count];478static const char* _pred [count];479480static void check_index(int index) { assert( 0 <= index && index < count, "Invalid index"); }481482// Confirm that this is a separate sub-expression.483// Only need to catch common cases like " ... && shared ..."484// and avoid hazardous ones like "...->shared"485static bool valid_loc(char *pred, char *shared) {486// start of predicate is valid487if( shared == pred ) return true;488489// Check previous character and recurse if needed490char *prev = shared - 1;491char c = *prev;492switch( c ) {493case ' ':494case '\n':495return dfa_shared_preds::valid_loc(pred, prev);496case '!':497case '(':498case '<':499case '=':500return true;501case '"': // such as: #line 10 "myfile.ad"\n mypredicate502return true;503case '|':504if( prev != pred && *(prev-1) == '|' ) return true;505case '&':506if( prev != pred && *(prev-1) == '&' ) return true;507default:508return false;509}510511return false;512}513514public:515516static bool found(int index){ check_index(index); return _found[index]; }517static void set_found(int index, bool val) { check_index(index); _found[index] = val; }518static void reset_found() {519for( int i = 0; i < count; ++i ) { _found[i] = false; }520};521522static const char* type(int index) { check_index(index); return _type[index]; }523static const char* var (int index) { check_index(index); return _var [index]; }524static const char* pred(int index) { check_index(index); return _pred[index]; }525526// Check each predicate in the MatchList for common sub-expressions527static void cse_matchlist(MatchList *matchList) {528for( MatchList *mList = matchList; mList != NULL; mList = mList->get_next() ) {529Predicate* predicate = mList->get_pred_obj();530char* pred = mList->get_pred();531if( pred != NULL ) {532for(int index = 0; index < count; ++index ) {533const char *shared_pred = dfa_shared_preds::pred(index);534const char *shared_pred_var = dfa_shared_preds::var(index);535bool result = dfa_shared_preds::cse_predicate(predicate, shared_pred, shared_pred_var);536if( result ) dfa_shared_preds::set_found(index, true);537}538}539}540}541542// If the Predicate contains a common sub-expression, replace the Predicate's543// string with one that uses the variable name.544static bool cse_predicate(Predicate* predicate, const char *shared_pred, const char *shared_pred_var) {545bool result = false;546char *pred = predicate->_pred;547if( pred != NULL ) {548char *new_pred = pred;549for( char *shared_pred_loc = strstr(new_pred, shared_pred);550shared_pred_loc != NULL && dfa_shared_preds::valid_loc(new_pred,shared_pred_loc);551shared_pred_loc = strstr(new_pred, shared_pred) ) {552// Do not modify the original predicate string, it is shared553if( new_pred == pred ) {554new_pred = strdup(pred);555shared_pred_loc = strstr(new_pred, shared_pred);556}557// Replace shared_pred with variable name558strncpy(shared_pred_loc, shared_pred_var, strlen(shared_pred_var));559}560// Install new predicate561if( new_pred != pred ) {562predicate->_pred = new_pred;563result = true;564}565}566return result;567}568569// Output the hoisted common sub-expression if we found it in predicates570static void generate_cse(FILE *fp) {571for(int j = 0; j < count; ++j ) {572if( dfa_shared_preds::found(j) ) {573const char *shared_pred_type = dfa_shared_preds::type(j);574const char *shared_pred_var = dfa_shared_preds::var(j);575const char *shared_pred = dfa_shared_preds::pred(j);576fprintf(fp, " %s %s = %s;\n", shared_pred_type, shared_pred_var, shared_pred);577}578}579}580};581// shared predicates, _var and _pred entry should be the same length582bool dfa_shared_preds::_found[dfa_shared_preds::count]583= { false, false, false, false };584const char* dfa_shared_preds::_type[dfa_shared_preds::count]585= { "int", "jlong", "intptr_t", "bool" };586const char* dfa_shared_preds::_var [dfa_shared_preds::count]587= { "_n_get_int__", "_n_get_long__", "_n_get_intptr_t__", "Compile__current____select_24_bit_instr__" };588const char* dfa_shared_preds::_pred[dfa_shared_preds::count]589= { "n->get_int()", "n->get_long()", "n->get_intptr_t()", "Compile::current()->select_24_bit_instr()" };590591592void ArchDesc::gen_dfa_state_body(FILE* fp, Dict &minimize, ProductionState &status, Dict &operands_chained_from, int i) {593// Start the body of each Op_XXX sub-dfa with a clean state.594status.initialize();595596// Walk the list, compacting it597MatchList* mList = _mlistab[i];598do {599// Hash each entry using inputs as key and pointer as data.600// If there is already an entry, keep the one with lower cost, and601// remove the other one from the list.602prune_matchlist(minimize, *mList);603// Iterate604mList = mList->get_next();605} while(mList != NULL);606607// Hoist previously specified common sub-expressions out of predicates608dfa_shared_preds::reset_found();609dfa_shared_preds::cse_matchlist(_mlistab[i]);610dfa_shared_preds::generate_cse(fp);611612mList = _mlistab[i];613614// Walk the list again, generating code615do {616// Each match can generate its own chains617operands_chained_from.Clear();618gen_match(fp, *mList, status, operands_chained_from);619mList = mList->get_next();620} while(mList != NULL);621// Fill in any chain rules which add instructions622// These can generate their own chains as well.623operands_chained_from.Clear(); //624if( debug_output1 ) { fprintf(fp, "// top level chain rules for: %s \n", (char *)NodeClassNames[i]); } // %%%%% Explanation625const Expr *zeroCost = new Expr("0");626chain_rule(fp, " ", (char *)NodeClassNames[i], zeroCost, "Invalid",627operands_chained_from, status);628}629630631632//------------------------------Expr------------------------------------------633Expr *Expr::_unknown_expr = NULL;634char Expr::string_buffer[STRING_BUFFER_LENGTH];635char Expr::external_buffer[STRING_BUFFER_LENGTH];636bool Expr::_init_buffers = Expr::init_buffers();637638Expr::Expr() {639_external_name = NULL;640_expr = "Invalid_Expr";641_min_value = Expr::Max;642_max_value = Expr::Zero;643}644Expr::Expr(const char *cost) {645_external_name = NULL;646647int intval = 0;648if( cost == NULL ) {649_expr = "0";650_min_value = Expr::Zero;651_max_value = Expr::Zero;652}653else if( ADLParser::is_int_token(cost, intval) ) {654_expr = cost;655_min_value = intval;656_max_value = intval;657}658else {659assert( strcmp(cost,"0") != 0, "Recognize string zero as an int");660_expr = cost;661_min_value = Expr::Zero;662_max_value = Expr::Max;663}664}665666Expr::Expr(const char *name, const char *expression, int min_value, int max_value) {667_external_name = name;668_expr = expression ? expression : name;669_min_value = min_value;670_max_value = max_value;671assert(_min_value >= 0 && _min_value <= Expr::Max, "value out of range");672assert(_max_value >= 0 && _max_value <= Expr::Max, "value out of range");673}674675Expr *Expr::clone() const {676Expr *cost = new Expr();677cost->_external_name = _external_name;678cost->_expr = _expr;679cost->_min_value = _min_value;680cost->_max_value = _max_value;681682return cost;683}684685void Expr::add(const Expr *c) {686// Do not update fields until all computation is complete687const char *external = compute_external(this, c);688const char *expr = compute_expr(this, c);689int min_value = compute_min (this, c);690int max_value = compute_max (this, c);691692_external_name = external;693_expr = expr;694_min_value = min_value;695_max_value = max_value;696}697698void Expr::add(const char *c) {699Expr *cost = new Expr(c);700add(cost);701}702703void Expr::add(const char *c, ArchDesc &AD) {704const Expr *e = AD.globalDefs()[c];705if( e != NULL ) {706// use the value of 'c' defined in <arch>.ad707add(e);708} else {709Expr *cost = new Expr(c);710add(cost);711}712}713714const char *Expr::compute_external(const Expr *c1, const Expr *c2) {715const char * result = NULL;716717// Preserve use of external name which has a zero value718if( c1->_external_name != NULL ) {719sprintf( string_buffer, "%s", c1->as_string());720if( !c2->is_zero() ) {721strcat( string_buffer, "+");722strcat( string_buffer, c2->as_string());723}724result = strdup(string_buffer);725}726else if( c2->_external_name != NULL ) {727if( !c1->is_zero() ) {728sprintf( string_buffer, "%s", c1->as_string());729strcat( string_buffer, " + ");730} else {731string_buffer[0] = '\0';732}733strcat( string_buffer, c2->_external_name );734result = strdup(string_buffer);735}736return result;737}738739const char *Expr::compute_expr(const Expr *c1, const Expr *c2) {740if( !c1->is_zero() ) {741sprintf( string_buffer, "%s", c1->_expr);742if( !c2->is_zero() ) {743strcat( string_buffer, "+");744strcat( string_buffer, c2->_expr);745}746}747else if( !c2->is_zero() ) {748sprintf( string_buffer, "%s", c2->_expr);749}750else {751sprintf( string_buffer, "0");752}753char *cost = strdup(string_buffer);754755return cost;756}757758int Expr::compute_min(const Expr *c1, const Expr *c2) {759int v1 = c1->_min_value;760int v2 = c2->_min_value;761assert(0 <= v2 && v2 <= Expr::Max, "sanity");762assert(v1 <= Expr::Max - v2, "Invalid cost computation");763764return v1 + v2;765}766767768int Expr::compute_max(const Expr *c1, const Expr *c2) {769int v1 = c1->_max_value;770int v2 = c2->_max_value;771772// Check for overflow without producing UB. If v2 is positive773// and not larger than Max, the subtraction cannot underflow.774assert(0 <= v2 && v2 <= Expr::Max, "sanity");775if (v1 > Expr::Max - v2) {776return Expr::Max;777}778779return v1 + v2;780}781782void Expr::print() const {783if( _external_name != NULL ) {784printf(" %s == (%s) === [%d, %d]\n", _external_name, _expr, _min_value, _max_value);785} else {786printf(" %s === [%d, %d]\n", _expr, _min_value, _max_value);787}788}789790void Expr::print_define(FILE *fp) const {791assert( _external_name != NULL, "definition does not have a name");792assert( _min_value == _max_value, "Expect user definitions to have constant value");793fprintf(fp, "#define %s (%s) \n", _external_name, _expr);794fprintf(fp, "// value == %d \n", _min_value);795}796797void Expr::print_assert(FILE *fp) const {798assert( _external_name != NULL, "definition does not have a name");799assert( _min_value == _max_value, "Expect user definitions to have constant value");800fprintf(fp, " assert( %s == %d, \"Expect (%s) to equal %d\");\n", _external_name, _min_value, _expr, _min_value);801}802803Expr *Expr::get_unknown() {804if( Expr::_unknown_expr == NULL ) {805Expr::_unknown_expr = new Expr();806}807808return Expr::_unknown_expr;809}810811bool Expr::init_buffers() {812// Fill buffers with 0813for( int i = 0; i < STRING_BUFFER_LENGTH; ++i ) {814external_buffer[i] = '\0';815string_buffer[i] = '\0';816}817818return true;819}820821bool Expr::check_buffers() {822// returns 'true' if buffer use may have overflowed823bool ok = true;824for( int i = STRING_BUFFER_LENGTH - 100; i < STRING_BUFFER_LENGTH; ++i) {825if( external_buffer[i] != '\0' || string_buffer[i] != '\0' ) {826ok = false;827assert( false, "Expr:: Buffer overflow");828}829}830831return ok;832}833834835//------------------------------ExprDict---------------------------------------836// Constructor837ExprDict::ExprDict( CmpKey cmp, Hash hash, Arena *arena )838: _expr(cmp, hash, arena), _defines() {839}840ExprDict::~ExprDict() {841}842843// Return # of name-Expr pairs in dict844int ExprDict::Size(void) const {845return _expr.Size();846}847848// define inserts the given key-value pair into the dictionary,849// and records the name in order for later output, ...850const Expr *ExprDict::define(const char *name, Expr *expr) {851const Expr *old_expr = (*this)[name];852assert(old_expr == NULL, "Implementation does not support redefinition");853854_expr.Insert(name, expr);855_defines.addName(name);856857return old_expr;858}859860// Insert inserts the given key-value pair into the dictionary. The prior861// value of the key is returned; NULL if the key was not previously defined.862const Expr *ExprDict::Insert(const char *name, Expr *expr) {863return (Expr*)_expr.Insert((void*)name, (void*)expr);864}865866// Finds the value of a given key; or NULL if not found.867// The dictionary is NOT changed.868const Expr *ExprDict::operator [](const char *name) const {869return (Expr*)_expr[name];870}871872void ExprDict::print_defines(FILE *fp) {873fprintf(fp, "\n");874const char *name = NULL;875for( _defines.reset(); (name = _defines.iter()) != NULL; ) {876const Expr *expr = (const Expr*)_expr[name];877assert( expr != NULL, "name in ExprDict without matching Expr in dictionary");878expr->print_define(fp);879}880}881void ExprDict::print_asserts(FILE *fp) {882fprintf(fp, "\n");883fprintf(fp, " // Following assertions generated from definition section\n");884const char *name = NULL;885for( _defines.reset(); (name = _defines.iter()) != NULL; ) {886const Expr *expr = (const Expr*)_expr[name];887assert( expr != NULL, "name in ExprDict without matching Expr in dictionary");888expr->print_assert(fp);889}890}891892// Print out the dictionary contents as key-value pairs893static void dumpekey(const void* key) { fprintf(stdout, "%s", (char*) key); }894static void dumpexpr(const void* expr) { fflush(stdout); ((Expr*)expr)->print(); }895896void ExprDict::dump() {897_expr.print(dumpekey, dumpexpr);898}899900901//------------------------------ExprDict::private------------------------------902// Disable public use of constructor, copy-ctor, operator =, operator ==903ExprDict::ExprDict( ) : _expr(cmpkey,hashkey), _defines() {904assert( false, "NotImplemented");905}906ExprDict::ExprDict( const ExprDict & ) : _expr(cmpkey,hashkey), _defines() {907assert( false, "NotImplemented");908}909ExprDict &ExprDict::operator =( const ExprDict &rhs) {910assert( false, "NotImplemented");911_expr = rhs._expr;912return *this;913}914// == compares two dictionaries; they must have the same keys (their keys915// must match using CmpKey) and they must have the same values (pointer916// comparison). If so 1 is returned, if not 0 is returned.917bool ExprDict::operator ==(const ExprDict &d) const {918assert( false, "NotImplemented");919return false;920}921922923//------------------------------Production-------------------------------------924Production::Production(const char *result, const char *constraint, const char *valid) {925initialize();926_result = result;927_constraint = constraint;928_valid = valid;929}930931void Production::initialize() {932_result = NULL;933_constraint = NULL;934_valid = knownInvalid;935_cost_lb = Expr::get_unknown();936_cost_ub = Expr::get_unknown();937}938939void Production::print() {940printf("%s", (_result == NULL ? "NULL" : _result ) );941printf("%s", (_constraint == NULL ? "NULL" : _constraint ) );942printf("%s", (_valid == NULL ? "NULL" : _valid ) );943_cost_lb->print();944_cost_ub->print();945}946947948//------------------------------ProductionState--------------------------------949void ProductionState::initialize() {950_constraint = noConstraint;951952// reset each Production currently in the dictionary953DictI iter( &_production );954const void *x, *y = NULL;955for( ; iter.test(); ++iter) {956x = iter._key;957y = iter._value;958Production *p = (Production*)y;959if( p != NULL ) {960p->initialize();961}962}963}964965Production *ProductionState::getProduction(const char *result) {966Production *p = (Production *)_production[result];967if( p == NULL ) {968p = new Production(result, _constraint, knownInvalid);969_production.Insert(result, p);970}971972return p;973}974975void ProductionState::set_constraint(const char *constraint) {976_constraint = constraint;977}978979const char *ProductionState::valid(const char *result) {980return getProduction(result)->valid();981}982983void ProductionState::set_valid(const char *result) {984Production *p = getProduction(result);985986// Update valid as allowed by current constraints987if( _constraint == noConstraint ) {988p->_valid = knownValid;989} else {990if( p->_valid != knownValid ) {991p->_valid = unknownValid;992}993}994}995996Expr *ProductionState::cost_lb(const char *result) {997return getProduction(result)->cost_lb();998}9991000Expr *ProductionState::cost_ub(const char *result) {1001return getProduction(result)->cost_ub();1002}10031004void ProductionState::set_cost_bounds(const char *result, const Expr *cost, bool has_state_check, bool has_cost_check) {1005Production *p = getProduction(result);10061007if( p->_valid == knownInvalid ) {1008// Our cost bounds are not unknown, just not defined.1009p->_cost_lb = cost->clone();1010p->_cost_ub = cost->clone();1011} else if (has_state_check || _constraint != noConstraint) {1012// The production is protected by a condition, so1013// the cost bounds may expand.1014// _cost_lb = min(cost, _cost_lb)1015if( cost->less_than_or_equal(p->_cost_lb) ) {1016p->_cost_lb = cost->clone();1017}1018// _cost_ub = max(cost, _cost_ub)1019if( p->_cost_ub->less_than_or_equal(cost) ) {1020p->_cost_ub = cost->clone();1021}1022} else if (has_cost_check) {1023// The production has no condition check, but does1024// have a cost check that could reduce the upper1025// and/or lower bound.1026// _cost_lb = min(cost, _cost_lb)1027if( cost->less_than_or_equal(p->_cost_lb) ) {1028p->_cost_lb = cost->clone();1029}1030// _cost_ub = min(cost, _cost_ub)1031if( cost->less_than_or_equal(p->_cost_ub) ) {1032p->_cost_ub = cost->clone();1033}1034} else {1035// The costs are unconditionally set.1036p->_cost_lb = cost->clone();1037p->_cost_ub = cost->clone();1038}10391040}10411042// Print out the dictionary contents as key-value pairs1043static void print_key (const void* key) { fprintf(stdout, "%s", (char*) key); }1044static void print_production(const void* production) { fflush(stdout); ((Production*)production)->print(); }10451046void ProductionState::print() {1047_production.print(print_key, print_production);1048}104910501051