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