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