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