RegAllocCommon no longer includes CommandLine.h so we have to include it
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9InstrSelection.cpp
1 //===-- SparcInstrSelection.cpp -------------------------------------------===//
2 //
3 //  BURS instruction selection for SPARC V9 architecture.      
4 //
5 //===----------------------------------------------------------------------===//
6
7 #include "SparcInternals.h"
8 #include "SparcInstrSelectionSupport.h"
9 #include "SparcRegClassInfo.h"
10 #include "llvm/CodeGen/InstrSelectionSupport.h"
11 #include "llvm/CodeGen/MachineInstr.h"
12 #include "llvm/CodeGen/MachineInstrAnnot.h"
13 #include "llvm/CodeGen/InstrForest.h"
14 #include "llvm/CodeGen/InstrSelection.h"
15 #include "llvm/CodeGen/MachineCodeForMethod.h"
16 #include "llvm/CodeGen/MachineCodeForInstruction.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOther.h"
21 #include "llvm/Function.h"
22 #include "llvm/Constants.h"
23 #include "Support/MathExtras.h"
24 #include <math.h>
25 using std::vector;
26
27 //************************ Internal Functions ******************************/
28
29
30 static inline MachineOpCode 
31 ChooseBprInstruction(const InstructionNode* instrNode)
32 {
33   MachineOpCode opCode;
34   
35   Instruction* setCCInstr =
36     ((InstructionNode*) instrNode->leftChild())->getInstruction();
37   
38   switch(setCCInstr->getOpcode())
39     {
40     case Instruction::SetEQ: opCode = BRZ;   break;
41     case Instruction::SetNE: opCode = BRNZ;  break;
42     case Instruction::SetLE: opCode = BRLEZ; break;
43     case Instruction::SetGE: opCode = BRGEZ; break;
44     case Instruction::SetLT: opCode = BRLZ;  break;
45     case Instruction::SetGT: opCode = BRGZ;  break;
46     default:
47       assert(0 && "Unrecognized VM instruction!");
48       opCode = INVALID_OPCODE;
49       break; 
50     }
51   
52   return opCode;
53 }
54
55
56 static inline MachineOpCode 
57 ChooseBpccInstruction(const InstructionNode* instrNode,
58                       const BinaryOperator* setCCInstr)
59 {
60   MachineOpCode opCode = INVALID_OPCODE;
61   
62   bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
63   
64   if (isSigned)
65     {
66       switch(setCCInstr->getOpcode())
67         {
68         case Instruction::SetEQ: opCode = BE;  break;
69         case Instruction::SetNE: opCode = BNE; break;
70         case Instruction::SetLE: opCode = BLE; break;
71         case Instruction::SetGE: opCode = BGE; break;
72         case Instruction::SetLT: opCode = BL;  break;
73         case Instruction::SetGT: opCode = BG;  break;
74         default:
75           assert(0 && "Unrecognized VM instruction!");
76           break; 
77         }
78     }
79   else
80     {
81       switch(setCCInstr->getOpcode())
82         {
83         case Instruction::SetEQ: opCode = BE;   break;
84         case Instruction::SetNE: opCode = BNE;  break;
85         case Instruction::SetLE: opCode = BLEU; break;
86         case Instruction::SetGE: opCode = BCC;  break;
87         case Instruction::SetLT: opCode = BCS;  break;
88         case Instruction::SetGT: opCode = BGU;  break;
89         default:
90           assert(0 && "Unrecognized VM instruction!");
91           break; 
92         }
93     }
94   
95   return opCode;
96 }
97
98 static inline MachineOpCode 
99 ChooseBFpccInstruction(const InstructionNode* instrNode,
100                        const BinaryOperator* setCCInstr)
101 {
102   MachineOpCode opCode = INVALID_OPCODE;
103   
104   switch(setCCInstr->getOpcode())
105     {
106     case Instruction::SetEQ: opCode = FBE;  break;
107     case Instruction::SetNE: opCode = FBNE; break;
108     case Instruction::SetLE: opCode = FBLE; break;
109     case Instruction::SetGE: opCode = FBGE; break;
110     case Instruction::SetLT: opCode = FBL;  break;
111     case Instruction::SetGT: opCode = FBG;  break;
112     default:
113       assert(0 && "Unrecognized VM instruction!");
114       break; 
115     }
116   
117   return opCode;
118 }
119
120
121 // Create a unique TmpInstruction for a boolean value,
122 // representing the CC register used by a branch on that value.
123 // For now, hack this using a little static cache of TmpInstructions.
124 // Eventually the entire BURG instruction selection should be put
125 // into a separate class that can hold such information.
126 // The static cache is not too bad because the memory for these
127 // TmpInstructions will be freed along with the rest of the Function anyway.
128 // 
129 static TmpInstruction*
130 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType)
131 {
132   typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
133   static BoolTmpCache boolToTmpCache;     // Map boolVal -> TmpInstruction*
134   static const Function *lastFunction = 0;// Use to flush cache between funcs
135   
136   assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
137   
138   if (lastFunction != F)
139     {
140       lastFunction = F;
141       boolToTmpCache.clear();
142     }
143   
144   // Look for tmpI and create a new one otherwise.  The new value is
145   // directly written to map using the ref returned by operator[].
146   TmpInstruction*& tmpI = boolToTmpCache[boolVal];
147   if (tmpI == NULL)
148     tmpI = new TmpInstruction(ccType, boolVal);
149   
150   return tmpI;
151 }
152
153
154 static inline MachineOpCode 
155 ChooseBccInstruction(const InstructionNode* instrNode,
156                      bool& isFPBranch)
157 {
158   InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
159   assert(setCCNode->getOpLabel() == SetCCOp);
160   BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
161   const Type* setCCType = setCCInstr->getOperand(0)->getType();
162   
163   isFPBranch = setCCType->isFloatingPoint(); // Return value: don't delete!
164   
165   if (isFPBranch)
166     return ChooseBFpccInstruction(instrNode, setCCInstr);
167   else
168     return ChooseBpccInstruction(instrNode, setCCInstr);
169 }
170
171
172 static inline MachineOpCode 
173 ChooseMovFpccInstruction(const InstructionNode* instrNode)
174 {
175   MachineOpCode opCode = INVALID_OPCODE;
176   
177   switch(instrNode->getInstruction()->getOpcode())
178     {
179     case Instruction::SetEQ: opCode = MOVFE;  break;
180     case Instruction::SetNE: opCode = MOVFNE; break;
181     case Instruction::SetLE: opCode = MOVFLE; break;
182     case Instruction::SetGE: opCode = MOVFGE; break;
183     case Instruction::SetLT: opCode = MOVFL;  break;
184     case Instruction::SetGT: opCode = MOVFG;  break;
185     default:
186       assert(0 && "Unrecognized VM instruction!");
187       break; 
188     }
189   
190   return opCode;
191 }
192
193
194 // Assumes that SUBcc v1, v2 -> v3 has been executed.
195 // In most cases, we want to clear v3 and then follow it by instruction
196 // MOVcc 1 -> v3.
197 // Set mustClearReg=false if v3 need not be cleared before conditional move.
198 // Set valueToMove=0 if we want to conditionally move 0 instead of 1
199 //                      (i.e., we want to test inverse of a condition)
200 // (The latter two cases do not seem to arise because SetNE needs nothing.)
201 // 
202 static MachineOpCode
203 ChooseMovpccAfterSub(const InstructionNode* instrNode,
204                      bool& mustClearReg,
205                      int& valueToMove)
206 {
207   MachineOpCode opCode = INVALID_OPCODE;
208   mustClearReg = true;
209   valueToMove = 1;
210   
211   switch(instrNode->getInstruction()->getOpcode())
212     {
213     case Instruction::SetEQ: opCode = MOVE;  break;
214     case Instruction::SetLE: opCode = MOVLE; break;
215     case Instruction::SetGE: opCode = MOVGE; break;
216     case Instruction::SetLT: opCode = MOVL;  break;
217     case Instruction::SetGT: opCode = MOVG;  break;
218     case Instruction::SetNE: assert(0 && "No move required!"); break;
219     default:                 assert(0 && "Unrecognized VM instr!"); break; 
220     }
221   
222   return opCode;
223 }
224
225 static inline MachineOpCode
226 ChooseConvertToFloatInstr(OpLabel vopCode, const Type* opType)
227 {
228   MachineOpCode opCode = INVALID_OPCODE;
229   
230   switch(vopCode)
231     {
232     case ToFloatTy: 
233       if (opType == Type::SByteTy || opType == Type::ShortTy || opType == Type::IntTy)
234         opCode = FITOS;
235       else if (opType == Type::LongTy)
236         opCode = FXTOS;
237       else if (opType == Type::DoubleTy)
238         opCode = FDTOS;
239       else if (opType == Type::FloatTy)
240         ;
241       else
242         assert(0 && "Cannot convert this type to FLOAT on SPARC");
243       break;
244       
245     case ToDoubleTy: 
246       // This is usually used in conjunction with CreateCodeToCopyIntToFloat().
247       // Both functions should treat the integer as a 32-bit value for types
248       // of 4 bytes or less, and as a 64-bit value otherwise.
249       if (opType == Type::SByteTy || opType == Type::UByteTy ||
250           opType == Type::ShortTy || opType == Type::UShortTy ||
251           opType == Type::IntTy   || opType == Type::UIntTy)
252         opCode = FITOD;
253       else if (opType == Type::LongTy || opType == Type::ULongTy)
254         opCode = FXTOD;
255       else if (opType == Type::FloatTy)
256         opCode = FSTOD;
257       else if (opType == Type::DoubleTy)
258         ;
259       else
260         assert(0 && "Cannot convert this type to DOUBLE on SPARC");
261       break;
262       
263     default:
264       break;
265     }
266   
267   return opCode;
268 }
269
270 static inline MachineOpCode 
271 ChooseConvertToIntInstr(Type::PrimitiveID tid, const Type* opType)
272 {
273   MachineOpCode opCode = INVALID_OPCODE;;
274   
275   if (tid==Type::SByteTyID || tid==Type::ShortTyID  || tid==Type::IntTyID ||
276       tid==Type::UByteTyID || tid==Type::UShortTyID || tid==Type::UIntTyID)
277     {
278       switch (opType->getPrimitiveID())
279         {
280         case Type::FloatTyID:   opCode = FSTOI; break;
281         case Type::DoubleTyID:  opCode = FDTOI; break;
282         default:
283           assert(0 && "Non-numeric non-bool type cannot be converted to Int");
284           break;
285         }
286     }
287   else if (tid==Type::LongTyID || tid==Type::ULongTyID)
288     {
289       switch (opType->getPrimitiveID())
290         {
291         case Type::FloatTyID:   opCode = FSTOX; break;
292         case Type::DoubleTyID:  opCode = FDTOX; break;
293         default:
294           assert(0 && "Non-numeric non-bool type cannot be converted to Long");
295           break;
296         }
297     }
298   else
299       assert(0 && "Should not get here, Mo!");
300   
301   return opCode;
302 }
303
304 MachineInstr*
305 CreateConvertToIntInstr(Type::PrimitiveID destTID, Value* srcVal,Value* destVal)
306 {
307   MachineOpCode opCode = ChooseConvertToIntInstr(destTID, srcVal->getType());
308   assert(opCode != INVALID_OPCODE && "Expected to need conversion!");
309   
310   MachineInstr* M = new MachineInstr(opCode);
311   M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister, srcVal);
312   M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, destVal);
313   return M;
314 }
315
316 // CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned integer
317 // The FP value must be converted to the dest type in an FP register,
318 // and the result is then copied from FP to int register via memory.
319 //
320 // Since fdtoi converts to signed integers, any FP value V between MAXINT+1
321 // and MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly
322 // *only* when converting to an unsigned int.  (Unsigned byte, short or long
323 // don't have this problem.)
324 // For unsigned int, we therefore have to generate the code sequence:
325 // 
326 //      if (V > (float) MAXINT) {
327 //        unsigned result = (unsigned) (V  - (float) MAXINT);
328 //        result = result + (unsigned) MAXINT;
329 //      }
330 //      else
331 //        result = (unsigned int) V;
332 // 
333 static void
334 CreateCodeToConvertFloatToInt(const TargetMachine& target,
335                               Value* opVal,
336                               Instruction* destI,
337                               std::vector<MachineInstr*>& mvec,
338                               MachineCodeForInstruction& mcfi)
339 {
340   // Create a temporary to represent the FP register into which the
341   // int value will placed after conversion.  The type of this temporary
342   // depends on the type of FP register to use: single-prec for a 32-bit
343   // int or smaller; double-prec for a 64-bit int.
344   // 
345   size_t destSize = target.DataLayout.getTypeSize(destI->getType());
346   const Type* destTypeToUse = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
347   TmpInstruction* destForCast = new TmpInstruction(destTypeToUse, opVal);
348   mcfi.addTemp(destForCast);
349
350   // Create the fp-to-int conversion code
351   MachineInstr* M = CreateConvertToIntInstr(destI->getType()->getPrimitiveID(),
352                                             opVal, destForCast);
353   mvec.push_back(M);
354
355   // Create the fpreg-to-intreg copy code
356   target.getInstrInfo().
357     CreateCodeToCopyFloatToInt(target, destI->getParent()->getParent(),
358                                destForCast, destI, mvec, mcfi);
359 }
360
361
362 static inline MachineOpCode 
363 ChooseAddInstruction(const InstructionNode* instrNode)
364 {
365   return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
366 }
367
368
369 static inline MachineInstr* 
370 CreateMovFloatInstruction(const InstructionNode* instrNode,
371                           const Type* resultType)
372 {
373   MachineInstr* minstr = new MachineInstr((resultType == Type::FloatTy)
374                                           ? FMOVS : FMOVD);
375   minstr->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
376                                instrNode->leftChild()->getValue());
377   minstr->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,
378                                instrNode->getValue());
379   return minstr;
380 }
381
382 static inline MachineInstr* 
383 CreateAddConstInstruction(const InstructionNode* instrNode)
384 {
385   MachineInstr* minstr = NULL;
386   
387   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
388   assert(isa<Constant>(constOp));
389   
390   // Cases worth optimizing are:
391   // (1) Add with 0 for float or double: use an FMOV of appropriate type,
392   //     instead of an FADD (1 vs 3 cycles).  There is no integer MOV.
393   // 
394   if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
395       double dval = FPC->getValue();
396       if (dval == 0.0)
397         minstr = CreateMovFloatInstruction(instrNode,
398                                    instrNode->getInstruction()->getType());
399     }
400   
401   return minstr;
402 }
403
404
405 static inline MachineOpCode 
406 ChooseSubInstructionByType(const Type* resultType)
407 {
408   MachineOpCode opCode = INVALID_OPCODE;
409   
410   if (resultType->isInteger() || isa<PointerType>(resultType))
411     {
412       opCode = SUB;
413     }
414   else
415     switch(resultType->getPrimitiveID())
416       {
417       case Type::FloatTyID:  opCode = FSUBS; break;
418       case Type::DoubleTyID: opCode = FSUBD; break;
419       default: assert(0 && "Invalid type for SUB instruction"); break; 
420       }
421   
422   return opCode;
423 }
424
425
426 static inline MachineInstr* 
427 CreateSubConstInstruction(const InstructionNode* instrNode)
428 {
429   MachineInstr* minstr = NULL;
430   
431   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
432   assert(isa<Constant>(constOp));
433   
434   // Cases worth optimizing are:
435   // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
436   //     instead of an FSUB (1 vs 3 cycles).  There is no integer MOV.
437   // 
438   if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
439     double dval = FPC->getValue();
440     if (dval == 0.0)
441       minstr = CreateMovFloatInstruction(instrNode,
442                                         instrNode->getInstruction()->getType());
443   }
444   
445   return minstr;
446 }
447
448
449 static inline MachineOpCode 
450 ChooseFcmpInstruction(const InstructionNode* instrNode)
451 {
452   MachineOpCode opCode = INVALID_OPCODE;
453   
454   Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
455   switch(operand->getType()->getPrimitiveID()) {
456   case Type::FloatTyID:  opCode = FCMPS; break;
457   case Type::DoubleTyID: opCode = FCMPD; break;
458   default: assert(0 && "Invalid type for FCMP instruction"); break; 
459   }
460   
461   return opCode;
462 }
463
464
465 // Assumes that leftArg and rightArg are both cast instructions.
466 //
467 static inline bool
468 BothFloatToDouble(const InstructionNode* instrNode)
469 {
470   InstrTreeNode* leftArg = instrNode->leftChild();
471   InstrTreeNode* rightArg = instrNode->rightChild();
472   InstrTreeNode* leftArgArg = leftArg->leftChild();
473   InstrTreeNode* rightArgArg = rightArg->leftChild();
474   assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
475   
476   // Check if both arguments are floats cast to double
477   return (leftArg->getValue()->getType() == Type::DoubleTy &&
478           leftArgArg->getValue()->getType() == Type::FloatTy &&
479           rightArgArg->getValue()->getType() == Type::FloatTy);
480 }
481
482
483 static inline MachineOpCode 
484 ChooseMulInstructionByType(const Type* resultType)
485 {
486   MachineOpCode opCode = INVALID_OPCODE;
487   
488   if (resultType->isInteger())
489     opCode = MULX;
490   else
491     switch(resultType->getPrimitiveID())
492       {
493       case Type::FloatTyID:  opCode = FMULS; break;
494       case Type::DoubleTyID: opCode = FMULD; break;
495       default: assert(0 && "Invalid type for MUL instruction"); break; 
496       }
497   
498   return opCode;
499 }
500
501
502
503 static inline MachineInstr*
504 CreateIntNegInstruction(const TargetMachine& target,
505                         Value* vreg)
506 {
507   MachineInstr* minstr = new MachineInstr(SUB);
508   minstr->SetMachineOperandReg(0, target.getRegInfo().getZeroRegNum());
509   minstr->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, vreg);
510   minstr->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, vreg);
511   return minstr;
512 }
513
514
515 // Create instruction sequence for any shift operation.
516 // SLL or SLLX on an operand smaller than the integer reg. size (64bits)
517 // requires a second instruction for explicit sign-extension.
518 // Note that we only have to worry about a sign-bit appearing in the
519 // most significant bit of the operand after shifting (e.g., bit 32 of
520 // Int or bit 16 of Short), so we do not have to worry about results
521 // that are as large as a normal integer register.
522 // 
523 static inline void
524 CreateShiftInstructions(const TargetMachine& target,
525                         Function* F,
526                         MachineOpCode shiftOpCode,
527                         Value* argVal1,
528                         Value* optArgVal2, /* Use optArgVal2 if not NULL */
529                         unsigned int optShiftNum, /* else use optShiftNum */
530                         Instruction* destVal,
531                         vector<MachineInstr*>& mvec,
532                         MachineCodeForInstruction& mcfi)
533 {
534   assert((optArgVal2 != NULL || optShiftNum <= 64) &&
535          "Large shift sizes unexpected, but can be handled below: "
536          "You need to check whether or not it fits in immed field below");
537   
538   // If this is a logical left shift of a type smaller than the standard
539   // integer reg. size, we have to extend the sign-bit into upper bits
540   // of dest, so we need to put the result of the SLL into a temporary.
541   // 
542   Value* shiftDest = destVal;
543   const Type* opType = argVal1->getType();
544   unsigned opSize = target.DataLayout.getTypeSize(argVal1->getType());
545   if ((shiftOpCode == SLL || shiftOpCode == SLLX)
546       && opSize < target.DataLayout.getIntegerRegize())
547     { // put SLL result into a temporary
548       shiftDest = new TmpInstruction(argVal1, optArgVal2, "sllTmp");
549       mcfi.addTemp(shiftDest);
550     }
551   
552   MachineInstr* M = (optArgVal2 != NULL)
553     ? Create3OperandInstr(shiftOpCode, argVal1, optArgVal2, shiftDest)
554     : Create3OperandInstr_UImmed(shiftOpCode, argVal1, optShiftNum, shiftDest);
555   mvec.push_back(M);
556   
557   if (shiftDest != destVal)
558     { // extend the sign-bit of the result into all upper bits of dest
559       assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
560       target.getInstrInfo().
561         CreateSignExtensionInstructions(target, F, shiftDest, 8*opSize,
562                                         destVal, mvec, mcfi);
563     }
564 }
565
566
567 // Does not create any instructions if we cannot exploit constant to
568 // create a cheaper instruction.
569 // This returns the approximate cost of the instructions generated,
570 // which is used to pick the cheapest when both operands are constant.
571 static inline unsigned int
572 CreateMulConstInstruction(const TargetMachine &target, Function* F,
573                           Value* lval, Value* rval, Instruction* destVal,
574                           vector<MachineInstr*>& mvec,
575                           MachineCodeForInstruction& mcfi)
576 {
577   /* Use max. multiply cost, viz., cost of MULX */
578   unsigned int cost = target.getInstrInfo().minLatency(MULX);
579   unsigned int firstNewInstr = mvec.size();
580   
581   Value* constOp = rval;
582   if (! isa<Constant>(constOp))
583     return cost;
584   
585   // Cases worth optimizing are:
586   // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
587   // (2) Multiply by 2^x for integer types: replace with Shift
588   // 
589   const Type* resultType = destVal->getType();
590   
591   if (resultType->isInteger() || isa<PointerType>(resultType))
592     {
593       bool isValidConst;
594       int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
595       if (isValidConst)
596         {
597           unsigned pow;
598           bool needNeg = false;
599           if (C < 0)
600             {
601               needNeg = true;
602               C = -C;
603             }
604           
605           if (C == 0 || C == 1)
606             {
607               cost = target.getInstrInfo().minLatency(ADD);
608               MachineInstr* M = (C == 0)
609                 ? Create3OperandInstr_Reg(ADD,
610                                           target.getRegInfo().getZeroRegNum(),
611                                           target.getRegInfo().getZeroRegNum(),
612                                           destVal)
613                 : Create3OperandInstr_Reg(ADD, lval,
614                                           target.getRegInfo().getZeroRegNum(),
615                                           destVal);
616               mvec.push_back(M);
617             }
618           else if (isPowerOf2(C, pow))
619             {
620               unsigned int opSize = target.DataLayout.getTypeSize(resultType);
621               MachineOpCode opCode = (opSize <= 32)? SLL : SLLX;
622               CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
623                                       destVal, mvec, mcfi); 
624             }
625           
626           if (mvec.size() > 0 && needNeg)
627             { // insert <reg = SUB 0, reg> after the instr to flip the sign
628               MachineInstr* M = CreateIntNegInstruction(target, destVal);
629               mvec.push_back(M);
630             }
631         }
632     }
633   else
634     {
635       if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp))
636         {
637           double dval = FPC->getValue();
638           if (fabs(dval) == 1)
639             {
640               MachineOpCode opCode =  (dval < 0)
641                 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
642                 : (resultType == Type::FloatTy? FMOVS : FMOVD);
643               MachineInstr* M = Create2OperandInstr(opCode, lval, destVal);
644               mvec.push_back(M);
645             } 
646         }
647     }
648   
649   if (firstNewInstr < mvec.size())
650     {
651       cost = 0;
652       for (unsigned int i=firstNewInstr; i < mvec.size(); ++i)
653         cost += target.getInstrInfo().minLatency(mvec[i]->getOpCode());
654     }
655   
656   return cost;
657 }
658
659
660 // Does not create any instructions if we cannot exploit constant to
661 // create a cheaper instruction.
662 // 
663 static inline void
664 CreateCheapestMulConstInstruction(const TargetMachine &target,
665                                   Function* F,
666                                   Value* lval, Value* rval,
667                                   Instruction* destVal,
668                                   vector<MachineInstr*>& mvec,
669                                   MachineCodeForInstruction& mcfi)
670 {
671   Value* constOp;
672   if (isa<Constant>(lval) && isa<Constant>(rval))
673     { // both operands are constant: try both orders!
674       vector<MachineInstr*> mvec1, mvec2;
675       unsigned int lcost = CreateMulConstInstruction(target, F, lval, rval,
676                                                      destVal, mvec1, mcfi);
677       unsigned int rcost = CreateMulConstInstruction(target, F, rval, lval,
678                                                      destVal, mvec2, mcfi);
679       vector<MachineInstr*>& mincostMvec =  (lcost <= rcost)? mvec1 : mvec2;
680       vector<MachineInstr*>& maxcostMvec =  (lcost <= rcost)? mvec2 : mvec1;
681       mvec.insert(mvec.end(), mincostMvec.begin(), mincostMvec.end()); 
682
683       for (unsigned int i=0; i < maxcostMvec.size(); ++i)
684         delete maxcostMvec[i];
685     }
686   else if (isa<Constant>(rval))         // rval is constant, but not lval
687     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
688   else if (isa<Constant>(lval))         // lval is constant, but not rval
689     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
690   
691   // else neither is constant
692   return;
693 }
694
695 // Return NULL if we cannot exploit constant to create a cheaper instruction
696 static inline void
697 CreateMulInstruction(const TargetMachine &target, Function* F,
698                      Value* lval, Value* rval, Instruction* destVal,
699                      vector<MachineInstr*>& mvec,
700                      MachineCodeForInstruction& mcfi,
701                      MachineOpCode forceMulOp = INVALID_MACHINE_OPCODE)
702 {
703   unsigned int L = mvec.size();
704   CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
705   if (mvec.size() == L)
706     { // no instructions were added so create MUL reg, reg, reg.
707       // Use FSMULD if both operands are actually floats cast to doubles.
708       // Otherwise, use the default opcode for the appropriate type.
709       MachineOpCode mulOp = ((forceMulOp != INVALID_MACHINE_OPCODE)
710                              ? forceMulOp 
711                              : ChooseMulInstructionByType(destVal->getType()));
712       MachineInstr* M = new MachineInstr(mulOp);
713       M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister, lval);
714       M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, rval);
715       M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, destVal);
716       mvec.push_back(M);
717     }
718 }
719
720
721 // Generate a divide instruction for Div or Rem.
722 // For Rem, this assumes that the operand type will be signed if the result
723 // type is signed.  This is correct because they must have the same sign.
724 // 
725 static inline MachineOpCode 
726 ChooseDivInstruction(TargetMachine &target,
727                      const InstructionNode* instrNode)
728 {
729   MachineOpCode opCode = INVALID_OPCODE;
730   
731   const Type* resultType = instrNode->getInstruction()->getType();
732   
733   if (resultType->isInteger())
734     opCode = resultType->isSigned()? SDIVX : UDIVX;
735   else
736     switch(resultType->getPrimitiveID())
737       {
738       case Type::FloatTyID:  opCode = FDIVS; break;
739       case Type::DoubleTyID: opCode = FDIVD; break;
740       default: assert(0 && "Invalid type for DIV instruction"); break; 
741       }
742   
743   return opCode;
744 }
745
746
747 // Return NULL if we cannot exploit constant to create a cheaper instruction
748 static inline void
749 CreateDivConstInstruction(TargetMachine &target,
750                           const InstructionNode* instrNode,
751                           vector<MachineInstr*>& mvec)
752 {
753   MachineInstr* minstr1 = NULL;
754   MachineInstr* minstr2 = NULL;
755   
756   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
757   if (! isa<Constant>(constOp))
758     return;
759   
760   // Cases worth optimizing are:
761   // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
762   // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
763   // 
764   const Type* resultType = instrNode->getInstruction()->getType();
765   
766   if (resultType->isInteger())
767     {
768       unsigned pow;
769       bool isValidConst;
770       int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
771       if (isValidConst)
772         {
773           bool needNeg = false;
774           if (C < 0)
775             {
776               needNeg = true;
777               C = -C;
778             }
779           
780           if (C == 1)
781             {
782               minstr1 = new MachineInstr(ADD);
783               minstr1->SetMachineOperandVal(0,
784                                            MachineOperand::MO_VirtualRegister,
785                                            instrNode->leftChild()->getValue());
786               minstr1->SetMachineOperandReg(1,
787                                         target.getRegInfo().getZeroRegNum());
788             }
789           else if (isPowerOf2(C, pow))
790             {
791               MachineOpCode opCode= ((resultType->isSigned())
792                                      ? (resultType==Type::LongTy)? SRAX : SRA
793                                      : (resultType==Type::LongTy)? SRLX : SRL);
794               minstr1 = new MachineInstr(opCode);
795               minstr1->SetMachineOperandVal(0,
796                                            MachineOperand::MO_VirtualRegister,
797                                            instrNode->leftChild()->getValue());
798               minstr1->SetMachineOperandConst(1,
799                                           MachineOperand::MO_UnextendedImmed,
800                                           pow);
801             }
802           
803           if (minstr1 && needNeg)
804             { // insert <reg = SUB 0, reg> after the instr to flip the sign
805               minstr2 = CreateIntNegInstruction(target,
806                                                    instrNode->getValue());
807             }
808         }
809     }
810   else
811     {
812       if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp))
813         {
814           double dval = FPC->getValue();
815           if (fabs(dval) == 1)
816             {
817               bool needNeg = (dval < 0);
818               
819               MachineOpCode opCode = needNeg
820                 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
821                 : (resultType == Type::FloatTy? FMOVS : FMOVD);
822               
823               minstr1 = new MachineInstr(opCode);
824               minstr1->SetMachineOperandVal(0,
825                                            MachineOperand::MO_VirtualRegister,
826                                            instrNode->leftChild()->getValue());
827             } 
828         }
829     }
830   
831   if (minstr1 != NULL)
832     minstr1->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
833                                  instrNode->getValue());   
834   
835   if (minstr1)
836     mvec.push_back(minstr1);
837   if (minstr2)
838     mvec.push_back(minstr2);
839 }
840
841
842 static void
843 CreateCodeForVariableSizeAlloca(const TargetMachine& target,
844                                 Instruction* result,
845                                 unsigned int tsize,
846                                 Value* numElementsVal,
847                                 vector<MachineInstr*>& getMvec)
848 {
849   MachineInstr* M;
850   
851   // Create a Value to hold the (constant) element size
852   Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
853
854   // Get the constant offset from SP for dynamically allocated storage
855   // and create a temporary Value to hold it.
856   assert(result && result->getParent() && "Result value is not part of a fn?");
857   Function *F = result->getParent()->getParent();
858   MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(F);
859   bool growUp;
860   ConstantSInt* dynamicAreaOffset =
861     ConstantSInt::get(Type::IntTy,
862                       target.getFrameInfo().getDynamicAreaOffset(mcInfo,growUp));
863   assert(! growUp && "Has SPARC v9 stack frame convention changed?");
864
865   // Create a temporary value to hold the result of MUL
866   TmpInstruction* tmpProd = new TmpInstruction(numElementsVal, tsizeVal);
867   MachineCodeForInstruction::get(result).addTemp(tmpProd);
868   
869   // Instruction 1: mul numElements, typeSize -> tmpProd
870   M = new MachineInstr(MULX);
871   M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister, numElementsVal);
872   M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, tsizeVal);
873   M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, tmpProd);
874   getMvec.push_back(M);
875         
876   // Instruction 2: sub %sp, tmpProd -> %sp
877   M = new MachineInstr(SUB);
878   M->SetMachineOperandReg(0, target.getRegInfo().getStackPointer());
879   M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, tmpProd);
880   M->SetMachineOperandReg(2, target.getRegInfo().getStackPointer());
881   getMvec.push_back(M);
882   
883   // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
884   M = new MachineInstr(ADD);
885   M->SetMachineOperandReg(0, target.getRegInfo().getStackPointer());
886   M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, dynamicAreaOffset);
887   M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, result);
888   getMvec.push_back(M);
889 }        
890
891
892 static void
893 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
894                              Instruction* result,
895                              unsigned int tsize,
896                              unsigned int numElements,
897                              vector<MachineInstr*>& getMvec)
898 {
899   assert(result && result->getParent() &&
900          "Result value is not part of a function?");
901   Function *F = result->getParent()->getParent();
902   MachineCodeForMethod &mcInfo = MachineCodeForMethod::get(F);
903
904   // Check if the offset would small enough to use as an immediate in
905   // load/stores (check LDX because all load/stores have the same-size immediate
906   // field).  If not, put the variable in the dynamically sized area of the
907   // frame.
908   unsigned int paddedSizeIgnored;
909   int offsetFromFP = mcInfo.computeOffsetforLocalVar(target, result,
910                                                      paddedSizeIgnored,
911                                                      tsize * numElements);
912   if (! target.getInstrInfo().constantFitsInImmedField(LDX, offsetFromFP))
913     {
914       CreateCodeForVariableSizeAlloca(target, result, tsize, 
915                                       ConstantSInt::get(Type::IntTy,numElements),
916                                       getMvec);
917       return;
918     }
919   
920   // else offset fits in immediate field so go ahead and allocate it.
921   offsetFromFP = mcInfo.allocateLocalVar(target, result, tsize * numElements);
922   
923   // Create a temporary Value to hold the constant offset.
924   // This is needed because it may not fit in the immediate field.
925   ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
926   
927   // Instruction 1: add %fp, offsetFromFP -> result
928   MachineInstr* M = new MachineInstr(ADD);
929   M->SetMachineOperandReg(0, target.getRegInfo().getFramePointer());
930   M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, offsetVal); 
931   M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, result);
932   
933   getMvec.push_back(M);
934 }
935
936
937 //------------------------------------------------------------------------ 
938 // Function SetOperandsForMemInstr
939 //
940 // Choose addressing mode for the given load or store instruction.
941 // Use [reg+reg] if it is an indexed reference, and the index offset is
942 //               not a constant or if it cannot fit in the offset field.
943 // Use [reg+offset] in all other cases.
944 // 
945 // This assumes that all array refs are "lowered" to one of these forms:
946 //      %x = load (subarray*) ptr, constant     ; single constant offset
947 //      %x = load (subarray*) ptr, offsetVal    ; single non-constant offset
948 // Generally, this should happen via strength reduction + LICM.
949 // Also, strength reduction should take care of using the same register for
950 // the loop index variable and an array index, when that is profitable.
951 //------------------------------------------------------------------------ 
952
953 static void
954 SetOperandsForMemInstr(vector<MachineInstr*>& mvec,
955                        const InstructionNode* vmInstrNode,
956                        const TargetMachine& target)
957 {
958   Instruction* memInst = vmInstrNode->getInstruction();
959   vector<MachineInstr*>::iterator mvecI = mvec.end() - 1;
960
961   // Index vector, ptr value, and flag if all indices are const.
962   vector<Value*> idxVec;
963   bool allConstantIndices;
964   Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
965
966   // Now create the appropriate operands for the machine instruction.
967   // First, initialize so we default to storing the offset in a register.
968   int64_t smallConstOffset = 0;
969   Value* valueForRegOffset = NULL;
970   MachineOperand::MachineOperandType offsetOpType =
971     MachineOperand::MO_VirtualRegister;
972
973   // Check if there is an index vector and if so, compute the
974   // right offset for structures and for arrays 
975   // 
976   if (!idxVec.empty())
977     {
978       const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
979       
980       // If all indices are constant, compute the combined offset directly.
981       if (allConstantIndices)
982         {
983           // Compute the offset value using the index vector. Create a
984           // virtual reg. for it since it may not fit in the immed field.
985           uint64_t offset = target.DataLayout.getIndexedOffset(ptrType,idxVec);
986           valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
987         }
988       else
989         {
990           // There is at least one non-constant offset.  Therefore, this must
991           // be an array ref, and must have been lowered to a single non-zero
992           // offset.  (An extra leading zero offset, if any, can be ignored.)
993           // Generate code sequence to compute address from index.
994           // 
995           bool firstIdxIsZero =
996             (idxVec[0] == Constant::getNullValue(idxVec[0]->getType()));
997           assert(idxVec.size() == 1U + firstIdxIsZero 
998                  && "Array refs must be lowered before Instruction Selection");
999
1000           Value* idxVal = idxVec[firstIdxIsZero];
1001           assert(! isa<Constant>(idxVal) && "Need to sign-extend uint to 64b!");
1002
1003           vector<MachineInstr*> mulVec;
1004           Instruction* addr = new TmpInstruction(Type::UIntTy, memInst);
1005           MachineCodeForInstruction::get(memInst).addTemp(addr);
1006
1007           // Get the array type indexed by idxVal, and compute its element size.
1008           // The call to getTypeSize() will fail if size is not constant.
1009           const Type* vecType = (firstIdxIsZero
1010                                  ? GetElementPtrInst::getIndexedType(ptrType,
1011                                            std::vector<Value*>(1U, idxVec[0]),
1012                                            /*AllowCompositeLeaf*/ true)
1013                                  : ptrType);
1014           const Type* eltType = cast<SequentialType>(vecType)->getElementType();
1015           ConstantUInt* eltSizeVal = ConstantUInt::get(Type::UIntTy,
1016                                        target.DataLayout.getTypeSize(eltType));
1017
1018           // CreateMulInstruction() folds constants intelligently enough.
1019           CreateMulInstruction(target,
1020                                memInst->getParent()->getParent(),
1021                                idxVal,         /* lval, not likely to be const*/
1022                                eltSizeVal,     /* rval, likely to be constant */
1023                                addr,           /* result */
1024                                mulVec,
1025                                MachineCodeForInstruction::get(memInst),
1026                                INVALID_MACHINE_OPCODE);
1027
1028           // Sign-extend the result of MUL  from 32 to 64 bits.
1029           target.getInstrInfo().CreateSignExtensionInstructions(target, memInst->getParent()->getParent(), addr, /*srcSizeInBits*/32, addr, mulVec, MachineCodeForInstruction::get(memInst));
1030
1031           // Insert mulVec[] before *mvecI in mvec[] and update mvecI
1032           // to point to the same instruction it pointed to before.
1033           assert(mulVec.size() > 0 && "No multiply code created?");
1034           vector<MachineInstr*>::iterator oldMvecI = mvecI;
1035           for (unsigned i=0, N=mulVec.size(); i < N; ++i)
1036             mvecI = mvec.insert(mvecI, mulVec[i]) + 1;  // pts to mem instr
1037
1038           valueForRegOffset = addr;
1039         }
1040     }
1041   else
1042     {
1043       offsetOpType = MachineOperand::MO_SignExtendedImmed;
1044       smallConstOffset = 0;
1045     }
1046
1047   // For STORE:
1048   //   Operand 0 is value, operand 1 is ptr, operand 2 is offset
1049   // For LOAD or GET_ELEMENT_PTR,
1050   //   Operand 0 is ptr, operand 1 is offset, operand 2 is result.
1051   // 
1052   unsigned offsetOpNum, ptrOpNum;
1053   if (memInst->getOpcode() == Instruction::Store)
1054     {
1055       (*mvecI)->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1056                                      vmInstrNode->leftChild()->getValue());
1057       ptrOpNum = 1;
1058       offsetOpNum = 2;
1059     }
1060   else
1061     {
1062       ptrOpNum = 0;
1063       offsetOpNum = 1;
1064       (*mvecI)->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
1065                                      memInst);
1066     }
1067   
1068   (*mvecI)->SetMachineOperandVal(ptrOpNum, MachineOperand::MO_VirtualRegister,
1069                                  ptrVal);
1070   
1071   if (offsetOpType == MachineOperand::MO_VirtualRegister)
1072     {
1073       assert(valueForRegOffset != NULL);
1074       (*mvecI)->SetMachineOperandVal(offsetOpNum, offsetOpType,
1075                                      valueForRegOffset); 
1076     }
1077   else
1078     (*mvecI)->SetMachineOperandConst(offsetOpNum, offsetOpType,
1079                                      smallConstOffset);
1080 }
1081
1082
1083 // 
1084 // Substitute operand `operandNum' of the instruction in node `treeNode'
1085 // in place of the use(s) of that instruction in node `parent'.
1086 // Check both explicit and implicit operands!
1087 // Also make sure to skip over a parent who:
1088 // (1) is a list node in the Burg tree, or
1089 // (2) itself had its results forwarded to its parent
1090 // 
1091 static void
1092 ForwardOperand(InstructionNode* treeNode,
1093                InstrTreeNode*   parent,
1094                int operandNum)
1095 {
1096   assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1097   
1098   Instruction* unusedOp = treeNode->getInstruction();
1099   Value* fwdOp = unusedOp->getOperand(operandNum);
1100
1101   // The parent itself may be a list node, so find the real parent instruction
1102   while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1103     {
1104       parent = parent->parent();
1105       assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1106     }
1107   InstructionNode* parentInstrNode = (InstructionNode*) parent;
1108   
1109   Instruction* userInstr = parentInstrNode->getInstruction();
1110   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
1111
1112   // The parent's mvec would be empty if it was itself forwarded.
1113   // Recursively call ForwardOperand in that case...
1114   //
1115   if (mvec.size() == 0)
1116     {
1117       assert(parent->parent() != NULL &&
1118              "Parent could not have been forwarded, yet has no instructions?");
1119       ForwardOperand(treeNode, parent->parent(), operandNum);
1120     }
1121   else
1122     {
1123       for (unsigned i=0, N=mvec.size(); i < N; i++)
1124         {
1125           MachineInstr* minstr = mvec[i];
1126           for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i)
1127             {
1128               const MachineOperand& mop = minstr->getOperand(i);
1129               if (mop.getOperandType() == MachineOperand::MO_VirtualRegister &&
1130                   mop.getVRegValue() == unusedOp)
1131                 minstr->SetMachineOperandVal(i,
1132                                 MachineOperand::MO_VirtualRegister, fwdOp);
1133             }
1134           
1135           for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
1136             if (minstr->getImplicitRef(i) == unusedOp)
1137               minstr->setImplicitRef(i, fwdOp,
1138                                      minstr->implicitRefIsDefined(i),
1139                                      minstr->implicitRefIsDefinedAndUsed(i));
1140         }
1141     }
1142 }
1143
1144
1145 inline bool
1146 AllUsesAreBranches(const Instruction* setccI)
1147 {
1148   for (Value::use_const_iterator UI=setccI->use_begin(), UE=setccI->use_end();
1149        UI != UE; ++UI)
1150     if (! isa<TmpInstruction>(*UI)     // ignore tmp instructions here
1151         && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
1152       return false;
1153   return true;
1154 }
1155
1156 //******************* Externally Visible Functions *************************/
1157
1158 //------------------------------------------------------------------------ 
1159 // External Function: ThisIsAChainRule
1160 //
1161 // Purpose:
1162 //   Check if a given BURG rule is a chain rule.
1163 //------------------------------------------------------------------------ 
1164
1165 extern bool
1166 ThisIsAChainRule(int eruleno)
1167 {
1168   switch(eruleno)
1169     {
1170     case 111:   // stmt:  reg
1171     case 123:
1172     case 124:
1173     case 125:
1174     case 126:
1175     case 127:
1176     case 128:
1177     case 129:
1178     case 130:
1179     case 131:
1180     case 132:
1181     case 133:
1182     case 155:
1183     case 221:
1184     case 222:
1185     case 241:
1186     case 242:
1187     case 243:
1188     case 244:
1189     case 245:
1190     case 321:
1191       return true; break;
1192
1193     default:
1194       return false; break;
1195     }
1196 }
1197
1198
1199 //------------------------------------------------------------------------ 
1200 // External Function: GetInstructionsByRule
1201 //
1202 // Purpose:
1203 //   Choose machine instructions for the SPARC according to the
1204 //   patterns chosen by the BURG-generated parser.
1205 //------------------------------------------------------------------------ 
1206
1207 void
1208 GetInstructionsByRule(InstructionNode* subtreeRoot,
1209                       int ruleForNode,
1210                       short* nts,
1211                       TargetMachine &target,
1212                       vector<MachineInstr*>& mvec)
1213 {
1214   bool checkCast = false;               // initialize here to use fall-through
1215   bool maskUnsignedResult = false;
1216   int nextRule;
1217   int forwardOperandNum = -1;
1218   unsigned int allocaSize = 0;
1219   MachineInstr* M, *M2;
1220   unsigned int L;
1221
1222   mvec.clear(); 
1223   
1224   // If the code for this instruction was folded into the parent (user),
1225   // then do nothing!
1226   if (subtreeRoot->isFoldedIntoParent())
1227     return;
1228   
1229   // 
1230   // Let's check for chain rules outside the switch so that we don't have
1231   // to duplicate the list of chain rule production numbers here again
1232   // 
1233   if (ThisIsAChainRule(ruleForNode))
1234     {
1235       // Chain rules have a single nonterminal on the RHS.
1236       // Get the rule that matches the RHS non-terminal and use that instead.
1237       // 
1238       assert(nts[0] && ! nts[1]
1239              && "A chain rule should have only one RHS non-terminal!");
1240       nextRule = burm_rule(subtreeRoot->state, nts[0]);
1241       nts = burm_nts[nextRule];
1242       GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
1243     }
1244   else
1245     {
1246       switch(ruleForNode) {
1247       case 1:   // stmt:   Ret
1248       case 2:   // stmt:   RetValue(reg)
1249       {         // NOTE: Prepass of register allocation is responsible
1250                 //       for moving return value to appropriate register.
1251                 // Mark the return-address register as a hidden virtual reg.
1252                 // Mark the return value   register as an implicit ref of
1253                 // the machine instruction.
1254                 // Finally put a NOP in the delay slot.
1255         ReturnInst *returnInstr =
1256           cast<ReturnInst>(subtreeRoot->getInstruction());
1257         assert(returnInstr->getOpcode() == Instruction::Ret);
1258         
1259         Instruction* returnReg = new TmpInstruction(returnInstr);
1260         MachineCodeForInstruction::get(returnInstr).addTemp(returnReg);
1261         
1262         M = new MachineInstr(JMPLRET);
1263         M->SetMachineOperandReg(0, MachineOperand::MO_VirtualRegister,
1264                                       returnReg);
1265         M->SetMachineOperandConst(1,MachineOperand::MO_SignExtendedImmed,
1266                                    (int64_t)8);
1267         M->SetMachineOperandReg(2, target.getRegInfo().getZeroRegNum());
1268         
1269         if (returnInstr->getReturnValue() != NULL)
1270           M->addImplicitRef(returnInstr->getReturnValue());
1271         
1272         mvec.push_back(M);
1273         mvec.push_back(new MachineInstr(NOP));
1274         
1275         break;
1276       }  
1277         
1278       case 3:   // stmt:   Store(reg,reg)
1279       case 4:   // stmt:   Store(reg,ptrreg)
1280         mvec.push_back(new MachineInstr(
1281                          ChooseStoreInstruction(
1282                             subtreeRoot->leftChild()->getValue()->getType())));
1283         SetOperandsForMemInstr(mvec, subtreeRoot, target);
1284         break;
1285
1286       case 5:   // stmt:   BrUncond
1287         M = new MachineInstr(BA);
1288         M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1289              cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(0));
1290         mvec.push_back(M);
1291         
1292         // delay slot
1293         mvec.push_back(new MachineInstr(NOP));
1294         break;
1295
1296       case 206: // stmt:   BrCond(setCCconst)
1297       { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1298         // If the constant is ZERO, we can use the branch-on-integer-register
1299         // instructions and avoid the SUBcc instruction entirely.
1300         // Otherwise this is just the same as case 5, so just fall through.
1301         // 
1302         InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1303         assert(constNode &&
1304                constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1305         Constant *constVal = cast<Constant>(constNode->getValue());
1306         bool isValidConst;
1307         
1308         if ((constVal->getType()->isInteger()
1309              || isa<PointerType>(constVal->getType()))
1310             && GetConstantValueAsSignedInt(constVal, isValidConst) == 0
1311             && isValidConst)
1312           {
1313             // That constant is a zero after all...
1314             // Use the left child of setCC as the first argument!
1315             // Mark the setCC node so that no code is generated for it.
1316             InstructionNode* setCCNode = (InstructionNode*)
1317                                          subtreeRoot->leftChild();
1318             assert(setCCNode->getOpLabel() == SetCCOp);
1319             setCCNode->markFoldedIntoParent();
1320             
1321             BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1322             
1323             M = new MachineInstr(ChooseBprInstruction(subtreeRoot));
1324             M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1325                                     setCCNode->leftChild()->getValue());
1326             M->SetMachineOperandVal(1, MachineOperand::MO_PCRelativeDisp,
1327                                     brInst->getSuccessor(0));
1328             mvec.push_back(M);
1329             
1330             // delay slot
1331             mvec.push_back(new MachineInstr(NOP));
1332
1333             // false branch
1334             M = new MachineInstr(BA);
1335             M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1336                                     brInst->getSuccessor(1));
1337             mvec.push_back(M);
1338             
1339             // delay slot
1340             mvec.push_back(new MachineInstr(NOP));
1341             
1342             break;
1343           }
1344         // ELSE FALL THROUGH
1345       }
1346
1347       case 6:   // stmt:   BrCond(setCC)
1348       { // bool => boolean was computed with SetCC.
1349         // The branch to use depends on whether it is FP, signed, or unsigned.
1350         // If it is an integer CC, we also need to find the unique
1351         // TmpInstruction representing that CC.
1352         // 
1353         BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1354         bool isFPBranch;
1355         M = new MachineInstr(ChooseBccInstruction(subtreeRoot, isFPBranch));
1356
1357         Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1358                                      brInst->getParent()->getParent(),
1359                                      isFPBranch? Type::FloatTy : Type::IntTy);
1360         
1361         M->SetMachineOperandVal(0, MachineOperand::MO_CCRegister, ccValue);
1362         M->SetMachineOperandVal(1, MachineOperand::MO_PCRelativeDisp,
1363                                    brInst->getSuccessor(0));
1364         mvec.push_back(M);
1365
1366         // delay slot
1367         mvec.push_back(new MachineInstr(NOP));
1368
1369         // false branch
1370         M = new MachineInstr(BA);
1371         M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1372                                    brInst->getSuccessor(1));
1373         mvec.push_back(M);
1374
1375         // delay slot
1376         mvec.push_back(new MachineInstr(NOP));
1377         break;
1378       }
1379         
1380       case 208: // stmt:   BrCond(boolconst)
1381       {
1382         // boolconst => boolean is a constant; use BA to first or second label
1383         Constant* constVal = 
1384           cast<Constant>(subtreeRoot->leftChild()->getValue());
1385         unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1386         
1387         M = new MachineInstr(BA);
1388         M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1389           cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
1390         mvec.push_back(M);
1391         
1392         // delay slot
1393         mvec.push_back(new MachineInstr(NOP));
1394         break;
1395       }
1396         
1397       case   8: // stmt:   BrCond(boolreg)
1398       { // boolreg   => boolean is stored in an existing register.
1399         // Just use the branch-on-integer-register instruction!
1400         // 
1401         M = new MachineInstr(BRNZ);
1402         M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1403                                       subtreeRoot->leftChild()->getValue());
1404         M->SetMachineOperandVal(1, MachineOperand::MO_PCRelativeDisp,
1405               cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(0));
1406         mvec.push_back(M);
1407
1408         // delay slot
1409         mvec.push_back(new MachineInstr(NOP));
1410
1411         // false branch
1412         M = new MachineInstr(BA);
1413         M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1414               cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(1));
1415         mvec.push_back(M);
1416         
1417         // delay slot
1418         mvec.push_back(new MachineInstr(NOP));
1419         break;
1420       }  
1421       
1422       case 9:   // stmt:   Switch(reg)
1423         assert(0 && "*** SWITCH instruction is not implemented yet.");
1424         break;
1425
1426       case 10:  // reg:   VRegList(reg, reg)
1427         assert(0 && "VRegList should never be the topmost non-chain rule");
1428         break;
1429
1430       case 21:  // bool:  Not(bool,reg): Both these are implemented as:
1431       case 421: // reg:   BNot(reg,reg):        reg = reg XOR-NOT 0
1432       { // First find the unary operand. It may be left or right, usually right.
1433         Value* notArg = BinaryOperator::getNotArgument(
1434                            cast<BinaryOperator>(subtreeRoot->getInstruction()));
1435         mvec.push_back(Create3OperandInstr_Reg(XNOR, notArg,
1436                                           target.getRegInfo().getZeroRegNum(),
1437                                           subtreeRoot->getValue()));
1438         break;
1439       }
1440
1441       case 22:  // reg:   ToBoolTy(reg):
1442       {
1443         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1444         assert(opType->isIntegral() || isa<PointerType>(opType));
1445         forwardOperandNum = 0;          // forward first operand to user
1446         break;
1447       }
1448       
1449       case 23:  // reg:   ToUByteTy(reg)
1450       case 25:  // reg:   ToUShortTy(reg)
1451       case 27:  // reg:   ToUIntTy(reg)
1452       case 29:  // reg:   ToULongTy(reg)
1453       {
1454         Instruction* destI =  subtreeRoot->getInstruction();
1455         Value* opVal = subtreeRoot->leftChild()->getValue();
1456         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1457         if (opType->isIntegral() || isa<PointerType>(opType))
1458           {
1459             unsigned opSize = target.DataLayout.getTypeSize(opType);
1460             unsigned destSize = target.DataLayout.getTypeSize(destI->getType());
1461             if (opSize > destSize ||
1462                 (opType->isSigned()
1463                  && destSize < target.DataLayout.getIntegerRegize()))
1464               { // operand is larger than dest,
1465                 //    OR both are equal but smaller than the full register size
1466                 //       AND operand is signed, so it may have extra sign bits:
1467                 // mask high bits using AND
1468                 M = Create3OperandInstr(AND, opVal,
1469                                         ConstantUInt::get(Type::ULongTy,
1470                                               ((uint64_t) 1 << 8*destSize) - 1),
1471                                         destI);
1472                 mvec.push_back(M);
1473               }
1474             else
1475               forwardOperandNum = 0;          // forward first operand to user
1476           }
1477         else if (opType->isFloatingPoint())
1478           {
1479             CreateCodeToConvertFloatToInt(target, opVal, destI, mvec,
1480                                          MachineCodeForInstruction::get(destI));
1481             maskUnsignedResult = true;  // not handled by convert code
1482           }
1483         else
1484           assert(0 && "Unrecognized operand type for convert-to-unsigned");
1485
1486         break;
1487       }
1488       
1489       case 24:  // reg:   ToSByteTy(reg)
1490       case 26:  // reg:   ToShortTy(reg)
1491       case 28:  // reg:   ToIntTy(reg)
1492       case 30:  // reg:   ToLongTy(reg)
1493       {
1494         Instruction* destI =  subtreeRoot->getInstruction();
1495         Value* opVal = subtreeRoot->leftChild()->getValue();
1496         MachineCodeForInstruction& mcfi =MachineCodeForInstruction::get(destI);
1497
1498         const Type* opType = opVal->getType();
1499         if (opType->isIntegral() || isa<PointerType>(opType))
1500           {
1501             // These operand types have the same format as the destination,
1502             // but may have different size: add sign bits or mask as needed.
1503             // 
1504             const Type* destType = destI->getType();
1505             unsigned opSize = target.DataLayout.getTypeSize(opType);
1506             unsigned destSize = target.DataLayout.getTypeSize(destType);
1507             
1508             if (opSize < destSize ||
1509                 (opSize == destSize &&
1510                  opSize == target.DataLayout.getIntegerRegize()))
1511               { // operand is smaller or both operand and result fill register
1512                 forwardOperandNum = 0;          // forward first operand to user
1513               }
1514             else
1515               { // need to mask (possibly) and then sign-extend (definitely)
1516                 Value* srcForSignExt = opVal;
1517                 unsigned srcSizeForSignExt = 8 * opSize;
1518                 if (opSize > destSize)
1519                   { // operand is larger than dest: mask high bits
1520                     TmpInstruction *tmpI = new TmpInstruction(destType, opVal,
1521                                                               destI, "maskHi");
1522                     mcfi.addTemp(tmpI);
1523                     M = Create3OperandInstr(AND, opVal,
1524                                             ConstantUInt::get(Type::ULongTy,
1525                                               ((uint64_t) 1 << 8*destSize)-1),
1526                                             tmpI);
1527                     mvec.push_back(M);
1528                     srcForSignExt = tmpI;
1529                     srcSizeForSignExt = 8 * destSize;
1530                   }
1531                 
1532                 // sign-extend
1533                 target.getInstrInfo().CreateSignExtensionInstructions(target, destI->getParent()->getParent(), srcForSignExt, srcSizeForSignExt, destI, mvec, mcfi);
1534               }
1535           }
1536         else if (opType->isFloatingPoint())
1537           CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
1538         else
1539           assert(0 && "Unrecognized operand type for convert-to-signed");
1540
1541         break;
1542       }  
1543
1544       case  31: // reg:   ToFloatTy(reg):
1545       case  32: // reg:   ToDoubleTy(reg):
1546       case 232: // reg:   ToDoubleTy(Constant):
1547       
1548         // If this instruction has a parent (a user) in the tree 
1549         // and the user is translated as an FsMULd instruction,
1550         // then the cast is unnecessary.  So check that first.
1551         // In the future, we'll want to do the same for the FdMULq instruction,
1552         // so do the check here instead of only for ToFloatTy(reg).
1553         // 
1554         if (subtreeRoot->parent() != NULL)
1555           {
1556             const MachineCodeForInstruction& mcfi =
1557               MachineCodeForInstruction::get(
1558                 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
1559             if (mcfi.size() == 0 || mcfi.front()->getOpCode() == FSMULD)
1560               forwardOperandNum = 0;    // forward first operand to user
1561           }
1562
1563         if (forwardOperandNum != 0)     // we do need the cast
1564           {
1565             Value* leftVal = subtreeRoot->leftChild()->getValue();
1566             const Type* opType = leftVal->getType();
1567             MachineOpCode opCode=ChooseConvertToFloatInstr(
1568                                        subtreeRoot->getOpLabel(), opType);
1569             if (opCode == INVALID_OPCODE)       // no conversion needed
1570               {
1571                 forwardOperandNum = 0;      // forward first operand to user
1572               }
1573             else
1574               {
1575                 // If the source operand is a non-FP type it must be
1576                 // first copied from int to float register via memory!
1577                 Instruction *dest = subtreeRoot->getInstruction();
1578                 Value* srcForCast;
1579                 int n = 0;
1580                 if (! opType->isFloatingPoint())
1581                   {
1582                     // Create a temporary to represent the FP register
1583                     // into which the integer will be copied via memory.
1584                     // The type of this temporary will determine the FP
1585                     // register used: single-prec for a 32-bit int or smaller,
1586                     // double-prec for a 64-bit int.
1587                     // 
1588                     uint64_t srcSize =
1589                       target.DataLayout.getTypeSize(leftVal->getType());
1590                     Type* tmpTypeToUse =
1591                       (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1592                     srcForCast = new TmpInstruction(tmpTypeToUse, dest);
1593                     MachineCodeForInstruction &destMCFI = 
1594                       MachineCodeForInstruction::get(dest);
1595                     destMCFI.addTemp(srcForCast);
1596
1597                     target.getInstrInfo().CreateCodeToCopyIntToFloat(target,
1598                          dest->getParent()->getParent(),
1599                          leftVal, cast<Instruction>(srcForCast),
1600                          mvec, destMCFI);
1601                   }
1602                 else
1603                   srcForCast = leftVal;
1604                 
1605                 M = new MachineInstr(opCode);
1606                 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1607                                            srcForCast);
1608                 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,
1609                                            dest);
1610                 mvec.push_back(M);
1611               }
1612           }
1613         break;
1614
1615       case 19:  // reg:   ToArrayTy(reg):
1616       case 20:  // reg:   ToPointerTy(reg):
1617         forwardOperandNum = 0;          // forward first operand to user
1618         break;
1619
1620       case 233: // reg:   Add(reg, Constant)
1621         maskUnsignedResult = true;
1622         M = CreateAddConstInstruction(subtreeRoot);
1623         if (M != NULL)
1624           {
1625             mvec.push_back(M);
1626             break;
1627           }
1628         // ELSE FALL THROUGH
1629         
1630       case 33:  // reg:   Add(reg, reg)
1631         maskUnsignedResult = true;
1632         mvec.push_back(new MachineInstr(ChooseAddInstruction(subtreeRoot)));
1633         Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1634         break;
1635
1636       case 234: // reg:   Sub(reg, Constant)
1637         maskUnsignedResult = true;
1638         M = CreateSubConstInstruction(subtreeRoot);
1639         if (M != NULL)
1640           {
1641             mvec.push_back(M);
1642             break;
1643           }
1644         // ELSE FALL THROUGH
1645         
1646       case 34:  // reg:   Sub(reg, reg)
1647         maskUnsignedResult = true;
1648         mvec.push_back(new MachineInstr(ChooseSubInstructionByType(
1649                                    subtreeRoot->getInstruction()->getType())));
1650         Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1651         break;
1652
1653       case 135: // reg:   Mul(todouble, todouble)
1654         checkCast = true;
1655         // FALL THROUGH 
1656
1657       case 35:  // reg:   Mul(reg, reg)
1658       {
1659         maskUnsignedResult = true;
1660         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
1661                                  ? FSMULD
1662                                  : INVALID_MACHINE_OPCODE);
1663         Instruction* mulInstr = subtreeRoot->getInstruction();
1664         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
1665                              subtreeRoot->leftChild()->getValue(),
1666                              subtreeRoot->rightChild()->getValue(),
1667                              mulInstr, mvec,
1668                              MachineCodeForInstruction::get(mulInstr),forceOp);
1669         break;
1670       }
1671       case 335: // reg:   Mul(todouble, todoubleConst)
1672         checkCast = true;
1673         // FALL THROUGH 
1674
1675       case 235: // reg:   Mul(reg, Constant)
1676       {
1677         maskUnsignedResult = true;
1678         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
1679                                  ? FSMULD
1680                                  : INVALID_MACHINE_OPCODE);
1681         Instruction* mulInstr = subtreeRoot->getInstruction();
1682         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
1683                              subtreeRoot->leftChild()->getValue(),
1684                              subtreeRoot->rightChild()->getValue(),
1685                              mulInstr, mvec,
1686                              MachineCodeForInstruction::get(mulInstr),
1687                              forceOp);
1688         break;
1689       }
1690       case 236: // reg:   Div(reg, Constant)
1691         maskUnsignedResult = true;
1692         L = mvec.size();
1693         CreateDivConstInstruction(target, subtreeRoot, mvec);
1694         if (mvec.size() > L)
1695           break;
1696         // ELSE FALL THROUGH
1697       
1698       case 36:  // reg:   Div(reg, reg)
1699         maskUnsignedResult = true;
1700         mvec.push_back(new MachineInstr(ChooseDivInstruction(target, subtreeRoot)));
1701         Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1702         break;
1703
1704       case  37: // reg:   Rem(reg, reg)
1705       case 237: // reg:   Rem(reg, Constant)
1706       {
1707         maskUnsignedResult = true;
1708         Instruction* remInstr = subtreeRoot->getInstruction();
1709         
1710         TmpInstruction* quot = new TmpInstruction(
1711                                         subtreeRoot->leftChild()->getValue(),
1712                                         subtreeRoot->rightChild()->getValue());
1713         TmpInstruction* prod = new TmpInstruction(
1714                                         quot,
1715                                         subtreeRoot->rightChild()->getValue());
1716         MachineCodeForInstruction::get(remInstr).addTemp(quot).addTemp(prod); 
1717         
1718         M = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1719         Set3OperandsFromInstr(M, subtreeRoot, target);
1720         M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,quot);
1721         mvec.push_back(M);
1722         
1723         M = Create3OperandInstr(ChooseMulInstructionByType(
1724                                    subtreeRoot->getInstruction()->getType()),
1725                                 quot, subtreeRoot->rightChild()->getValue(),
1726                                 prod);
1727         mvec.push_back(M);
1728         
1729         M = new MachineInstr(ChooseSubInstructionByType(
1730                                    subtreeRoot->getInstruction()->getType()));
1731         Set3OperandsFromInstr(M, subtreeRoot, target);
1732         M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,prod);
1733         mvec.push_back(M);
1734         
1735         break;
1736       }
1737       
1738       case  38: // bool:   And(bool, bool)
1739       case 238: // bool:   And(bool, boolconst)
1740       case 338: // reg :   BAnd(reg, reg)
1741       case 538: // reg :   BAnd(reg, Constant)
1742         mvec.push_back(new MachineInstr(AND));
1743         Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1744         break;
1745
1746       case 138: // bool:   And(bool, not)
1747       case 438: // bool:   BAnd(bool, bnot)
1748       { // Use the argument of NOT as the second argument!
1749         // Mark the NOT node so that no code is generated for it.
1750         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
1751         Value* notArg = BinaryOperator::getNotArgument(
1752                            cast<BinaryOperator>(notNode->getInstruction()));
1753         notNode->markFoldedIntoParent();
1754         mvec.push_back(Create3OperandInstr(ANDN,
1755                                            subtreeRoot->leftChild()->getValue(),
1756                                            notArg, subtreeRoot->getValue()));
1757         break;
1758       }
1759
1760       case  39: // bool:   Or(bool, bool)
1761       case 239: // bool:   Or(bool, boolconst)
1762       case 339: // reg :   BOr(reg, reg)
1763       case 539: // reg :   BOr(reg, Constant)
1764         mvec.push_back(new MachineInstr(OR));
1765         Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1766         break;
1767
1768       case 139: // bool:   Or(bool, not)
1769       case 439: // bool:   BOr(bool, bnot)
1770       { // Use the argument of NOT as the second argument!
1771         // Mark the NOT node so that no code is generated for it.
1772         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
1773         Value* notArg = BinaryOperator::getNotArgument(
1774                            cast<BinaryOperator>(notNode->getInstruction()));
1775         notNode->markFoldedIntoParent();
1776         mvec.push_back(Create3OperandInstr(ORN,
1777                                            subtreeRoot->leftChild()->getValue(),
1778                                            notArg, subtreeRoot->getValue()));
1779         break;
1780       }
1781
1782       case  40: // bool:   Xor(bool, bool)
1783       case 240: // bool:   Xor(bool, boolconst)
1784       case 340: // reg :   BXor(reg, reg)
1785       case 540: // reg :   BXor(reg, Constant)
1786         mvec.push_back(new MachineInstr(XOR));
1787         Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1788         break;
1789
1790       case 140: // bool:   Xor(bool, not)
1791       case 440: // bool:   BXor(bool, bnot)
1792       { // Use the argument of NOT as the second argument!
1793         // Mark the NOT node so that no code is generated for it.
1794         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
1795         Value* notArg = BinaryOperator::getNotArgument(
1796                            cast<BinaryOperator>(notNode->getInstruction()));
1797         notNode->markFoldedIntoParent();
1798         mvec.push_back(Create3OperandInstr(XNOR,
1799                                            subtreeRoot->leftChild()->getValue(),
1800                                            notArg, subtreeRoot->getValue()));
1801         break;
1802       }
1803
1804       case 41:  // boolconst:   SetCC(reg, Constant)
1805         // 
1806         // If the SetCC was folded into the user (parent), it will be
1807         // caught above.  All other cases are the same as case 42,
1808         // so just fall through.
1809         // 
1810       case 42:  // bool:   SetCC(reg, reg):
1811       {
1812         // This generates a SUBCC instruction, putting the difference in
1813         // a result register, and setting a condition code.
1814         // 
1815         // If the boolean result of the SetCC is used by anything other
1816         // than a branch instruction, or if it is used outside the current
1817         // basic block, the boolean must be
1818         // computed and stored in the result register.  Otherwise, discard
1819         // the difference (by using %g0) and keep only the condition code.
1820         // 
1821         // To compute the boolean result in a register we use a conditional
1822         // move, unless the result of the SUBCC instruction can be used as
1823         // the bool!  This assumes that zero is FALSE and any non-zero
1824         // integer is TRUE.
1825         // 
1826         InstructionNode* parentNode = (InstructionNode*) subtreeRoot->parent();
1827         Instruction* setCCInstr = subtreeRoot->getInstruction();
1828         
1829         bool keepBoolVal = parentNode == NULL ||
1830                            ! AllUsesAreBranches(setCCInstr);
1831         bool subValIsBoolVal = setCCInstr->getOpcode() == Instruction::SetNE;
1832         bool keepSubVal = keepBoolVal && subValIsBoolVal;
1833         bool computeBoolVal = keepBoolVal && ! subValIsBoolVal;
1834         
1835         bool mustClearReg;
1836         int valueToMove;
1837         MachineOpCode movOpCode = 0;
1838         
1839         // Mark the 4th operand as being a CC register, and as a def
1840         // A TmpInstruction is created to represent the CC "result".
1841         // Unlike other instances of TmpInstruction, this one is used
1842         // by machine code of multiple LLVM instructions, viz.,
1843         // the SetCC and the branch.  Make sure to get the same one!
1844         // Note that we do this even for FP CC registers even though they
1845         // are explicit operands, because the type of the operand
1846         // needs to be a floating point condition code, not an integer
1847         // condition code.  Think of this as casting the bool result to
1848         // a FP condition code register.
1849         // 
1850         Value* leftVal = subtreeRoot->leftChild()->getValue();
1851         bool isFPCompare = leftVal->getType()->isFloatingPoint();
1852         
1853         TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
1854                                      setCCInstr->getParent()->getParent(),
1855                                      isFPCompare ? Type::FloatTy : Type::IntTy);
1856         MachineCodeForInstruction::get(setCCInstr).addTemp(tmpForCC);
1857         
1858         if (! isFPCompare)
1859           {
1860             // Integer condition: dest. should be %g0 or an integer register.
1861             // If result must be saved but condition is not SetEQ then we need
1862             // a separate instruction to compute the bool result, so discard
1863             // result of SUBcc instruction anyway.
1864             // 
1865             M = new MachineInstr(SUBcc);
1866             Set3OperandsFromInstr(M, subtreeRoot, target, ! keepSubVal);
1867             M->SetMachineOperandVal(3, MachineOperand::MO_CCRegister,
1868                                     tmpForCC, /*def*/true);
1869             mvec.push_back(M);
1870             
1871             if (computeBoolVal)
1872               { // recompute bool using the integer condition codes
1873                 movOpCode =
1874                   ChooseMovpccAfterSub(subtreeRoot,mustClearReg,valueToMove);
1875               }
1876           }
1877         else
1878           {
1879             // FP condition: dest of FCMP should be some FCCn register
1880             M = new MachineInstr(ChooseFcmpInstruction(subtreeRoot));
1881             M->SetMachineOperandVal(0, MachineOperand::MO_CCRegister,
1882                                           tmpForCC);
1883             M->SetMachineOperandVal(1,MachineOperand::MO_VirtualRegister,
1884                                          subtreeRoot->leftChild()->getValue());
1885             M->SetMachineOperandVal(2,MachineOperand::MO_VirtualRegister,
1886                                         subtreeRoot->rightChild()->getValue());
1887             mvec.push_back(M);
1888             
1889             if (computeBoolVal)
1890               {// recompute bool using the FP condition codes
1891                 mustClearReg = true;
1892                 valueToMove = 1;
1893                 movOpCode = ChooseMovFpccInstruction(subtreeRoot);
1894               }
1895           }
1896         
1897         if (computeBoolVal)
1898           {
1899             if (mustClearReg)
1900               {// Unconditionally set register to 0
1901                 M = new MachineInstr(SETHI);
1902                 M->SetMachineOperandConst(0,MachineOperand::MO_UnextendedImmed,
1903                                           (int64_t)0);
1904                 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,
1905                                         setCCInstr);
1906                 mvec.push_back(M);
1907               }
1908             
1909             // Now conditionally move `valueToMove' (0 or 1) into the register
1910             // Mark the register as a use (as well as a def) because the old
1911             // value should be retained if the condition is false.
1912             M = new MachineInstr(movOpCode);
1913             M->SetMachineOperandVal(0, MachineOperand::MO_CCRegister,
1914                                     tmpForCC);
1915             M->SetMachineOperandConst(1, MachineOperand::MO_UnextendedImmed,
1916                                       valueToMove);
1917             M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
1918                                     setCCInstr, /*isDef*/ true,
1919                                     /*isDefAndUse*/ true);
1920             mvec.push_back(M);
1921           }
1922         break;
1923       }    
1924
1925       case 51:  // reg:   Load(reg)
1926       case 52:  // reg:   Load(ptrreg)
1927         mvec.push_back(new MachineInstr(ChooseLoadInstruction(
1928                                      subtreeRoot->getValue()->getType())));
1929         SetOperandsForMemInstr(mvec, subtreeRoot, target);
1930         break;
1931
1932       case 55:  // reg:   GetElemPtr(reg)
1933       case 56:  // reg:   GetElemPtrIdx(reg,reg)
1934         // If the GetElemPtr was folded into the user (parent), it will be
1935         // caught above.  For other cases, we have to compute the address.
1936         mvec.push_back(new MachineInstr(ADD));
1937         SetOperandsForMemInstr(mvec, subtreeRoot, target);
1938         break;
1939         
1940       case 57:  // reg:  Alloca: Implement as 1 instruction:
1941       {         //          add %fp, offsetFromFP -> result
1942         AllocationInst* instr =
1943           cast<AllocationInst>(subtreeRoot->getInstruction());
1944         unsigned int tsize =
1945           target.findOptimalStorageSize(instr->getAllocatedType());
1946         assert(tsize != 0);
1947         CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
1948         break;
1949       }
1950       
1951       case 58:  // reg:   Alloca(reg): Implement as 3 instructions:
1952                 //      mul num, typeSz -> tmp
1953                 //      sub %sp, tmp    -> %sp
1954       {         //      add %sp, frameSizeBelowDynamicArea -> result
1955         AllocationInst* instr =
1956           cast<AllocationInst>(subtreeRoot->getInstruction());
1957         const Type* eltType = instr->getAllocatedType();
1958         
1959         // If #elements is constant, use simpler code for fixed-size allocas
1960         int tsize = (int) target.findOptimalStorageSize(eltType);
1961         Value* numElementsVal = NULL;
1962         bool isArray = instr->isArrayAllocation();
1963         
1964         if (!isArray ||
1965             isa<Constant>(numElementsVal = instr->getArraySize()))
1966           { // total size is constant: generate code for fixed-size alloca
1967             unsigned int numElements = isArray? 
1968               cast<ConstantUInt>(numElementsVal)->getValue() : 1;
1969             CreateCodeForFixedSizeAlloca(target, instr, tsize,
1970                                          numElements, mvec);
1971           }
1972         else // total size is not constant.
1973           CreateCodeForVariableSizeAlloca(target, instr, tsize,
1974                                           numElementsVal, mvec);
1975         break;
1976       }
1977       
1978       case 61:  // reg:   Call
1979       {         // Generate a direct (CALL) or indirect (JMPL). depending
1980                 // Mark the return-address register and the indirection
1981                 // register (if any) as hidden virtual registers.
1982                 // Also, mark the operands of the Call and return value (if
1983                 // any) as implicit operands of the CALL machine instruction.
1984                 // 
1985                 // If this is a varargs function, floating point arguments
1986                 // have to passed in integer registers so insert
1987                 // copy-float-to-int instructions for each float operand.
1988                 // 
1989         CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
1990         Value *callee = callInstr->getCalledValue();
1991         
1992         // Create hidden virtual register for return address, with type void*. 
1993         TmpInstruction* retAddrReg =
1994           new TmpInstruction(PointerType::get(Type::VoidTy), callInstr);
1995         MachineCodeForInstruction::get(callInstr).addTemp(retAddrReg);
1996         
1997         // Generate the machine instruction and its operands.
1998         // Use CALL for direct function calls; this optimistically assumes
1999         // the PC-relative address fits in the CALL address field (22 bits).
2000         // Use JMPL for indirect calls.
2001         // 
2002         if (isa<Function>(callee))
2003           { // direct function call
2004             M = new MachineInstr(CALL);
2005             M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
2006                                     callee);
2007           } 
2008         else
2009           { // indirect function call
2010             M = new MachineInstr(JMPLCALL);
2011             M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
2012                                     callee);
2013             M->SetMachineOperandConst(1, MachineOperand::MO_SignExtendedImmed,
2014                                       (int64_t) 0);
2015             M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
2016                                     retAddrReg);
2017           }
2018         
2019         mvec.push_back(M);
2020
2021         const FunctionType* funcType =
2022           cast<FunctionType>(cast<PointerType>(callee->getType())
2023                              ->getElementType());
2024         bool isVarArgs = funcType->isVarArg();
2025         bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
2026         
2027         // Use an annotation to pass information about call arguments
2028         // to the register allocator.
2029         CallArgsDescriptor* argDesc = new CallArgsDescriptor(callInstr,
2030                                          retAddrReg, isVarArgs, noPrototype);
2031         M->addAnnotation(argDesc);
2032         
2033         assert(callInstr->getOperand(0) == callee
2034                && "This is assumed in the loop below!");
2035         
2036         for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i)
2037           {
2038             Value* argVal = callInstr->getOperand(i);
2039             Instruction* intArgReg = NULL;
2040             
2041             // Check for FP arguments to varargs functions.
2042             // Any such argument in the first $K$ args must be passed in an
2043             // integer register, where K = #integer argument registers.
2044             if (isVarArgs && argVal->getType()->isFloatingPoint())
2045               {
2046                 // If it is a function with no prototype, pass value
2047                 // as an FP value as well as a varargs value
2048                 if (noPrototype)
2049                   argDesc->getArgInfo(i-1).setUseFPArgReg();
2050                 
2051                 // If this arg. is in the first $K$ regs, add a copy
2052                 // float-to-int instruction to pass the value as an integer.
2053                 if (i < target.getRegInfo().GetNumOfIntArgRegs())
2054                   {
2055                     MachineCodeForInstruction &destMCFI = 
2056                       MachineCodeForInstruction::get(callInstr);   
2057                     intArgReg = new TmpInstruction(Type::IntTy, argVal);
2058                     destMCFI.addTemp(intArgReg);
2059                     
2060                     vector<MachineInstr*> copyMvec;
2061                     target.getInstrInfo().CreateCodeToCopyFloatToInt(target,
2062                                            callInstr->getParent()->getParent(),
2063                                            argVal, (TmpInstruction*) intArgReg,
2064                                            copyMvec, destMCFI);
2065                     mvec.insert(mvec.begin(),copyMvec.begin(),copyMvec.end());
2066                     
2067                     argDesc->getArgInfo(i-1).setUseIntArgReg();
2068                     argDesc->getArgInfo(i-1).setArgCopy(intArgReg);
2069                   }
2070                 else
2071                   // Cannot fit in first $K$ regs so pass the arg on the stack
2072                   argDesc->getArgInfo(i-1).setUseStackSlot();
2073               }
2074             
2075             if (intArgReg)
2076               mvec.back()->addImplicitRef(intArgReg);
2077             
2078             mvec.back()->addImplicitRef(argVal);
2079           }
2080         
2081         // Add the return value as an implicit ref.  The call operands
2082         // were added above.
2083         if (callInstr->getType() != Type::VoidTy)
2084           mvec.back()->addImplicitRef(callInstr, /*isDef*/ true);
2085         
2086         // For the CALL instruction, the ret. addr. reg. is also implicit
2087         if (isa<Function>(callee))
2088           mvec.back()->addImplicitRef(retAddrReg, /*isDef*/ true);
2089         
2090         // delay slot
2091         mvec.push_back(new MachineInstr(NOP));
2092         break;
2093       }
2094       
2095       case 62:  // reg:   Shl(reg, reg)
2096       {
2097         Value* argVal1 = subtreeRoot->leftChild()->getValue();
2098         Value* argVal2 = subtreeRoot->rightChild()->getValue();
2099         Instruction* shlInstr = subtreeRoot->getInstruction();
2100         
2101         const Type* opType = argVal1->getType();
2102         assert((opType->isInteger() || isa<PointerType>(opType)) &&
2103                "Shl unsupported for other types");
2104         
2105         CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
2106                                 (opType == Type::LongTy)? SLLX : SLL,
2107                                 argVal1, argVal2, 0, shlInstr, mvec,
2108                                 MachineCodeForInstruction::get(shlInstr));
2109         break;
2110       }
2111       
2112       case 63:  // reg:   Shr(reg, reg)
2113       { const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2114         assert((opType->isInteger() || isa<PointerType>(opType)) &&
2115                "Shr unsupported for other types");
2116         mvec.push_back(new MachineInstr((opType->isSigned()
2117                                    ? ((opType == Type::LongTy)? SRAX : SRA)
2118                                    : ((opType == Type::LongTy)? SRLX : SRL))));
2119         Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
2120         break;
2121       }
2122       
2123       case 64:  // reg:   Phi(reg,reg)
2124         break;                          // don't forward the value
2125
2126       case 71:  // reg:     VReg
2127       case 72:  // reg:     Constant
2128         break;                          // don't forward the value
2129
2130       default:
2131         assert(0 && "Unrecognized BURG rule");
2132         break;
2133       }
2134     }
2135
2136   if (forwardOperandNum >= 0)
2137     { // We did not generate a machine instruction but need to use operand.
2138       // If user is in the same tree, replace Value in its machine operand.
2139       // If not, insert a copy instruction which should get coalesced away
2140       // by register allocation.
2141       if (subtreeRoot->parent() != NULL)
2142         ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2143       else
2144         {
2145           vector<MachineInstr*> minstrVec;
2146           Instruction* instr = subtreeRoot->getInstruction();
2147           target.getInstrInfo().
2148             CreateCopyInstructionsByType(target,
2149                                          instr->getParent()->getParent(),
2150                                          instr->getOperand(forwardOperandNum),
2151                                          instr, minstrVec,
2152                                         MachineCodeForInstruction::get(instr));
2153           assert(minstrVec.size() > 0);
2154           mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
2155         }
2156     }
2157
2158   if (maskUnsignedResult)
2159     { // If result is unsigned and smaller than int reg size,
2160       // we need to clear high bits of result value.
2161       assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
2162       Instruction* dest = subtreeRoot->getInstruction();
2163       if (dest->getType()->isUnsigned())
2164         {
2165           unsigned destSize = target.DataLayout.getTypeSize(dest->getType());
2166           if (destSize <= 4)
2167             { // Mask high bits.  Use a TmpInstruction to represent the
2168               // intermediate result before masking.  Since those instructions
2169               // have already been generated, go back and substitute tmpI
2170               // for dest in the result position of each one of them.
2171               TmpInstruction *tmpI = new TmpInstruction(dest->getType(), dest,
2172                                                         NULL, "maskHi");
2173               MachineCodeForInstruction::get(dest).addTemp(tmpI);
2174
2175               for (unsigned i=0, N=mvec.size(); i < N; ++i)
2176                 mvec[i]->substituteValue(dest, tmpI);
2177
2178               M = Create3OperandInstr_UImmed(SRL, tmpI, 4-destSize, dest);
2179               mvec.push_back(M);
2180             }
2181           else if (destSize < target.DataLayout.getIntegerRegize())
2182             assert(0 && "Unsupported type size: 32 < size < 64 bits");
2183         }
2184     }
2185 }