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