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