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