formssel.cpp revision 5776:de6a9e811145
1/*
2 * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
24
25// FORMS.CPP - Definitions for ADL Parser Forms Classes
26#include "adlc.hpp"
27
28//==============================Instructions===================================
29//------------------------------InstructForm-----------------------------------
30InstructForm::InstructForm(const char *id, bool ideal_only)
31  : _ident(id), _ideal_only(ideal_only),
32    _localNames(cmpstr, hashstr, Form::arena),
33    _effects(cmpstr, hashstr, Form::arena),
34    _is_mach_constant(false),
35    _has_call(false)
36{
37      _ftype = Form::INS;
38
39      _matrule   = NULL;
40      _insencode = NULL;
41      _constant  = NULL;
42      _opcode    = NULL;
43      _size      = NULL;
44      _attribs   = NULL;
45      _predicate = NULL;
46      _exprule   = NULL;
47      _rewrule   = NULL;
48      _format    = NULL;
49      _peephole  = NULL;
50      _ins_pipe  = NULL;
51      _uniq_idx  = NULL;
52      _num_uniq  = 0;
53      _cisc_spill_operand = Not_cisc_spillable;// Which operand may cisc-spill
54      _cisc_spill_alternate = NULL;            // possible cisc replacement
55      _cisc_reg_mask_name = NULL;
56      _is_cisc_alternate = false;
57      _is_short_branch = false;
58      _short_branch_form = NULL;
59      _alignment = 1;
60}
61
62InstructForm::InstructForm(const char *id, InstructForm *instr, MatchRule *rule)
63  : _ident(id), _ideal_only(false),
64    _localNames(instr->_localNames),
65    _effects(instr->_effects),
66    _is_mach_constant(false),
67    _has_call(false)
68{
69      _ftype = Form::INS;
70
71      _matrule   = rule;
72      _insencode = instr->_insencode;
73      _constant  = instr->_constant;
74      _opcode    = instr->_opcode;
75      _size      = instr->_size;
76      _attribs   = instr->_attribs;
77      _predicate = instr->_predicate;
78      _exprule   = instr->_exprule;
79      _rewrule   = instr->_rewrule;
80      _format    = instr->_format;
81      _peephole  = instr->_peephole;
82      _ins_pipe  = instr->_ins_pipe;
83      _uniq_idx  = instr->_uniq_idx;
84      _num_uniq  = instr->_num_uniq;
85      _cisc_spill_operand = Not_cisc_spillable;// Which operand may cisc-spill
86      _cisc_spill_alternate = NULL;            // possible cisc replacement
87      _cisc_reg_mask_name = NULL;
88      _is_cisc_alternate = false;
89      _is_short_branch = false;
90      _short_branch_form = NULL;
91      _alignment = 1;
92     // Copy parameters
93     const char *name;
94     instr->_parameters.reset();
95     for (; (name = instr->_parameters.iter()) != NULL;)
96       _parameters.addName(name);
97}
98
99InstructForm::~InstructForm() {
100}
101
102InstructForm *InstructForm::is_instruction() const {
103  return (InstructForm*)this;
104}
105
106bool InstructForm::ideal_only() const {
107  return _ideal_only;
108}
109
110bool InstructForm::sets_result() const {
111  return (_matrule != NULL && _matrule->sets_result());
112}
113
114bool InstructForm::needs_projections() {
115  _components.reset();
116  for( Component *comp; (comp = _components.iter()) != NULL; ) {
117    if (comp->isa(Component::KILL)) {
118      return true;
119    }
120  }
121  return false;
122}
123
124
125bool InstructForm::has_temps() {
126  if (_matrule) {
127    // Examine each component to see if it is a TEMP
128    _components.reset();
129    // Skip the first component, if already handled as (SET dst (...))
130    Component *comp = NULL;
131    if (sets_result())  comp = _components.iter();
132    while ((comp = _components.iter()) != NULL) {
133      if (comp->isa(Component::TEMP)) {
134        return true;
135      }
136    }
137  }
138
139  return false;
140}
141
142uint InstructForm::num_defs_or_kills() {
143  uint   defs_or_kills = 0;
144
145  _components.reset();
146  for( Component *comp; (comp = _components.iter()) != NULL; ) {
147    if( comp->isa(Component::DEF) || comp->isa(Component::KILL) ) {
148      ++defs_or_kills;
149    }
150  }
151
152  return  defs_or_kills;
153}
154
155// This instruction has an expand rule?
156bool InstructForm::expands() const {
157  return ( _exprule != NULL );
158}
159
160// This instruction has a peephole rule?
161Peephole *InstructForm::peepholes() const {
162  return _peephole;
163}
164
165// This instruction has a peephole rule?
166void InstructForm::append_peephole(Peephole *peephole) {
167  if( _peephole == NULL ) {
168    _peephole = peephole;
169  } else {
170    _peephole->append_peephole(peephole);
171  }
172}
173
174
175// ideal opcode enumeration
176const char *InstructForm::ideal_Opcode( FormDict &globalNames )  const {
177  if( !_matrule ) return "Node"; // Something weird
178  // Chain rules do not really have ideal Opcodes; use their source
179  // operand ideal Opcode instead.
180  if( is_simple_chain_rule(globalNames) ) {
181    const char *src = _matrule->_rChild->_opType;
182    OperandForm *src_op = globalNames[src]->is_operand();
183    assert( src_op, "Not operand class of chain rule" );
184    if( !src_op->_matrule ) return "Node";
185    return src_op->_matrule->_opType;
186  }
187  // Operand chain rules do not really have ideal Opcodes
188  if( _matrule->is_chain_rule(globalNames) )
189    return "Node";
190  return strcmp(_matrule->_opType,"Set")
191    ? _matrule->_opType
192    : _matrule->_rChild->_opType;
193}
194
195// Recursive check on all operands' match rules in my match rule
196bool InstructForm::is_pinned(FormDict &globals) {
197  if ( ! _matrule)  return false;
198
199  int  index   = 0;
200  if (_matrule->find_type("Goto",          index)) return true;
201  if (_matrule->find_type("If",            index)) return true;
202  if (_matrule->find_type("CountedLoopEnd",index)) return true;
203  if (_matrule->find_type("Return",        index)) return true;
204  if (_matrule->find_type("Rethrow",       index)) return true;
205  if (_matrule->find_type("TailCall",      index)) return true;
206  if (_matrule->find_type("TailJump",      index)) return true;
207  if (_matrule->find_type("Halt",          index)) return true;
208  if (_matrule->find_type("Jump",          index)) return true;
209
210  return is_parm(globals);
211}
212
213// Recursive check on all operands' match rules in my match rule
214bool InstructForm::is_projection(FormDict &globals) {
215  if ( ! _matrule)  return false;
216
217  int  index   = 0;
218  if (_matrule->find_type("Goto",    index)) return true;
219  if (_matrule->find_type("Return",  index)) return true;
220  if (_matrule->find_type("Rethrow", index)) return true;
221  if (_matrule->find_type("TailCall",index)) return true;
222  if (_matrule->find_type("TailJump",index)) return true;
223  if (_matrule->find_type("Halt",    index)) return true;
224
225  return false;
226}
227
228// Recursive check on all operands' match rules in my match rule
229bool InstructForm::is_parm(FormDict &globals) {
230  if ( ! _matrule)  return false;
231
232  int  index   = 0;
233  if (_matrule->find_type("Parm",index)) return true;
234
235  return false;
236}
237
238bool InstructForm::is_ideal_negD() const {
239  return (_matrule && _matrule->_rChild && strcmp(_matrule->_rChild->_opType, "NegD") == 0);
240}
241
242// Return 'true' if this instruction matches an ideal 'Copy*' node
243int InstructForm::is_ideal_copy() const {
244  return _matrule ? _matrule->is_ideal_copy() : 0;
245}
246
247// Return 'true' if this instruction is too complex to rematerialize.
248int InstructForm::is_expensive() const {
249  // We can prove it is cheap if it has an empty encoding.
250  // This helps with platform-specific nops like ThreadLocal and RoundFloat.
251  if (is_empty_encoding())
252    return 0;
253
254  if (is_tls_instruction())
255    return 1;
256
257  if (_matrule == NULL)  return 0;
258
259  return _matrule->is_expensive();
260}
261
262// Has an empty encoding if _size is a constant zero or there
263// are no ins_encode tokens.
264int InstructForm::is_empty_encoding() const {
265  if (_insencode != NULL) {
266    _insencode->reset();
267    if (_insencode->encode_class_iter() == NULL) {
268      return 1;
269    }
270  }
271  if (_size != NULL && strcmp(_size, "0") == 0) {
272    return 1;
273  }
274  return 0;
275}
276
277int InstructForm::is_tls_instruction() const {
278  if (_ident != NULL &&
279      ( ! strcmp( _ident,"tlsLoadP") ||
280        ! strncmp(_ident,"tlsLoadP_",9)) ) {
281    return 1;
282  }
283
284  if (_matrule != NULL && _insencode != NULL) {
285    const char* opType = _matrule->_opType;
286    if (strcmp(opType, "Set")==0)
287      opType = _matrule->_rChild->_opType;
288    if (strcmp(opType,"ThreadLocal")==0) {
289      fprintf(stderr, "Warning: ThreadLocal instruction %s should be named 'tlsLoadP_*'\n",
290              (_ident == NULL ? "NULL" : _ident));
291      return 1;
292    }
293  }
294
295  return 0;
296}
297
298
299// Return 'true' if this instruction matches an ideal 'If' node
300bool InstructForm::is_ideal_if() const {
301  if( _matrule == NULL ) return false;
302
303  return _matrule->is_ideal_if();
304}
305
306// Return 'true' if this instruction matches an ideal 'FastLock' node
307bool InstructForm::is_ideal_fastlock() const {
308  if( _matrule == NULL ) return false;
309
310  return _matrule->is_ideal_fastlock();
311}
312
313// Return 'true' if this instruction matches an ideal 'MemBarXXX' node
314bool InstructForm::is_ideal_membar() const {
315  if( _matrule == NULL ) return false;
316
317  return _matrule->is_ideal_membar();
318}
319
320// Return 'true' if this instruction matches an ideal 'LoadPC' node
321bool InstructForm::is_ideal_loadPC() const {
322  if( _matrule == NULL ) return false;
323
324  return _matrule->is_ideal_loadPC();
325}
326
327// Return 'true' if this instruction matches an ideal 'Box' node
328bool InstructForm::is_ideal_box() const {
329  if( _matrule == NULL ) return false;
330
331  return _matrule->is_ideal_box();
332}
333
334// Return 'true' if this instruction matches an ideal 'Goto' node
335bool InstructForm::is_ideal_goto() const {
336  if( _matrule == NULL ) return false;
337
338  return _matrule->is_ideal_goto();
339}
340
341// Return 'true' if this instruction matches an ideal 'Jump' node
342bool InstructForm::is_ideal_jump() const {
343  if( _matrule == NULL ) return false;
344
345  return _matrule->is_ideal_jump();
346}
347
348// Return 'true' if instruction matches ideal 'If' | 'Goto' | 'CountedLoopEnd'
349bool InstructForm::is_ideal_branch() const {
350  if( _matrule == NULL ) return false;
351
352  return _matrule->is_ideal_if() || _matrule->is_ideal_goto();
353}
354
355
356// Return 'true' if this instruction matches an ideal 'Return' node
357bool InstructForm::is_ideal_return() const {
358  if( _matrule == NULL ) return false;
359
360  // Check MatchRule to see if the first entry is the ideal "Return" node
361  int  index   = 0;
362  if (_matrule->find_type("Return",index)) return true;
363  if (_matrule->find_type("Rethrow",index)) return true;
364  if (_matrule->find_type("TailCall",index)) return true;
365  if (_matrule->find_type("TailJump",index)) return true;
366
367  return false;
368}
369
370// Return 'true' if this instruction matches an ideal 'Halt' node
371bool InstructForm::is_ideal_halt() const {
372  int  index   = 0;
373  return _matrule && _matrule->find_type("Halt",index);
374}
375
376// Return 'true' if this instruction matches an ideal 'SafePoint' node
377bool InstructForm::is_ideal_safepoint() const {
378  int  index   = 0;
379  return _matrule && _matrule->find_type("SafePoint",index);
380}
381
382// Return 'true' if this instruction matches an ideal 'Nop' node
383bool InstructForm::is_ideal_nop() const {
384  return _ident && _ident[0] == 'N' && _ident[1] == 'o' && _ident[2] == 'p' && _ident[3] == '_';
385}
386
387bool InstructForm::is_ideal_control() const {
388  if ( ! _matrule)  return false;
389
390  return is_ideal_return() || is_ideal_branch() || _matrule->is_ideal_jump() || is_ideal_halt();
391}
392
393// Return 'true' if this instruction matches an ideal 'Call' node
394Form::CallType InstructForm::is_ideal_call() const {
395  if( _matrule == NULL ) return Form::invalid_type;
396
397  // Check MatchRule to see if the first entry is the ideal "Call" node
398  int  idx   = 0;
399  if(_matrule->find_type("CallStaticJava",idx))   return Form::JAVA_STATIC;
400  idx = 0;
401  if(_matrule->find_type("Lock",idx))             return Form::JAVA_STATIC;
402  idx = 0;
403  if(_matrule->find_type("Unlock",idx))           return Form::JAVA_STATIC;
404  idx = 0;
405  if(_matrule->find_type("CallDynamicJava",idx))  return Form::JAVA_DYNAMIC;
406  idx = 0;
407  if(_matrule->find_type("CallRuntime",idx))      return Form::JAVA_RUNTIME;
408  idx = 0;
409  if(_matrule->find_type("CallLeaf",idx))         return Form::JAVA_LEAF;
410  idx = 0;
411  if(_matrule->find_type("CallLeafNoFP",idx))     return Form::JAVA_LEAF;
412  idx = 0;
413
414  return Form::invalid_type;
415}
416
417// Return 'true' if this instruction matches an ideal 'Load?' node
418Form::DataType InstructForm::is_ideal_load() const {
419  if( _matrule == NULL ) return Form::none;
420
421  return  _matrule->is_ideal_load();
422}
423
424// Return 'true' if this instruction matches an ideal 'LoadKlass' node
425bool InstructForm::skip_antidep_check() const {
426  if( _matrule == NULL ) return false;
427
428  return  _matrule->skip_antidep_check();
429}
430
431// Return 'true' if this instruction matches an ideal 'Load?' node
432Form::DataType InstructForm::is_ideal_store() const {
433  if( _matrule == NULL ) return Form::none;
434
435  return  _matrule->is_ideal_store();
436}
437
438// Return 'true' if this instruction matches an ideal vector node
439bool InstructForm::is_vector() const {
440  if( _matrule == NULL ) return false;
441
442  return _matrule->is_vector();
443}
444
445
446// Return the input register that must match the output register
447// If this is not required, return 0
448uint InstructForm::two_address(FormDict &globals) {
449  uint  matching_input = 0;
450  if(_components.count() == 0) return 0;
451
452  _components.reset();
453  Component *comp = _components.iter();
454  // Check if there is a DEF
455  if( comp->isa(Component::DEF) ) {
456    // Check that this is a register
457    const char  *def_type = comp->_type;
458    const Form  *form     = globals[def_type];
459    OperandForm *op       = form->is_operand();
460    if( op ) {
461      if( op->constrained_reg_class() != NULL &&
462          op->interface_type(globals) == Form::register_interface ) {
463        // Remember the local name for equality test later
464        const char *def_name = comp->_name;
465        // Check if a component has the same name and is a USE
466        do {
467          if( comp->isa(Component::USE) && strcmp(comp->_name,def_name)==0 ) {
468            return operand_position_format(def_name);
469          }
470        } while( (comp = _components.iter()) != NULL);
471      }
472    }
473  }
474
475  return 0;
476}
477
478
479// when chaining a constant to an instruction, returns 'true' and sets opType
480Form::DataType InstructForm::is_chain_of_constant(FormDict &globals) {
481  const char *dummy  = NULL;
482  const char *dummy2 = NULL;
483  return is_chain_of_constant(globals, dummy, dummy2);
484}
485Form::DataType InstructForm::is_chain_of_constant(FormDict &globals,
486                const char * &opTypeParam) {
487  const char *result = NULL;
488
489  return is_chain_of_constant(globals, opTypeParam, result);
490}
491
492Form::DataType InstructForm::is_chain_of_constant(FormDict &globals,
493                const char * &opTypeParam, const char * &resultParam) {
494  Form::DataType  data_type = Form::none;
495  if ( ! _matrule)  return data_type;
496
497  // !!!!!
498  // The source of the chain rule is 'position = 1'
499  uint         position = 1;
500  const char  *result   = NULL;
501  const char  *name     = NULL;
502  const char  *opType   = NULL;
503  // Here base_operand is looking for an ideal type to be returned (opType).
504  if ( _matrule->is_chain_rule(globals)
505       && _matrule->base_operand(position, globals, result, name, opType) ) {
506    data_type = ideal_to_const_type(opType);
507
508    // if it isn't an ideal constant type, just return
509    if ( data_type == Form::none ) return data_type;
510
511    // Ideal constant types also adjust the opType parameter.
512    resultParam = result;
513    opTypeParam = opType;
514    return data_type;
515  }
516
517  return data_type;
518}
519
520// Check if a simple chain rule
521bool InstructForm::is_simple_chain_rule(FormDict &globals) const {
522  if( _matrule && _matrule->sets_result()
523      && _matrule->_rChild->_lChild == NULL
524      && globals[_matrule->_rChild->_opType]
525      && globals[_matrule->_rChild->_opType]->is_opclass() ) {
526    return true;
527  }
528  return false;
529}
530
531// check for structural rematerialization
532bool InstructForm::rematerialize(FormDict &globals, RegisterForm *registers ) {
533  bool   rematerialize = false;
534
535  Form::DataType data_type = is_chain_of_constant(globals);
536  if( data_type != Form::none )
537    rematerialize = true;
538
539  // Constants
540  if( _components.count() == 1 && _components[0]->is(Component::USE_DEF) )
541    rematerialize = true;
542
543  // Pseudo-constants (values easily available to the runtime)
544  if (is_empty_encoding() && is_tls_instruction())
545    rematerialize = true;
546
547  // 1-input, 1-output, such as copies or increments.
548  if( _components.count() == 2 &&
549      _components[0]->is(Component::DEF) &&
550      _components[1]->isa(Component::USE) )
551    rematerialize = true;
552
553  // Check for an ideal 'Load?' and eliminate rematerialize option
554  if ( is_ideal_load() != Form::none || // Ideal load?  Do not rematerialize
555       is_ideal_copy() != Form::none || // Ideal copy?  Do not rematerialize
556       is_expensive()  != Form::none) { // Expensive?   Do not rematerialize
557    rematerialize = false;
558  }
559
560  // Always rematerialize the flags.  They are more expensive to save &
561  // restore than to recompute (and possibly spill the compare's inputs).
562  if( _components.count() >= 1 ) {
563    Component *c = _components[0];
564    const Form *form = globals[c->_type];
565    OperandForm *opform = form->is_operand();
566    if( opform ) {
567      // Avoid the special stack_slots register classes
568      const char *rc_name = opform->constrained_reg_class();
569      if( rc_name ) {
570        if( strcmp(rc_name,"stack_slots") ) {
571          // Check for ideal_type of RegFlags
572          const char *type = opform->ideal_type( globals, registers );
573          if( (type != NULL) && !strcmp(type, "RegFlags") )
574            rematerialize = true;
575        } else
576          rematerialize = false; // Do not rematerialize things target stk
577      }
578    }
579  }
580
581  return rematerialize;
582}
583
584// loads from memory, so must check for anti-dependence
585bool InstructForm::needs_anti_dependence_check(FormDict &globals) const {
586  if ( skip_antidep_check() ) return false;
587
588  // Machine independent loads must be checked for anti-dependences
589  if( is_ideal_load() != Form::none )  return true;
590
591  // !!!!! !!!!! !!!!!
592  // TEMPORARY
593  // if( is_simple_chain_rule(globals) )  return false;
594
595  // String.(compareTo/equals/indexOf) and Arrays.equals use many memorys edges,
596  // but writes none
597  if( _matrule && _matrule->_rChild &&
598      ( strcmp(_matrule->_rChild->_opType,"StrComp"    )==0 ||
599        strcmp(_matrule->_rChild->_opType,"StrEquals"  )==0 ||
600        strcmp(_matrule->_rChild->_opType,"StrIndexOf" )==0 ||
601        strcmp(_matrule->_rChild->_opType,"AryEq"      )==0 ))
602    return true;
603
604  // Check if instruction has a USE of a memory operand class, but no defs
605  bool USE_of_memory  = false;
606  bool DEF_of_memory  = false;
607  Component     *comp = NULL;
608  ComponentList &components = (ComponentList &)_components;
609
610  components.reset();
611  while( (comp = components.iter()) != NULL ) {
612    const Form  *form = globals[comp->_type];
613    if( !form ) continue;
614    OpClassForm *op   = form->is_opclass();
615    if( !op ) continue;
616    if( form->interface_type(globals) == Form::memory_interface ) {
617      if( comp->isa(Component::USE) ) USE_of_memory = true;
618      if( comp->isa(Component::DEF) ) {
619        OperandForm *oper = form->is_operand();
620        if( oper && oper->is_user_name_for_sReg() ) {
621          // Stack slots are unaliased memory handled by allocator
622          oper = oper;  // debug stopping point !!!!!
623        } else {
624          DEF_of_memory = true;
625        }
626      }
627    }
628  }
629  return (USE_of_memory && !DEF_of_memory);
630}
631
632
633bool InstructForm::is_wide_memory_kill(FormDict &globals) const {
634  if( _matrule == NULL ) return false;
635  if( !_matrule->_opType ) return false;
636
637  if( strcmp(_matrule->_opType,"MemBarRelease") == 0 ) return true;
638  if( strcmp(_matrule->_opType,"MemBarAcquire") == 0 ) return true;
639  if( strcmp(_matrule->_opType,"MemBarReleaseLock") == 0 ) return true;
640  if( strcmp(_matrule->_opType,"MemBarAcquireLock") == 0 ) return true;
641  if( strcmp(_matrule->_opType,"MemBarStoreStore") == 0 ) return true;
642
643  return false;
644}
645
646int InstructForm::memory_operand(FormDict &globals) const {
647  // Machine independent loads must be checked for anti-dependences
648  // Check if instruction has a USE of a memory operand class, or a def.
649  int USE_of_memory  = 0;
650  int DEF_of_memory  = 0;
651  const char*    last_memory_DEF = NULL; // to test DEF/USE pairing in asserts
652  Component     *unique          = NULL;
653  Component     *comp            = NULL;
654  ComponentList &components      = (ComponentList &)_components;
655
656  components.reset();
657  while( (comp = components.iter()) != NULL ) {
658    const Form  *form = globals[comp->_type];
659    if( !form ) continue;
660    OpClassForm *op   = form->is_opclass();
661    if( !op ) continue;
662    if( op->stack_slots_only(globals) )  continue;
663    if( form->interface_type(globals) == Form::memory_interface ) {
664      if( comp->isa(Component::DEF) ) {
665        last_memory_DEF = comp->_name;
666        DEF_of_memory++;
667        unique = comp;
668      } else if( comp->isa(Component::USE) ) {
669        if( last_memory_DEF != NULL ) {
670          assert(0 == strcmp(last_memory_DEF, comp->_name), "every memory DEF is followed by a USE of the same name");
671          last_memory_DEF = NULL;
672        }
673        USE_of_memory++;
674        if (DEF_of_memory == 0)  // defs take precedence
675          unique = comp;
676      } else {
677        assert(last_memory_DEF == NULL, "unpaired memory DEF");
678      }
679    }
680  }
681  assert(last_memory_DEF == NULL, "unpaired memory DEF");
682  assert(USE_of_memory >= DEF_of_memory, "unpaired memory DEF");
683  USE_of_memory -= DEF_of_memory;   // treat paired DEF/USE as one occurrence
684  if( (USE_of_memory + DEF_of_memory) > 0 ) {
685    if( is_simple_chain_rule(globals) ) {
686      //fprintf(stderr, "Warning: chain rule is not really a memory user.\n");
687      //((InstructForm*)this)->dump();
688      // Preceding code prints nothing on sparc and these insns on intel:
689      // leaP8 leaP32 leaPIdxOff leaPIdxScale leaPIdxScaleOff leaP8 leaP32
690      // leaPIdxOff leaPIdxScale leaPIdxScaleOff
691      return NO_MEMORY_OPERAND;
692    }
693
694    if( DEF_of_memory == 1 ) {
695      assert(unique != NULL, "");
696      if( USE_of_memory == 0 ) {
697        // unique def, no uses
698      } else {
699        // // unique def, some uses
700        // // must return bottom unless all uses match def
701        // unique = NULL;
702      }
703    } else if( DEF_of_memory > 0 ) {
704      // multiple defs, don't care about uses
705      unique = NULL;
706    } else if( USE_of_memory == 1) {
707      // unique use, no defs
708      assert(unique != NULL, "");
709    } else if( USE_of_memory > 0 ) {
710      // multiple uses, no defs
711      unique = NULL;
712    } else {
713      assert(false, "bad case analysis");
714    }
715    // process the unique DEF or USE, if there is one
716    if( unique == NULL ) {
717      return MANY_MEMORY_OPERANDS;
718    } else {
719      int pos = components.operand_position(unique->_name);
720      if( unique->isa(Component::DEF) ) {
721        pos += 1;                // get corresponding USE from DEF
722      }
723      assert(pos >= 1, "I was just looking at it!");
724      return pos;
725    }
726  }
727
728  // missed the memory op??
729  if( true ) {  // %%% should not be necessary
730    if( is_ideal_store() != Form::none ) {
731      fprintf(stderr, "Warning: cannot find memory opnd in instr.\n");
732      ((InstructForm*)this)->dump();
733      // pretend it has multiple defs and uses
734      return MANY_MEMORY_OPERANDS;
735    }
736    if( is_ideal_load()  != Form::none ) {
737      fprintf(stderr, "Warning: cannot find memory opnd in instr.\n");
738      ((InstructForm*)this)->dump();
739      // pretend it has multiple uses and no defs
740      return MANY_MEMORY_OPERANDS;
741    }
742  }
743
744  return NO_MEMORY_OPERAND;
745}
746
747
748// This instruction captures the machine-independent bottom_type
749// Expected use is for pointer vs oop determination for LoadP
750bool InstructForm::captures_bottom_type(FormDict &globals) const {
751  if( _matrule && _matrule->_rChild &&
752       (!strcmp(_matrule->_rChild->_opType,"CastPP")       ||  // new result type
753        !strcmp(_matrule->_rChild->_opType,"CastX2P")      ||  // new result type
754        !strcmp(_matrule->_rChild->_opType,"DecodeN")      ||
755        !strcmp(_matrule->_rChild->_opType,"EncodeP")      ||
756        !strcmp(_matrule->_rChild->_opType,"DecodeNKlass") ||
757        !strcmp(_matrule->_rChild->_opType,"EncodePKlass") ||
758        !strcmp(_matrule->_rChild->_opType,"LoadN")        ||
759        !strcmp(_matrule->_rChild->_opType,"LoadNKlass")   ||
760        !strcmp(_matrule->_rChild->_opType,"CreateEx")     ||  // type of exception
761        !strcmp(_matrule->_rChild->_opType,"CheckCastPP")  ||
762        !strcmp(_matrule->_rChild->_opType,"GetAndSetP")   ||
763        !strcmp(_matrule->_rChild->_opType,"GetAndSetN")) )  return true;
764  else if ( is_ideal_load() == Form::idealP )                return true;
765  else if ( is_ideal_store() != Form::none  )                return true;
766
767  if (needs_base_oop_edge(globals)) return true;
768
769  if (is_vector()) return true;
770  if (is_mach_constant()) return true;
771
772  return  false;
773}
774
775
776// Access instr_cost attribute or return NULL.
777const char* InstructForm::cost() {
778  for (Attribute* cur = _attribs; cur != NULL; cur = (Attribute*)cur->_next) {
779    if( strcmp(cur->_ident,AttributeForm::_ins_cost) == 0 ) {
780      return cur->_val;
781    }
782  }
783  return NULL;
784}
785
786// Return count of top-level operands.
787uint InstructForm::num_opnds() {
788  int  num_opnds = _components.num_operands();
789
790  // Need special handling for matching some ideal nodes
791  // i.e. Matching a return node
792  /*
793  if( _matrule ) {
794    if( strcmp(_matrule->_opType,"Return"   )==0 ||
795        strcmp(_matrule->_opType,"Halt"     )==0 )
796      return 3;
797  }
798    */
799  return num_opnds;
800}
801
802const char* InstructForm::opnd_ident(int idx) {
803  return _components.at(idx)->_name;
804}
805
806const char* InstructForm::unique_opnd_ident(uint idx) {
807  uint i;
808  for (i = 1; i < num_opnds(); ++i) {
809    if (unique_opnds_idx(i) == idx) {
810      break;
811    }
812  }
813  return (_components.at(i) != NULL) ? _components.at(i)->_name : "";
814}
815
816// Return count of unmatched operands.
817uint InstructForm::num_post_match_opnds() {
818  uint  num_post_match_opnds = _components.count();
819  uint  num_match_opnds = _components.match_count();
820  num_post_match_opnds = num_post_match_opnds - num_match_opnds;
821
822  return num_post_match_opnds;
823}
824
825// Return the number of leaves below this complex operand
826uint InstructForm::num_consts(FormDict &globals) const {
827  if ( ! _matrule) return 0;
828
829  // This is a recursive invocation on all operands in the matchrule
830  return _matrule->num_consts(globals);
831}
832
833// Constants in match rule with specified type
834uint InstructForm::num_consts(FormDict &globals, Form::DataType type) const {
835  if ( ! _matrule) return 0;
836
837  // This is a recursive invocation on all operands in the matchrule
838  return _matrule->num_consts(globals, type);
839}
840
841
842// Return the register class associated with 'leaf'.
843const char *InstructForm::out_reg_class(FormDict &globals) {
844  assert( false, "InstructForm::out_reg_class(FormDict &globals); Not Implemented");
845
846  return NULL;
847}
848
849
850
851// Lookup the starting position of inputs we are interested in wrt. ideal nodes
852uint InstructForm::oper_input_base(FormDict &globals) {
853  if( !_matrule ) return 1;     // Skip control for most nodes
854
855  // Need special handling for matching some ideal nodes
856  // i.e. Matching a return node
857  if( strcmp(_matrule->_opType,"Return"    )==0 ||
858      strcmp(_matrule->_opType,"Rethrow"   )==0 ||
859      strcmp(_matrule->_opType,"TailCall"  )==0 ||
860      strcmp(_matrule->_opType,"TailJump"  )==0 ||
861      strcmp(_matrule->_opType,"SafePoint" )==0 ||
862      strcmp(_matrule->_opType,"Halt"      )==0 )
863    return AdlcVMDeps::Parms;   // Skip the machine-state edges
864
865  if( _matrule->_rChild &&
866      ( strcmp(_matrule->_rChild->_opType,"AryEq"     )==0 ||
867        strcmp(_matrule->_rChild->_opType,"StrComp"   )==0 ||
868        strcmp(_matrule->_rChild->_opType,"StrEquals" )==0 ||
869        strcmp(_matrule->_rChild->_opType,"StrIndexOf")==0 ||
870        strcmp(_matrule->_rChild->_opType,"EncodeISOArray")==0)) {
871        // String.(compareTo/equals/indexOf) and Arrays.equals
872        // and sun.nio.cs.iso8859_1$Encoder.EncodeISOArray
873        // take 1 control and 1 memory edges.
874    return 2;
875  }
876
877  // Check for handling of 'Memory' input/edge in the ideal world.
878  // The AD file writer is shielded from knowledge of these edges.
879  int base = 1;                 // Skip control
880  base += _matrule->needs_ideal_memory_edge(globals);
881
882  // Also skip the base-oop value for uses of derived oops.
883  // The AD file writer is shielded from knowledge of these edges.
884  base += needs_base_oop_edge(globals);
885
886  return base;
887}
888
889// This function determines the order of the MachOper in _opnds[]
890// by writing the operand names into the _components list.
891//
892// Implementation does not modify state of internal structures
893void InstructForm::build_components() {
894  // Add top-level operands to the components
895  if (_matrule)  _matrule->append_components(_localNames, _components);
896
897  // Add parameters that "do not appear in match rule".
898  bool has_temp = false;
899  const char *name;
900  const char *kill_name = NULL;
901  for (_parameters.reset(); (name = _parameters.iter()) != NULL;) {
902    OperandForm *opForm = (OperandForm*)_localNames[name];
903
904    Effect* e = NULL;
905    {
906      const Form* form = _effects[name];
907      e = form ? form->is_effect() : NULL;
908    }
909
910    if (e != NULL) {
911      has_temp |= e->is(Component::TEMP);
912
913      // KILLs must be declared after any TEMPs because TEMPs are real
914      // uses so their operand numbering must directly follow the real
915      // inputs from the match rule.  Fixing the numbering seems
916      // complex so simply enforce the restriction during parse.
917      if (kill_name != NULL &&
918          e->isa(Component::TEMP) && !e->isa(Component::DEF)) {
919        OperandForm* kill = (OperandForm*)_localNames[kill_name];
920        globalAD->syntax_err(_linenum, "%s: %s %s must be at the end of the argument list\n",
921                             _ident, kill->_ident, kill_name);
922      } else if (e->isa(Component::KILL) && !e->isa(Component::USE)) {
923        kill_name = name;
924      }
925    }
926
927    const Component *component  = _components.search(name);
928    if ( component  == NULL ) {
929      if (e) {
930        _components.insert(name, opForm->_ident, e->_use_def, false);
931        component = _components.search(name);
932        if (component->isa(Component::USE) && !component->isa(Component::TEMP) && _matrule) {
933          const Form *form = globalAD->globalNames()[component->_type];
934          assert( form, "component type must be a defined form");
935          OperandForm *op   = form->is_operand();
936          if (op->_interface && op->_interface->is_RegInterface()) {
937            globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
938                                 _ident, opForm->_ident, name);
939          }
940        }
941      } else {
942        // This would be a nice warning but it triggers in a few places in a benign way
943        // if (_matrule != NULL && !expands()) {
944        //   globalAD->syntax_err(_linenum, "%s: %s %s not mentioned in effect or match rule\n",
945        //                        _ident, opForm->_ident, name);
946        // }
947        _components.insert(name, opForm->_ident, Component::INVALID, false);
948      }
949    }
950    else if (e) {
951      // Component was found in the list
952      // Check if there is a new effect that requires an extra component.
953      // This happens when adding 'USE' to a component that is not yet one.
954      if ((!component->isa( Component::USE) && ((e->_use_def & Component::USE) != 0))) {
955        if (component->isa(Component::USE) && _matrule) {
956          const Form *form = globalAD->globalNames()[component->_type];
957          assert( form, "component type must be a defined form");
958          OperandForm *op   = form->is_operand();
959          if (op->_interface && op->_interface->is_RegInterface()) {
960            globalAD->syntax_err(_linenum, "%s: illegal USE of non-input: %s %s\n",
961                                 _ident, opForm->_ident, name);
962          }
963        }
964        _components.insert(name, opForm->_ident, e->_use_def, false);
965      } else {
966        Component  *comp = (Component*)component;
967        comp->promote_use_def_info(e->_use_def);
968      }
969      // Component positions are zero based.
970      int  pos  = _components.operand_position(name);
971      assert( ! (component->isa(Component::DEF) && (pos >= 1)),
972              "Component::DEF can only occur in the first position");
973    }
974  }
975
976  // Resolving the interactions between expand rules and TEMPs would
977  // be complex so simply disallow it.
978  if (_matrule == NULL && has_temp) {
979    globalAD->syntax_err(_linenum, "%s: TEMPs without match rule isn't supported\n", _ident);
980  }
981
982  return;
983}
984
985// Return zero-based position in component list;  -1 if not in list.
986int   InstructForm::operand_position(const char *name, int usedef) {
987  return unique_opnds_idx(_components.operand_position(name, usedef, this));
988}
989
990int   InstructForm::operand_position_format(const char *name) {
991  return unique_opnds_idx(_components.operand_position_format(name, this));
992}
993
994// Return zero-based position in component list; -1 if not in list.
995int   InstructForm::label_position() {
996  return unique_opnds_idx(_components.label_position());
997}
998
999int   InstructForm::method_position() {
1000  return unique_opnds_idx(_components.method_position());
1001}
1002
1003// Return number of relocation entries needed for this instruction.
1004uint  InstructForm::reloc(FormDict &globals) {
1005  uint reloc_entries  = 0;
1006  // Check for "Call" nodes
1007  if ( is_ideal_call() )      ++reloc_entries;
1008  if ( is_ideal_return() )    ++reloc_entries;
1009  if ( is_ideal_safepoint() ) ++reloc_entries;
1010
1011
1012  // Check if operands MAYBE oop pointers, by checking for ConP elements
1013  // Proceed through the leaves of the match-tree and check for ConPs
1014  if ( _matrule != NULL ) {
1015    uint         position = 0;
1016    const char  *result   = NULL;
1017    const char  *name     = NULL;
1018    const char  *opType   = NULL;
1019    while (_matrule->base_operand(position, globals, result, name, opType)) {
1020      if ( strcmp(opType,"ConP") == 0 ) {
1021#ifdef SPARC
1022        reloc_entries += 2; // 1 for sethi + 1 for setlo
1023#else
1024        ++reloc_entries;
1025#endif
1026      }
1027      ++position;
1028    }
1029  }
1030
1031  // Above is only a conservative estimate
1032  // because it did not check contents of operand classes.
1033  // !!!!! !!!!!
1034  // Add 1 to reloc info for each operand class in the component list.
1035  Component  *comp;
1036  _components.reset();
1037  while ( (comp = _components.iter()) != NULL ) {
1038    const Form        *form = globals[comp->_type];
1039    assert( form, "Did not find component's type in global names");
1040    const OpClassForm *opc  = form->is_opclass();
1041    const OperandForm *oper = form->is_operand();
1042    if ( opc && (oper == NULL) ) {
1043      ++reloc_entries;
1044    } else if ( oper ) {
1045      // floats and doubles loaded out of method's constant pool require reloc info
1046      Form::DataType type = oper->is_base_constant(globals);
1047      if ( (type == Form::idealF) || (type == Form::idealD) ) {
1048        ++reloc_entries;
1049      }
1050    }
1051  }
1052
1053  // Float and Double constants may come from the CodeBuffer table
1054  // and require relocatable addresses for access
1055  // !!!!!
1056  // Check for any component being an immediate float or double.
1057  Form::DataType data_type = is_chain_of_constant(globals);
1058  if( data_type==idealD || data_type==idealF ) {
1059#ifdef SPARC
1060    // sparc required more relocation entries for floating constants
1061    // (expires 9/98)
1062    reloc_entries += 6;
1063#else
1064    reloc_entries++;
1065#endif
1066  }
1067
1068  return reloc_entries;
1069}
1070
1071// Utility function defined in archDesc.cpp
1072extern bool is_def(int usedef);
1073
1074// Return the result of reducing an instruction
1075const char *InstructForm::reduce_result() {
1076  const char* result = "Universe";  // default
1077  _components.reset();
1078  Component *comp = _components.iter();
1079  if (comp != NULL && comp->isa(Component::DEF)) {
1080    result = comp->_type;
1081    // Override this if the rule is a store operation:
1082    if (_matrule && _matrule->_rChild &&
1083        is_store_to_memory(_matrule->_rChild->_opType))
1084      result = "Universe";
1085  }
1086  return result;
1087}
1088
1089// Return the name of the operand on the right hand side of the binary match
1090// Return NULL if there is no right hand side
1091const char *InstructForm::reduce_right(FormDict &globals)  const {
1092  if( _matrule == NULL ) return NULL;
1093  return  _matrule->reduce_right(globals);
1094}
1095
1096// Similar for left
1097const char *InstructForm::reduce_left(FormDict &globals)   const {
1098  if( _matrule == NULL ) return NULL;
1099  return  _matrule->reduce_left(globals);
1100}
1101
1102
1103// Base class for this instruction, MachNode except for calls
1104const char *InstructForm::mach_base_class(FormDict &globals)  const {
1105  if( is_ideal_call() == Form::JAVA_STATIC ) {
1106    return "MachCallStaticJavaNode";
1107  }
1108  else if( is_ideal_call() == Form::JAVA_DYNAMIC ) {
1109    return "MachCallDynamicJavaNode";
1110  }
1111  else if( is_ideal_call() == Form::JAVA_RUNTIME ) {
1112    return "MachCallRuntimeNode";
1113  }
1114  else if( is_ideal_call() == Form::JAVA_LEAF ) {
1115    return "MachCallLeafNode";
1116  }
1117  else if (is_ideal_return()) {
1118    return "MachReturnNode";
1119  }
1120  else if (is_ideal_halt()) {
1121    return "MachHaltNode";
1122  }
1123  else if (is_ideal_safepoint()) {
1124    return "MachSafePointNode";
1125  }
1126  else if (is_ideal_if()) {
1127    return "MachIfNode";
1128  }
1129  else if (is_ideal_goto()) {
1130    return "MachGotoNode";
1131  }
1132  else if (is_ideal_fastlock()) {
1133    return "MachFastLockNode";
1134  }
1135  else if (is_ideal_nop()) {
1136    return "MachNopNode";
1137  }
1138  else if (is_mach_constant()) {
1139    return "MachConstantNode";
1140  }
1141  else if (captures_bottom_type(globals)) {
1142    return "MachTypeNode";
1143  } else {
1144    return "MachNode";
1145  }
1146  assert( false, "ShouldNotReachHere()");
1147  return NULL;
1148}
1149
1150// Compare the instruction predicates for textual equality
1151bool equivalent_predicates( const InstructForm *instr1, const InstructForm *instr2 ) {
1152  const Predicate *pred1  = instr1->_predicate;
1153  const Predicate *pred2  = instr2->_predicate;
1154  if( pred1 == NULL && pred2 == NULL ) {
1155    // no predicates means they are identical
1156    return true;
1157  }
1158  if( pred1 != NULL && pred2 != NULL ) {
1159    // compare the predicates
1160    if (ADLParser::equivalent_expressions(pred1->_pred, pred2->_pred)) {
1161      return true;
1162    }
1163  }
1164
1165  return false;
1166}
1167
1168// Check if this instruction can cisc-spill to 'alternate'
1169bool InstructForm::cisc_spills_to(ArchDesc &AD, InstructForm *instr) {
1170  assert( _matrule != NULL && instr->_matrule != NULL, "must have match rules");
1171  // Do not replace if a cisc-version has been found.
1172  if( cisc_spill_operand() != Not_cisc_spillable ) return false;
1173
1174  int         cisc_spill_operand = Maybe_cisc_spillable;
1175  char       *result             = NULL;
1176  char       *result2            = NULL;
1177  const char *op_name            = NULL;
1178  const char *reg_type           = NULL;
1179  FormDict   &globals            = AD.globalNames();
1180  cisc_spill_operand = _matrule->matchrule_cisc_spill_match(globals, AD.get_registers(), instr->_matrule, op_name, reg_type);
1181  if( (cisc_spill_operand != Not_cisc_spillable) && (op_name != NULL) && equivalent_predicates(this, instr) ) {
1182    cisc_spill_operand = operand_position(op_name, Component::USE);
1183    int def_oper  = operand_position(op_name, Component::DEF);
1184    if( def_oper == NameList::Not_in_list && instr->num_opnds() == num_opnds()) {
1185      // Do not support cisc-spilling for destination operands and
1186      // make sure they have the same number of operands.
1187      _cisc_spill_alternate = instr;
1188      instr->set_cisc_alternate(true);
1189      if( AD._cisc_spill_debug ) {
1190        fprintf(stderr, "Instruction %s cisc-spills-to %s\n", _ident, instr->_ident);
1191        fprintf(stderr, "   using operand %s %s at index %d\n", reg_type, op_name, cisc_spill_operand);
1192      }
1193      // Record that a stack-version of the reg_mask is needed
1194      // !!!!!
1195      OperandForm *oper = (OperandForm*)(globals[reg_type]->is_operand());
1196      assert( oper != NULL, "cisc-spilling non operand");
1197      const char *reg_class_name = oper->constrained_reg_class();
1198      AD.set_stack_or_reg(reg_class_name);
1199      const char *reg_mask_name  = AD.reg_mask(*oper);
1200      set_cisc_reg_mask_name(reg_mask_name);
1201      const char *stack_or_reg_mask_name = AD.stack_or_reg_mask(*oper);
1202    } else {
1203      cisc_spill_operand = Not_cisc_spillable;
1204    }
1205  } else {
1206    cisc_spill_operand = Not_cisc_spillable;
1207  }
1208
1209  set_cisc_spill_operand(cisc_spill_operand);
1210  return (cisc_spill_operand != Not_cisc_spillable);
1211}
1212
1213// Check to see if this instruction can be replaced with the short branch
1214// instruction `short-branch'
1215bool InstructForm::check_branch_variant(ArchDesc &AD, InstructForm *short_branch) {
1216  if (_matrule != NULL &&
1217      this != short_branch &&   // Don't match myself
1218      !is_short_branch() &&     // Don't match another short branch variant
1219      reduce_result() != NULL &&
1220      strcmp(reduce_result(), short_branch->reduce_result()) == 0 &&
1221      _matrule->equivalent(AD.globalNames(), short_branch->_matrule)) {
1222    // The instructions are equivalent.
1223
1224    // Now verify that both instructions have the same parameters and
1225    // the same effects. Both branch forms should have the same inputs
1226    // and resulting projections to correctly replace a long branch node
1227    // with corresponding short branch node during code generation.
1228
1229    bool different = false;
1230    if (short_branch->_components.count() != _components.count()) {
1231       different = true;
1232    } else if (_components.count() > 0) {
1233      short_branch->_components.reset();
1234      _components.reset();
1235      Component *comp;
1236      while ((comp = _components.iter()) != NULL) {
1237        Component *short_comp = short_branch->_components.iter();
1238        if (short_comp == NULL ||
1239            short_comp->_type != comp->_type ||
1240            short_comp->_usedef != comp->_usedef) {
1241          different = true;
1242          break;
1243        }
1244      }
1245      if (short_branch->_components.iter() != NULL)
1246        different = true;
1247    }
1248    if (different) {
1249      globalAD->syntax_err(short_branch->_linenum, "Instruction %s and its short form %s have different parameters\n", _ident, short_branch->_ident);
1250    }
1251    if (AD._adl_debug > 1 || AD._short_branch_debug) {
1252      fprintf(stderr, "Instruction %s has short form %s\n", _ident, short_branch->_ident);
1253    }
1254    _short_branch_form = short_branch;
1255    return true;
1256  }
1257  return false;
1258}
1259
1260
1261// --------------------------- FILE *output_routines
1262//
1263// Generate the format call for the replacement variable
1264void InstructForm::rep_var_format(FILE *fp, const char *rep_var) {
1265  // Handle special constant table variables.
1266  if (strcmp(rep_var, "constanttablebase") == 0) {
1267    fprintf(fp, "char reg[128];  ra->dump_register(in(mach_constant_base_node_input()), reg);\n");
1268    fprintf(fp, "    st->print(\"%%s\", reg);\n");
1269    return;
1270  }
1271  if (strcmp(rep_var, "constantoffset") == 0) {
1272    fprintf(fp, "st->print(\"#%%d\", constant_offset());\n");
1273    return;
1274  }
1275  if (strcmp(rep_var, "constantaddress") == 0) {
1276    fprintf(fp, "st->print(\"constant table base + #%%d\", constant_offset());\n");
1277    return;
1278  }
1279
1280  // Find replacement variable's type
1281  const Form *form   = _localNames[rep_var];
1282  if (form == NULL) {
1283    globalAD->syntax_err(_linenum, "Unknown replacement variable %s in format statement of %s.",
1284                         rep_var, _ident);
1285    return;
1286  }
1287  OpClassForm *opc   = form->is_opclass();
1288  assert( opc, "replacement variable was not found in local names");
1289  // Lookup the index position of the replacement variable
1290  int idx  = operand_position_format(rep_var);
1291  if ( idx == -1 ) {
1292    globalAD->syntax_err(_linenum, "Could not find replacement variable %s in format statement of %s.\n",
1293                         rep_var, _ident);
1294    assert(strcmp(opc->_ident, "label") == 0, "Unimplemented");
1295    return;
1296  }
1297
1298  if (is_noninput_operand(idx)) {
1299    // This component isn't in the input array.  Print out the static
1300    // name of the register.
1301    OperandForm* oper = form->is_operand();
1302    if (oper != NULL && oper->is_bound_register()) {
1303      const RegDef* first = oper->get_RegClass()->find_first_elem();
1304      fprintf(fp, "    st->print(\"%s\");\n", first->_regname);
1305    } else {
1306      globalAD->syntax_err(_linenum, "In %s can't find format for %s %s", _ident, opc->_ident, rep_var);
1307    }
1308  } else {
1309    // Output the format call for this operand
1310    fprintf(fp,"opnd_array(%d)->",idx);
1311    if (idx == 0)
1312      fprintf(fp,"int_format(ra, this, st); // %s\n", rep_var);
1313    else
1314      fprintf(fp,"ext_format(ra, this,idx%d, st); // %s\n", idx, rep_var );
1315  }
1316}
1317
1318// Seach through operands to determine parameters unique positions.
1319void InstructForm::set_unique_opnds() {
1320  uint* uniq_idx = NULL;
1321  uint  nopnds = num_opnds();
1322  uint  num_uniq = nopnds;
1323  uint i;
1324  _uniq_idx_length = 0;
1325  if (nopnds > 0) {
1326    // Allocate index array.  Worst case we're mapping from each
1327    // component back to an index and any DEF always goes at 0 so the
1328    // length of the array has to be the number of components + 1.
1329    _uniq_idx_length = _components.count() + 1;
1330    uniq_idx = (uint*) malloc(sizeof(uint) * _uniq_idx_length);
1331    for (i = 0; i < _uniq_idx_length; i++) {
1332      uniq_idx[i] = i;
1333    }
1334  }
1335  // Do it only if there is a match rule and no expand rule.  With an
1336  // expand rule it is done by creating new mach node in Expand()
1337  // method.
1338  if (nopnds > 0 && _matrule != NULL && _exprule == NULL) {
1339    const char *name;
1340    uint count;
1341    bool has_dupl_use = false;
1342
1343    _parameters.reset();
1344    while ((name = _parameters.iter()) != NULL) {
1345      count = 0;
1346      uint position = 0;
1347      uint uniq_position = 0;
1348      _components.reset();
1349      Component *comp = NULL;
1350      if (sets_result()) {
1351        comp = _components.iter();
1352        position++;
1353      }
1354      // The next code is copied from the method operand_position().
1355      for (; (comp = _components.iter()) != NULL; ++position) {
1356        // When the first component is not a DEF,
1357        // leave space for the result operand!
1358        if (position==0 && (!comp->isa(Component::DEF))) {
1359          ++position;
1360        }
1361        if (strcmp(name, comp->_name) == 0) {
1362          if (++count > 1) {
1363            assert(position < _uniq_idx_length, "out of bounds");
1364            uniq_idx[position] = uniq_position;
1365            has_dupl_use = true;
1366          } else {
1367            uniq_position = position;
1368          }
1369        }
1370        if (comp->isa(Component::DEF) && comp->isa(Component::USE)) {
1371          ++position;
1372          if (position != 1)
1373            --position;   // only use two slots for the 1st USE_DEF
1374        }
1375      }
1376    }
1377    if (has_dupl_use) {
1378      for (i = 1; i < nopnds; i++) {
1379        if (i != uniq_idx[i]) {
1380          break;
1381        }
1382      }
1383      uint j = i;
1384      for (; i < nopnds; i++) {
1385        if (i == uniq_idx[i]) {
1386          uniq_idx[i] = j++;
1387        }
1388      }
1389      num_uniq = j;
1390    }
1391  }
1392  _uniq_idx = uniq_idx;
1393  _num_uniq = num_uniq;
1394}
1395
1396// Generate index values needed for determining the operand position
1397void InstructForm::index_temps(FILE *fp, FormDict &globals, const char *prefix, const char *receiver) {
1398  uint  idx = 0;                  // position of operand in match rule
1399  int   cur_num_opnds = num_opnds();
1400
1401  // Compute the index into vector of operand pointers:
1402  // idx0=0 is used to indicate that info comes from this same node, not from input edge.
1403  // idx1 starts at oper_input_base()
1404  if ( cur_num_opnds >= 1 ) {
1405    fprintf(fp,"  // Start at oper_input_base() and count operands\n");
1406    fprintf(fp,"  unsigned %sidx0 = %d;\n", prefix, oper_input_base(globals));
1407    fprintf(fp,"  unsigned %sidx1 = %d;", prefix, oper_input_base(globals));
1408    fprintf(fp," \t// %s\n", unique_opnd_ident(1));
1409
1410    // Generate starting points for other unique operands if they exist
1411    for ( idx = 2; idx < num_unique_opnds(); ++idx ) {
1412      if( *receiver == 0 ) {
1413        fprintf(fp,"  unsigned %sidx%d = %sidx%d + opnd_array(%d)->num_edges();",
1414                prefix, idx, prefix, idx-1, idx-1 );
1415      } else {
1416        fprintf(fp,"  unsigned %sidx%d = %sidx%d + %s_opnds[%d]->num_edges();",
1417                prefix, idx, prefix, idx-1, receiver, idx-1 );
1418      }
1419      fprintf(fp," \t// %s\n", unique_opnd_ident(idx));
1420    }
1421  }
1422  if( *receiver != 0 ) {
1423    // This value is used by generate_peepreplace when copying a node.
1424    // Don't emit it in other cases since it can hide bugs with the
1425    // use invalid idx's.
1426    fprintf(fp,"  unsigned %sidx%d = %sreq(); \n", prefix, idx, receiver);
1427  }
1428
1429}
1430
1431// ---------------------------
1432bool InstructForm::verify() {
1433  // !!!!! !!!!!
1434  // Check that a "label" operand occurs last in the operand list, if present
1435  return true;
1436}
1437
1438void InstructForm::dump() {
1439  output(stderr);
1440}
1441
1442void InstructForm::output(FILE *fp) {
1443  fprintf(fp,"\nInstruction: %s\n", (_ident?_ident:""));
1444  if (_matrule)   _matrule->output(fp);
1445  if (_insencode) _insencode->output(fp);
1446  if (_constant)  _constant->output(fp);
1447  if (_opcode)    _opcode->output(fp);
1448  if (_attribs)   _attribs->output(fp);
1449  if (_predicate) _predicate->output(fp);
1450  if (_effects.Size()) {
1451    fprintf(fp,"Effects\n");
1452    _effects.dump();
1453  }
1454  if (_exprule)   _exprule->output(fp);
1455  if (_rewrule)   _rewrule->output(fp);
1456  if (_format)    _format->output(fp);
1457  if (_peephole)  _peephole->output(fp);
1458}
1459
1460void MachNodeForm::dump() {
1461  output(stderr);
1462}
1463
1464void MachNodeForm::output(FILE *fp) {
1465  fprintf(fp,"\nMachNode: %s\n", (_ident?_ident:""));
1466}
1467
1468//------------------------------build_predicate--------------------------------
1469// Build instruction predicates.  If the user uses the same operand name
1470// twice, we need to check that the operands are pointer-eequivalent in
1471// the DFA during the labeling process.
1472Predicate *InstructForm::build_predicate() {
1473  char buf[1024], *s=buf;
1474  Dict names(cmpstr,hashstr,Form::arena);       // Map Names to counts
1475
1476  MatchNode *mnode =
1477    strcmp(_matrule->_opType, "Set") ? _matrule : _matrule->_rChild;
1478  mnode->count_instr_names(names);
1479
1480  uint first = 1;
1481  // Start with the predicate supplied in the .ad file.
1482  if( _predicate ) {
1483    if( first ) first=0;
1484    strcpy(s,"("); s += strlen(s);
1485    strcpy(s,_predicate->_pred);
1486    s += strlen(s);
1487    strcpy(s,")"); s += strlen(s);
1488  }
1489  for( DictI i(&names); i.test(); ++i ) {
1490    uintptr_t cnt = (uintptr_t)i._value;
1491    if( cnt > 1 ) {             // Need a predicate at all?
1492      assert( cnt == 2, "Unimplemented" );
1493      // Handle many pairs
1494      if( first ) first=0;
1495      else {                    // All tests must pass, so use '&&'
1496        strcpy(s," && ");
1497        s += strlen(s);
1498      }
1499      // Add predicate to working buffer
1500      sprintf(s,"/*%s*/(",(char*)i._key);
1501      s += strlen(s);
1502      mnode->build_instr_pred(s,(char*)i._key,0);
1503      s += strlen(s);
1504      strcpy(s," == "); s += strlen(s);
1505      mnode->build_instr_pred(s,(char*)i._key,1);
1506      s += strlen(s);
1507      strcpy(s,")"); s += strlen(s);
1508    }
1509  }
1510  if( s == buf ) s = NULL;
1511  else {
1512    assert( strlen(buf) < sizeof(buf), "String buffer overflow" );
1513    s = strdup(buf);
1514  }
1515  return new Predicate(s);
1516}
1517
1518//------------------------------EncodeForm-------------------------------------
1519// Constructor
1520EncodeForm::EncodeForm()
1521  : _encClass(cmpstr,hashstr, Form::arena) {
1522}
1523EncodeForm::~EncodeForm() {
1524}
1525
1526// record a new register class
1527EncClass *EncodeForm::add_EncClass(const char *className) {
1528  EncClass *encClass = new EncClass(className);
1529  _eclasses.addName(className);
1530  _encClass.Insert(className,encClass);
1531  return encClass;
1532}
1533
1534// Lookup the function body for an encoding class
1535EncClass  *EncodeForm::encClass(const char *className) {
1536  assert( className != NULL, "Must provide a defined encoding name");
1537
1538  EncClass *encClass = (EncClass*)_encClass[className];
1539  return encClass;
1540}
1541
1542// Lookup the function body for an encoding class
1543const char *EncodeForm::encClassBody(const char *className) {
1544  if( className == NULL ) return NULL;
1545
1546  EncClass *encClass = (EncClass*)_encClass[className];
1547  assert( encClass != NULL, "Encode Class is missing.");
1548  encClass->_code.reset();
1549  const char *code = (const char*)encClass->_code.iter();
1550  assert( code != NULL, "Found an empty encode class body.");
1551
1552  return code;
1553}
1554
1555// Lookup the function body for an encoding class
1556const char *EncodeForm::encClassPrototype(const char *className) {
1557  assert( className != NULL, "Encode class name must be non NULL.");
1558
1559  return className;
1560}
1561
1562void EncodeForm::dump() {                  // Debug printer
1563  output(stderr);
1564}
1565
1566void EncodeForm::output(FILE *fp) {          // Write info to output files
1567  const char *name;
1568  fprintf(fp,"\n");
1569  fprintf(fp,"-------------------- Dump EncodeForm --------------------\n");
1570  for (_eclasses.reset(); (name = _eclasses.iter()) != NULL;) {
1571    ((EncClass*)_encClass[name])->output(fp);
1572  }
1573  fprintf(fp,"-------------------- end  EncodeForm --------------------\n");
1574}
1575//------------------------------EncClass---------------------------------------
1576EncClass::EncClass(const char *name)
1577  : _localNames(cmpstr,hashstr, Form::arena), _name(name) {
1578}
1579EncClass::~EncClass() {
1580}
1581
1582// Add a parameter <type,name> pair
1583void EncClass::add_parameter(const char *parameter_type, const char *parameter_name) {
1584  _parameter_type.addName( parameter_type );
1585  _parameter_name.addName( parameter_name );
1586}
1587
1588// Verify operand types in parameter list
1589bool EncClass::check_parameter_types(FormDict &globals) {
1590  // !!!!!
1591  return false;
1592}
1593
1594// Add the decomposed "code" sections of an encoding's code-block
1595void EncClass::add_code(const char *code) {
1596  _code.addName(code);
1597}
1598
1599// Add the decomposed "replacement variables" of an encoding's code-block
1600void EncClass::add_rep_var(char *replacement_var) {
1601  _code.addName(NameList::_signal);
1602  _rep_vars.addName(replacement_var);
1603}
1604
1605// Lookup the function body for an encoding class
1606int EncClass::rep_var_index(const char *rep_var) {
1607  uint        position = 0;
1608  const char *name     = NULL;
1609
1610  _parameter_name.reset();
1611  while ( (name = _parameter_name.iter()) != NULL ) {
1612    if ( strcmp(rep_var,name) == 0 ) return position;
1613    ++position;
1614  }
1615
1616  return -1;
1617}
1618
1619// Check after parsing
1620bool EncClass::verify() {
1621  // 1!!!!
1622  // Check that each replacement variable, '$name' in architecture description
1623  // is actually a local variable for this encode class, or a reserved name
1624  // "primary, secondary, tertiary"
1625  return true;
1626}
1627
1628void EncClass::dump() {
1629  output(stderr);
1630}
1631
1632// Write info to output files
1633void EncClass::output(FILE *fp) {
1634  fprintf(fp,"EncClass: %s", (_name ? _name : ""));
1635
1636  // Output the parameter list
1637  _parameter_type.reset();
1638  _parameter_name.reset();
1639  const char *type = _parameter_type.iter();
1640  const char *name = _parameter_name.iter();
1641  fprintf(fp, " ( ");
1642  for ( ; (type != NULL) && (name != NULL);
1643        (type = _parameter_type.iter()), (name = _parameter_name.iter()) ) {
1644    fprintf(fp, " %s %s,", type, name);
1645  }
1646  fprintf(fp, " ) ");
1647
1648  // Output the code block
1649  _code.reset();
1650  _rep_vars.reset();
1651  const char *code;
1652  while ( (code = _code.iter()) != NULL ) {
1653    if ( _code.is_signal(code) ) {
1654      // A replacement variable
1655      const char *rep_var = _rep_vars.iter();
1656      fprintf(fp,"($%s)", rep_var);
1657    } else {
1658      // A section of code
1659      fprintf(fp,"%s", code);
1660    }
1661  }
1662
1663}
1664
1665//------------------------------Opcode-----------------------------------------
1666Opcode::Opcode(char *primary, char *secondary, char *tertiary)
1667  : _primary(primary), _secondary(secondary), _tertiary(tertiary) {
1668}
1669
1670Opcode::~Opcode() {
1671}
1672
1673Opcode::opcode_type Opcode::as_opcode_type(const char *param) {
1674  if( strcmp(param,"primary") == 0 ) {
1675    return Opcode::PRIMARY;
1676  }
1677  else if( strcmp(param,"secondary") == 0 ) {
1678    return Opcode::SECONDARY;
1679  }
1680  else if( strcmp(param,"tertiary") == 0 ) {
1681    return Opcode::TERTIARY;
1682  }
1683  return Opcode::NOT_AN_OPCODE;
1684}
1685
1686bool Opcode::print_opcode(FILE *fp, Opcode::opcode_type desired_opcode) {
1687  // Default values previously provided by MachNode::primary()...
1688  const char *description = NULL;
1689  const char *value       = NULL;
1690  // Check if user provided any opcode definitions
1691  if( this != NULL ) {
1692    // Update 'value' if user provided a definition in the instruction
1693    switch (desired_opcode) {
1694    case PRIMARY:
1695      description = "primary()";
1696      if( _primary   != NULL)  { value = _primary;     }
1697      break;
1698    case SECONDARY:
1699      description = "secondary()";
1700      if( _secondary != NULL ) { value = _secondary;   }
1701      break;
1702    case TERTIARY:
1703      description = "tertiary()";
1704      if( _tertiary  != NULL ) { value = _tertiary;    }
1705      break;
1706    default:
1707      assert( false, "ShouldNotReachHere();");
1708      break;
1709    }
1710  }
1711  if (value != NULL) {
1712    fprintf(fp, "(%s /*%s*/)", value, description);
1713  }
1714  return value != NULL;
1715}
1716
1717void Opcode::dump() {
1718  output(stderr);
1719}
1720
1721// Write info to output files
1722void Opcode::output(FILE *fp) {
1723  if (_primary   != NULL) fprintf(fp,"Primary   opcode: %s\n", _primary);
1724  if (_secondary != NULL) fprintf(fp,"Secondary opcode: %s\n", _secondary);
1725  if (_tertiary  != NULL) fprintf(fp,"Tertiary  opcode: %s\n", _tertiary);
1726}
1727
1728//------------------------------InsEncode--------------------------------------
1729InsEncode::InsEncode() {
1730}
1731InsEncode::~InsEncode() {
1732}
1733
1734// Add "encode class name" and its parameters
1735NameAndList *InsEncode::add_encode(char *encoding) {
1736  assert( encoding != NULL, "Must provide name for encoding");
1737
1738  // add_parameter(NameList::_signal);
1739  NameAndList *encode = new NameAndList(encoding);
1740  _encoding.addName((char*)encode);
1741
1742  return encode;
1743}
1744
1745// Access the list of encodings
1746void InsEncode::reset() {
1747  _encoding.reset();
1748  // _parameter.reset();
1749}
1750const char* InsEncode::encode_class_iter() {
1751  NameAndList  *encode_class = (NameAndList*)_encoding.iter();
1752  return  ( encode_class != NULL ? encode_class->name() : NULL );
1753}
1754// Obtain parameter name from zero based index
1755const char *InsEncode::rep_var_name(InstructForm &inst, uint param_no) {
1756  NameAndList *params = (NameAndList*)_encoding.current();
1757  assert( params != NULL, "Internal Error");
1758  const char *param = (*params)[param_no];
1759
1760  // Remove '$' if parser placed it there.
1761  return ( param != NULL && *param == '$') ? (param+1) : param;
1762}
1763
1764void InsEncode::dump() {
1765  output(stderr);
1766}
1767
1768// Write info to output files
1769void InsEncode::output(FILE *fp) {
1770  NameAndList *encoding  = NULL;
1771  const char  *parameter = NULL;
1772
1773  fprintf(fp,"InsEncode: ");
1774  _encoding.reset();
1775
1776  while ( (encoding = (NameAndList*)_encoding.iter()) != 0 ) {
1777    // Output the encoding being used
1778    fprintf(fp,"%s(", encoding->name() );
1779
1780    // Output its parameter list, if any
1781    bool first_param = true;
1782    encoding->reset();
1783    while (  (parameter = encoding->iter()) != 0 ) {
1784      // Output the ',' between parameters
1785      if ( ! first_param )  fprintf(fp,", ");
1786      first_param = false;
1787      // Output the parameter
1788      fprintf(fp,"%s", parameter);
1789    } // done with parameters
1790    fprintf(fp,")  ");
1791  } // done with encodings
1792
1793  fprintf(fp,"\n");
1794}
1795
1796//------------------------------Effect-----------------------------------------
1797static int effect_lookup(const char *name) {
1798  if(!strcmp(name, "USE")) return Component::USE;
1799  if(!strcmp(name, "DEF")) return Component::DEF;
1800  if(!strcmp(name, "USE_DEF")) return Component::USE_DEF;
1801  if(!strcmp(name, "KILL")) return Component::KILL;
1802  if(!strcmp(name, "USE_KILL")) return Component::USE_KILL;
1803  if(!strcmp(name, "TEMP")) return Component::TEMP;
1804  if(!strcmp(name, "INVALID")) return Component::INVALID;
1805  if(!strcmp(name, "CALL")) return Component::CALL;
1806  assert( false,"Invalid effect name specified\n");
1807  return Component::INVALID;
1808}
1809
1810const char *Component::getUsedefName() {
1811  switch (_usedef) {
1812    case Component::INVALID:  return "INVALID";  break;
1813    case Component::USE:      return "USE";      break;
1814    case Component::USE_DEF:  return "USE_DEF";  break;
1815    case Component::USE_KILL: return "USE_KILL"; break;
1816    case Component::KILL:     return "KILL";     break;
1817    case Component::TEMP:     return "TEMP";     break;
1818    case Component::DEF:      return "DEF";      break;
1819    case Component::CALL:     return "CALL";     break;
1820    default: assert(false, "unknown effect");
1821  }
1822  return "Undefined Use/Def info";
1823}
1824
1825Effect::Effect(const char *name) : _name(name), _use_def(effect_lookup(name)) {
1826  _ftype = Form::EFF;
1827}
1828
1829Effect::~Effect() {
1830}
1831
1832// Dynamic type check
1833Effect *Effect::is_effect() const {
1834  return (Effect*)this;
1835}
1836
1837
1838// True if this component is equal to the parameter.
1839bool Effect::is(int use_def_kill_enum) const {
1840  return (_use_def == use_def_kill_enum ? true : false);
1841}
1842// True if this component is used/def'd/kill'd as the parameter suggests.
1843bool Effect::isa(int use_def_kill_enum) const {
1844  return (_use_def & use_def_kill_enum) == use_def_kill_enum;
1845}
1846
1847void Effect::dump() {
1848  output(stderr);
1849}
1850
1851void Effect::output(FILE *fp) {          // Write info to output files
1852  fprintf(fp,"Effect: %s\n", (_name?_name:""));
1853}
1854
1855//------------------------------ExpandRule-------------------------------------
1856ExpandRule::ExpandRule() : _expand_instrs(),
1857                           _newopconst(cmpstr, hashstr, Form::arena) {
1858  _ftype = Form::EXP;
1859}
1860
1861ExpandRule::~ExpandRule() {                  // Destructor
1862}
1863
1864void ExpandRule::add_instruction(NameAndList *instruction_name_and_operand_list) {
1865  _expand_instrs.addName((char*)instruction_name_and_operand_list);
1866}
1867
1868void ExpandRule::reset_instructions() {
1869  _expand_instrs.reset();
1870}
1871
1872NameAndList* ExpandRule::iter_instructions() {
1873  return (NameAndList*)_expand_instrs.iter();
1874}
1875
1876
1877void ExpandRule::dump() {
1878  output(stderr);
1879}
1880
1881void ExpandRule::output(FILE *fp) {         // Write info to output files
1882  NameAndList *expand_instr = NULL;
1883  const char *opid = NULL;
1884
1885  fprintf(fp,"\nExpand Rule:\n");
1886
1887  // Iterate over the instructions 'node' expands into
1888  for(reset_instructions(); (expand_instr = iter_instructions()) != NULL; ) {
1889    fprintf(fp,"%s(", expand_instr->name());
1890
1891    // iterate over the operand list
1892    for( expand_instr->reset(); (opid = expand_instr->iter()) != NULL; ) {
1893      fprintf(fp,"%s ", opid);
1894    }
1895    fprintf(fp,");\n");
1896  }
1897}
1898
1899//------------------------------RewriteRule------------------------------------
1900RewriteRule::RewriteRule(char* params, char* block)
1901  : _tempParams(params), _tempBlock(block) { };  // Constructor
1902RewriteRule::~RewriteRule() {                 // Destructor
1903}
1904
1905void RewriteRule::dump() {
1906  output(stderr);
1907}
1908
1909void RewriteRule::output(FILE *fp) {         // Write info to output files
1910  fprintf(fp,"\nRewrite Rule:\n%s\n%s\n",
1911          (_tempParams?_tempParams:""),
1912          (_tempBlock?_tempBlock:""));
1913}
1914
1915
1916//==============================MachNodes======================================
1917//------------------------------MachNodeForm-----------------------------------
1918MachNodeForm::MachNodeForm(char *id)
1919  : _ident(id) {
1920}
1921
1922MachNodeForm::~MachNodeForm() {
1923}
1924
1925MachNodeForm *MachNodeForm::is_machnode() const {
1926  return (MachNodeForm*)this;
1927}
1928
1929//==============================Operand Classes================================
1930//------------------------------OpClassForm------------------------------------
1931OpClassForm::OpClassForm(const char* id) : _ident(id) {
1932  _ftype = Form::OPCLASS;
1933}
1934
1935OpClassForm::~OpClassForm() {
1936}
1937
1938bool OpClassForm::ideal_only() const { return 0; }
1939
1940OpClassForm *OpClassForm::is_opclass() const {
1941  return (OpClassForm*)this;
1942}
1943
1944Form::InterfaceType OpClassForm::interface_type(FormDict &globals) const {
1945  if( _oplst.count() == 0 ) return Form::no_interface;
1946
1947  // Check that my operands have the same interface type
1948  Form::InterfaceType  interface;
1949  bool  first = true;
1950  NameList &op_list = (NameList &)_oplst;
1951  op_list.reset();
1952  const char *op_name;
1953  while( (op_name = op_list.iter()) != NULL ) {
1954    const Form  *form    = globals[op_name];
1955    OperandForm *operand = form->is_operand();
1956    assert( operand, "Entry in operand class that is not an operand");
1957    if( first ) {
1958      first     = false;
1959      interface = operand->interface_type(globals);
1960    } else {
1961      interface = (interface == operand->interface_type(globals) ? interface : Form::no_interface);
1962    }
1963  }
1964  return interface;
1965}
1966
1967bool OpClassForm::stack_slots_only(FormDict &globals) const {
1968  if( _oplst.count() == 0 ) return false;  // how?
1969
1970  NameList &op_list = (NameList &)_oplst;
1971  op_list.reset();
1972  const char *op_name;
1973  while( (op_name = op_list.iter()) != NULL ) {
1974    const Form  *form    = globals[op_name];
1975    OperandForm *operand = form->is_operand();
1976    assert( operand, "Entry in operand class that is not an operand");
1977    if( !operand->stack_slots_only(globals) )  return false;
1978  }
1979  return true;
1980}
1981
1982
1983void OpClassForm::dump() {
1984  output(stderr);
1985}
1986
1987void OpClassForm::output(FILE *fp) {
1988  const char *name;
1989  fprintf(fp,"\nOperand Class: %s\n", (_ident?_ident:""));
1990  fprintf(fp,"\nCount = %d\n", _oplst.count());
1991  for(_oplst.reset(); (name = _oplst.iter()) != NULL;) {
1992    fprintf(fp,"%s, ",name);
1993  }
1994  fprintf(fp,"\n");
1995}
1996
1997
1998//==============================Operands=======================================
1999//------------------------------OperandForm------------------------------------
2000OperandForm::OperandForm(const char* id)
2001  : OpClassForm(id), _ideal_only(false),
2002    _localNames(cmpstr, hashstr, Form::arena) {
2003      _ftype = Form::OPER;
2004
2005      _matrule   = NULL;
2006      _interface = NULL;
2007      _attribs   = NULL;
2008      _predicate = NULL;
2009      _constraint= NULL;
2010      _construct = NULL;
2011      _format    = NULL;
2012}
2013OperandForm::OperandForm(const char* id, bool ideal_only)
2014  : OpClassForm(id), _ideal_only(ideal_only),
2015    _localNames(cmpstr, hashstr, Form::arena) {
2016      _ftype = Form::OPER;
2017
2018      _matrule   = NULL;
2019      _interface = NULL;
2020      _attribs   = NULL;
2021      _predicate = NULL;
2022      _constraint= NULL;
2023      _construct = NULL;
2024      _format    = NULL;
2025}
2026OperandForm::~OperandForm() {
2027}
2028
2029
2030OperandForm *OperandForm::is_operand() const {
2031  return (OperandForm*)this;
2032}
2033
2034bool OperandForm::ideal_only() const {
2035  return _ideal_only;
2036}
2037
2038Form::InterfaceType OperandForm::interface_type(FormDict &globals) const {
2039  if( _interface == NULL )  return Form::no_interface;
2040
2041  return _interface->interface_type(globals);
2042}
2043
2044
2045bool OperandForm::stack_slots_only(FormDict &globals) const {
2046  if( _constraint == NULL )  return false;
2047  return _constraint->stack_slots_only();
2048}
2049
2050
2051// Access op_cost attribute or return NULL.
2052const char* OperandForm::cost() {
2053  for (Attribute* cur = _attribs; cur != NULL; cur = (Attribute*)cur->_next) {
2054    if( strcmp(cur->_ident,AttributeForm::_op_cost) == 0 ) {
2055      return cur->_val;
2056    }
2057  }
2058  return NULL;
2059}
2060
2061// Return the number of leaves below this complex operand
2062uint OperandForm::num_leaves() const {
2063  if ( ! _matrule) return 0;
2064
2065  int num_leaves = _matrule->_numleaves;
2066  return num_leaves;
2067}
2068
2069// Return the number of constants contained within this complex operand
2070uint OperandForm::num_consts(FormDict &globals) const {
2071  if ( ! _matrule) return 0;
2072
2073  // This is a recursive invocation on all operands in the matchrule
2074  return _matrule->num_consts(globals);
2075}
2076
2077// Return the number of constants in match rule with specified type
2078uint OperandForm::num_consts(FormDict &globals, Form::DataType type) const {
2079  if ( ! _matrule) return 0;
2080
2081  // This is a recursive invocation on all operands in the matchrule
2082  return _matrule->num_consts(globals, type);
2083}
2084
2085// Return the number of pointer constants contained within this complex operand
2086uint OperandForm::num_const_ptrs(FormDict &globals) const {
2087  if ( ! _matrule) return 0;
2088
2089  // This is a recursive invocation on all operands in the matchrule
2090  return _matrule->num_const_ptrs(globals);
2091}
2092
2093uint OperandForm::num_edges(FormDict &globals) const {
2094  uint edges  = 0;
2095  uint leaves = num_leaves();
2096  uint consts = num_consts(globals);
2097
2098  // If we are matching a constant directly, there are no leaves.
2099  edges = ( leaves > consts ) ? leaves - consts : 0;
2100
2101  // !!!!!
2102  // Special case operands that do not have a corresponding ideal node.
2103  if( (edges == 0) && (consts == 0) ) {
2104    if( constrained_reg_class() != NULL ) {
2105      edges = 1;
2106    } else {
2107      if( _matrule
2108          && (_matrule->_lChild == NULL) && (_matrule->_rChild == NULL) ) {
2109        const Form *form = globals[_matrule->_opType];
2110        OperandForm *oper = form ? form->is_operand() : NULL;
2111        if( oper ) {
2112          return oper->num_edges(globals);
2113        }
2114      }
2115    }
2116  }
2117
2118  return edges;
2119}
2120
2121
2122// Check if this operand is usable for cisc-spilling
2123bool  OperandForm::is_cisc_reg(FormDict &globals) const {
2124  const char *ideal = ideal_type(globals);
2125  bool is_cisc_reg = (ideal && (ideal_to_Reg_type(ideal) != none));
2126  return is_cisc_reg;
2127}
2128
2129bool  OpClassForm::is_cisc_mem(FormDict &globals) const {
2130  Form::InterfaceType my_interface = interface_type(globals);
2131  return (my_interface == memory_interface);
2132}
2133
2134
2135// node matches ideal 'Bool'
2136bool OperandForm::is_ideal_bool() const {
2137  if( _matrule == NULL ) return false;
2138
2139  return _matrule->is_ideal_bool();
2140}
2141
2142// Require user's name for an sRegX to be stackSlotX
2143Form::DataType OperandForm::is_user_name_for_sReg() const {
2144  DataType data_type = none;
2145  if( _ident != NULL ) {
2146    if(      strcmp(_ident,"stackSlotI") == 0 ) data_type = Form::idealI;
2147    else if( strcmp(_ident,"stackSlotP") == 0 ) data_type = Form::idealP;
2148    else if( strcmp(_ident,"stackSlotD") == 0 ) data_type = Form::idealD;
2149    else if( strcmp(_ident,"stackSlotF") == 0 ) data_type = Form::idealF;
2150    else if( strcmp(_ident,"stackSlotL") == 0 ) data_type = Form::idealL;
2151  }
2152  assert((data_type == none) || (_matrule == NULL), "No match-rule for stackSlotX");
2153
2154  return data_type;
2155}
2156
2157
2158// Return ideal type, if there is a single ideal type for this operand
2159const char *OperandForm::ideal_type(FormDict &globals, RegisterForm *registers) const {
2160  const char *type = NULL;
2161  if (ideal_only()) type = _ident;
2162  else if( _matrule == NULL ) {
2163    // Check for condition code register
2164    const char *rc_name = constrained_reg_class();
2165    // !!!!!
2166    if (rc_name == NULL) return NULL;
2167    // !!!!! !!!!!
2168    // Check constraints on result's register class
2169    if( registers ) {
2170      RegClass *reg_class  = registers->getRegClass(rc_name);
2171      assert( reg_class != NULL, "Register class is not defined");
2172
2173      // Check for ideal type of entries in register class, all are the same type
2174      reg_class->reset();
2175      RegDef *reg_def = reg_class->RegDef_iter();
2176      assert( reg_def != NULL, "No entries in register class");
2177      assert( reg_def->_idealtype != NULL, "Did not define ideal type for register");
2178      // Return substring that names the register's ideal type
2179      type = reg_def->_idealtype + 3;
2180      assert( *(reg_def->_idealtype + 0) == 'O', "Expect Op_ prefix");
2181      assert( *(reg_def->_idealtype + 1) == 'p', "Expect Op_ prefix");
2182      assert( *(reg_def->_idealtype + 2) == '_', "Expect Op_ prefix");
2183    }
2184  }
2185  else if( _matrule->_lChild == NULL && _matrule->_rChild == NULL ) {
2186    // This operand matches a single type, at the top level.
2187    // Check for ideal type
2188    type = _matrule->_opType;
2189    if( strcmp(type,"Bool") == 0 )
2190      return "Bool";
2191    // transitive lookup
2192    const Form *frm = globals[type];
2193    OperandForm *op = frm->is_operand();
2194    type = op->ideal_type(globals, registers);
2195  }
2196  return type;
2197}
2198
2199
2200// If there is a single ideal type for this interface field, return it.
2201const char *OperandForm::interface_ideal_type(FormDict &globals,
2202                                              const char *field) const {
2203  const char  *ideal_type = NULL;
2204  const char  *value      = NULL;
2205
2206  // Check if "field" is valid for this operand's interface
2207  if ( ! is_interface_field(field, value) )   return ideal_type;
2208
2209  // !!!!! !!!!! !!!!!
2210  // If a valid field has a constant value, identify "ConI" or "ConP" or ...
2211
2212  // Else, lookup type of field's replacement variable
2213
2214  return ideal_type;
2215}
2216
2217
2218RegClass* OperandForm::get_RegClass() const {
2219  if (_interface && !_interface->is_RegInterface()) return NULL;
2220  return globalAD->get_registers()->getRegClass(constrained_reg_class());
2221}
2222
2223
2224bool OperandForm::is_bound_register() const {
2225  RegClass* reg_class = get_RegClass();
2226  if (reg_class == NULL) {
2227    return false;
2228  }
2229
2230  const char* name = ideal_type(globalAD->globalNames());
2231  if (name == NULL) {
2232    return false;
2233  }
2234
2235  uint size = 0;
2236  if (strcmp(name, "RegFlags") == 0) size = 1;
2237  if (strcmp(name, "RegI") == 0) size = 1;
2238  if (strcmp(name, "RegF") == 0) size = 1;
2239  if (strcmp(name, "RegD") == 0) size = 2;
2240  if (strcmp(name, "RegL") == 0) size = 2;
2241  if (strcmp(name, "RegN") == 0) size = 1;
2242  if (strcmp(name, "RegP") == 0) size = globalAD->get_preproc_def("_LP64") ? 2 : 1;
2243  if (size == 0) {
2244    return false;
2245  }
2246  return size == reg_class->size();
2247}
2248
2249
2250// Check if this is a valid field for this operand,
2251// Return 'true' if valid, and set the value to the string the user provided.
2252bool  OperandForm::is_interface_field(const char *field,
2253                                      const char * &value) const {
2254  return false;
2255}
2256
2257
2258// Return register class name if a constraint specifies the register class.
2259const char *OperandForm::constrained_reg_class() const {
2260  const char *reg_class  = NULL;
2261  if ( _constraint ) {
2262    // !!!!!
2263    Constraint *constraint = _constraint;
2264    if ( strcmp(_constraint->_func,"ALLOC_IN_RC") == 0 ) {
2265      reg_class = _constraint->_arg;
2266    }
2267  }
2268
2269  return reg_class;
2270}
2271
2272
2273// Return the register class associated with 'leaf'.
2274const char *OperandForm::in_reg_class(uint leaf, FormDict &globals) {
2275  const char *reg_class = NULL; // "RegMask::Empty";
2276
2277  if((_matrule == NULL) || (_matrule->is_chain_rule(globals))) {
2278    reg_class = constrained_reg_class();
2279    return reg_class;
2280  }
2281  const char *result   = NULL;
2282  const char *name     = NULL;
2283  const char *type     = NULL;
2284  // iterate through all base operands
2285  // until we reach the register that corresponds to "leaf"
2286  // This function is not looking for an ideal type.  It needs the first
2287  // level user type associated with the leaf.
2288  for(uint idx = 0;_matrule->base_operand(idx,globals,result,name,type);++idx) {
2289    const Form *form = (_localNames[name] ? _localNames[name] : globals[result]);
2290    OperandForm *oper = form ? form->is_operand() : NULL;
2291    if( oper ) {
2292      reg_class = oper->constrained_reg_class();
2293      if( reg_class ) {
2294        reg_class = reg_class;
2295      } else {
2296        // ShouldNotReachHere();
2297      }
2298    } else {
2299      // ShouldNotReachHere();
2300    }
2301
2302    // Increment our target leaf position if current leaf is not a candidate.
2303    if( reg_class == NULL)    ++leaf;
2304    // Exit the loop with the value of reg_class when at the correct index
2305    if( idx == leaf )         break;
2306    // May iterate through all base operands if reg_class for 'leaf' is NULL
2307  }
2308  return reg_class;
2309}
2310
2311
2312// Recursive call to construct list of top-level operands.
2313// Implementation does not modify state of internal structures
2314void OperandForm::build_components() {
2315  if (_matrule)  _matrule->append_components(_localNames, _components);
2316
2317  // Add parameters that "do not appear in match rule".
2318  const char *name;
2319  for (_parameters.reset(); (name = _parameters.iter()) != NULL;) {
2320    OperandForm *opForm = (OperandForm*)_localNames[name];
2321
2322    if ( _components.operand_position(name) == -1 ) {
2323      _components.insert(name, opForm->_ident, Component::INVALID, false);
2324    }
2325  }
2326
2327  return;
2328}
2329
2330int OperandForm::operand_position(const char *name, int usedef) {
2331  return _components.operand_position(name, usedef, this);
2332}
2333
2334
2335// Return zero-based position in component list, only counting constants;
2336// Return -1 if not in list.
2337int OperandForm::constant_position(FormDict &globals, const Component *last) {
2338  // Iterate through components and count constants preceding 'constant'
2339  int position = 0;
2340  Component *comp;
2341  _components.reset();
2342  while( (comp = _components.iter()) != NULL  && (comp != last) ) {
2343    // Special case for operands that take a single user-defined operand
2344    // Skip the initial definition in the component list.
2345    if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2346
2347    const char *type = comp->_type;
2348    // Lookup operand form for replacement variable's type
2349    const Form *form = globals[type];
2350    assert( form != NULL, "Component's type not found");
2351    OperandForm *oper = form ? form->is_operand() : NULL;
2352    if( oper ) {
2353      if( oper->_matrule->is_base_constant(globals) != Form::none ) {
2354        ++position;
2355      }
2356    }
2357  }
2358
2359  // Check for being passed a component that was not in the list
2360  if( comp != last )  position = -1;
2361
2362  return position;
2363}
2364// Provide position of constant by "name"
2365int OperandForm::constant_position(FormDict &globals, const char *name) {
2366  const Component *comp = _components.search(name);
2367  int idx = constant_position( globals, comp );
2368
2369  return idx;
2370}
2371
2372
2373// Return zero-based position in component list, only counting constants;
2374// Return -1 if not in list.
2375int OperandForm::register_position(FormDict &globals, const char *reg_name) {
2376  // Iterate through components and count registers preceding 'last'
2377  uint  position = 0;
2378  Component *comp;
2379  _components.reset();
2380  while( (comp = _components.iter()) != NULL
2381         && (strcmp(comp->_name,reg_name) != 0) ) {
2382    // Special case for operands that take a single user-defined operand
2383    // Skip the initial definition in the component list.
2384    if( strcmp(comp->_name,this->_ident) == 0 ) continue;
2385
2386    const char *type = comp->_type;
2387    // Lookup operand form for component's type
2388    const Form *form = globals[type];
2389    assert( form != NULL, "Component's type not found");
2390    OperandForm *oper = form ? form->is_operand() : NULL;
2391    if( oper ) {
2392      if( oper->_matrule->is_base_register(globals) ) {
2393        ++position;
2394      }
2395    }
2396  }
2397
2398  return position;
2399}
2400
2401
2402const char *OperandForm::reduce_result()  const {
2403  return _ident;
2404}
2405// Return the name of the operand on the right hand side of the binary match
2406// Return NULL if there is no right hand side
2407const char *OperandForm::reduce_right(FormDict &globals)  const {
2408  return  ( _matrule ? _matrule->reduce_right(globals) : NULL );
2409}
2410
2411// Similar for left
2412const char *OperandForm::reduce_left(FormDict &globals)   const {
2413  return  ( _matrule ? _matrule->reduce_left(globals) : NULL );
2414}
2415
2416
2417// --------------------------- FILE *output_routines
2418//
2419// Output code for disp_is_oop, if true.
2420void OperandForm::disp_is_oop(FILE *fp, FormDict &globals) {
2421  //  Check it is a memory interface with a non-user-constant disp field
2422  if ( this->_interface == NULL ) return;
2423  MemInterface *mem_interface = this->_interface->is_MemInterface();
2424  if ( mem_interface == NULL )    return;
2425  const char   *disp  = mem_interface->_disp;
2426  if ( *disp != '$' )             return;
2427
2428  // Lookup replacement variable in operand's component list
2429  const char   *rep_var = disp + 1;
2430  const Component *comp = this->_components.search(rep_var);
2431  assert( comp != NULL, "Replacement variable not found in components");
2432  // Lookup operand form for replacement variable's type
2433  const char      *type = comp->_type;
2434  Form            *form = (Form*)globals[type];
2435  assert( form != NULL, "Replacement variable's type not found");
2436  OperandForm     *op   = form->is_operand();
2437  assert( op, "Memory Interface 'disp' can only emit an operand form");
2438  // Check if this is a ConP, which may require relocation
2439  if ( op->is_base_constant(globals) == Form::idealP ) {
2440    // Find the constant's index:  _c0, _c1, _c2, ... , _cN
2441    uint idx  = op->constant_position( globals, rep_var);
2442    fprintf(fp,"  virtual relocInfo::relocType disp_reloc() const {");
2443    fprintf(fp,  "  return _c%d->reloc();", idx);
2444    fprintf(fp, " }\n");
2445  }
2446}
2447
2448// Generate code for internal and external format methods
2449//
2450// internal access to reg# node->_idx
2451// access to subsumed constant _c0, _c1,
2452void  OperandForm::int_format(FILE *fp, FormDict &globals, uint index) {
2453  Form::DataType dtype;
2454  if (_matrule && (_matrule->is_base_register(globals) ||
2455                   strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2456    // !!!!! !!!!!
2457    fprintf(fp,"  { char reg_str[128];\n");
2458    fprintf(fp,"    ra->dump_register(node,reg_str);\n");
2459    fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2460    fprintf(fp,"  }\n");
2461  } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2462    format_constant( fp, index, dtype );
2463  } else if (ideal_to_sReg_type(_ident) != Form::none) {
2464    // Special format for Stack Slot Register
2465    fprintf(fp,"  { char reg_str[128];\n");
2466    fprintf(fp,"    ra->dump_register(node,reg_str);\n");
2467    fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2468    fprintf(fp,"  }\n");
2469  } else {
2470    fprintf(fp,"  st->print(\"No format defined for %s\n\");\n", _ident);
2471    fflush(fp);
2472    fprintf(stderr,"No format defined for %s\n", _ident);
2473    dump();
2474    assert( false,"Internal error:\n  output_internal_operand() attempting to output other than a Register or Constant");
2475  }
2476}
2477
2478// Similar to "int_format" but for cases where data is external to operand
2479// external access to reg# node->in(idx)->_idx,
2480void  OperandForm::ext_format(FILE *fp, FormDict &globals, uint index) {
2481  Form::DataType dtype;
2482  if (_matrule && (_matrule->is_base_register(globals) ||
2483                   strcmp(ideal_type(globalAD->globalNames()), "RegFlags") == 0)) {
2484    fprintf(fp,"  { char reg_str[128];\n");
2485    fprintf(fp,"    ra->dump_register(node->in(idx");
2486    if ( index != 0 ) fprintf(fp,              "+%d",index);
2487    fprintf(fp,                                      "),reg_str);\n");
2488    fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2489    fprintf(fp,"  }\n");
2490  } else if (_matrule && (dtype = _matrule->is_base_constant(globals)) != Form::none) {
2491    format_constant( fp, index, dtype );
2492  } else if (ideal_to_sReg_type(_ident) != Form::none) {
2493    // Special format for Stack Slot Register
2494    fprintf(fp,"  { char reg_str[128];\n");
2495    fprintf(fp,"    ra->dump_register(node->in(idx");
2496    if ( index != 0 ) fprintf(fp,                  "+%d",index);
2497    fprintf(fp,                                       "),reg_str);\n");
2498    fprintf(fp,"    st->print(\"%cs\",reg_str);\n",'%');
2499    fprintf(fp,"  }\n");
2500  } else {
2501    fprintf(fp,"  st->print(\"No format defined for %s\n\");\n", _ident);
2502    assert( false,"Internal error:\n  output_external_operand() attempting to output other than a Register or Constant");
2503  }
2504}
2505
2506void OperandForm::format_constant(FILE *fp, uint const_index, uint const_type) {
2507  switch(const_type) {
2508  case Form::idealI: fprintf(fp,"  st->print(\"#%%d\", _c%d);\n", const_index); break;
2509  case Form::idealP: fprintf(fp,"  if (_c%d) _c%d->dump_on(st);\n", const_index, const_index); break;
2510  case Form::idealNKlass:
2511  case Form::idealN: fprintf(fp,"  if (_c%d) _c%d->dump_on(st);\n", const_index, const_index); break;
2512  case Form::idealL: fprintf(fp,"  st->print(\"#%%lld\", _c%d);\n", const_index); break;
2513  case Form::idealF: fprintf(fp,"  st->print(\"#%%f\", _c%d);\n", const_index); break;
2514  case Form::idealD: fprintf(fp,"  st->print(\"#%%f\", _c%d);\n", const_index); break;
2515  default:
2516    assert( false, "ShouldNotReachHere()");
2517  }
2518}
2519
2520// Return the operand form corresponding to the given index, else NULL.
2521OperandForm *OperandForm::constant_operand(FormDict &globals,
2522                                           uint      index) {
2523  // !!!!!
2524  // Check behavior on complex operands
2525  uint n_consts = num_consts(globals);
2526  if( n_consts > 0 ) {
2527    uint i = 0;
2528    const char *type;
2529    Component  *comp;
2530    _components.reset();
2531    if ((comp = _components.iter()) == NULL) {
2532      assert(n_consts == 1, "Bad component list detected.\n");
2533      // Current operand is THE operand
2534      if ( index == 0 ) {
2535        return this;
2536      }
2537    } // end if NULL
2538    else {
2539      // Skip the first component, it can not be a DEF of a constant
2540      do {
2541        type = comp->base_type(globals);
2542        // Check that "type" is a 'ConI', 'ConP', ...
2543        if ( ideal_to_const_type(type) != Form::none ) {
2544          // When at correct component, get corresponding Operand
2545          if ( index == 0 ) {
2546            return globals[comp->_type]->is_operand();
2547          }
2548          // Decrement number of constants to go
2549          --index;
2550        }
2551      } while((comp = _components.iter()) != NULL);
2552    }
2553  }
2554
2555  // Did not find a constant for this index.
2556  return NULL;
2557}
2558
2559// If this operand has a single ideal type, return its type
2560Form::DataType OperandForm::simple_type(FormDict &globals) const {
2561  const char *type_name = ideal_type(globals);
2562  Form::DataType type   = type_name ? ideal_to_const_type( type_name )
2563                                    : Form::none;
2564  return type;
2565}
2566
2567Form::DataType OperandForm::is_base_constant(FormDict &globals) const {
2568  if ( _matrule == NULL )    return Form::none;
2569
2570  return _matrule->is_base_constant(globals);
2571}
2572
2573// "true" if this operand is a simple type that is swallowed
2574bool  OperandForm::swallowed(FormDict &globals) const {
2575  Form::DataType type   = simple_type(globals);
2576  if( type != Form::none ) {
2577    return true;
2578  }
2579
2580  return false;
2581}
2582
2583// Output code to access the value of the index'th constant
2584void OperandForm::access_constant(FILE *fp, FormDict &globals,
2585                                  uint const_index) {
2586  OperandForm *oper = constant_operand(globals, const_index);
2587  assert( oper, "Index exceeds number of constants in operand");
2588  Form::DataType dtype = oper->is_base_constant(globals);
2589
2590  switch(dtype) {
2591  case idealI: fprintf(fp,"_c%d",           const_index); break;
2592  case idealP: fprintf(fp,"_c%d->get_con()",const_index); break;
2593  case idealL: fprintf(fp,"_c%d",           const_index); break;
2594  case idealF: fprintf(fp,"_c%d",           const_index); break;
2595  case idealD: fprintf(fp,"_c%d",           const_index); break;
2596  default:
2597    assert( false, "ShouldNotReachHere()");
2598  }
2599}
2600
2601
2602void OperandForm::dump() {
2603  output(stderr);
2604}
2605
2606void OperandForm::output(FILE *fp) {
2607  fprintf(fp,"\nOperand: %s\n", (_ident?_ident:""));
2608  if (_matrule)    _matrule->dump();
2609  if (_interface)  _interface->dump();
2610  if (_attribs)    _attribs->dump();
2611  if (_predicate)  _predicate->dump();
2612  if (_constraint) _constraint->dump();
2613  if (_construct)  _construct->dump();
2614  if (_format)     _format->dump();
2615}
2616
2617//------------------------------Constraint-------------------------------------
2618Constraint::Constraint(const char *func, const char *arg)
2619  : _func(func), _arg(arg) {
2620}
2621Constraint::~Constraint() { /* not owner of char* */
2622}
2623
2624bool Constraint::stack_slots_only() const {
2625  return strcmp(_func, "ALLOC_IN_RC") == 0
2626      && strcmp(_arg,  "stack_slots") == 0;
2627}
2628
2629void Constraint::dump() {
2630  output(stderr);
2631}
2632
2633void Constraint::output(FILE *fp) {           // Write info to output files
2634  assert((_func != NULL && _arg != NULL),"missing constraint function or arg");
2635  fprintf(fp,"Constraint: %s ( %s )\n", _func, _arg);
2636}
2637
2638//------------------------------Predicate--------------------------------------
2639Predicate::Predicate(char *pr)
2640  : _pred(pr) {
2641}
2642Predicate::~Predicate() {
2643}
2644
2645void Predicate::dump() {
2646  output(stderr);
2647}
2648
2649void Predicate::output(FILE *fp) {
2650  fprintf(fp,"Predicate");  // Write to output files
2651}
2652//------------------------------Interface--------------------------------------
2653Interface::Interface(const char *name) : _name(name) {
2654}
2655Interface::~Interface() {
2656}
2657
2658Form::InterfaceType Interface::interface_type(FormDict &globals) const {
2659  Interface *thsi = (Interface*)this;
2660  if ( thsi->is_RegInterface()   ) return Form::register_interface;
2661  if ( thsi->is_MemInterface()   ) return Form::memory_interface;
2662  if ( thsi->is_ConstInterface() ) return Form::constant_interface;
2663  if ( thsi->is_CondInterface()  ) return Form::conditional_interface;
2664
2665  return Form::no_interface;
2666}
2667
2668RegInterface   *Interface::is_RegInterface() {
2669  if ( strcmp(_name,"REG_INTER") != 0 )
2670    return NULL;
2671  return (RegInterface*)this;
2672}
2673MemInterface   *Interface::is_MemInterface() {
2674  if ( strcmp(_name,"MEMORY_INTER") != 0 )  return NULL;
2675  return (MemInterface*)this;
2676}
2677ConstInterface *Interface::is_ConstInterface() {
2678  if ( strcmp(_name,"CONST_INTER") != 0 )  return NULL;
2679  return (ConstInterface*)this;
2680}
2681CondInterface  *Interface::is_CondInterface() {
2682  if ( strcmp(_name,"COND_INTER") != 0 )  return NULL;
2683  return (CondInterface*)this;
2684}
2685
2686
2687void Interface::dump() {
2688  output(stderr);
2689}
2690
2691// Write info to output files
2692void Interface::output(FILE *fp) {
2693  fprintf(fp,"Interface: %s\n", (_name ? _name : "") );
2694}
2695
2696//------------------------------RegInterface-----------------------------------
2697RegInterface::RegInterface() : Interface("REG_INTER") {
2698}
2699RegInterface::~RegInterface() {
2700}
2701
2702void RegInterface::dump() {
2703  output(stderr);
2704}
2705
2706// Write info to output files
2707void RegInterface::output(FILE *fp) {
2708  Interface::output(fp);
2709}
2710
2711//------------------------------ConstInterface---------------------------------
2712ConstInterface::ConstInterface() : Interface("CONST_INTER") {
2713}
2714ConstInterface::~ConstInterface() {
2715}
2716
2717void ConstInterface::dump() {
2718  output(stderr);
2719}
2720
2721// Write info to output files
2722void ConstInterface::output(FILE *fp) {
2723  Interface::output(fp);
2724}
2725
2726//------------------------------MemInterface-----------------------------------
2727MemInterface::MemInterface(char *base, char *index, char *scale, char *disp)
2728  : Interface("MEMORY_INTER"), _base(base), _index(index), _scale(scale), _disp(disp) {
2729}
2730MemInterface::~MemInterface() {
2731  // not owner of any character arrays
2732}
2733
2734void MemInterface::dump() {
2735  output(stderr);
2736}
2737
2738// Write info to output files
2739void MemInterface::output(FILE *fp) {
2740  Interface::output(fp);
2741  if ( _base  != NULL ) fprintf(fp,"  base  == %s\n", _base);
2742  if ( _index != NULL ) fprintf(fp,"  index == %s\n", _index);
2743  if ( _scale != NULL ) fprintf(fp,"  scale == %s\n", _scale);
2744  if ( _disp  != NULL ) fprintf(fp,"  disp  == %s\n", _disp);
2745  // fprintf(fp,"\n");
2746}
2747
2748//------------------------------CondInterface----------------------------------
2749CondInterface::CondInterface(const char* equal,         const char* equal_format,
2750                             const char* not_equal,     const char* not_equal_format,
2751                             const char* less,          const char* less_format,
2752                             const char* greater_equal, const char* greater_equal_format,
2753                             const char* less_equal,    const char* less_equal_format,
2754                             const char* greater,       const char* greater_format,
2755                             const char* overflow,      const char* overflow_format,
2756                             const char* no_overflow,   const char* no_overflow_format)
2757  : Interface("COND_INTER"),
2758    _equal(equal),                 _equal_format(equal_format),
2759    _not_equal(not_equal),         _not_equal_format(not_equal_format),
2760    _less(less),                   _less_format(less_format),
2761    _greater_equal(greater_equal), _greater_equal_format(greater_equal_format),
2762    _less_equal(less_equal),       _less_equal_format(less_equal_format),
2763    _greater(greater),             _greater_format(greater_format),
2764    _overflow(overflow),           _overflow_format(overflow_format),
2765    _no_overflow(no_overflow),     _no_overflow_format(no_overflow_format) {
2766}
2767CondInterface::~CondInterface() {
2768  // not owner of any character arrays
2769}
2770
2771void CondInterface::dump() {
2772  output(stderr);
2773}
2774
2775// Write info to output files
2776void CondInterface::output(FILE *fp) {
2777  Interface::output(fp);
2778  if ( _equal  != NULL )     fprintf(fp," equal        == %s\n", _equal);
2779  if ( _not_equal  != NULL ) fprintf(fp," not_equal    == %s\n", _not_equal);
2780  if ( _less  != NULL )      fprintf(fp," less         == %s\n", _less);
2781  if ( _greater_equal  != NULL ) fprintf(fp," greater_equal    == %s\n", _greater_equal);
2782  if ( _less_equal  != NULL ) fprintf(fp," less_equal   == %s\n", _less_equal);
2783  if ( _greater  != NULL )    fprintf(fp," greater      == %s\n", _greater);
2784  if ( _overflow != NULL )    fprintf(fp," overflow     == %s\n", _overflow);
2785  if ( _no_overflow != NULL ) fprintf(fp," no_overflow  == %s\n", _no_overflow);
2786  // fprintf(fp,"\n");
2787}
2788
2789//------------------------------ConstructRule----------------------------------
2790ConstructRule::ConstructRule(char *cnstr)
2791  : _construct(cnstr) {
2792}
2793ConstructRule::~ConstructRule() {
2794}
2795
2796void ConstructRule::dump() {
2797  output(stderr);
2798}
2799
2800void ConstructRule::output(FILE *fp) {
2801  fprintf(fp,"\nConstruct Rule\n");  // Write to output files
2802}
2803
2804
2805//==============================Shared Forms===================================
2806//------------------------------AttributeForm----------------------------------
2807int         AttributeForm::_insId   = 0;           // start counter at 0
2808int         AttributeForm::_opId    = 0;           // start counter at 0
2809const char* AttributeForm::_ins_cost = "ins_cost"; // required name
2810const char* AttributeForm::_op_cost  = "op_cost";  // required name
2811
2812AttributeForm::AttributeForm(char *attr, int type, char *attrdef)
2813  : Form(Form::ATTR), _attrname(attr), _atype(type), _attrdef(attrdef) {
2814    if (type==OP_ATTR) {
2815      id = ++_opId;
2816    }
2817    else if (type==INS_ATTR) {
2818      id = ++_insId;
2819    }
2820    else assert( false,"");
2821}
2822AttributeForm::~AttributeForm() {
2823}
2824
2825// Dynamic type check
2826AttributeForm *AttributeForm::is_attribute() const {
2827  return (AttributeForm*)this;
2828}
2829
2830
2831// inlined  // int  AttributeForm::type() { return id;}
2832
2833void AttributeForm::dump() {
2834  output(stderr);
2835}
2836
2837void AttributeForm::output(FILE *fp) {
2838  if( _attrname && _attrdef ) {
2839    fprintf(fp,"\n// AttributeForm \nstatic const int %s = %s;\n",
2840            _attrname, _attrdef);
2841  }
2842  else {
2843    fprintf(fp,"\n// AttributeForm missing name %s or definition %s\n",
2844            (_attrname?_attrname:""), (_attrdef?_attrdef:"") );
2845  }
2846}
2847
2848//------------------------------Component--------------------------------------
2849Component::Component(const char *name, const char *type, int usedef)
2850  : _name(name), _type(type), _usedef(usedef) {
2851    _ftype = Form::COMP;
2852}
2853Component::~Component() {
2854}
2855
2856// True if this component is equal to the parameter.
2857bool Component::is(int use_def_kill_enum) const {
2858  return (_usedef == use_def_kill_enum ? true : false);
2859}
2860// True if this component is used/def'd/kill'd as the parameter suggests.
2861bool Component::isa(int use_def_kill_enum) const {
2862  return (_usedef & use_def_kill_enum) == use_def_kill_enum;
2863}
2864
2865// Extend this component with additional use/def/kill behavior
2866int Component::promote_use_def_info(int new_use_def) {
2867  _usedef |= new_use_def;
2868
2869  return _usedef;
2870}
2871
2872// Check the base type of this component, if it has one
2873const char *Component::base_type(FormDict &globals) {
2874  const Form *frm = globals[_type];
2875  if (frm == NULL) return NULL;
2876  OperandForm *op = frm->is_operand();
2877  if (op == NULL) return NULL;
2878  if (op->ideal_only()) return op->_ident;
2879  return (char *)op->ideal_type(globals);
2880}
2881
2882void Component::dump() {
2883  output(stderr);
2884}
2885
2886void Component::output(FILE *fp) {
2887  fprintf(fp,"Component:");  // Write to output files
2888  fprintf(fp, "  name = %s", _name);
2889  fprintf(fp, ", type = %s", _type);
2890  assert(_usedef != 0, "unknown effect");
2891  fprintf(fp, ", use/def = %s\n", getUsedefName());
2892}
2893
2894
2895//------------------------------ComponentList---------------------------------
2896ComponentList::ComponentList() : NameList(), _matchcnt(0) {
2897}
2898ComponentList::~ComponentList() {
2899  // // This list may not own its elements if copied via assignment
2900  // Component *component;
2901  // for (reset(); (component = iter()) != NULL;) {
2902  //   delete component;
2903  // }
2904}
2905
2906void   ComponentList::insert(Component *component, bool mflag) {
2907  NameList::addName((char *)component);
2908  if(mflag) _matchcnt++;
2909}
2910void   ComponentList::insert(const char *name, const char *opType, int usedef,
2911                             bool mflag) {
2912  Component * component = new Component(name, opType, usedef);
2913  insert(component, mflag);
2914}
2915Component *ComponentList::current() { return (Component*)NameList::current(); }
2916Component *ComponentList::iter()    { return (Component*)NameList::iter(); }
2917Component *ComponentList::match_iter() {
2918  if(_iter < _matchcnt) return (Component*)NameList::iter();
2919  return NULL;
2920}
2921Component *ComponentList::post_match_iter() {
2922  Component *comp = iter();
2923  // At end of list?
2924  if ( comp == NULL ) {
2925    return comp;
2926  }
2927  // In post-match components?
2928  if (_iter > match_count()-1) {
2929    return comp;
2930  }
2931
2932  return post_match_iter();
2933}
2934
2935void       ComponentList::reset()   { NameList::reset(); }
2936int        ComponentList::count()   { return NameList::count(); }
2937
2938Component *ComponentList::operator[](int position) {
2939  // Shortcut complete iteration if there are not enough entries
2940  if (position >= count()) return NULL;
2941
2942  int        index     = 0;
2943  Component *component = NULL;
2944  for (reset(); (component = iter()) != NULL;) {
2945    if (index == position) {
2946      return component;
2947    }
2948    ++index;
2949  }
2950
2951  return NULL;
2952}
2953
2954const Component *ComponentList::search(const char *name) {
2955  PreserveIter pi(this);
2956  reset();
2957  for( Component *comp = NULL; ((comp = iter()) != NULL); ) {
2958    if( strcmp(comp->_name,name) == 0 ) return comp;
2959  }
2960
2961  return NULL;
2962}
2963
2964// Return number of USEs + number of DEFs
2965// When there are no components, or the first component is a USE,
2966// then we add '1' to hold a space for the 'result' operand.
2967int ComponentList::num_operands() {
2968  PreserveIter pi(this);
2969  uint       count = 1;           // result operand
2970  uint       position = 0;
2971
2972  Component *component  = NULL;
2973  for( reset(); (component = iter()) != NULL; ++position ) {
2974    if( component->isa(Component::USE) ||
2975        ( position == 0 && (! component->isa(Component::DEF))) ) {
2976      ++count;
2977    }
2978  }
2979
2980  return count;
2981}
2982
2983// Return zero-based position of operand 'name' in list;  -1 if not in list.
2984// if parameter 'usedef' is ::USE, it will match USE, USE_DEF, ...
2985int ComponentList::operand_position(const char *name, int usedef, Form *fm) {
2986  PreserveIter pi(this);
2987  int position = 0;
2988  int num_opnds = num_operands();
2989  Component *component;
2990  Component* preceding_non_use = NULL;
2991  Component* first_def = NULL;
2992  for (reset(); (component = iter()) != NULL; ++position) {
2993    // When the first component is not a DEF,
2994    // leave space for the result operand!
2995    if ( position==0 && (! component->isa(Component::DEF)) ) {
2996      ++position;
2997      ++num_opnds;
2998    }
2999    if (strcmp(name, component->_name)==0 && (component->isa(usedef))) {
3000      // When the first entry in the component list is a DEF and a USE
3001      // Treat them as being separate, a DEF first, then a USE
3002      if( position==0
3003          && usedef==Component::USE && component->isa(Component::DEF) ) {
3004        assert(position+1 < num_opnds, "advertised index in bounds");
3005        return position+1;
3006      } else {
3007        if( preceding_non_use && strcmp(component->_name, preceding_non_use->_name) ) {
3008          fprintf(stderr, "the name '%s(%s)' should not precede the name '%s(%s)'",
3009                  preceding_non_use->_name, preceding_non_use->getUsedefName(),
3010                  name, component->getUsedefName());
3011          if (fm && fm->is_instruction()) fprintf(stderr,  "in form '%s'", fm->is_instruction()->_ident);
3012          if (fm && fm->is_operand()) fprintf(stderr,  "in form '%s'", fm->is_operand()->_ident);
3013          fprintf(stderr,  "\n");
3014        }
3015        if( position >= num_opnds ) {
3016          fprintf(stderr, "the name '%s' is too late in its name list", name);
3017          if (fm && fm->is_instruction()) fprintf(stderr,  "in form '%s'", fm->is_instruction()->_ident);
3018          if (fm && fm->is_operand()) fprintf(stderr,  "in form '%s'", fm->is_operand()->_ident);
3019          fprintf(stderr,  "\n");
3020        }
3021        assert(position < num_opnds, "advertised index in bounds");
3022        return position;
3023      }
3024    }
3025    if( component->isa(Component::DEF)
3026        && component->isa(Component::USE) ) {
3027      ++position;
3028      if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3029    }
3030    if( component->isa(Component::DEF) && !first_def ) {
3031      first_def = component;
3032    }
3033    if( !component->isa(Component::USE) && component != first_def ) {
3034      preceding_non_use = component;
3035    } else if( preceding_non_use && !strcmp(component->_name, preceding_non_use->_name) ) {
3036      preceding_non_use = NULL;
3037    }
3038  }
3039  return Not_in_list;
3040}
3041
3042// Find position for this name, regardless of use/def information
3043int ComponentList::operand_position(const char *name) {
3044  PreserveIter pi(this);
3045  int position = 0;
3046  Component *component;
3047  for (reset(); (component = iter()) != NULL; ++position) {
3048    // When the first component is not a DEF,
3049    // leave space for the result operand!
3050    if ( position==0 && (! component->isa(Component::DEF)) ) {
3051      ++position;
3052    }
3053    if (strcmp(name, component->_name)==0) {
3054      return position;
3055    }
3056    if( component->isa(Component::DEF)
3057        && component->isa(Component::USE) ) {
3058      ++position;
3059      if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3060    }
3061  }
3062  return Not_in_list;
3063}
3064
3065int ComponentList::operand_position_format(const char *name, Form *fm) {
3066  PreserveIter pi(this);
3067  int  first_position = operand_position(name);
3068  int  use_position   = operand_position(name, Component::USE, fm);
3069
3070  return ((first_position < use_position) ? use_position : first_position);
3071}
3072
3073int ComponentList::label_position() {
3074  PreserveIter pi(this);
3075  int position = 0;
3076  reset();
3077  for( Component *comp; (comp = iter()) != NULL; ++position) {
3078    // When the first component is not a DEF,
3079    // leave space for the result operand!
3080    if ( position==0 && (! comp->isa(Component::DEF)) ) {
3081      ++position;
3082    }
3083    if (strcmp(comp->_type, "label")==0) {
3084      return position;
3085    }
3086    if( comp->isa(Component::DEF)
3087        && comp->isa(Component::USE) ) {
3088      ++position;
3089      if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3090    }
3091  }
3092
3093  return -1;
3094}
3095
3096int ComponentList::method_position() {
3097  PreserveIter pi(this);
3098  int position = 0;
3099  reset();
3100  for( Component *comp; (comp = iter()) != NULL; ++position) {
3101    // When the first component is not a DEF,
3102    // leave space for the result operand!
3103    if ( position==0 && (! comp->isa(Component::DEF)) ) {
3104      ++position;
3105    }
3106    if (strcmp(comp->_type, "method")==0) {
3107      return position;
3108    }
3109    if( comp->isa(Component::DEF)
3110        && comp->isa(Component::USE) ) {
3111      ++position;
3112      if( position != 1 )  --position;   // only use two slots for the 1st USE_DEF
3113    }
3114  }
3115
3116  return -1;
3117}
3118
3119void ComponentList::dump() { output(stderr); }
3120
3121void ComponentList::output(FILE *fp) {
3122  PreserveIter pi(this);
3123  fprintf(fp, "\n");
3124  Component *component;
3125  for (reset(); (component = iter()) != NULL;) {
3126    component->output(fp);
3127  }
3128  fprintf(fp, "\n");
3129}
3130
3131//------------------------------MatchNode--------------------------------------
3132MatchNode::MatchNode(ArchDesc &ad, const char *result, const char *mexpr,
3133                     const char *opType, MatchNode *lChild, MatchNode *rChild)
3134  : _AD(ad), _result(result), _name(mexpr), _opType(opType),
3135    _lChild(lChild), _rChild(rChild), _internalop(0), _numleaves(0),
3136    _commutative_id(0) {
3137  _numleaves = (lChild ? lChild->_numleaves : 0)
3138               + (rChild ? rChild->_numleaves : 0);
3139}
3140
3141MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode)
3142  : _AD(ad), _result(mnode._result), _name(mnode._name),
3143    _opType(mnode._opType), _lChild(mnode._lChild), _rChild(mnode._rChild),
3144    _internalop(0), _numleaves(mnode._numleaves),
3145    _commutative_id(mnode._commutative_id) {
3146}
3147
3148MatchNode::MatchNode(ArchDesc &ad, MatchNode& mnode, int clone)
3149  : _AD(ad), _result(mnode._result), _name(mnode._name),
3150    _opType(mnode._opType),
3151    _internalop(0), _numleaves(mnode._numleaves),
3152    _commutative_id(mnode._commutative_id) {
3153  if (mnode._lChild) {
3154    _lChild = new MatchNode(ad, *mnode._lChild, clone);
3155  } else {
3156    _lChild = NULL;
3157  }
3158  if (mnode._rChild) {
3159    _rChild = new MatchNode(ad, *mnode._rChild, clone);
3160  } else {
3161    _rChild = NULL;
3162  }
3163}
3164
3165MatchNode::~MatchNode() {
3166  // // This node may not own its children if copied via assignment
3167  // if( _lChild ) delete _lChild;
3168  // if( _rChild ) delete _rChild;
3169}
3170
3171bool  MatchNode::find_type(const char *type, int &position) const {
3172  if ( (_lChild != NULL) && (_lChild->find_type(type, position)) ) return true;
3173  if ( (_rChild != NULL) && (_rChild->find_type(type, position)) ) return true;
3174
3175  if (strcmp(type,_opType)==0)  {
3176    return true;
3177  } else {
3178    ++position;
3179  }
3180  return false;
3181}
3182
3183// Recursive call collecting info on top-level operands, not transitive.
3184// Implementation does not modify state of internal structures.
3185void MatchNode::append_components(FormDict& locals, ComponentList& components,
3186                                  bool def_flag) const {
3187  int usedef = def_flag ? Component::DEF : Component::USE;
3188  FormDict &globals = _AD.globalNames();
3189
3190  assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
3191  // Base case
3192  if (_lChild==NULL && _rChild==NULL) {
3193    // If _opType is not an operation, do not build a component for it #####
3194    const Form *f = globals[_opType];
3195    if( f != NULL ) {
3196      // Add non-ideals that are operands, operand-classes,
3197      if( ! f->ideal_only()
3198          && (f->is_opclass() || f->is_operand()) ) {
3199        components.insert(_name, _opType, usedef, true);
3200      }
3201    }
3202    return;
3203  }
3204  // Promote results of "Set" to DEF
3205  bool tmpdef_flag = (!strcmp(_opType, "Set")) ? true : false;
3206  if (_lChild) _lChild->append_components(locals, components, tmpdef_flag);
3207  tmpdef_flag = false;   // only applies to component immediately following 'Set'
3208  if (_rChild) _rChild->append_components(locals, components, tmpdef_flag);
3209}
3210
3211// Find the n'th base-operand in the match node,
3212// recursively investigates match rules of user-defined operands.
3213//
3214// Implementation does not modify state of internal structures since they
3215// can be shared.
3216bool MatchNode::base_operand(uint &position, FormDict &globals,
3217                             const char * &result, const char * &name,
3218                             const char * &opType) const {
3219  assert (_name != NULL, "MatchNode::base_operand encountered empty node\n");
3220  // Base case
3221  if (_lChild==NULL && _rChild==NULL) {
3222    // Check for special case: "Universe", "label"
3223    if (strcmp(_opType,"Universe") == 0 || strcmp(_opType,"label")==0 ) {
3224      if (position == 0) {
3225        result = _result;
3226        name   = _name;
3227        opType = _opType;
3228        return 1;
3229      } else {
3230        -- position;
3231        return 0;
3232      }
3233    }
3234
3235    const Form *form = globals[_opType];
3236    MatchNode *matchNode = NULL;
3237    // Check for user-defined type
3238    if (form) {
3239      // User operand or instruction?
3240      OperandForm  *opForm = form->is_operand();
3241      InstructForm *inForm = form->is_instruction();
3242      if ( opForm ) {
3243        matchNode = (MatchNode*)opForm->_matrule;
3244      } else if ( inForm ) {
3245        matchNode = (MatchNode*)inForm->_matrule;
3246      }
3247    }
3248    // if this is user-defined, recurse on match rule
3249    // User-defined operand and instruction forms have a match-rule.
3250    if (matchNode) {
3251      return (matchNode->base_operand(position,globals,result,name,opType));
3252    } else {
3253      // Either not a form, or a system-defined form (no match rule).
3254      if (position==0) {
3255        result = _result;
3256        name   = _name;
3257        opType = _opType;
3258        return 1;
3259      } else {
3260        --position;
3261        return 0;
3262      }
3263    }
3264
3265  } else {
3266    // Examine the left child and right child as well
3267    if (_lChild) {
3268      if (_lChild->base_operand(position, globals, result, name, opType))
3269        return 1;
3270    }
3271
3272    if (_rChild) {
3273      if (_rChild->base_operand(position, globals, result, name, opType))
3274        return 1;
3275    }
3276  }
3277
3278  return 0;
3279}
3280
3281// Recursive call on all operands' match rules in my match rule.
3282uint  MatchNode::num_consts(FormDict &globals) const {
3283  uint        index      = 0;
3284  uint        num_consts = 0;
3285  const char *result;
3286  const char *name;
3287  const char *opType;
3288
3289  for (uint position = index;
3290       base_operand(position,globals,result,name,opType); position = index) {
3291    ++index;
3292    if( ideal_to_const_type(opType) )        num_consts++;
3293  }
3294
3295  return num_consts;
3296}
3297
3298// Recursive call on all operands' match rules in my match rule.
3299// Constants in match rule subtree with specified type
3300uint  MatchNode::num_consts(FormDict &globals, Form::DataType type) const {
3301  uint        index      = 0;
3302  uint        num_consts = 0;
3303  const char *result;
3304  const char *name;
3305  const char *opType;
3306
3307  for (uint position = index;
3308       base_operand(position,globals,result,name,opType); position = index) {
3309    ++index;
3310    if( ideal_to_const_type(opType) == type ) num_consts++;
3311  }
3312
3313  return num_consts;
3314}
3315
3316// Recursive call on all operands' match rules in my match rule.
3317uint  MatchNode::num_const_ptrs(FormDict &globals) const {
3318  return  num_consts( globals, Form::idealP );
3319}
3320
3321bool  MatchNode::sets_result() const {
3322  return   ( (strcmp(_name,"Set") == 0) ? true : false );
3323}
3324
3325const char *MatchNode::reduce_right(FormDict &globals) const {
3326  // If there is no right reduction, return NULL.
3327  const char      *rightStr    = NULL;
3328
3329  // If we are a "Set", start from the right child.
3330  const MatchNode *const mnode = sets_result() ?
3331    (const MatchNode *)this->_rChild :
3332    (const MatchNode *)this;
3333
3334  // If our right child exists, it is the right reduction
3335  if ( mnode->_rChild ) {
3336    rightStr = mnode->_rChild->_internalop ? mnode->_rChild->_internalop
3337      : mnode->_rChild->_opType;
3338  }
3339  // Else, May be simple chain rule: (Set dst operand_form), rightStr=NULL;
3340  return rightStr;
3341}
3342
3343const char *MatchNode::reduce_left(FormDict &globals) const {
3344  // If there is no left reduction, return NULL.
3345  const char  *leftStr  = NULL;
3346
3347  // If we are a "Set", start from the right child.
3348  const MatchNode *const mnode = sets_result() ?
3349    (const MatchNode *)this->_rChild :
3350    (const MatchNode *)this;
3351
3352  // If our left child exists, it is the left reduction
3353  if ( mnode->_lChild ) {
3354    leftStr = mnode->_lChild->_internalop ? mnode->_lChild->_internalop
3355      : mnode->_lChild->_opType;
3356  } else {
3357    // May be simple chain rule: (Set dst operand_form_source)
3358    if ( sets_result() ) {
3359      OperandForm *oper = globals[mnode->_opType]->is_operand();
3360      if( oper ) {
3361        leftStr = mnode->_opType;
3362      }
3363    }
3364  }
3365  return leftStr;
3366}
3367
3368//------------------------------count_instr_names------------------------------
3369// Count occurrences of operands names in the leaves of the instruction
3370// match rule.
3371void MatchNode::count_instr_names( Dict &names ) {
3372  if( !this ) return;
3373  if( _lChild ) _lChild->count_instr_names(names);
3374  if( _rChild ) _rChild->count_instr_names(names);
3375  if( !_lChild && !_rChild ) {
3376    uintptr_t cnt = (uintptr_t)names[_name];
3377    cnt++;                      // One more name found
3378    names.Insert(_name,(void*)cnt);
3379  }
3380}
3381
3382//------------------------------build_instr_pred-------------------------------
3383// Build a path to 'name' in buf.  Actually only build if cnt is zero, so we
3384// can skip some leading instances of 'name'.
3385int MatchNode::build_instr_pred( char *buf, const char *name, int cnt ) {
3386  if( _lChild ) {
3387    if( !cnt ) strcpy( buf, "_kids[0]->" );
3388    cnt = _lChild->build_instr_pred( buf+strlen(buf), name, cnt );
3389    if( cnt < 0 ) return cnt;   // Found it, all done
3390  }
3391  if( _rChild ) {
3392    if( !cnt ) strcpy( buf, "_kids[1]->" );
3393    cnt = _rChild->build_instr_pred( buf+strlen(buf), name, cnt );
3394    if( cnt < 0 ) return cnt;   // Found it, all done
3395  }
3396  if( !_lChild && !_rChild ) {  // Found a leaf
3397    // Wrong name?  Give up...
3398    if( strcmp(name,_name) ) return cnt;
3399    if( !cnt ) strcpy(buf,"_leaf");
3400    return cnt-1;
3401  }
3402  return cnt;
3403}
3404
3405
3406//------------------------------build_internalop-------------------------------
3407// Build string representation of subtree
3408void MatchNode::build_internalop( ) {
3409  char *iop, *subtree;
3410  const char *lstr, *rstr;
3411  // Build string representation of subtree
3412  // Operation lchildType rchildType
3413  int len = (int)strlen(_opType) + 4;
3414  lstr = (_lChild) ? ((_lChild->_internalop) ?
3415                       _lChild->_internalop : _lChild->_opType) : "";
3416  rstr = (_rChild) ? ((_rChild->_internalop) ?
3417                       _rChild->_internalop : _rChild->_opType) : "";
3418  len += (int)strlen(lstr) + (int)strlen(rstr);
3419  subtree = (char *)malloc(len);
3420  sprintf(subtree,"_%s_%s_%s", _opType, lstr, rstr);
3421  // Hash the subtree string in _internalOps; if a name exists, use it
3422  iop = (char *)_AD._internalOps[subtree];
3423  // Else create a unique name, and add it to the hash table
3424  if (iop == NULL) {
3425    iop = subtree;
3426    _AD._internalOps.Insert(subtree, iop);
3427    _AD._internalOpNames.addName(iop);
3428    _AD._internalMatch.Insert(iop, this);
3429  }
3430  // Add the internal operand name to the MatchNode
3431  _internalop = iop;
3432  _result = iop;
3433}
3434
3435
3436void MatchNode::dump() {
3437  output(stderr);
3438}
3439
3440void MatchNode::output(FILE *fp) {
3441  if (_lChild==0 && _rChild==0) {
3442    fprintf(fp," %s",_name);    // operand
3443  }
3444  else {
3445    fprintf(fp," (%s ",_name);  // " (opcodeName "
3446    if(_lChild) _lChild->output(fp); //               left operand
3447    if(_rChild) _rChild->output(fp); //                    right operand
3448    fprintf(fp,")");                 //                                 ")"
3449  }
3450}
3451
3452int MatchNode::needs_ideal_memory_edge(FormDict &globals) const {
3453  static const char *needs_ideal_memory_list[] = {
3454    "StoreI","StoreL","StoreP","StoreN","StoreNKlass","StoreD","StoreF" ,
3455    "StoreB","StoreC","Store" ,"StoreFP",
3456    "LoadI", "LoadL", "LoadP" ,"LoadN", "LoadD" ,"LoadF"  ,
3457    "LoadB" , "LoadUB", "LoadUS" ,"LoadS" ,"Load" ,
3458    "StoreVector", "LoadVector",
3459    "LoadRange", "LoadKlass", "LoadNKlass", "LoadL_unaligned", "LoadD_unaligned",
3460    "LoadPLocked",
3461    "StorePConditional", "StoreIConditional", "StoreLConditional",
3462    "CompareAndSwapI", "CompareAndSwapL", "CompareAndSwapP", "CompareAndSwapN",
3463    "StoreCM",
3464    "ClearArray",
3465    "GetAndAddI", "GetAndSetI", "GetAndSetP",
3466    "GetAndAddL", "GetAndSetL", "GetAndSetN",
3467  };
3468  int cnt = sizeof(needs_ideal_memory_list)/sizeof(char*);
3469  if( strcmp(_opType,"PrefetchRead")==0 ||
3470      strcmp(_opType,"PrefetchWrite")==0 ||
3471      strcmp(_opType,"PrefetchAllocation")==0 )
3472    return 1;
3473  if( _lChild ) {
3474    const char *opType = _lChild->_opType;
3475    for( int i=0; i<cnt; i++ )
3476      if( strcmp(opType,needs_ideal_memory_list[i]) == 0 )
3477        return 1;
3478    if( _lChild->needs_ideal_memory_edge(globals) )
3479      return 1;
3480  }
3481  if( _rChild ) {
3482    const char *opType = _rChild->_opType;
3483    for( int i=0; i<cnt; i++ )
3484      if( strcmp(opType,needs_ideal_memory_list[i]) == 0 )
3485        return 1;
3486    if( _rChild->needs_ideal_memory_edge(globals) )
3487      return 1;
3488  }
3489
3490  return 0;
3491}
3492
3493// TRUE if defines a derived oop, and so needs a base oop edge present
3494// post-matching.
3495int MatchNode::needs_base_oop_edge() const {
3496  if( !strcmp(_opType,"AddP") ) return 1;
3497  if( strcmp(_opType,"Set") ) return 0;
3498  return !strcmp(_rChild->_opType,"AddP");
3499}
3500
3501int InstructForm::needs_base_oop_edge(FormDict &globals) const {
3502  if( is_simple_chain_rule(globals) ) {
3503    const char *src = _matrule->_rChild->_opType;
3504    OperandForm *src_op = globals[src]->is_operand();
3505    assert( src_op, "Not operand class of chain rule" );
3506    return src_op->_matrule ? src_op->_matrule->needs_base_oop_edge() : 0;
3507  }                             // Else check instruction
3508
3509  return _matrule ? _matrule->needs_base_oop_edge() : 0;
3510}
3511
3512
3513//-------------------------cisc spilling methods-------------------------------
3514// helper routines and methods for detecting cisc-spilling instructions
3515//-------------------------cisc_spill_merge------------------------------------
3516int MatchNode::cisc_spill_merge(int left_spillable, int right_spillable) {
3517  int cisc_spillable  = Maybe_cisc_spillable;
3518
3519  // Combine results of left and right checks
3520  if( (left_spillable == Maybe_cisc_spillable) && (right_spillable == Maybe_cisc_spillable) ) {
3521    // neither side is spillable, nor prevents cisc spilling
3522    cisc_spillable = Maybe_cisc_spillable;
3523  }
3524  else if( (left_spillable == Maybe_cisc_spillable) && (right_spillable > Maybe_cisc_spillable) ) {
3525    // right side is spillable
3526    cisc_spillable = right_spillable;
3527  }
3528  else if( (right_spillable == Maybe_cisc_spillable) && (left_spillable > Maybe_cisc_spillable) ) {
3529    // left side is spillable
3530    cisc_spillable = left_spillable;
3531  }
3532  else if( (left_spillable == Not_cisc_spillable) || (right_spillable == Not_cisc_spillable) ) {
3533    // left or right prevents cisc spilling this instruction
3534    cisc_spillable = Not_cisc_spillable;
3535  }
3536  else {
3537    // Only allow one to spill
3538    cisc_spillable = Not_cisc_spillable;
3539  }
3540
3541  return cisc_spillable;
3542}
3543
3544//-------------------------root_ops_match--------------------------------------
3545bool static root_ops_match(FormDict &globals, const char *op1, const char *op2) {
3546  // Base Case: check that the current operands/operations match
3547  assert( op1, "Must have op's name");
3548  assert( op2, "Must have op's name");
3549  const Form *form1 = globals[op1];
3550  const Form *form2 = globals[op2];
3551
3552  return (form1 == form2);
3553}
3554
3555//-------------------------cisc_spill_match_node-------------------------------
3556// Recursively check two MatchRules for legal conversion via cisc-spilling
3557int MatchNode::cisc_spill_match(FormDict& globals, RegisterForm* registers, MatchNode* mRule2, const char* &operand, const char* &reg_type) {
3558  int cisc_spillable  = Maybe_cisc_spillable;
3559  int left_spillable  = Maybe_cisc_spillable;
3560  int right_spillable = Maybe_cisc_spillable;
3561
3562  // Check that each has same number of operands at this level
3563  if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) )
3564    return Not_cisc_spillable;
3565
3566  // Base Case: check that the current operands/operations match
3567  // or are CISC spillable
3568  assert( _opType, "Must have _opType");
3569  assert( mRule2->_opType, "Must have _opType");
3570  const Form *form  = globals[_opType];
3571  const Form *form2 = globals[mRule2->_opType];
3572  if( form == form2 ) {
3573    cisc_spillable = Maybe_cisc_spillable;
3574  } else {
3575    const InstructForm *form2_inst = form2 ? form2->is_instruction() : NULL;
3576    const char *name_left  = mRule2->_lChild ? mRule2->_lChild->_opType : NULL;
3577    const char *name_right = mRule2->_rChild ? mRule2->_rChild->_opType : NULL;
3578    DataType data_type = Form::none;
3579    if (form->is_operand()) {
3580      // Make sure the loadX matches the type of the reg
3581      data_type = form->ideal_to_Reg_type(form->is_operand()->ideal_type(globals));
3582    }
3583    // Detect reg vs (loadX memory)
3584    if( form->is_cisc_reg(globals)
3585        && form2_inst
3586        && data_type != Form::none
3587        && (is_load_from_memory(mRule2->_opType) == data_type) // reg vs. (load memory)
3588        && (name_left != NULL)       // NOT (load)
3589        && (name_right == NULL) ) {  // NOT (load memory foo)
3590      const Form *form2_left = name_left ? globals[name_left] : NULL;
3591      if( form2_left && form2_left->is_cisc_mem(globals) ) {
3592        cisc_spillable = Is_cisc_spillable;
3593        operand        = _name;
3594        reg_type       = _result;
3595        return Is_cisc_spillable;
3596      } else {
3597        cisc_spillable = Not_cisc_spillable;
3598      }
3599    }
3600    // Detect reg vs memory
3601    else if( form->is_cisc_reg(globals) && form2->is_cisc_mem(globals) ) {
3602      cisc_spillable = Is_cisc_spillable;
3603      operand        = _name;
3604      reg_type       = _result;
3605      return Is_cisc_spillable;
3606    } else {
3607      cisc_spillable = Not_cisc_spillable;
3608    }
3609  }
3610
3611  // If cisc is still possible, check rest of tree
3612  if( cisc_spillable == Maybe_cisc_spillable ) {
3613    // Check that each has same number of operands at this level
3614    if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) ) return Not_cisc_spillable;
3615
3616    // Check left operands
3617    if( (_lChild == NULL) && (mRule2->_lChild == NULL) ) {
3618      left_spillable = Maybe_cisc_spillable;
3619    } else {
3620      left_spillable = _lChild->cisc_spill_match(globals, registers, mRule2->_lChild, operand, reg_type);
3621    }
3622
3623    // Check right operands
3624    if( (_rChild == NULL) && (mRule2->_rChild == NULL) ) {
3625      right_spillable =  Maybe_cisc_spillable;
3626    } else {
3627      right_spillable = _rChild->cisc_spill_match(globals, registers, mRule2->_rChild, operand, reg_type);
3628    }
3629
3630    // Combine results of left and right checks
3631    cisc_spillable = cisc_spill_merge(left_spillable, right_spillable);
3632  }
3633
3634  return cisc_spillable;
3635}
3636
3637//---------------------------cisc_spill_match_rule------------------------------
3638// Recursively check two MatchRules for legal conversion via cisc-spilling
3639// This method handles the root of Match tree,
3640// general recursive checks done in MatchNode
3641int  MatchRule::matchrule_cisc_spill_match(FormDict& globals, RegisterForm* registers,
3642                                           MatchRule* mRule2, const char* &operand,
3643                                           const char* &reg_type) {
3644  int cisc_spillable  = Maybe_cisc_spillable;
3645  int left_spillable  = Maybe_cisc_spillable;
3646  int right_spillable = Maybe_cisc_spillable;
3647
3648  // Check that each sets a result
3649  if( !(sets_result() && mRule2->sets_result()) ) return Not_cisc_spillable;
3650  // Check that each has same number of operands at this level
3651  if( (_lChild && !(mRule2->_lChild)) || (_rChild && !(mRule2->_rChild)) ) return Not_cisc_spillable;
3652
3653  // Check left operands: at root, must be target of 'Set'
3654  if( (_lChild == NULL) || (mRule2->_lChild == NULL) ) {
3655    left_spillable = Not_cisc_spillable;
3656  } else {
3657    // Do not support cisc-spilling instruction's target location
3658    if( root_ops_match(globals, _lChild->_opType, mRule2->_lChild->_opType) ) {
3659      left_spillable = Maybe_cisc_spillable;
3660    } else {
3661      left_spillable = Not_cisc_spillable;
3662    }
3663  }
3664
3665  // Check right operands: recursive walk to identify reg->mem operand
3666  if( (_rChild == NULL) && (mRule2->_rChild == NULL) ) {
3667    right_spillable =  Maybe_cisc_spillable;
3668  } else {
3669    right_spillable = _rChild->cisc_spill_match(globals, registers, mRule2->_rChild, operand, reg_type);
3670  }
3671
3672  // Combine results of left and right checks
3673  cisc_spillable = cisc_spill_merge(left_spillable, right_spillable);
3674
3675  return cisc_spillable;
3676}
3677
3678//----------------------------- equivalent ------------------------------------
3679// Recursively check to see if two match rules are equivalent.
3680// This rule handles the root.
3681bool MatchRule::equivalent(FormDict &globals, MatchNode *mRule2) {
3682  // Check that each sets a result
3683  if (sets_result() != mRule2->sets_result()) {
3684    return false;
3685  }
3686
3687  // Check that the current operands/operations match
3688  assert( _opType, "Must have _opType");
3689  assert( mRule2->_opType, "Must have _opType");
3690  const Form *form  = globals[_opType];
3691  const Form *form2 = globals[mRule2->_opType];
3692  if( form != form2 ) {
3693    return false;
3694  }
3695
3696  if (_lChild ) {
3697    if( !_lChild->equivalent(globals, mRule2->_lChild) )
3698      return false;
3699  } else if (mRule2->_lChild) {
3700    return false; // I have NULL left child, mRule2 has non-NULL left child.
3701  }
3702
3703  if (_rChild ) {
3704    if( !_rChild->equivalent(globals, mRule2->_rChild) )
3705      return false;
3706  } else if (mRule2->_rChild) {
3707    return false; // I have NULL right child, mRule2 has non-NULL right child.
3708  }
3709
3710  // We've made it through the gauntlet.
3711  return true;
3712}
3713
3714//----------------------------- equivalent ------------------------------------
3715// Recursively check to see if two match rules are equivalent.
3716// This rule handles the operands.
3717bool MatchNode::equivalent(FormDict &globals, MatchNode *mNode2) {
3718  if( !mNode2 )
3719    return false;
3720
3721  // Check that the current operands/operations match
3722  assert( _opType, "Must have _opType");
3723  assert( mNode2->_opType, "Must have _opType");
3724  const Form *form  = globals[_opType];
3725  const Form *form2 = globals[mNode2->_opType];
3726  if( form != form2 ) {
3727    return false;
3728  }
3729
3730  // Check that their children also match
3731  if (_lChild ) {
3732    if( !_lChild->equivalent(globals, mNode2->_lChild) )
3733      return false;
3734  } else if (mNode2->_lChild) {
3735    return false; // I have NULL left child, mNode2 has non-NULL left child.
3736  }
3737
3738  if (_rChild ) {
3739    if( !_rChild->equivalent(globals, mNode2->_rChild) )
3740      return false;
3741  } else if (mNode2->_rChild) {
3742    return false; // I have NULL right child, mNode2 has non-NULL right child.
3743  }
3744
3745  // We've made it through the gauntlet.
3746  return true;
3747}
3748
3749//-------------------------- has_commutative_op -------------------------------
3750// Recursively check for commutative operations with subtree operands
3751// which could be swapped.
3752void MatchNode::count_commutative_op(int& count) {
3753  static const char *commut_op_list[] = {
3754    "AddI","AddL","AddF","AddD",
3755    "AndI","AndL",
3756    "MaxI","MinI",
3757    "MulI","MulL","MulF","MulD",
3758    "OrI" ,"OrL" ,
3759    "XorI","XorL"
3760  };
3761  int cnt = sizeof(commut_op_list)/sizeof(char*);
3762
3763  if( _lChild && _rChild && (_lChild->_lChild || _rChild->_lChild) ) {
3764    // Don't swap if right operand is an immediate constant.
3765    bool is_const = false;
3766    if( _rChild->_lChild == NULL && _rChild->_rChild == NULL ) {
3767      FormDict &globals = _AD.globalNames();
3768      const Form *form = globals[_rChild->_opType];
3769      if ( form ) {
3770        OperandForm  *oper = form->is_operand();
3771        if( oper && oper->interface_type(globals) == Form::constant_interface )
3772          is_const = true;
3773      }
3774    }
3775    if( !is_const ) {
3776      for( int i=0; i<cnt; i++ ) {
3777        if( strcmp(_opType, commut_op_list[i]) == 0 ) {
3778          count++;
3779          _commutative_id = count; // id should be > 0
3780          break;
3781        }
3782      }
3783    }
3784  }
3785  if( _lChild )
3786    _lChild->count_commutative_op(count);
3787  if( _rChild )
3788    _rChild->count_commutative_op(count);
3789}
3790
3791//-------------------------- swap_commutative_op ------------------------------
3792// Recursively swap specified commutative operation with subtree operands.
3793void MatchNode::swap_commutative_op(bool atroot, int id) {
3794  if( _commutative_id == id ) { // id should be > 0
3795    assert(_lChild && _rChild && (_lChild->_lChild || _rChild->_lChild ),
3796            "not swappable operation");
3797    MatchNode* tmp = _lChild;
3798    _lChild = _rChild;
3799    _rChild = tmp;
3800    // Don't exit here since we need to build internalop.
3801  }
3802
3803  bool is_set = ( strcmp(_opType, "Set") == 0 );
3804  if( _lChild )
3805    _lChild->swap_commutative_op(is_set, id);
3806  if( _rChild )
3807    _rChild->swap_commutative_op(is_set, id);
3808
3809  // If not the root, reduce this subtree to an internal operand
3810  if( !atroot && (_lChild || _rChild) ) {
3811    build_internalop();
3812  }
3813}
3814
3815//-------------------------- swap_commutative_op ------------------------------
3816// Recursively swap specified commutative operation with subtree operands.
3817void MatchRule::matchrule_swap_commutative_op(const char* instr_ident, int count, int& match_rules_cnt) {
3818  assert(match_rules_cnt < 100," too many match rule clones");
3819  // Clone
3820  MatchRule* clone = new MatchRule(_AD, this);
3821  // Swap operands of commutative operation
3822  ((MatchNode*)clone)->swap_commutative_op(true, count);
3823  char* buf = (char*) malloc(strlen(instr_ident) + 4);
3824  sprintf(buf, "%s_%d", instr_ident, match_rules_cnt++);
3825  clone->_result = buf;
3826
3827  clone->_next = this->_next;
3828  this-> _next = clone;
3829  if( (--count) > 0 ) {
3830    this-> matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
3831    clone->matchrule_swap_commutative_op(instr_ident, count, match_rules_cnt);
3832  }
3833}
3834
3835//------------------------------MatchRule--------------------------------------
3836MatchRule::MatchRule(ArchDesc &ad)
3837  : MatchNode(ad), _depth(0), _construct(NULL), _numchilds(0) {
3838    _next = NULL;
3839}
3840
3841MatchRule::MatchRule(ArchDesc &ad, MatchRule* mRule)
3842  : MatchNode(ad, *mRule, 0), _depth(mRule->_depth),
3843    _construct(mRule->_construct), _numchilds(mRule->_numchilds) {
3844    _next = NULL;
3845}
3846
3847MatchRule::MatchRule(ArchDesc &ad, MatchNode* mroot, int depth, char *cnstr,
3848                     int numleaves)
3849  : MatchNode(ad,*mroot), _depth(depth), _construct(cnstr),
3850    _numchilds(0) {
3851      _next = NULL;
3852      mroot->_lChild = NULL;
3853      mroot->_rChild = NULL;
3854      delete mroot;
3855      _numleaves = numleaves;
3856      _numchilds = (_lChild ? 1 : 0) + (_rChild ? 1 : 0);
3857}
3858MatchRule::~MatchRule() {
3859}
3860
3861// Recursive call collecting info on top-level operands, not transitive.
3862// Implementation does not modify state of internal structures.
3863void MatchRule::append_components(FormDict& locals, ComponentList& components, bool def_flag) const {
3864  assert (_name != NULL, "MatchNode::build_components encountered empty node\n");
3865
3866  MatchNode::append_components(locals, components,
3867                               false /* not necessarily a def */);
3868}
3869
3870// Recursive call on all operands' match rules in my match rule.
3871// Implementation does not modify state of internal structures  since they
3872// can be shared.
3873// The MatchNode that is called first treats its
3874bool MatchRule::base_operand(uint &position0, FormDict &globals,
3875                             const char *&result, const char * &name,
3876                             const char * &opType)const{
3877  uint position = position0;
3878
3879  return (MatchNode::base_operand( position, globals, result, name, opType));
3880}
3881
3882
3883bool MatchRule::is_base_register(FormDict &globals) const {
3884  uint   position = 1;
3885  const char  *result   = NULL;
3886  const char  *name     = NULL;
3887  const char  *opType   = NULL;
3888  if (!base_operand(position, globals, result, name, opType)) {
3889    position = 0;
3890    if( base_operand(position, globals, result, name, opType) &&
3891        (strcmp(opType,"RegI")==0 ||
3892         strcmp(opType,"RegP")==0 ||
3893         strcmp(opType,"RegN")==0 ||
3894         strcmp(opType,"RegL")==0 ||
3895         strcmp(opType,"RegF")==0 ||
3896         strcmp(opType,"RegD")==0 ||
3897         strcmp(opType,"VecS")==0 ||
3898         strcmp(opType,"VecD")==0 ||
3899         strcmp(opType,"VecX")==0 ||
3900         strcmp(opType,"VecY")==0 ||
3901         strcmp(opType,"Reg" )==0) ) {
3902      return 1;
3903    }
3904  }
3905  return 0;
3906}
3907
3908Form::DataType MatchRule::is_base_constant(FormDict &globals) const {
3909  uint         position = 1;
3910  const char  *result   = NULL;
3911  const char  *name     = NULL;
3912  const char  *opType   = NULL;
3913  if (!base_operand(position, globals, result, name, opType)) {
3914    position = 0;
3915    if (base_operand(position, globals, result, name, opType)) {
3916      return ideal_to_const_type(opType);
3917    }
3918  }
3919  return Form::none;
3920}
3921
3922bool MatchRule::is_chain_rule(FormDict &globals) const {
3923
3924  // Check for chain rule, and do not generate a match list for it
3925  if ((_lChild == NULL) && (_rChild == NULL) ) {
3926    const Form *form = globals[_opType];
3927    // If this is ideal, then it is a base match, not a chain rule.
3928    if ( form && form->is_operand() && (!form->ideal_only())) {
3929      return true;
3930    }
3931  }
3932  // Check for "Set" form of chain rule, and do not generate a match list
3933  if (_rChild) {
3934    const char *rch = _rChild->_opType;
3935    const Form *form = globals[rch];
3936    if ((!strcmp(_opType,"Set") &&
3937         ((form) && form->is_operand()))) {
3938      return true;
3939    }
3940  }
3941  return false;
3942}
3943
3944int MatchRule::is_ideal_copy() const {
3945  if( _rChild ) {
3946    const char  *opType = _rChild->_opType;
3947#if 1
3948    if( strcmp(opType,"CastIP")==0 )
3949      return 1;
3950#else
3951    if( strcmp(opType,"CastII")==0 )
3952      return 1;
3953    // Do not treat *CastPP this way, because it
3954    // may transfer a raw pointer to an oop.
3955    // If the register allocator were to coalesce this
3956    // into a single LRG, the GC maps would be incorrect.
3957    //if( strcmp(opType,"CastPP")==0 )
3958    //  return 1;
3959    //if( strcmp(opType,"CheckCastPP")==0 )
3960    //  return 1;
3961    //
3962    // Do not treat CastX2P or CastP2X this way, because
3963    // raw pointers and int types are treated differently
3964    // when saving local & stack info for safepoints in
3965    // Output().
3966    //if( strcmp(opType,"CastX2P")==0 )
3967    //  return 1;
3968    //if( strcmp(opType,"CastP2X")==0 )
3969    //  return 1;
3970#endif
3971  }
3972  if( is_chain_rule(_AD.globalNames()) &&
3973      _lChild && strncmp(_lChild->_opType,"stackSlot",9)==0 )
3974    return 1;
3975  return 0;
3976}
3977
3978
3979int MatchRule::is_expensive() const {
3980  if( _rChild ) {
3981    const char  *opType = _rChild->_opType;
3982    if( strcmp(opType,"AtanD")==0 ||
3983        strcmp(opType,"CosD")==0 ||
3984        strcmp(opType,"DivD")==0 ||
3985        strcmp(opType,"DivF")==0 ||
3986        strcmp(opType,"DivI")==0 ||
3987        strcmp(opType,"ExpD")==0 ||
3988        strcmp(opType,"LogD")==0 ||
3989        strcmp(opType,"Log10D")==0 ||
3990        strcmp(opType,"ModD")==0 ||
3991        strcmp(opType,"ModF")==0 ||
3992        strcmp(opType,"ModI")==0 ||
3993        strcmp(opType,"PowD")==0 ||
3994        strcmp(opType,"SinD")==0 ||
3995        strcmp(opType,"SqrtD")==0 ||
3996        strcmp(opType,"TanD")==0 ||
3997        strcmp(opType,"ConvD2F")==0 ||
3998        strcmp(opType,"ConvD2I")==0 ||
3999        strcmp(opType,"ConvD2L")==0 ||
4000        strcmp(opType,"ConvF2D")==0 ||
4001        strcmp(opType,"ConvF2I")==0 ||
4002        strcmp(opType,"ConvF2L")==0 ||
4003        strcmp(opType,"ConvI2D")==0 ||
4004        strcmp(opType,"ConvI2F")==0 ||
4005        strcmp(opType,"ConvI2L")==0 ||
4006        strcmp(opType,"ConvL2D")==0 ||
4007        strcmp(opType,"ConvL2F")==0 ||
4008        strcmp(opType,"ConvL2I")==0 ||
4009        strcmp(opType,"DecodeN")==0 ||
4010        strcmp(opType,"EncodeP")==0 ||
4011        strcmp(opType,"EncodePKlass")==0 ||
4012        strcmp(opType,"DecodeNKlass")==0 ||
4013        strcmp(opType,"RoundDouble")==0 ||
4014        strcmp(opType,"RoundFloat")==0 ||
4015        strcmp(opType,"ReverseBytesI")==0 ||
4016        strcmp(opType,"ReverseBytesL")==0 ||
4017        strcmp(opType,"ReverseBytesUS")==0 ||
4018        strcmp(opType,"ReverseBytesS")==0 ||
4019        strcmp(opType,"ReplicateB")==0 ||
4020        strcmp(opType,"ReplicateS")==0 ||
4021        strcmp(opType,"ReplicateI")==0 ||
4022        strcmp(opType,"ReplicateL")==0 ||
4023        strcmp(opType,"ReplicateF")==0 ||
4024        strcmp(opType,"ReplicateD")==0 ||
4025        0 /* 0 to line up columns nicely */ )
4026      return 1;
4027  }
4028  return 0;
4029}
4030
4031bool MatchRule::is_ideal_if() const {
4032  if( !_opType ) return false;
4033  return
4034    !strcmp(_opType,"If"            ) ||
4035    !strcmp(_opType,"CountedLoopEnd");
4036}
4037
4038bool MatchRule::is_ideal_fastlock() const {
4039  if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4040    return (strcmp(_rChild->_opType,"FastLock") == 0);
4041  }
4042  return false;
4043}
4044
4045bool MatchRule::is_ideal_membar() const {
4046  if( !_opType ) return false;
4047  return
4048    !strcmp(_opType,"MemBarAcquire"  ) ||
4049    !strcmp(_opType,"MemBarRelease"  ) ||
4050    !strcmp(_opType,"MemBarAcquireLock") ||
4051    !strcmp(_opType,"MemBarReleaseLock") ||
4052    !strcmp(_opType,"MemBarVolatile" ) ||
4053    !strcmp(_opType,"MemBarCPUOrder" ) ||
4054    !strcmp(_opType,"MemBarStoreStore" );
4055}
4056
4057bool MatchRule::is_ideal_loadPC() const {
4058  if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4059    return (strcmp(_rChild->_opType,"LoadPC") == 0);
4060  }
4061  return false;
4062}
4063
4064bool MatchRule::is_ideal_box() const {
4065  if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4066    return (strcmp(_rChild->_opType,"Box") == 0);
4067  }
4068  return false;
4069}
4070
4071bool MatchRule::is_ideal_goto() const {
4072  bool   ideal_goto = false;
4073
4074  if( _opType && (strcmp(_opType,"Goto") == 0) ) {
4075    ideal_goto = true;
4076  }
4077  return ideal_goto;
4078}
4079
4080bool MatchRule::is_ideal_jump() const {
4081  if( _opType ) {
4082    if( !strcmp(_opType,"Jump") )
4083      return true;
4084  }
4085  return false;
4086}
4087
4088bool MatchRule::is_ideal_bool() const {
4089  if( _opType ) {
4090    if( !strcmp(_opType,"Bool") )
4091      return true;
4092  }
4093  return false;
4094}
4095
4096
4097Form::DataType MatchRule::is_ideal_load() const {
4098  Form::DataType ideal_load = Form::none;
4099
4100  if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4101    const char *opType = _rChild->_opType;
4102    ideal_load = is_load_from_memory(opType);
4103  }
4104
4105  return ideal_load;
4106}
4107
4108bool MatchRule::is_vector() const {
4109  static const char *vector_list[] = {
4110    "AddVB","AddVS","AddVI","AddVL","AddVF","AddVD",
4111    "SubVB","SubVS","SubVI","SubVL","SubVF","SubVD",
4112    "MulVS","MulVI","MulVF","MulVD",
4113    "DivVF","DivVD",
4114    "AndV" ,"XorV" ,"OrV",
4115    "LShiftCntV","RShiftCntV",
4116    "LShiftVB","LShiftVS","LShiftVI","LShiftVL",
4117    "RShiftVB","RShiftVS","RShiftVI","RShiftVL",
4118    "URShiftVB","URShiftVS","URShiftVI","URShiftVL",
4119    "ReplicateB","ReplicateS","ReplicateI","ReplicateL","ReplicateF","ReplicateD",
4120    "LoadVector","StoreVector",
4121    // Next are not supported currently.
4122    "PackB","PackS","PackI","PackL","PackF","PackD","Pack2L","Pack2D",
4123    "ExtractB","ExtractUB","ExtractC","ExtractS","ExtractI","ExtractL","ExtractF","ExtractD"
4124  };
4125  int cnt = sizeof(vector_list)/sizeof(char*);
4126  if (_rChild) {
4127    const char  *opType = _rChild->_opType;
4128    for (int i=0; i<cnt; i++)
4129      if (strcmp(opType,vector_list[i]) == 0)
4130        return true;
4131  }
4132  return false;
4133}
4134
4135
4136bool MatchRule::skip_antidep_check() const {
4137  // Some loads operate on what is effectively immutable memory so we
4138  // should skip the anti dep computations.  For some of these nodes
4139  // the rewritable field keeps the anti dep logic from triggering but
4140  // for certain kinds of LoadKlass it does not since they are
4141  // actually reading memory which could be rewritten by the runtime,
4142  // though never by generated code.  This disables it uniformly for
4143  // the nodes that behave like this: LoadKlass, LoadNKlass and
4144  // LoadRange.
4145  if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4146    const char *opType = _rChild->_opType;
4147    if (strcmp("LoadKlass", opType) == 0 ||
4148        strcmp("LoadNKlass", opType) == 0 ||
4149        strcmp("LoadRange", opType) == 0) {
4150      return true;
4151    }
4152  }
4153
4154  return false;
4155}
4156
4157
4158Form::DataType MatchRule::is_ideal_store() const {
4159  Form::DataType ideal_store = Form::none;
4160
4161  if ( _opType && (strcmp(_opType,"Set") == 0) && _rChild ) {
4162    const char *opType = _rChild->_opType;
4163    ideal_store = is_store_to_memory(opType);
4164  }
4165
4166  return ideal_store;
4167}
4168
4169
4170void MatchRule::dump() {
4171  output(stderr);
4172}
4173
4174// Write just one line.
4175void MatchRule::output_short(FILE *fp) {
4176  fprintf(fp,"MatchRule: ( %s",_name);
4177  if (_lChild) _lChild->output(fp);
4178  if (_rChild) _rChild->output(fp);
4179  fprintf(fp," )");
4180}
4181
4182void MatchRule::output(FILE *fp) {
4183  output_short(fp);
4184  fprintf(fp,"\n   nesting depth = %d\n", _depth);
4185  if (_result) fprintf(fp,"   Result Type = %s", _result);
4186  fprintf(fp,"\n");
4187}
4188
4189//------------------------------Attribute--------------------------------------
4190Attribute::Attribute(char *id, char* val, int type)
4191  : _ident(id), _val(val), _atype(type) {
4192}
4193Attribute::~Attribute() {
4194}
4195
4196int Attribute::int_val(ArchDesc &ad) {
4197  // Make sure it is an integer constant:
4198  int result = 0;
4199  if (!_val || !ADLParser::is_int_token(_val, result)) {
4200    ad.syntax_err(0, "Attribute %s must have an integer value: %s",
4201                  _ident, _val ? _val : "");
4202  }
4203  return result;
4204}
4205
4206void Attribute::dump() {
4207  output(stderr);
4208} // Debug printer
4209
4210// Write to output files
4211void Attribute::output(FILE *fp) {
4212  fprintf(fp,"Attribute: %s  %s\n", (_ident?_ident:""), (_val?_val:""));
4213}
4214
4215//------------------------------FormatRule----------------------------------
4216FormatRule::FormatRule(char *temp)
4217  : _temp(temp) {
4218}
4219FormatRule::~FormatRule() {
4220}
4221
4222void FormatRule::dump() {
4223  output(stderr);
4224}
4225
4226// Write to output files
4227void FormatRule::output(FILE *fp) {
4228  fprintf(fp,"\nFormat Rule: \n%s", (_temp?_temp:""));
4229  fprintf(fp,"\n");
4230}
4231