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