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