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