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