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