Add support for undef and unreachable
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9BurgISel.cpp
1 //===- SparcV9BurgISel.cpp - SparcV9 BURG-based Instruction Selector ------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // SparcV9 BURG-based instruction selector. It uses the SSA graph to
11 // construct a forest of BURG instruction trees (class InstrForest) and then
12 // uses the BURG-generated tree grammar (BURM) to find the optimal instruction
13 // sequences for the SparcV9.
14 //      
15 //===----------------------------------------------------------------------===//
16
17 #include "MachineInstrAnnot.h"
18 #include "SparcV9BurgISel.h"
19 #include "SparcV9InstrForest.h"
20 #include "SparcV9Internals.h"
21 #include "SparcV9TmpInstr.h"
22 #include "SparcV9FrameInfo.h"
23 #include "SparcV9RegisterInfo.h"
24 #include "MachineFunctionInfo.h"
25 #include "llvm/CodeGen/IntrinsicLowering.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/Constants.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Module.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Type.h"
40 #include "llvm/Config/alloca.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/LeakDetector.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/hash_map"
46 #include <algorithm>
47 #include <cmath>
48 #include <iostream>
49 using namespace llvm;
50
51 //==------------------------------------------------------------------------==//
52 //          InstrForest (V9ISel BURG instruction trees) implementation
53 //==------------------------------------------------------------------------==//
54
55 namespace llvm {
56
57 class InstructionNode : public InstrTreeNode {
58   bool codeIsFoldedIntoParent;
59   
60 public:
61   InstructionNode(Instruction *_instr);
62
63   Instruction *getInstruction() const {
64     assert(treeNodeType == NTInstructionNode);
65     return cast<Instruction>(val);
66   }
67
68   void markFoldedIntoParent() { codeIsFoldedIntoParent = true; }
69   bool isFoldedIntoParent()   { return codeIsFoldedIntoParent; }
70
71   // Methods to support type inquiry through isa, cast, and dyn_cast:
72   static inline bool classof(const InstructionNode *N) { return true; }
73   static inline bool classof(const InstrTreeNode *N) {
74     return N->getNodeType() == InstrTreeNode::NTInstructionNode;
75   }
76   
77 protected:
78   virtual void dumpNode(int indent) const;
79 };
80
81 class VRegListNode : public InstrTreeNode {
82 public:
83   VRegListNode() : InstrTreeNode(NTVRegListNode, 0) { opLabel = VRegListOp; }
84   // Methods to support type inquiry through isa, cast, and dyn_cast:
85   static inline bool classof(const VRegListNode  *N) { return true; }
86   static inline bool classof(const InstrTreeNode *N) {
87     return N->getNodeType() == InstrTreeNode::NTVRegListNode;
88   }
89 protected:
90   virtual void dumpNode(int indent) const;
91 };
92
93 class VRegNode : public InstrTreeNode {
94 public:
95   VRegNode(Value* _val) : InstrTreeNode(NTVRegNode, _val) {
96     opLabel = VRegNodeOp;
97   }
98   // Methods to support type inquiry through isa, cast, and dyn_cast:
99   static inline bool classof(const VRegNode  *N) { return true; }
100   static inline bool classof(const InstrTreeNode *N) {
101     return N->getNodeType() == InstrTreeNode::NTVRegNode;
102   }
103 protected:
104   virtual void dumpNode(int indent) const;
105 };
106
107 class ConstantNode : public InstrTreeNode {
108 public:
109   ConstantNode(Constant *constVal) 
110     : InstrTreeNode(NTConstNode, (Value*)constVal) {
111     opLabel = ConstantNodeOp;    
112   }
113   Constant *getConstVal() const { return (Constant*) val;}
114   // Methods to support type inquiry through isa, cast, and dyn_cast:
115   static inline bool classof(const ConstantNode  *N) { return true; }
116   static inline bool classof(const InstrTreeNode *N) {
117     return N->getNodeType() == InstrTreeNode::NTConstNode;
118   }
119 protected:
120   virtual void dumpNode(int indent) const;
121 };
122
123 class LabelNode : public InstrTreeNode {
124 public:
125   LabelNode(BasicBlock* BB) : InstrTreeNode(NTLabelNode, (Value*)BB) {
126     opLabel = LabelNodeOp;
127   }
128   BasicBlock *getBasicBlock() const { return (BasicBlock*)val;}
129   // Methods to support type inquiry through isa, cast, and dyn_cast:
130   static inline bool classof(const LabelNode     *N) { return true; }
131   static inline bool classof(const InstrTreeNode *N) {
132     return N->getNodeType() == InstrTreeNode::NTLabelNode;
133   }
134 protected:
135   virtual void dumpNode(int indent) const;
136 };
137
138 /// InstrForest -  A forest of instruction trees for a single function.
139 /// The goal of InstrForest is to group instructions into a single
140 /// tree if one or more of them might be potentially combined into a
141 /// single complex instruction in the target machine. We group two
142 /// instructions O and I if: (1) Instruction O computes an operand used
143 /// by instruction I, and (2) O and I are part of the same basic block,
144 /// and (3) O has only a single use, viz., I.
145 /// 
146 class InstrForest : private hash_map<const Instruction *, InstructionNode*> {
147 public:
148   // Use a vector for the root set to get a deterministic iterator
149   // for stable code generation.  Even though we need to erase nodes
150   // during forest construction, a vector should still be efficient
151   // because the elements to erase are nearly always near the end.
152   typedef std::vector<InstructionNode*> RootSet;
153   typedef RootSet::      iterator       root_iterator;
154   typedef RootSet::const_iterator const_root_iterator;
155   
156 private:
157   RootSet treeRoots;
158   
159 public:
160   /*ctor*/      InstrForest     (Function *F);
161   /*dtor*/      ~InstrForest    ();
162   
163   /// getTreeNodeForInstr - Returns the tree node for an Instruction.
164   ///
165   inline InstructionNode *getTreeNodeForInstr(Instruction* instr) {
166     return (*this)[instr];
167   }
168   
169   /// Iterators for the root nodes for all the trees.
170   ///
171   const_root_iterator roots_begin() const     { return treeRoots.begin(); }
172         root_iterator roots_begin()           { return treeRoots.begin(); }
173   const_root_iterator roots_end  () const     { return treeRoots.end();   }
174         root_iterator roots_end  ()           { return treeRoots.end();   }
175   
176   void dump() const;
177   
178 private:
179   // Methods used to build the instruction forest.
180   void eraseRoot    (InstructionNode* node);
181   void setLeftChild (InstrTreeNode* parent, InstrTreeNode* child);
182   void setRightChild(InstrTreeNode* parent, InstrTreeNode* child);
183   void setParent    (InstrTreeNode* child,  InstrTreeNode* parent);
184   void noteTreeNodeForInstr(Instruction* instr, InstructionNode* treeNode);
185   InstructionNode* buildTreeForInstruction(Instruction* instr);
186 };
187
188 void InstrTreeNode::dump(int dumpChildren, int indent) const {
189   dumpNode(indent);
190   
191   if (dumpChildren) {
192     if (LeftChild)
193       LeftChild->dump(dumpChildren, indent+1);
194     if (RightChild)
195       RightChild->dump(dumpChildren, indent+1);
196   }
197 }
198
199 InstructionNode::InstructionNode(Instruction* I)
200   : InstrTreeNode(NTInstructionNode, I), codeIsFoldedIntoParent(false) {
201   opLabel = I->getOpcode();
202
203   // Distinguish special cases of some instructions such as Ret and Br
204   // 
205   if (opLabel == Instruction::Ret && cast<ReturnInst>(I)->getReturnValue()) {
206     opLabel = RetValueOp;                // ret(value) operation
207   }
208   else if (opLabel ==Instruction::Br && !cast<BranchInst>(I)->isUnconditional())
209   {
210     opLabel = BrCondOp;         // br(cond) operation
211   } else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT) {
212     opLabel = SetCCOp;          // common label for all SetCC ops
213   } else if (opLabel == Instruction::Alloca && I->getNumOperands() > 0) {
214     opLabel = AllocaN;           // Alloca(ptr, N) operation
215   } else if (opLabel == Instruction::GetElementPtr &&
216              cast<GetElementPtrInst>(I)->hasIndices()) {
217     opLabel = opLabel + 100;             // getElem with index vector
218   } else if (opLabel == Instruction::Xor &&
219              BinaryOperator::isNot(I)) {
220     opLabel = (I->getType() == Type::BoolTy)?  NotOp  // boolean Not operator
221       : BNotOp; // bitwise Not operator
222   } else if (opLabel == Instruction::And || opLabel == Instruction::Or ||
223              opLabel == Instruction::Xor) {
224     // Distinguish bitwise operators from logical operators!
225     if (I->getType() != Type::BoolTy)
226       opLabel = opLabel + 100;   // bitwise operator
227   } else if (opLabel == Instruction::Cast) {
228     const Type *ITy = I->getType();
229     switch(ITy->getTypeID())
230     {
231     case Type::BoolTyID:    opLabel = ToBoolTy;    break;
232     case Type::UByteTyID:   opLabel = ToUByteTy;   break;
233     case Type::SByteTyID:   opLabel = ToSByteTy;   break;
234     case Type::UShortTyID:  opLabel = ToUShortTy;  break;
235     case Type::ShortTyID:   opLabel = ToShortTy;   break;
236     case Type::UIntTyID:    opLabel = ToUIntTy;    break;
237     case Type::IntTyID:     opLabel = ToIntTy;     break;
238     case Type::ULongTyID:   opLabel = ToULongTy;   break;
239     case Type::LongTyID:    opLabel = ToLongTy;    break;
240     case Type::FloatTyID:   opLabel = ToFloatTy;   break;
241     case Type::DoubleTyID:  opLabel = ToDoubleTy;  break;
242     case Type::ArrayTyID:   opLabel = ToArrayTy;   break;
243     case Type::PointerTyID: opLabel = ToPointerTy; break;
244     default:
245       // Just use `Cast' opcode otherwise. It's probably ignored.
246       break;
247     }
248   }
249 }
250
251 void InstructionNode::dumpNode(int indent) const {
252   for (int i=0; i < indent; i++)
253     std::cerr << "    ";
254   std::cerr << getInstruction()->getOpcodeName()
255             << " [label " << getOpLabel() << "]" << "\n";
256 }
257
258 void VRegListNode::dumpNode(int indent) const {
259   for (int i=0; i < indent; i++)
260     std::cerr << "    ";
261   
262   std::cerr << "List" << "\n";
263 }
264
265 void VRegNode::dumpNode(int indent) const {
266   for (int i=0; i < indent; i++)
267     std::cerr << "    ";
268     std::cerr << "VReg " << *getValue() << "\n";
269 }
270
271 void ConstantNode::dumpNode(int indent) const {
272   for (int i=0; i < indent; i++)
273     std::cerr << "    ";
274   std::cerr << "Constant " << *getValue() << "\n";
275 }
276
277 void LabelNode::dumpNode(int indent) const {
278   for (int i=0; i < indent; i++)
279     std::cerr << "    ";
280   
281   std::cerr << "Label " << *getValue() << "\n";
282 }
283
284 /// InstrForest ctor - Create a forest of instruction trees for a
285 /// single function.
286 ///
287 InstrForest::InstrForest(Function *F) {
288   for (Function::iterator BB = F->begin(), FE = F->end(); BB != FE; ++BB) {
289     for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
290       buildTreeForInstruction(I);
291   }
292 }
293
294 InstrForest::~InstrForest() {
295   for_each(treeRoots.begin(), treeRoots.end(), deleter<InstructionNode>);
296 }
297
298 void InstrForest::dump() const {
299   for (const_root_iterator I = roots_begin(); I != roots_end(); ++I)
300     (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
301 }
302
303 inline void InstrForest::eraseRoot(InstructionNode* node) {
304   for (RootSet::reverse_iterator RI=treeRoots.rbegin(), RE=treeRoots.rend();
305        RI != RE; ++RI)
306     if (*RI == node)
307       treeRoots.erase(RI.base()-1);
308 }
309
310 inline void InstrForest::noteTreeNodeForInstr(Instruction *instr,
311                                               InstructionNode *treeNode) {
312   (*this)[instr] = treeNode;
313   treeRoots.push_back(treeNode);        // mark node as root of a new tree
314 }
315
316 inline void InstrForest::setLeftChild(InstrTreeNode *parent,
317                                       InstrTreeNode *child) {
318   parent->LeftChild = child;
319   child->Parent = parent;
320   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
321     eraseRoot(instrNode); // no longer a tree root
322 }
323
324 inline void InstrForest::setRightChild(InstrTreeNode *parent,
325                                        InstrTreeNode *child) {
326   parent->RightChild = child;
327   child->Parent = parent;
328   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
329     eraseRoot(instrNode); // no longer a tree root
330 }
331
332 InstructionNode* InstrForest::buildTreeForInstruction(Instruction *instr) {
333   InstructionNode *treeNode = getTreeNodeForInstr(instr);
334   if (treeNode) {
335     // treeNode has already been constructed for this instruction
336     assert(treeNode->getInstruction() == instr);
337     return treeNode;
338   }
339   
340   // Otherwise, create a new tree node for this instruction.
341   treeNode = new InstructionNode(instr);
342   noteTreeNodeForInstr(instr, treeNode);
343   
344   if (instr->getOpcode() == Instruction::Call) {
345     // Operands of call instruction
346     return treeNode;
347   }
348   
349   // If the instruction has more than 2 instruction operands,
350   // then we need to create artificial list nodes to hold them.
351   // (Note that we only count operands that get tree nodes, and not
352   // others such as branch labels for a branch or switch instruction.)
353   // To do this efficiently, we'll walk all operands, build treeNodes
354   // for all appropriate operands and save them in an array.  We then
355   // insert children at the end, creating list nodes where needed.
356   // As a performance optimization, allocate a child array only
357   // if a fixed array is too small.
358   int numChildren = 0;
359   InstrTreeNode** childArray = new InstrTreeNode*[instr->getNumOperands()];
360   
361   // Walk the operands of the instruction
362   for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end();
363        ++O) {
364       Value* operand = *O;
365       
366       // Check if the operand is a data value, not an branch label, type,
367       // method or module.  If the operand is an address type (i.e., label
368       // or method) that is used in an non-branching operation, e.g., `add'.
369       // that should be considered a data value.
370       // Check latter condition here just to simplify the next IF.
371       bool includeAddressOperand =
372         (isa<BasicBlock>(operand) || isa<Function>(operand))
373         && !instr->isTerminator();
374     
375       if (includeAddressOperand || isa<Instruction>(operand) ||
376           isa<Constant>(operand) || isa<Argument>(operand)) {
377         // This operand is a data value.
378         // An instruction that computes the incoming value is added as a
379         // child of the current instruction if:
380         //   the value has only a single use
381         //   AND both instructions are in the same basic block.
382         //   AND the current instruction is not a PHI (because the incoming
383         //              value is conceptually in a predecessor block,
384         //              even though it may be in the same static block)
385         // (Note that if the value has only a single use (viz., `instr'),
386         //  the def of the value can be safely moved just before instr
387         //  and therefore it is safe to combine these two instructions.)
388         // In all other cases, the virtual register holding the value
389         // is used directly, i.e., made a child of the instruction node.
390         InstrTreeNode* opTreeNode;
391         if (isa<Instruction>(operand) && operand->hasOneUse() &&
392             cast<Instruction>(operand)->getParent() == instr->getParent() &&
393             instr->getOpcode() != Instruction::PHI &&
394             instr->getOpcode() != Instruction::Call) {
395           // Recursively create a treeNode for it.
396           opTreeNode = buildTreeForInstruction((Instruction*)operand);
397         } else if (Constant *CPV = dyn_cast<Constant>(operand)) {
398           if (isa<GlobalValue>(CPV))
399             opTreeNode = new VRegNode(operand);
400           else if (isa<UndefValue>(CPV)) {
401             opTreeNode = new
402                ConstantNode(Constant::getNullValue(CPV->getType()));
403           } else {
404             // Create a leaf node for a constant
405             opTreeNode = new ConstantNode(CPV);
406           }
407         } else {
408           // Create a leaf node for the virtual register
409           opTreeNode = new VRegNode(operand);
410         }
411
412         childArray[numChildren++] = opTreeNode;
413       }
414     }
415   
416   // Add any selected operands as children in the tree.
417   // Certain instructions can have more than 2 in some instances (viz.,
418   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
419   // array or struct). Make the operands of every such instruction into
420   // a right-leaning binary tree with the operand nodes at the leaves
421   // and VRegList nodes as internal nodes.
422   InstrTreeNode *parent = treeNode;
423   
424   if (numChildren > 2) {
425     unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
426     assert(instrOpcode == Instruction::PHI ||
427            instrOpcode == Instruction::Call ||
428            instrOpcode == Instruction::Load ||
429            instrOpcode == Instruction::Store ||
430            instrOpcode == Instruction::GetElementPtr);
431   }
432   
433   // Insert the first child as a direct child
434   if (numChildren >= 1)
435     setLeftChild(parent, childArray[0]);
436
437   int n;
438   
439   // Create a list node for children 2 .. N-1, if any
440   for (n = numChildren-1; n >= 2; n--) {
441     // We have more than two children
442     InstrTreeNode *listNode = new VRegListNode();
443     setRightChild(parent, listNode);
444     setLeftChild(listNode, childArray[numChildren - n]);
445     parent = listNode;
446   }
447   
448   // Now insert the last remaining child (if any).
449   if (numChildren >= 2) {
450     assert(n == 1);
451     setRightChild(parent, childArray[numChildren - 1]);
452   }
453
454   delete [] childArray;
455   return treeNode;
456 }
457 //==------------------------------------------------------------------------==//
458 //                V9ISel Command-line options and declarations
459 //==------------------------------------------------------------------------==//
460
461 namespace {
462   /// Allow the user to select the amount of debugging information printed
463   /// out by V9ISel.
464   ///
465   enum SelectDebugLevel_t {
466     Select_NoDebugInfo,
467     Select_PrintMachineCode, 
468     Select_DebugInstTrees, 
469     Select_DebugBurgTrees,
470   };
471   cl::opt<SelectDebugLevel_t>
472   SelectDebugLevel("dselect", cl::Hidden,
473                    cl::desc("enable instruction selection debug information"),
474                    cl::values(
475      clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
476      clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
477      clEnumValN(Select_DebugInstTrees,   "i",
478                 "print debugging info for instruction selection"),
479      clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"),
480                               clEnumValEnd));
481
482
483   /// V9ISel - This is the FunctionPass that drives the instruction selection
484   /// process on the SparcV9 target.
485   ///
486   class V9ISel : public FunctionPass {
487     TargetMachine &Target;
488     void InsertCodeForPhis(Function &F);
489     void InsertPhiElimInstructions(BasicBlock *BB,
490                                    const std::vector<MachineInstr*>& CpVec);
491     void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
492     void PostprocessMachineCodeForTree(InstructionNode* instrNode,
493                                        int ruleForNode, short* nts);
494   public:
495     V9ISel(TargetMachine &TM) : Target(TM) {}
496
497     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
498       AU.setPreservesCFG();
499     }
500     
501     bool runOnFunction(Function &F);
502     virtual const char *getPassName() const {
503       return "SparcV9 BURG Instruction Selector";
504     }
505   };
506 }
507
508
509 //==------------------------------------------------------------------------==//
510 //                     Various V9ISel helper functions
511 //==------------------------------------------------------------------------==//
512
513 static const uint32_t MAXLO   = (1 << 10) - 1; // set bits set by %lo(*)
514 static const uint32_t MAXSIMM = (1 << 12) - 1; // set bits in simm13 field of OR
515
516 /// ConvertConstantToIntType - Function to get the value of an integral
517 /// constant in the form that must be put into the machine register.  The
518 /// specified constant is interpreted as (i.e., converted if necessary to) the
519 /// specified destination type.  The result is always returned as an uint64_t,
520 /// since the representation of int64_t and uint64_t are identical.  The
521 /// argument can be any known const.  isValidConstant is set to true if a valid
522 /// constant was found.
523 /// 
524 uint64_t ConvertConstantToIntType(const TargetMachine &target, const Value *V,
525                                   const Type *destType, bool &isValidConstant) {
526   isValidConstant = false;
527   uint64_t C = 0;
528
529   if (! destType->isIntegral() && ! isa<PointerType>(destType))
530     return C;
531
532   if (! isa<Constant>(V) || isa<GlobalValue>(V))
533     return C;
534
535   // GlobalValue: no conversions needed: get value and return it
536   if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
537     isValidConstant = true;             // may be overwritten by recursive call
538     return ConvertConstantToIntType(target, GV, destType, isValidConstant);
539   }
540
541   // ConstantBool: no conversions needed: get value and return it
542   if (const ConstantBool *CB = dyn_cast<ConstantBool>(V)) {
543     isValidConstant = true;
544     return (uint64_t) CB->getValue();
545   }
546
547   // ConstantPointerNull: it's really just a big, shiny version of zero.
548   if (isa<ConstantPointerNull>(V)) {
549     isValidConstant = true;
550     return 0;
551   }
552
553   // For other types of constants, some conversion may be needed.
554   // First, extract the constant operand according to its own type
555   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
556     switch(CE->getOpcode()) {
557     case Instruction::Cast:             // recursively get the value as cast
558       C = ConvertConstantToIntType(target, CE->getOperand(0), CE->getType(),
559                                    isValidConstant);
560       break;
561     default:                            // not simplifying other ConstantExprs
562       break;
563     }
564   else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
565     isValidConstant = true;
566     C = CI->getRawValue();
567   } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
568     isValidConstant = true;
569     double fC = CFP->getValue();
570     C = (destType->isSigned()? (uint64_t) (int64_t) fC
571                              : (uint64_t)           fC);
572   } else if (isa<UndefValue>(V)) {
573     isValidConstant = true;
574     C = 0;
575   }
576
577   // Now if a valid value was found, convert it to destType.
578   if (isValidConstant) {
579     unsigned opSize   = target.getTargetData().getTypeSize(V->getType());
580     unsigned destSize = target.getTargetData().getTypeSize(destType);
581     uint64_t maskHi   = (destSize < 8)? (1U << 8*destSize) - 1 : ~0;
582     assert(opSize <= 8 && destSize <= 8 && ">8-byte int type unexpected");
583     
584     if (destType->isSigned()) {
585       if (opSize > destSize)            // operand is larger than dest:
586         C = C & maskHi;                 // mask high bits
587
588       if (opSize > destSize ||
589           (opSize == destSize && ! V->getType()->isSigned()))
590         if (C & (1U << (8*destSize - 1)))
591           C =  C | ~maskHi;             // sign-extend from destSize to 64 bits
592     }
593     else {
594       if (opSize > destSize || (V->getType()->isSigned() && destSize < 8)) {
595         // operand is larger than dest,
596         //    OR both are equal but smaller than the full register size
597         //       AND operand is signed, so it may have extra sign bits:
598         // mask high bits
599         C = C & maskHi;
600       }
601     }
602   }
603
604   return C;
605 }
606
607 /// CreateSETUWConst - Copy a 32-bit unsigned constant into the register
608 /// `dest', using SETHI, OR in the worst case.  This function correctly emulates
609 /// the SETUW pseudo-op for SPARC v9 (if argument isSigned == false). The
610 /// isSigned=true case is used to implement SETSW without duplicating code. It
611 /// optimizes some common cases:
612 /// (1) Small value that fits in simm13 field of OR: don't need SETHI.
613 /// (2) isSigned = true and C is a small negative signed value, i.e.,
614 ///     high bits are 1, and the remaining bits fit in simm13(OR).
615 static inline void
616 CreateSETUWConst(uint32_t C,
617                  Instruction* dest, std::vector<MachineInstr*>& mvec,
618                  bool isSigned = false) {
619   MachineInstr *miSETHI = NULL, *miOR = NULL;
620
621   // In order to get efficient code, we should not generate the SETHI if
622   // all high bits are 1 (i.e., this is a small signed value that fits in
623   // the simm13 field of OR).  So we check for and handle that case specially.
624   // NOTE: The value C = 0x80000000 is bad: sC < 0 *and* -sC < 0.
625   //       In fact, sC == -sC, so we have to check for this explicitly.
626   int32_t sC = (int32_t) C;
627   bool smallNegValue =isSigned && sC < 0 && sC != -sC && -sC < (int32_t)MAXSIMM;
628
629   // Set the high 22 bits in dest if non-zero and simm13 field of OR not enough
630   if (!smallNegValue && (C & ~MAXLO) && C > MAXSIMM) {
631     miSETHI = BuildMI(V9::SETHI, 2).addZImm(C).addRegDef(dest);
632     miSETHI->getOperand(0).markHi32();
633     mvec.push_back(miSETHI);
634   }
635   
636   // Set the low 10 or 12 bits in dest.  This is necessary if no SETHI
637   // was generated, or if the low 10 bits are non-zero.
638   if (miSETHI==NULL || C & MAXLO) {
639     if (miSETHI) {
640       // unsigned value with high-order bits set using SETHI
641       miOR = BuildMI(V9::ORi,3).addReg(dest).addZImm(C).addRegDef(dest);
642       miOR->getOperand(1).markLo32();
643     } else {
644       // unsigned or small signed value that fits in simm13 field of OR
645       assert(smallNegValue || (C & ~MAXSIMM) == 0);
646       miOR = BuildMI(V9::ORi, 3).addMReg(SparcV9::g0)
647         .addSImm(sC).addRegDef(dest);
648     }
649     mvec.push_back(miOR);
650   }
651   
652   assert((miSETHI || miOR) && "Oops, no code was generated!");
653 }
654
655 /// CreateSETSWConst - Set a 32-bit signed constant in the register `dest',
656 /// with sign-extension to 64 bits.  This uses SETHI, OR, SRA in the worst case.
657 /// This function correctly emulates the SETSW pseudo-op for SPARC v9.  It
658 /// optimizes the same cases as SETUWConst, plus:
659 /// (1) SRA is not needed for positive or small negative values.
660 /// 
661 static inline void
662 CreateSETSWConst(int32_t C,
663                  Instruction* dest, std::vector<MachineInstr*>& mvec) {
664   // Set the low 32 bits of dest
665   CreateSETUWConst((uint32_t) C,  dest, mvec, /*isSigned*/true);
666
667   // Sign-extend to the high 32 bits if needed.
668   // NOTE: The value C = 0x80000000 is bad: -C == C and so -C is < MAXSIMM
669   if (C < 0 && (C == -C || -C > (int32_t) MAXSIMM))
670     mvec.push_back(BuildMI(V9::SRAi5,3).addReg(dest).addZImm(0).addRegDef(dest));
671 }
672
673 /// CreateSETXConst - Set a 64-bit signed or unsigned constant in the
674 /// register `dest'.  Use SETUWConst for each 32 bit word, plus a
675 /// left-shift-by-32 in between.  This function correctly emulates the SETX
676 /// pseudo-op for SPARC v9.  It optimizes the same cases as SETUWConst for each
677 /// 32 bit word.
678 /// 
679 static inline void
680 CreateSETXConst(uint64_t C,
681                 Instruction* tmpReg, Instruction* dest,
682                 std::vector<MachineInstr*>& mvec) {
683   assert(C > (unsigned int) ~0 && "Use SETUW/SETSW for 32-bit values!");
684   
685   MachineInstr* MI;
686   
687   // Code to set the upper 32 bits of the value in register `tmpReg'
688   CreateSETUWConst((C >> 32), tmpReg, mvec);
689   
690   // Shift tmpReg left by 32 bits
691   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
692                  .addRegDef(tmpReg));
693   
694   // Code to set the low 32 bits of the value in register `dest'
695   CreateSETUWConst(C, dest, mvec);
696   
697   // dest = OR(tmpReg, dest)
698   mvec.push_back(BuildMI(V9::ORr,3).addReg(dest).addReg(tmpReg).addRegDef(dest));
699 }
700
701 /// CreateSETUWLabel - Set a 32-bit constant (given by a symbolic label) in
702 /// the register `dest'.
703 /// 
704 static inline void
705 CreateSETUWLabel(Value* val,
706                  Instruction* dest, std::vector<MachineInstr*>& mvec) {
707   MachineInstr* MI;
708   
709   // Set the high 22 bits in dest
710   MI = BuildMI(V9::SETHI, 2).addReg(val).addRegDef(dest);
711   MI->getOperand(0).markHi32();
712   mvec.push_back(MI);
713   
714   // Set the low 10 bits in dest
715   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(val).addRegDef(dest);
716   MI->getOperand(1).markLo32();
717   mvec.push_back(MI);
718 }
719
720 /// CreateSETXLabel - Set a 64-bit constant (given by a symbolic label) in the
721 /// register `dest'.
722 /// 
723 static inline void
724 CreateSETXLabel(Value* val, Instruction* tmpReg,
725                 Instruction* dest, std::vector<MachineInstr*>& mvec) {
726   assert(isa<Constant>(val) && 
727          "I only know about constant values and global addresses");
728   
729   MachineInstr* MI;
730   
731   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg);
732   MI->getOperand(0).markHi64();
733   mvec.push_back(MI);
734   
735   MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addPCDisp(val).addRegDef(tmpReg);
736   MI->getOperand(1).markLo64();
737   mvec.push_back(MI);
738   
739   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
740                  .addRegDef(tmpReg));
741   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(dest);
742   MI->getOperand(0).markHi32();
743   mvec.push_back(MI);
744   
745   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(tmpReg).addRegDef(dest);
746   mvec.push_back(MI);
747   
748   MI = BuildMI(V9::ORi, 3).addReg(dest).addPCDisp(val).addRegDef(dest);
749   MI->getOperand(1).markLo32();
750   mvec.push_back(MI);
751 }
752
753 /// CreateUIntSetInstruction - Create code to Set an unsigned constant in the
754 /// register `dest'.  Uses CreateSETUWConst, CreateSETSWConst or CreateSETXConst
755 /// as needed.  CreateSETSWConst is an optimization for the case that the
756 /// unsigned value has all ones in the 33 high bits (so that sign-extension sets
757 /// them all).
758 /// 
759 static inline void
760 CreateUIntSetInstruction(uint64_t C, Instruction* dest,
761                          std::vector<MachineInstr*>& mvec,
762                          MachineCodeForInstruction& mcfi) {
763   static const uint64_t lo32 = (uint32_t) ~0;
764   if (C <= lo32)                        // High 32 bits are 0.  Set low 32 bits.
765     CreateSETUWConst((uint32_t) C, dest, mvec);
766   else if ((C & ~lo32) == ~lo32 && (C & (1U << 31))) {
767     // All high 33 (not 32) bits are 1s: sign-extension will take care
768     // of high 32 bits, so use the sequence for signed int
769     CreateSETSWConst((int32_t) C, dest, mvec);
770   } else if (C > lo32) {
771     // C does not fit in 32 bits
772     TmpInstruction* tmpReg = new TmpInstruction(mcfi, Type::IntTy);
773     CreateSETXConst(C, tmpReg, dest, mvec);
774   }
775 }
776
777 /// CreateIntSetInstruction - Create code to Set a signed constant in the
778 /// register `dest'.  Really the same as CreateUIntSetInstruction.
779 /// 
780 static inline void
781 CreateIntSetInstruction(int64_t C, Instruction* dest,
782                         std::vector<MachineInstr*>& mvec,
783                         MachineCodeForInstruction& mcfi) {
784   CreateUIntSetInstruction((uint64_t) C, dest, mvec, mcfi);
785 }
786
787 /// MaxConstantsTableTy - Table mapping LLVM opcodes to the max. immediate
788 /// constant usable for that operation in the SparcV9 backend. Used by
789 /// ConstantMayNotFitInImmedField().
790 /// 
791 struct MaxConstantsTableTy {
792   // Entry == 0 ==> no immediate constant field exists at all.
793   // Entry >  0 ==> abs(immediate constant) <= Entry
794   std::vector<int> tbl;
795
796   int getMaxConstantForInstr (unsigned llvmOpCode);
797   MaxConstantsTableTy ();
798   unsigned size() const            { return tbl.size (); }
799   int &operator[] (unsigned index) { return tbl[index];  }
800 };
801
802 int MaxConstantsTableTy::getMaxConstantForInstr(unsigned llvmOpCode) {
803   int modelOpCode = -1;
804
805   if (llvmOpCode >= Instruction::BinaryOpsBegin &&
806       llvmOpCode <  Instruction::BinaryOpsEnd)
807     modelOpCode = V9::ADDi;
808   else
809     switch(llvmOpCode) {
810     case Instruction::Ret:   modelOpCode = V9::JMPLCALLi; break;
811
812     case Instruction::Malloc:         
813     case Instruction::Alloca:         
814     case Instruction::GetElementPtr:  
815     case Instruction::PHI:       
816     case Instruction::Cast:
817     case Instruction::Call:  modelOpCode = V9::ADDi; break;
818
819     case Instruction::Shl:
820     case Instruction::Shr:   modelOpCode = V9::SLLXi6; break;
821
822     default: break;
823     };
824
825   return (modelOpCode < 0)? 0: SparcV9MachineInstrDesc[modelOpCode].maxImmedConst;
826 }
827
828 MaxConstantsTableTy::MaxConstantsTableTy () : tbl (Instruction::OtherOpsEnd) {
829   unsigned op;
830   assert(tbl.size() == Instruction::OtherOpsEnd &&
831          "assignments below will be illegal!");
832   for (op = Instruction::TermOpsBegin; op < Instruction::TermOpsEnd; ++op)
833     tbl[op] = getMaxConstantForInstr(op);
834   for (op = Instruction::BinaryOpsBegin; op < Instruction::BinaryOpsEnd; ++op)
835     tbl[op] = getMaxConstantForInstr(op);
836   for (op = Instruction::MemoryOpsBegin; op < Instruction::MemoryOpsEnd; ++op)
837     tbl[op] = getMaxConstantForInstr(op);
838   for (op = Instruction::OtherOpsBegin; op < Instruction::OtherOpsEnd; ++op)
839     tbl[op] = getMaxConstantForInstr(op);
840 }
841
842 bool ConstantMayNotFitInImmedField(const Constant* CV, const Instruction* I) {
843   // The one and only MaxConstantsTable, used only by this function.
844   static MaxConstantsTableTy MaxConstantsTable;
845
846   if (I->getOpcode() >= MaxConstantsTable.size()) // user-defined op (or bug!)
847     return true;
848
849   // can always use %g0
850   if (isa<ConstantPointerNull>(CV) || isa<UndefValue>(CV))
851     return false;
852
853   if (isa<SwitchInst>(I)) // Switch instructions will be lowered!
854     return false;
855
856   if (const ConstantInt* CI = dyn_cast<ConstantInt>(CV))
857     return labs((int64_t)CI->getRawValue()) > MaxConstantsTable[I->getOpcode()];
858
859   if (isa<ConstantBool>(CV))
860     return 1 > MaxConstantsTable[I->getOpcode()];
861
862   return true;
863 }
864
865 /// ChooseLoadInstruction - Return the appropriate load instruction opcode
866 /// based on the given LLVM value type.
867 /// 
868 static inline MachineOpCode ChooseLoadInstruction(const Type *DestTy) {
869   switch (DestTy->getTypeID()) {
870   case Type::BoolTyID:
871   case Type::UByteTyID:   return V9::LDUBr;
872   case Type::SByteTyID:   return V9::LDSBr;
873   case Type::UShortTyID:  return V9::LDUHr;
874   case Type::ShortTyID:   return V9::LDSHr;
875   case Type::UIntTyID:    return V9::LDUWr;
876   case Type::IntTyID:     return V9::LDSWr;
877   case Type::PointerTyID:
878   case Type::ULongTyID:
879   case Type::LongTyID:    return V9::LDXr;
880   case Type::FloatTyID:   return V9::LDFr;
881   case Type::DoubleTyID:  return V9::LDDFr;
882   default: assert(0 && "Invalid type for Load instruction");
883   }
884   return 0;
885 }
886
887 /// ChooseStoreInstruction - Return the appropriate store instruction opcode
888 /// based on the given LLVM value type.
889 /// 
890 static inline MachineOpCode ChooseStoreInstruction(const Type *DestTy) {
891   switch (DestTy->getTypeID()) {
892   case Type::BoolTyID:
893   case Type::UByteTyID:
894   case Type::SByteTyID:   return V9::STBr;
895   case Type::UShortTyID:
896   case Type::ShortTyID:   return V9::STHr;
897   case Type::UIntTyID:
898   case Type::IntTyID:     return V9::STWr;
899   case Type::PointerTyID:
900   case Type::ULongTyID:
901   case Type::LongTyID:    return V9::STXr;
902   case Type::FloatTyID:   return V9::STFr;
903   case Type::DoubleTyID:  return V9::STDFr;
904   default: assert(0 && "Invalid type for Store instruction");
905   }
906   return 0;
907 }
908
909 static inline MachineOpCode ChooseAddInstructionByType(const Type* resultType) {
910   MachineOpCode opCode = V9::INVALID_OPCODE;
911   if (resultType->isIntegral() || isa<PointerType>(resultType)
912       || isa<FunctionType>(resultType) || resultType == Type::LabelTy) {
913     opCode = V9::ADDr;
914   } else
915     switch(resultType->getTypeID()) {
916     case Type::FloatTyID:  opCode = V9::FADDS; break;
917     case Type::DoubleTyID: opCode = V9::FADDD; break;
918     default: assert(0 && "Invalid type for ADD instruction"); break; 
919     }
920   
921   return opCode;
922 }
923
924 /// convertOpcodeFromRegToImm - Because the SparcV9 instruction selector likes
925 /// to re-write operands to instructions, making them change from a Value*
926 /// (virtual register) to a Constant* (making an immediate field), we need to
927 /// change the opcode from a register-based instruction to an immediate-based
928 /// instruction, hence this mapping.
929 /// 
930 static unsigned convertOpcodeFromRegToImm(unsigned Opcode) {
931   switch (Opcode) {
932     /* arithmetic */
933   case V9::ADDr:     return V9::ADDi;
934   case V9::ADDccr:   return V9::ADDcci;
935   case V9::ADDCr:    return V9::ADDCi;
936   case V9::ADDCccr:  return V9::ADDCcci;
937   case V9::SUBr:     return V9::SUBi;
938   case V9::SUBccr:   return V9::SUBcci;
939   case V9::SUBCr:    return V9::SUBCi;
940   case V9::SUBCccr:  return V9::SUBCcci;
941   case V9::MULXr:    return V9::MULXi;
942   case V9::SDIVXr:   return V9::SDIVXi;
943   case V9::UDIVXr:   return V9::UDIVXi;
944
945     /* logical */
946   case V9::ANDr:    return V9::ANDi;
947   case V9::ANDccr:  return V9::ANDcci;
948   case V9::ANDNr:   return V9::ANDNi;
949   case V9::ANDNccr: return V9::ANDNcci;
950   case V9::ORr:     return V9::ORi;
951   case V9::ORccr:   return V9::ORcci;
952   case V9::ORNr:    return V9::ORNi;
953   case V9::ORNccr:  return V9::ORNcci;
954   case V9::XORr:    return V9::XORi;
955   case V9::XORccr:  return V9::XORcci;
956   case V9::XNORr:   return V9::XNORi;
957   case V9::XNORccr: return V9::XNORcci;
958
959     /* shift */
960   case V9::SLLr5:   return V9::SLLi5;
961   case V9::SRLr5:   return V9::SRLi5;
962   case V9::SRAr5:   return V9::SRAi5;
963   case V9::SLLXr6:  return V9::SLLXi6;
964   case V9::SRLXr6:  return V9::SRLXi6;
965   case V9::SRAXr6:  return V9::SRAXi6;
966
967     /* Conditional move on int comparison with zero */
968   case V9::MOVRZr:   return V9::MOVRZi;
969   case V9::MOVRLEZr: return V9::MOVRLEZi;
970   case V9::MOVRLZr:  return V9::MOVRLZi;
971   case V9::MOVRNZr:  return V9::MOVRNZi;
972   case V9::MOVRGZr:  return V9::MOVRGZi;
973   case V9::MOVRGEZr: return V9::MOVRGEZi;
974
975
976     /* Conditional move on int condition code */
977   case V9::MOVAr:   return V9::MOVAi;
978   case V9::MOVNr:   return V9::MOVNi;
979   case V9::MOVNEr:  return V9::MOVNEi;
980   case V9::MOVEr:   return V9::MOVEi;
981   case V9::MOVGr:   return V9::MOVGi;
982   case V9::MOVLEr:  return V9::MOVLEi;
983   case V9::MOVGEr:  return V9::MOVGEi;
984   case V9::MOVLr:   return V9::MOVLi;
985   case V9::MOVGUr:  return V9::MOVGUi;
986   case V9::MOVLEUr: return V9::MOVLEUi;
987   case V9::MOVCCr:  return V9::MOVCCi;
988   case V9::MOVCSr:  return V9::MOVCSi;
989   case V9::MOVPOSr: return V9::MOVPOSi;
990   case V9::MOVNEGr: return V9::MOVNEGi;
991   case V9::MOVVCr:  return V9::MOVVCi;
992   case V9::MOVVSr:  return V9::MOVVSi;
993
994     /* Conditional move of int reg on fp condition code */
995   case V9::MOVFAr:   return V9::MOVFAi;
996   case V9::MOVFNr:   return V9::MOVFNi;
997   case V9::MOVFUr:   return V9::MOVFUi;
998   case V9::MOVFGr:   return V9::MOVFGi;
999   case V9::MOVFUGr:  return V9::MOVFUGi;
1000   case V9::MOVFLr:   return V9::MOVFLi;
1001   case V9::MOVFULr:  return V9::MOVFULi;
1002   case V9::MOVFLGr:  return V9::MOVFLGi;
1003   case V9::MOVFNEr:  return V9::MOVFNEi;
1004   case V9::MOVFEr:   return V9::MOVFEi;
1005   case V9::MOVFUEr:  return V9::MOVFUEi;
1006   case V9::MOVFGEr:  return V9::MOVFGEi;
1007   case V9::MOVFUGEr: return V9::MOVFUGEi;
1008   case V9::MOVFLEr:  return V9::MOVFLEi;
1009   case V9::MOVFULEr: return V9::MOVFULEi;
1010   case V9::MOVFOr:   return V9::MOVFOi;
1011
1012     /* load */
1013   case V9::LDSBr:   return V9::LDSBi;
1014   case V9::LDSHr:   return V9::LDSHi;
1015   case V9::LDSWr:   return V9::LDSWi;
1016   case V9::LDUBr:   return V9::LDUBi;
1017   case V9::LDUHr:   return V9::LDUHi;
1018   case V9::LDUWr:   return V9::LDUWi;
1019   case V9::LDXr:    return V9::LDXi;
1020   case V9::LDFr:    return V9::LDFi;
1021   case V9::LDDFr:   return V9::LDDFi;
1022   case V9::LDQFr:   return V9::LDQFi;
1023   case V9::LDFSRr:  return V9::LDFSRi;
1024   case V9::LDXFSRr: return V9::LDXFSRi;
1025
1026     /* store */
1027   case V9::STBr:    return V9::STBi;
1028   case V9::STHr:    return V9::STHi;
1029   case V9::STWr:    return V9::STWi;
1030   case V9::STXr:    return V9::STXi;
1031   case V9::STFr:    return V9::STFi;
1032   case V9::STDFr:   return V9::STDFi;
1033   case V9::STFSRr:  return V9::STFSRi;
1034   case V9::STXFSRr: return V9::STXFSRi;
1035
1036     /* jump & return */
1037   case V9::JMPLCALLr: return V9::JMPLCALLi;
1038   case V9::JMPLRETr:  return V9::JMPLRETi;
1039
1040   /* save and restore */
1041   case V9::SAVEr:     return V9::SAVEi;
1042   case V9::RESTOREr:  return V9::RESTOREi;
1043
1044   default:
1045     // It's already in correct format
1046     // Or, it's just not handled yet, but an assert() would break LLC
1047 #if 0
1048     std::cerr << "Unhandled opcode in convertOpcodeFromRegToImm(): " << Opcode 
1049               << "\n";
1050 #endif
1051     return Opcode;
1052   }
1053 }
1054
1055 /// CreateCodeToLoadConst - Create an instruction sequence to put the
1056 /// constant `val' into the virtual register `dest'.  `val' may be a Constant or
1057 /// a GlobalValue, viz., the constant address of a global variable or function.
1058 /// The generated instructions are returned in `mvec'. Any temp. registers
1059 /// (TmpInstruction) created are recorded in mcfi. Any stack space required is
1060 /// allocated via MachineFunction.
1061 /// 
1062 void CreateCodeToLoadConst(const TargetMachine& target, Function* F,
1063                            Value* val, Instruction* dest,
1064                            std::vector<MachineInstr*>& mvec,
1065                            MachineCodeForInstruction& mcfi) {
1066   assert(isa<Constant>(val) &&
1067          "I only know about constant values and global addresses");
1068   
1069   // Use a "set" instruction for known constants or symbolic constants (labels)
1070   // that can go in an integer reg.
1071   // We have to use a "load" instruction for all other constants,
1072   // in particular, floating point constants.
1073   const Type* valType = val->getType();
1074   
1075   if (isa<GlobalValue>(val)) {
1076       TmpInstruction* tmpReg =
1077         new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
1078       CreateSETXLabel(val, tmpReg, dest, mvec);
1079       return;
1080   }
1081
1082   bool isValid;
1083   uint64_t C = ConvertConstantToIntType(target, val, dest->getType(), isValid);
1084   if (isValid) {
1085     if (dest->getType()->isSigned())
1086       CreateUIntSetInstruction(C, dest, mvec, mcfi);
1087     else
1088       CreateIntSetInstruction((int64_t) C, dest, mvec, mcfi);
1089
1090   } else {
1091     // Make an instruction sequence to load the constant, viz:
1092     //            SETX <addr-of-constant>, tmpReg, addrReg
1093     //            LOAD  /*addr*/ addrReg, /*offset*/ 0, dest
1094     // First, create a tmp register to be used by the SETX sequence.
1095     TmpInstruction* tmpReg =
1096       new TmpInstruction(mcfi, PointerType::get(val->getType()));
1097       
1098     // Create another TmpInstruction for the address register
1099     TmpInstruction* addrReg =
1100       new TmpInstruction(mcfi, PointerType::get(val->getType()));
1101     
1102     // Get the constant pool index for this constant
1103     MachineConstantPool *CP = MachineFunction::get(F).getConstantPool();
1104     Constant *C = cast<Constant>(val);
1105     unsigned CPI = CP->getConstantPoolIndex(C);
1106
1107     // Put the address of the constant into a register
1108     MachineInstr* MI;
1109   
1110     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(tmpReg);
1111     MI->getOperand(0).markHi64();
1112     mvec.push_back(MI);
1113   
1114     MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addConstantPoolIndex(CPI)
1115       .addRegDef(tmpReg);
1116     MI->getOperand(1).markLo64();
1117     mvec.push_back(MI);
1118   
1119     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
1120                    .addRegDef(tmpReg));
1121     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(addrReg);
1122     MI->getOperand(0).markHi32();
1123     mvec.push_back(MI);
1124   
1125     MI = BuildMI(V9::ORr, 3).addReg(addrReg).addReg(tmpReg).addRegDef(addrReg);
1126     mvec.push_back(MI);
1127   
1128     MI = BuildMI(V9::ORi, 3).addReg(addrReg).addConstantPoolIndex(CPI)
1129       .addRegDef(addrReg);
1130     MI->getOperand(1).markLo32();
1131     mvec.push_back(MI);
1132
1133     // Now load the constant from out ConstantPool label
1134     unsigned Opcode = ChooseLoadInstruction(val->getType());
1135     Opcode = convertOpcodeFromRegToImm(Opcode);
1136     mvec.push_back(BuildMI(Opcode, 3)
1137                    .addReg(addrReg).addSImm((int64_t)0).addRegDef(dest));
1138   }
1139 }
1140
1141 /// CreateCodeToCopyFloatToInt - Similarly, create an instruction sequence
1142 /// to copy an FP register `val' to an integer register `dest' by copying to
1143 /// memory and back.  The generated instructions are returned in `mvec'.  Any
1144 /// temp. virtual registers (TmpInstruction) created are recorded in mcfi.
1145 /// Temporary stack space required is allocated via MachineFunction.
1146 /// 
1147 void CreateCodeToCopyFloatToInt(const TargetMachine& target, Function* F,
1148                                 Value* val, Instruction* dest,
1149                                 std::vector<MachineInstr*>& mvec,
1150                                 MachineCodeForInstruction& mcfi) {
1151   const Type* opTy   = val->getType();
1152   const Type* destTy = dest->getType();
1153   assert(opTy->isFloatingPoint() && "Source type must be float/double");
1154   assert((destTy->isIntegral() || isa<PointerType>(destTy))
1155          && "Dest type must be integer, bool or pointer");
1156
1157   // FIXME: For now, we allocate permanent space because the stack frame
1158   // manager does not allow locals to be allocated (e.g., for alloca) after
1159   // a temp is allocated!
1160   int offset = MachineFunction::get(F).getInfo<SparcV9FunctionInfo>()->allocateLocalVar(val); 
1161
1162   unsigned FPReg = target.getRegInfo()->getFramePointer();
1163
1164   // Store instruction stores `val' to [%fp+offset].
1165   // The store opCode is based only the source value being copied.
1166   unsigned StoreOpcode = ChooseStoreInstruction(opTy);
1167   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);  
1168   mvec.push_back(BuildMI(StoreOpcode, 3)
1169                  .addReg(val).addMReg(FPReg).addSImm(offset));
1170
1171   // Load instruction loads [%fp+offset] to `dest'.
1172   // The type of the load opCode is the integer type that matches the
1173   // source type in size:
1174   // On SparcV9: int for float, long for double.
1175   // Note that we *must* use signed loads even for unsigned dest types, to
1176   // ensure correct sign-extension for UByte, UShort or UInt:
1177   const Type* loadTy = (opTy == Type::FloatTy)? Type::IntTy : Type::LongTy;
1178   unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
1179   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1180   mvec.push_back(BuildMI(LoadOpcode, 3).addMReg(FPReg)
1181                  .addSImm(offset).addRegDef(dest));
1182 }
1183
1184 /// CreateBitExtensionInstructions - Helper function for sign-extension and
1185 /// zero-extension. For SPARC v9, we sign-extend the given operand using SLL;
1186 /// SRA/SRL.
1187 /// 
1188 inline void
1189 CreateBitExtensionInstructions(bool signExtend, const TargetMachine& target,
1190                                Function* F, Value* srcVal, Value* destVal,
1191                                unsigned int numLowBits,
1192                                std::vector<MachineInstr*>& mvec,
1193                                MachineCodeForInstruction& mcfi) {
1194   MachineInstr* M;
1195
1196   assert(numLowBits <= 32 && "Otherwise, nothing should be done here!");
1197
1198   if (numLowBits < 32) {
1199     // SLL is needed since operand size is < 32 bits.
1200     TmpInstruction *tmpI = new TmpInstruction(mcfi, destVal->getType(),
1201                                               srcVal, destVal, "make32");
1202     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(srcVal)
1203                    .addZImm(32-numLowBits).addRegDef(tmpI));
1204     srcVal = tmpI;
1205   }
1206
1207   mvec.push_back(BuildMI(signExtend? V9::SRAi5 : V9::SRLi5, 3)
1208                  .addReg(srcVal).addZImm(32-numLowBits).addRegDef(destVal));
1209 }
1210
1211 /// CreateSignExtensionInstructions - Create instruction sequence to produce
1212 /// a sign-extended register value from an arbitrary-sized integer value (sized
1213 /// in bits, not bytes). The generated instructions are returned in `mvec'. Any
1214 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1215 /// space required is allocated via MachineFunction.
1216 /// 
1217 void CreateSignExtensionInstructions(const TargetMachine& target,
1218                                      Function* F, Value* srcVal, Value* destVal,
1219                                      unsigned int numLowBits,
1220                                      std::vector<MachineInstr*>& mvec,
1221                                      MachineCodeForInstruction& mcfi) {
1222   CreateBitExtensionInstructions(/*signExtend*/ true, target, F, srcVal,
1223                                  destVal, numLowBits, mvec, mcfi);
1224 }
1225
1226 /// CreateZeroExtensionInstructions - Create instruction sequence to produce
1227 /// a zero-extended register value from an arbitrary-sized integer value (sized
1228 /// in bits, not bytes).  For SPARC v9, we sign-extend the given operand using
1229 /// SLL; SRL.  The generated instructions are returned in `mvec'.  Any temp.
1230 /// registers (TmpInstruction) created are recorded in mcfi.  Any stack space
1231 /// required is allocated via MachineFunction.
1232 /// 
1233 void CreateZeroExtensionInstructions(const TargetMachine& target,
1234                                      Function* F, Value* srcVal, Value* destVal,
1235                                      unsigned int numLowBits,
1236                                      std::vector<MachineInstr*>& mvec,
1237                                      MachineCodeForInstruction& mcfi) {
1238   CreateBitExtensionInstructions(/*signExtend*/ false, target, F, srcVal,
1239                                  destVal, numLowBits, mvec, mcfi);
1240 }
1241
1242 /// CreateCodeToCopyIntToFloat - Create an instruction sequence to copy an
1243 /// integer register `val' to a floating point register `dest' by copying to
1244 /// memory and back. val must be an integral type.  dest must be a Float or
1245 /// Double. The generated instructions are returned in `mvec'. Any temp.
1246 /// registers (TmpInstruction) created are recorded in mcfi. Any stack space
1247 /// required is allocated via MachineFunction.
1248 ///
1249 void CreateCodeToCopyIntToFloat(const TargetMachine& target,
1250                                 Function* F, Value* val, Instruction* dest,
1251                                 std::vector<MachineInstr*>& mvec,
1252                                 MachineCodeForInstruction& mcfi) {
1253   assert((val->getType()->isIntegral() || isa<PointerType>(val->getType()))
1254          && "Source type must be integral (integer or bool) or pointer");
1255   assert(dest->getType()->isFloatingPoint()
1256          && "Dest type must be float/double");
1257
1258   // Get a stack slot to use for the copy
1259   int offset = MachineFunction::get(F).getInfo<SparcV9FunctionInfo>()->allocateLocalVar(val);
1260
1261   // Get the size of the source value being copied. 
1262   size_t srcSize = target.getTargetData().getTypeSize(val->getType());
1263
1264   // Store instruction stores `val' to [%fp+offset].
1265   // The store and load opCodes are based on the size of the source value.
1266   // If the value is smaller than 32 bits, we must sign- or zero-extend it
1267   // to 32 bits since the load-float will load 32 bits.
1268   // Note that the store instruction is the same for signed and unsigned ints.
1269   const Type* storeType = (srcSize <= 4)? Type::IntTy : Type::LongTy;
1270   Value* storeVal = val;
1271   if (srcSize < target.getTargetData().getTypeSize(Type::FloatTy)) {
1272     // sign- or zero-extend respectively
1273     storeVal = new TmpInstruction(mcfi, storeType, val);
1274     if (val->getType()->isSigned())
1275       CreateSignExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1276                                       mvec, mcfi);
1277     else
1278       CreateZeroExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1279                                       mvec, mcfi);
1280   }
1281
1282   unsigned FPReg = target.getRegInfo()->getFramePointer();
1283   unsigned StoreOpcode = ChooseStoreInstruction(storeType);
1284   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
1285   mvec.push_back(BuildMI(StoreOpcode, 3)
1286                  .addReg(storeVal).addMReg(FPReg).addSImm(offset));
1287
1288   // Load instruction loads [%fp+offset] to `dest'.
1289   // The type of the load opCode is the floating point type that matches the
1290   // stored type in size:
1291   // On SparcV9: float for int or smaller, double for long.
1292   const Type* loadType = (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1293   unsigned LoadOpcode = ChooseLoadInstruction(loadType);
1294   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1295   mvec.push_back(BuildMI(LoadOpcode, 3)
1296                  .addMReg(FPReg).addSImm(offset).addRegDef(dest));
1297 }
1298
1299 /// InsertCodeToLoadConstant - Generates code to load the constant
1300 /// into a TmpInstruction (virtual reg) and returns the virtual register.
1301 /// 
1302 static TmpInstruction*
1303 InsertCodeToLoadConstant(Function *F, Value* opValue, Instruction* vmInstr,
1304                          std::vector<MachineInstr*>& loadConstVec,
1305                          TargetMachine& target) {
1306   // Create a tmp virtual register to hold the constant.
1307   MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
1308   TmpInstruction* tmpReg = new TmpInstruction(mcfi, opValue);
1309   
1310   CreateCodeToLoadConst(target, F, opValue, tmpReg, loadConstVec, mcfi);
1311   
1312   // Record the mapping from the tmp VM instruction to machine instruction.
1313   // Do this for all machine instructions that were not mapped to any
1314   // other temp values created by 
1315   // tmpReg->addMachineInstruction(loadConstVec.back());
1316   return tmpReg;
1317 }
1318
1319 MachineOperand::MachineOperandType
1320 ChooseRegOrImmed(int64_t intValue, bool isSigned,
1321                  MachineOpCode opCode, const TargetMachine& target,
1322                  bool canUseImmed, unsigned int& getMachineRegNum,
1323                  int64_t& getImmedValue) {
1324   MachineOperand::MachineOperandType opType=MachineOperand::MO_VirtualRegister;
1325   getMachineRegNum = 0;
1326   getImmedValue = 0;
1327
1328   if (canUseImmed &&
1329       target.getInstrInfo()->constantFitsInImmedField(opCode, intValue)) {
1330       opType = isSigned? MachineOperand::MO_SignExtendedImmed
1331                        : MachineOperand::MO_UnextendedImmed;
1332       getImmedValue = intValue;
1333   } else if (intValue == 0 &&
1334              target.getRegInfo()->getZeroRegNum() != (unsigned)-1) {
1335     opType = MachineOperand::MO_MachineRegister;
1336     getMachineRegNum = target.getRegInfo()->getZeroRegNum();
1337   }
1338
1339   return opType;
1340 }
1341
1342 MachineOperand::MachineOperandType
1343 ChooseRegOrImmed(Value* val,
1344                  MachineOpCode opCode, const TargetMachine& target,
1345                  bool canUseImmed, unsigned int& getMachineRegNum,
1346                  int64_t& getImmedValue) {
1347   getMachineRegNum = 0;
1348   getImmedValue = 0;
1349
1350   // To use reg or immed, constant needs to be integer, bool, or a NULL pointer.
1351   // ConvertConstantToIntType() does the right conversions.
1352   bool isValidConstant;
1353   uint64_t valueToUse =
1354     ConvertConstantToIntType(target, val, val->getType(), isValidConstant);
1355   if (! isValidConstant)
1356     return MachineOperand::MO_VirtualRegister;
1357
1358   // Now check if the constant value fits in the IMMED field.
1359   return ChooseRegOrImmed((int64_t) valueToUse, val->getType()->isSigned(),
1360                           opCode, target, canUseImmed,
1361                           getMachineRegNum, getImmedValue);
1362 }
1363
1364 /// CreateCopyInstructionsByType - Create instruction(s) to copy src to dest,
1365 /// for arbitrary types. The generated instructions are returned in `mvec'. Any
1366 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1367 /// space required is allocated via MachineFunction.
1368 /// 
1369 void CreateCopyInstructionsByType(const TargetMachine& target,
1370                                   Function *F, Value* src, Instruction* dest,
1371                                   std::vector<MachineInstr*>& mvec,
1372                                   MachineCodeForInstruction& mcfi) {
1373   bool loadConstantToReg = false;
1374   const Type* resultType = dest->getType();
1375   MachineOpCode opCode = ChooseAddInstructionByType(resultType);
1376   assert (opCode != V9::INVALID_OPCODE
1377           && "Unsupported result type in CreateCopyInstructionsByType()");
1378
1379   // If `src' is a constant that doesn't fit in the immed field or if it is
1380   // a global variable (i.e., a constant address), generate a load
1381   // instruction instead of an add.
1382   if (isa<GlobalValue>(src))
1383     loadConstantToReg = true;
1384   else if (isa<Constant>(src)) {
1385     unsigned int machineRegNum;
1386     int64_t immedValue;
1387     MachineOperand::MachineOperandType opType =
1388       ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
1389                        machineRegNum, immedValue);
1390       
1391     if (opType == MachineOperand::MO_VirtualRegister)
1392       loadConstantToReg = true;
1393   }
1394   
1395   if (loadConstantToReg) { 
1396     // `src' is constant and cannot fit in immed field for the ADD.
1397     // Insert instructions to "load" the constant into a register.
1398     CreateCodeToLoadConst(target, F, src, dest, mvec, mcfi);
1399   } else { 
1400     // Create a reg-to-reg copy instruction for the given type:
1401     // -- For FP values, create a FMOVS or FMOVD instruction
1402     // -- For non-FP values, create an add-with-0 instruction (opCode as above)
1403     // Make `src' the second operand, in case it is a small constant!
1404     MachineInstr* MI;
1405     if (resultType->isFloatingPoint())
1406       MI = (BuildMI(resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1407             .addReg(src).addRegDef(dest));
1408     else {
1409         const Type* Ty =isa<PointerType>(resultType)? Type::ULongTy :resultType;
1410         MI = (BuildMI(opCode, 3)
1411               .addSImm((int64_t) 0).addReg(src).addRegDef(dest));
1412     }
1413     mvec.push_back(MI);
1414   }
1415 }
1416
1417 /// FixConstantOperandsForInstr - Make a machine instruction use its constant
1418 /// operands more efficiently.  If the constant is 0, then use the hardwired 0
1419 /// register, if any.  Else, if the constant fits in the IMMEDIATE field, then
1420 /// use that field.  Otherwise, else create instructions to put the constant
1421 /// into a register, either directly or by loading explicitly from the constant
1422 /// pool.  In the first 2 cases, the operand of `minstr' is modified in place.
1423 /// Returns a vector of machine instructions generated for operands that fall
1424 /// under case 3; these must be inserted before `minstr'.
1425 /// 
1426 std::vector<MachineInstr*>
1427 FixConstantOperandsForInstr(Instruction* vmInstr, MachineInstr* minstr,
1428                             TargetMachine& target) {
1429   std::vector<MachineInstr*> MVec;
1430   
1431   MachineOpCode opCode = minstr->getOpcode();
1432   const TargetInstrInfo& instrInfo = *target.getInstrInfo();
1433   int resultPos = instrInfo.get(opCode).resultPos;
1434   int immedPos = instrInfo.getImmedConstantPos(opCode);
1435
1436   Function *F = vmInstr->getParent()->getParent();
1437
1438   for (unsigned op=0; op < minstr->getNumOperands(); op++) {
1439       const MachineOperand& mop = minstr->getOperand(op);
1440           
1441       // Skip the result position, preallocated machine registers, or operands
1442       // that cannot be constants (CC regs or PC-relative displacements)
1443       if (resultPos == (int)op ||
1444           mop.getType() == MachineOperand::MO_MachineRegister ||
1445           mop.getType() == MachineOperand::MO_CCRegister ||
1446           mop.getType() == MachineOperand::MO_PCRelativeDisp)
1447         continue;
1448
1449       bool constantThatMustBeLoaded = false;
1450       unsigned int machineRegNum = 0;
1451       int64_t immedValue = 0;
1452       Value* opValue = NULL;
1453       MachineOperand::MachineOperandType opType =
1454         MachineOperand::MO_VirtualRegister;
1455
1456       // Operand may be a virtual register or a compile-time constant
1457       if (mop.getType() == MachineOperand::MO_VirtualRegister) {
1458         assert(mop.getVRegValue() != NULL);
1459         opValue = mop.getVRegValue();
1460         if (Constant *opConst = dyn_cast<Constant>(opValue)) 
1461           if (!isa<GlobalValue>(opConst)) {
1462             opType = ChooseRegOrImmed(opConst, opCode, target,
1463                                       (immedPos == (int)op), machineRegNum,
1464                                       immedValue);
1465             if (opType == MachineOperand::MO_VirtualRegister)
1466               constantThatMustBeLoaded = true;
1467           }
1468       } else {
1469         // If the operand is from the constant pool, don't try to change it.
1470         if (mop.getType() == MachineOperand::MO_ConstantPoolIndex) {
1471           continue;
1472         }
1473         assert(mop.isImmediate());
1474         bool isSigned = mop.getType() == MachineOperand::MO_SignExtendedImmed;
1475
1476         // Bit-selection flags indicate an instruction that is extracting
1477         // bits from its operand so ignore this even if it is a big constant.
1478         if (mop.isHiBits32() || mop.isLoBits32() ||
1479             mop.isHiBits64() || mop.isLoBits64())
1480           continue;
1481
1482         opType = ChooseRegOrImmed(mop.getImmedValue(), isSigned,
1483                                   opCode, target, (immedPos == (int)op), 
1484                                   machineRegNum, immedValue);
1485
1486         if (opType == MachineOperand::MO_SignExtendedImmed ||
1487             opType == MachineOperand::MO_UnextendedImmed) {
1488           // The optype is an immediate value
1489           // This means we need to change the opcode, e.g. ADDr -> ADDi
1490           unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1491           minstr->setOpcode(newOpcode);
1492         }
1493
1494         if (opType == mop.getType()) 
1495           continue;           // no change: this is the most common case
1496
1497         if (opType == MachineOperand::MO_VirtualRegister) {
1498           constantThatMustBeLoaded = true;
1499           opValue = isSigned
1500             ? (Value*)ConstantSInt::get(Type::LongTy, immedValue)
1501             : (Value*)ConstantUInt::get(Type::ULongTy,(uint64_t)immedValue);
1502         }
1503       }
1504
1505       if (opType == MachineOperand::MO_MachineRegister)
1506         minstr->SetMachineOperandReg(op, machineRegNum);
1507       else if (opType == MachineOperand::MO_SignExtendedImmed ||
1508                opType == MachineOperand::MO_UnextendedImmed) {
1509         minstr->SetMachineOperandConst(op, opType, immedValue);
1510         // The optype is or has become an immediate
1511         // This means we need to change the opcode, e.g. ADDr -> ADDi
1512         unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1513         minstr->setOpcode(newOpcode);
1514       } else if (constantThatMustBeLoaded ||
1515                (opValue && isa<GlobalValue>(opValue)))
1516         { // opValue is a constant that must be explicitly loaded into a reg
1517           assert(opValue);
1518           TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
1519                                                             MVec, target);
1520           minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
1521                                        tmpReg);
1522         }
1523     }
1524   
1525   // Also, check for implicit operands used by the machine instruction
1526   // (no need to check those defined since they cannot be constants).
1527   // These include:
1528   // -- arguments to a Call
1529   // -- return value of a Return
1530   // Any such operand that is a constant value needs to be fixed also.
1531   // The current instructions with implicit refs (viz., Call and Return)
1532   // have no immediate fields, so the constant always needs to be loaded
1533   // into a register.
1534   bool isCall = instrInfo.isCall(opCode);
1535   unsigned lastCallArgNum = 0;          // unused if not a call
1536   CallArgsDescriptor* argDesc = NULL;   // unused if not a call
1537   if (isCall)
1538     argDesc = CallArgsDescriptor::get(minstr);
1539   
1540   for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
1541     if (isa<Constant>(minstr->getImplicitRef(i))) {
1542         Value* oldVal = minstr->getImplicitRef(i);
1543         TmpInstruction* tmpReg =
1544           InsertCodeToLoadConstant(F, oldVal, vmInstr, MVec, target);
1545         minstr->setImplicitRef(i, tmpReg);
1546         
1547         if (isCall) {
1548           // find and replace the argument in the CallArgsDescriptor
1549           unsigned i=lastCallArgNum;
1550           while (argDesc->getArgInfo(i).getArgVal() != oldVal)
1551             ++i;
1552           assert(i < argDesc->getNumArgs() &&
1553                  "Constant operands to a call *must* be in the arg list");
1554           lastCallArgNum = i;
1555           argDesc->getArgInfo(i).replaceArgVal(tmpReg);
1556         }
1557       }
1558   
1559   return MVec;
1560 }
1561
1562 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
1563                                     std::vector<MachineInstr*>& mvec) {
1564   mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
1565                                    .addReg(Node->rightChild()->getValue())
1566                                    .addRegDef(Node->getValue()));
1567 }
1568
1569 /// IsZero - Check for a constant 0.
1570 ///
1571 static inline bool IsZero(Value* idx) {
1572   return (isa<Constant>(idx) && cast<Constant>(idx)->isNullValue()) ||
1573          isa<UndefValue>(idx);
1574 }
1575
1576 /// FoldGetElemChain - Fold a chain of GetElementPtr instructions containing
1577 /// only constant offsets into an equivalent (Pointer, IndexVector) pair.
1578 /// Returns the pointer Value, and stores the resulting IndexVector in argument
1579 /// chainIdxVec. This is a helper function for FoldConstantIndices that does the
1580 /// actual folding.
1581 //
1582 static Value*
1583 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
1584                  bool lastInstHasLeadingNonZero) {
1585   InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
1586   GetElementPtrInst* gepInst =
1587     dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
1588
1589   // ptr value is not computed in this tree or ptr value does not come from GEP
1590   // instruction
1591   if (gepInst == NULL)
1592     return NULL;
1593
1594   // Return NULL if we don't fold any instructions in.
1595   Value* ptrVal = NULL;
1596
1597   // Now chase the chain of getElementInstr instructions, if any.
1598   // Check for any non-constant indices and stop there.
1599   // Also, stop if the first index of child is a non-zero array index
1600   // and the last index of the current node is a non-array index:
1601   // in that case, a non-array declared type is being accessed as an array
1602   // which is not type-safe, but could be legal.
1603   InstructionNode* ptrChild = gepNode;
1604   while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
1605                       ptrChild->getOpLabel() == GetElemPtrIdx)) {
1606     // Child is a GetElemPtr instruction
1607     gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
1608     User::op_iterator OI, firstIdx = gepInst->idx_begin();
1609     User::op_iterator lastIdx = gepInst->idx_end();
1610     bool allConstantOffsets = true;
1611
1612     // The first index of every GEP must be an array index.
1613     assert((*firstIdx)->getType() == Type::LongTy &&
1614            "INTERNAL ERROR: Structure index for a pointer type!");
1615
1616     // If the last instruction had a leading non-zero index, check if the
1617     // current one references a sequential (i.e., indexable) type.
1618     // If not, the code is not type-safe and we would create an illegal GEP
1619     // by folding them, so don't fold any more instructions.
1620     if (lastInstHasLeadingNonZero)
1621       if (! isa<SequentialType>(gepInst->getType()->getElementType()))
1622         break;   // cannot fold in any preceding getElementPtr instrs.
1623
1624     // Check that all offsets are constant for this instruction
1625     for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
1626       allConstantOffsets = isa<ConstantInt>(*OI);
1627
1628     if (allConstantOffsets) {
1629       // Get pointer value out of ptrChild.
1630       ptrVal = gepInst->getPointerOperand();
1631
1632       // Insert its index vector at the start, skipping any leading [0]
1633       // Remember the old size to check if anything was inserted.
1634       unsigned oldSize = chainIdxVec.size();
1635       int firstIsZero = IsZero(*firstIdx);
1636       chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
1637
1638       // Remember if it has leading zero index: it will be discarded later.
1639       if (oldSize < chainIdxVec.size())
1640         lastInstHasLeadingNonZero = !firstIsZero;
1641
1642       // Mark the folded node so no code is generated for it.
1643       ((InstructionNode*) ptrChild)->markFoldedIntoParent();
1644
1645       // Get the previous GEP instruction and continue trying to fold
1646       ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
1647     } else // cannot fold this getElementPtr instr. or any preceding ones
1648       break;
1649   }
1650
1651   // If the first getElementPtr instruction had a leading [0], add it back.
1652   // Note that this instruction is the *last* one that was successfully
1653   // folded *and* contributed any indices, in the loop above.
1654   if (ptrVal && ! lastInstHasLeadingNonZero) 
1655     chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
1656
1657   return ptrVal;
1658 }
1659
1660 /// GetGEPInstArgs - Helper function for GetMemInstArgs that handles the
1661 /// final getElementPtr instruction used by (or same as) the memory operation.
1662 /// Extracts the indices of the current instruction and tries to fold in
1663 /// preceding ones if all indices of the current one are constant.
1664 ///
1665 static Value *GetGEPInstArgs(InstructionNode *gepNode,
1666                              std::vector<Value *> &idxVec,
1667                              bool &allConstantIndices) {
1668   allConstantIndices = true;
1669   GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
1670
1671   // Default pointer is the one from the current instruction.
1672   Value* ptrVal = gepI->getPointerOperand();
1673   InstrTreeNode* ptrChild = gepNode->leftChild(); 
1674
1675   // Extract the index vector of the GEP instruction.
1676   // If all indices are constant and first index is zero, try to fold
1677   // in preceding GEPs with all constant indices.
1678   for (User::op_iterator OI=gepI->idx_begin(),  OE=gepI->idx_end();
1679        allConstantIndices && OI != OE; ++OI)
1680     if (! isa<Constant>(*OI))
1681       allConstantIndices = false;     // note: this also terminates loop!
1682
1683   // If we have only constant indices, fold chains of constant indices
1684   // in this and any preceding GetElemPtr instructions.
1685   bool foldedGEPs = false;
1686   bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
1687   if (allConstantIndices)
1688     if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
1689       ptrVal = newPtr;
1690       foldedGEPs = true;
1691     }
1692
1693   // Append the index vector of the current instruction.
1694   // Skip the leading [0] index if preceding GEPs were folded into this.
1695   idxVec.insert(idxVec.end(),
1696                 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
1697                 gepI->idx_end());
1698
1699   return ptrVal;
1700 }
1701
1702 /// GetMemInstArgs - Get the pointer value and the index vector for a memory
1703 /// operation (GetElementPtr, Load, or Store).  If all indices of the given
1704 /// memory operation are constant, fold in constant indices in a chain of
1705 /// preceding GetElementPtr instructions (if any), and return the pointer value
1706 /// of the first instruction in the chain. All folded instructions are marked so
1707 /// no code is generated for them. Returns the pointer Value to use, and
1708 /// returns the resulting IndexVector in idxVec. Sets allConstantIndices
1709 /// to true/false if all indices are/aren't const.
1710 /// 
1711 static Value *GetMemInstArgs(InstructionNode *memInstrNode,
1712                              std::vector<Value*> &idxVec,
1713                              bool& allConstantIndices) {
1714   allConstantIndices = false;
1715   Instruction* memInst = memInstrNode->getInstruction();
1716   assert(idxVec.size() == 0 && "Need empty vector to return indices");
1717
1718   // If there is a GetElemPtr instruction to fold in to this instr,
1719   // it must be in the left child for Load and GetElemPtr, and in the
1720   // right child for Store instructions.
1721   InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
1722                              ? memInstrNode->rightChild()
1723                              : memInstrNode->leftChild()); 
1724   
1725   // Default pointer is the one from the current instruction.
1726   Value* ptrVal = ptrChild->getValue(); 
1727
1728   // Find the "last" GetElemPtr instruction: this one or the immediate child.
1729   // There will be none if this is a load or a store from a scalar pointer.
1730   InstructionNode* gepNode = NULL;
1731   if (isa<GetElementPtrInst>(memInst))
1732     gepNode = memInstrNode;
1733   else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
1734     // Child of load/store is a GEP and memInst is its only use.
1735     // Use its indices and mark it as folded.
1736     gepNode = cast<InstructionNode>(ptrChild);
1737     gepNode->markFoldedIntoParent();
1738   }
1739
1740   // If there are no indices, return the current pointer.
1741   // Else extract the pointer from the GEP and fold the indices.
1742   return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
1743                  : ptrVal;
1744 }
1745
1746 static inline MachineOpCode 
1747 ChooseBprInstruction(const InstructionNode* instrNode) {
1748   MachineOpCode opCode;
1749   
1750   Instruction* setCCInstr =
1751     ((InstructionNode*) instrNode->leftChild())->getInstruction();
1752   
1753   switch(setCCInstr->getOpcode()) {
1754   case Instruction::SetEQ: opCode = V9::BRZ;   break;
1755   case Instruction::SetNE: opCode = V9::BRNZ;  break;
1756   case Instruction::SetLE: opCode = V9::BRLEZ; break;
1757   case Instruction::SetGE: opCode = V9::BRGEZ; break;
1758   case Instruction::SetLT: opCode = V9::BRLZ;  break;
1759   case Instruction::SetGT: opCode = V9::BRGZ;  break;
1760   default:
1761     assert(0 && "Unrecognized VM instruction!");
1762     opCode = V9::INVALID_OPCODE;
1763     break; 
1764   }
1765   
1766   return opCode;
1767 }
1768
1769 static inline MachineOpCode 
1770 ChooseBpccInstruction(const InstructionNode* instrNode,
1771                       const BinaryOperator* setCCInstr) {
1772   MachineOpCode opCode = V9::INVALID_OPCODE;
1773   
1774   bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
1775   
1776   if (isSigned) {
1777     switch(setCCInstr->getOpcode()) {
1778     case Instruction::SetEQ: opCode = V9::BE;  break;
1779     case Instruction::SetNE: opCode = V9::BNE; break;
1780     case Instruction::SetLE: opCode = V9::BLE; break;
1781     case Instruction::SetGE: opCode = V9::BGE; break;
1782     case Instruction::SetLT: opCode = V9::BL;  break;
1783     case Instruction::SetGT: opCode = V9::BG;  break;
1784     default:
1785       assert(0 && "Unrecognized VM instruction!");
1786       break; 
1787     }
1788   } else {
1789     switch(setCCInstr->getOpcode()) {
1790     case Instruction::SetEQ: opCode = V9::BE;   break;
1791     case Instruction::SetNE: opCode = V9::BNE;  break;
1792     case Instruction::SetLE: opCode = V9::BLEU; break;
1793     case Instruction::SetGE: opCode = V9::BCC;  break;
1794     case Instruction::SetLT: opCode = V9::BCS;  break;
1795     case Instruction::SetGT: opCode = V9::BGU;  break;
1796     default:
1797       assert(0 && "Unrecognized VM instruction!");
1798       break; 
1799     }
1800   }
1801   
1802   return opCode;
1803 }
1804
1805 static inline MachineOpCode 
1806 ChooseBFpccInstruction(const InstructionNode* instrNode,
1807                        const BinaryOperator* setCCInstr) {
1808   MachineOpCode opCode = V9::INVALID_OPCODE;
1809   
1810   switch(setCCInstr->getOpcode()) {
1811   case Instruction::SetEQ: opCode = V9::FBE;  break;
1812   case Instruction::SetNE: opCode = V9::FBNE; break;
1813   case Instruction::SetLE: opCode = V9::FBLE; break;
1814   case Instruction::SetGE: opCode = V9::FBGE; break;
1815   case Instruction::SetLT: opCode = V9::FBL;  break;
1816   case Instruction::SetGT: opCode = V9::FBG;  break;
1817   default:
1818     assert(0 && "Unrecognized VM instruction!");
1819     break; 
1820   }
1821   
1822   return opCode;
1823 }
1824
1825 // GetTmpForCC - Create a unique TmpInstruction for a boolean value,
1826 // representing the CC register used by a branch on that value.
1827 // For now, hack this using a little static cache of TmpInstructions.
1828 // Eventually the entire BURG instruction selection should be put
1829 // into a separate class that can hold such information.
1830 // The static cache is not too bad because the memory for these
1831 // TmpInstructions will be freed along with the rest of the Function anyway.
1832 // 
1833 static TmpInstruction *GetTmpForCC (Value* boolVal, const Function *F,
1834                                     const Type* ccType,
1835                                     MachineCodeForInstruction& mcfi) {
1836   typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
1837   static BoolTmpCache boolToTmpCache;     // Map boolVal -> TmpInstruction*
1838   static const Function *lastFunction = 0;// Use to flush cache between funcs
1839   
1840   assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
1841   
1842   if (lastFunction != F) {
1843     lastFunction = F;
1844     boolToTmpCache.clear();
1845   }
1846   
1847   // Look for tmpI and create a new one otherwise.  The new value is
1848   // directly written to map using the ref returned by operator[].
1849   TmpInstruction*& tmpI = boolToTmpCache[boolVal];
1850   if (tmpI == NULL)
1851     tmpI = new TmpInstruction(mcfi, ccType, boolVal);
1852   
1853   return tmpI;
1854 }
1855
1856 static inline MachineOpCode 
1857 ChooseBccInstruction(const InstructionNode* instrNode, const Type*& setCCType) {
1858   InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
1859   assert(setCCNode->getOpLabel() == SetCCOp);
1860   BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
1861   setCCType = setCCInstr->getOperand(0)->getType();
1862   
1863   if (setCCType->isFloatingPoint())
1864     return ChooseBFpccInstruction(instrNode, setCCInstr);
1865   else
1866     return ChooseBpccInstruction(instrNode, setCCInstr);
1867 }
1868
1869 /// ChooseMovFpcciInstruction - WARNING: since this function has only one
1870 /// caller, it always returns the opcode that expects an immediate and a
1871 /// register. If this function is ever used in cases where an opcode that takes
1872 /// two registers is required, then modify this function and use
1873 /// convertOpcodeFromRegToImm() where required. It will be necessary to expand
1874 /// convertOpcodeFromRegToImm() to handle the new cases of opcodes.
1875 /// 
1876 static inline MachineOpCode 
1877 ChooseMovFpcciInstruction(const InstructionNode* instrNode) {
1878   MachineOpCode opCode = V9::INVALID_OPCODE;
1879   
1880   switch(instrNode->getInstruction()->getOpcode()) {
1881   case Instruction::SetEQ: opCode = V9::MOVFEi;  break;
1882   case Instruction::SetNE: opCode = V9::MOVFNEi; break;
1883   case Instruction::SetLE: opCode = V9::MOVFLEi; break;
1884   case Instruction::SetGE: opCode = V9::MOVFGEi; break;
1885   case Instruction::SetLT: opCode = V9::MOVFLi;  break;
1886   case Instruction::SetGT: opCode = V9::MOVFGi;  break;
1887   default:
1888     assert(0 && "Unrecognized VM instruction!");
1889     break; 
1890   }
1891   
1892   return opCode;
1893 }
1894
1895 /// ChooseMovpcciForSetCC -- Choose a conditional-move instruction
1896 /// based on the type of SetCC operation.
1897 /// 
1898 /// WARNING: like the previous function, this function always returns
1899 /// the opcode that expects an immediate and a register.  See above.
1900 /// 
1901 static MachineOpCode ChooseMovpcciForSetCC(const InstructionNode* instrNode) {
1902   MachineOpCode opCode = V9::INVALID_OPCODE;
1903
1904   const Type* opType = instrNode->leftChild()->getValue()->getType();
1905   assert(opType->isIntegral() || isa<PointerType>(opType));
1906   bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
1907   
1908   switch(instrNode->getInstruction()->getOpcode()) {
1909   case Instruction::SetEQ: opCode = V9::MOVEi;                        break;
1910   case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
1911   case Instruction::SetGE: opCode = noSign? V9::MOVCCi  : V9::MOVGEi; break;
1912   case Instruction::SetLT: opCode = noSign? V9::MOVCSi  : V9::MOVLi;  break;
1913   case Instruction::SetGT: opCode = noSign? V9::MOVGUi  : V9::MOVGi;  break;
1914   case Instruction::SetNE: opCode = V9::MOVNEi;                       break;
1915   default: assert(0 && "Unrecognized LLVM instr!"); break; 
1916   }
1917   
1918   return opCode;
1919 }
1920
1921 /// ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
1922 /// instruction based on the type of SetCC operation.  These instructions
1923 /// compare a register with 0 and perform the move is the comparison is true.
1924 /// 
1925 /// WARNING: like the previous function, this function it always returns
1926 /// the opcode that expects an immediate and a register.  See above.
1927 /// 
1928 static MachineOpCode ChooseMovpregiForSetCC(const InstructionNode* instrNode) {
1929   MachineOpCode opCode = V9::INVALID_OPCODE;
1930   
1931   switch(instrNode->getInstruction()->getOpcode()) {
1932   case Instruction::SetEQ: opCode = V9::MOVRZi;  break;
1933   case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
1934   case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
1935   case Instruction::SetLT: opCode = V9::MOVRLZi;  break;
1936   case Instruction::SetGT: opCode = V9::MOVRGZi;  break;
1937   case Instruction::SetNE: opCode = V9::MOVRNZi; break;
1938   default: assert(0 && "Unrecognized VM instr!"); break; 
1939   }
1940   
1941   return opCode;
1942 }
1943
1944 static inline MachineOpCode
1945 ChooseConvertToFloatInstr(const TargetMachine& target,
1946                           OpLabel vopCode, const Type* opType) {
1947   assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
1948          "Unrecognized convert-to-float opcode!");
1949   assert((opType->isIntegral() || opType->isFloatingPoint() ||
1950           isa<PointerType>(opType))
1951          && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
1952
1953   MachineOpCode opCode = V9::INVALID_OPCODE;
1954
1955   unsigned opSize = target.getTargetData().getTypeSize(opType);
1956
1957   if (opType == Type::FloatTy)
1958     opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
1959   else if (opType == Type::DoubleTy)
1960     opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
1961   else if (opSize <= 4)
1962     opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
1963   else {
1964     assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
1965     opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
1966   }
1967   
1968   return opCode;
1969 }
1970
1971 static inline MachineOpCode 
1972 ChooseConvertFPToIntInstr(const TargetMachine& target,
1973                           const Type* destType, const Type* opType) {
1974   assert((opType == Type::FloatTy || opType == Type::DoubleTy)
1975          && "This function should only be called for FLOAT or DOUBLE");
1976   assert((destType->isIntegral() || isa<PointerType>(destType))
1977          && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
1978
1979   MachineOpCode opCode = V9::INVALID_OPCODE;
1980
1981   unsigned destSize = target.getTargetData().getTypeSize(destType);
1982
1983   if (destType == Type::UIntTy)
1984     assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
1985   else if (destSize <= 4)
1986     opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
1987   else {
1988     assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
1989     opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
1990   }
1991
1992   return opCode;
1993 }
1994
1995 static MachineInstr*
1996 CreateConvertFPToIntInstr(const TargetMachine& target, Value* srcVal,
1997                           Value* destVal, const Type* destType) {
1998   MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
1999                                                    srcVal->getType());
2000   assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
2001   return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
2002 }
2003
2004 /// CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned
2005 /// integer.  The FP value must be converted to the dest type in an FP register,
2006 /// and the result is then copied from FP to int register via memory.  SPARC
2007 /// does not have a float-to-uint conversion, only a float-to-int (fdtoi).
2008 /// Since fdtoi converts to signed integers, any FP value V between MAXINT+1 and
2009 /// MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
2010 /// Therefore, for converting an FP value to uint32_t, we first need to convert
2011 /// to uint64_t and then to uint32_t.
2012 /// 
2013 static void
2014 CreateCodeToConvertFloatToInt(const TargetMachine& target,
2015                               Value* opVal, Instruction* destI,
2016                               std::vector<MachineInstr*>& mvec,
2017                               MachineCodeForInstruction& mcfi) {
2018   Function* F = destI->getParent()->getParent();
2019
2020   // Create a temporary to represent the FP register into which the
2021   // int value will placed after conversion.  The type of this temporary
2022   // depends on the type of FP register to use: single-prec for a 32-bit
2023   // int or smaller; double-prec for a 64-bit int.
2024   size_t destSize = target.getTargetData().getTypeSize(destI->getType());
2025
2026   const Type* castDestType = destI->getType(); // type for the cast instr result
2027   const Type* castDestRegType;          // type for cast instruction result reg
2028   TmpInstruction* destForCast;          // dest for cast instruction
2029   Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
2030
2031   // For converting an FP value to uint32_t, we first need to convert to
2032   // uint64_t and then to uint32_t, as explained above.
2033   if (destI->getType() == Type::UIntTy) {
2034     castDestType    = Type::ULongTy;       // use this instead of type of destI
2035     castDestRegType = Type::DoubleTy;      // uint64_t needs 64-bit FP register.
2036     destForCast     = new TmpInstruction(mcfi, castDestRegType, opVal);
2037     fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
2038   } else {
2039     castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
2040     destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
2041   }
2042
2043   // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
2044   mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
2045                                            castDestType));
2046
2047   // Create the fpreg-to-intreg copy code
2048   CreateCodeToCopyFloatToInt(target, F, destForCast, fpToIntCopyDest, mvec,
2049                              mcfi);
2050
2051   // Create the uint64_t to uint32_t conversion, if needed
2052   if (destI->getType() == Type::UIntTy)
2053     CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
2054                                     /*numLowBits*/ 32, mvec, mcfi);
2055 }
2056
2057 static inline MachineOpCode 
2058 ChooseAddInstruction(const InstructionNode* instrNode) {
2059   return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
2060 }
2061
2062 static inline MachineInstr* 
2063 CreateMovFloatInstruction(const InstructionNode* instrNode,
2064                           const Type* resultType) {
2065   return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
2066                    .addReg(instrNode->leftChild()->getValue())
2067                    .addRegDef(instrNode->getValue());
2068 }
2069
2070 static inline MachineInstr* 
2071 CreateAddConstInstruction(const InstructionNode* instrNode) {
2072   MachineInstr* minstr = NULL;
2073   
2074   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2075   assert(isa<Constant>(constOp));
2076   
2077   // Cases worth optimizing are:
2078   // (1) Add with 0 for float or double: use an FMOV of appropriate type,
2079   //     instead of an FADD (1 vs 3 cycles).  There is no integer MOV.
2080   if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2081     double dval = FPC->getValue();
2082     if (dval == 0.0)
2083       minstr = CreateMovFloatInstruction(instrNode,
2084                                         instrNode->getInstruction()->getType());
2085   }
2086   
2087   return minstr;
2088 }
2089
2090 static inline MachineOpCode ChooseSubInstructionByType(const Type* resultType) {
2091   MachineOpCode opCode = V9::INVALID_OPCODE;
2092   
2093   if (resultType->isInteger() || isa<PointerType>(resultType)) {
2094       opCode = V9::SUBr;
2095   } else {
2096     switch(resultType->getTypeID()) {
2097     case Type::FloatTyID:  opCode = V9::FSUBS; break;
2098     case Type::DoubleTyID: opCode = V9::FSUBD; break;
2099     default: assert(0 && "Invalid type for SUB instruction"); break; 
2100     }
2101   }
2102
2103   return opCode;
2104 }
2105
2106 static inline MachineInstr* 
2107 CreateSubConstInstruction(const InstructionNode* instrNode) {
2108   MachineInstr* minstr = NULL;
2109   
2110   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2111   assert(isa<Constant>(constOp));
2112   
2113   // Cases worth optimizing are:
2114   // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
2115   //     instead of an FSUB (1 vs 3 cycles).  There is no integer MOV.
2116   if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2117     double dval = FPC->getValue();
2118     if (dval == 0.0)
2119       minstr = CreateMovFloatInstruction(instrNode,
2120                                         instrNode->getInstruction()->getType());
2121   }
2122   
2123   return minstr;
2124 }
2125
2126 static inline MachineOpCode 
2127 ChooseFcmpInstruction(const InstructionNode* instrNode) {
2128   MachineOpCode opCode = V9::INVALID_OPCODE;
2129   
2130   Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
2131   switch(operand->getType()->getTypeID()) {
2132   case Type::FloatTyID:  opCode = V9::FCMPS; break;
2133   case Type::DoubleTyID: opCode = V9::FCMPD; break;
2134   default: assert(0 && "Invalid type for FCMP instruction"); break; 
2135   }
2136   
2137   return opCode;
2138 }
2139
2140 /// BothFloatToDouble - Assumes that leftArg and rightArg of instrNode are both
2141 /// cast instructions. Returns true if both are floats cast to double.
2142 /// 
2143 static inline bool BothFloatToDouble(const InstructionNode* instrNode) {
2144   InstrTreeNode* leftArg = instrNode->leftChild();
2145   InstrTreeNode* rightArg = instrNode->rightChild();
2146   InstrTreeNode* leftArgArg = leftArg->leftChild();
2147   InstrTreeNode* rightArgArg = rightArg->leftChild();
2148   assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
2149   return (leftArg->getValue()->getType() == Type::DoubleTy &&
2150           leftArgArg->getValue()->getType() == Type::FloatTy &&
2151           rightArgArg->getValue()->getType() == Type::FloatTy);
2152 }
2153
2154 static inline MachineOpCode ChooseMulInstructionByType(const Type* resultType) {
2155   MachineOpCode opCode = V9::INVALID_OPCODE;
2156   
2157   if (resultType->isInteger())
2158     opCode = V9::MULXr;
2159   else
2160     switch(resultType->getTypeID()) {
2161     case Type::FloatTyID:  opCode = V9::FMULS; break;
2162     case Type::DoubleTyID: opCode = V9::FMULD; break;
2163     default: assert(0 && "Invalid type for MUL instruction"); break; 
2164     }
2165   
2166   return opCode;
2167 }
2168
2169 static inline MachineInstr*
2170 CreateIntNegInstruction(const TargetMachine& target, Value* vreg) {
2171   return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo()->getZeroRegNum())
2172     .addReg(vreg).addRegDef(vreg);
2173 }
2174
2175 /// CreateShiftInstructions - Create instruction sequence for any shift
2176 /// operation. SLL or SLLX on an operand smaller than the integer reg. size
2177 /// (64bits) requires a second instruction for explicit sign-extension. Note
2178 /// that we only have to worry about a sign-bit appearing in the most
2179 /// significant bit of the operand after shifting (e.g., bit 32 of Int or bit 16
2180 /// of Short), so we do not have to worry about results that are as large as a
2181 /// normal integer register.
2182 /// 
2183 static inline void
2184 CreateShiftInstructions(const TargetMachine& target, Function* F,
2185                         MachineOpCode shiftOpCode, Value* argVal1,
2186                         Value* optArgVal2, /* Use optArgVal2 if not NULL */
2187                         unsigned optShiftNum, /* else use optShiftNum */
2188                         Instruction* destVal, std::vector<MachineInstr*>& mvec,
2189                         MachineCodeForInstruction& mcfi) {
2190   assert((optArgVal2 != NULL || optShiftNum <= 64) &&
2191          "Large shift sizes unexpected, but can be handled below: "
2192          "You need to check whether or not it fits in immed field below");
2193   
2194   // If this is a logical left shift of a type smaller than the standard
2195   // integer reg. size, we have to extend the sign-bit into upper bits
2196   // of dest, so we need to put the result of the SLL into a temporary.
2197   Value* shiftDest = destVal;
2198   unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
2199
2200   if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
2201     // put SLL result into a temporary
2202     shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
2203   }
2204   
2205   MachineInstr* M = (optArgVal2 != NULL)
2206     ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
2207                              .addReg(shiftDest, MachineOperand::Def)
2208     : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
2209                              .addReg(shiftDest, MachineOperand::Def);
2210   mvec.push_back(M);
2211   
2212   if (shiftDest != destVal) {
2213     // extend the sign-bit of the result into all upper bits of dest
2214     assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
2215     CreateSignExtensionInstructions(target, F, shiftDest, destVal, 8*opSize,
2216                                     mvec, mcfi);
2217   }
2218 }
2219
2220 /// CreateMulConstInstruction - Does not create any instructions if we
2221 /// cannot exploit constant to create a cheaper instruction. This returns the
2222 /// approximate cost of the instructions generated, which is used to pick the
2223 /// cheapest when both operands are constant.
2224 /// 
2225 static unsigned
2226 CreateMulConstInstruction(const TargetMachine &target, Function* F,
2227                           Value* lval, Value* rval, Instruction* destVal,
2228                           std::vector<MachineInstr*>& mvec,
2229                           MachineCodeForInstruction& mcfi) {
2230   // Use max. multiply cost, viz., cost of MULX
2231   unsigned cost = target.getInstrInfo()->minLatency(V9::MULXr);
2232   unsigned firstNewInstr = mvec.size();
2233   
2234   Value* constOp = rval;
2235   if (! isa<Constant>(constOp))
2236     return cost;
2237   
2238   // Cases worth optimizing are:
2239   // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
2240   // (2) Multiply by 2^x for integer types: replace with Shift
2241   const Type* resultType = destVal->getType();
2242   
2243   if (resultType->isInteger() || isa<PointerType>(resultType)) {
2244     bool isValidConst;
2245     int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2246                                                    constOp->getType(),
2247                                                    isValidConst);
2248     if (isValidConst) {
2249       unsigned pow;
2250       bool needNeg = false;
2251       if (C < 0) {
2252         needNeg = true;
2253         C = -C;
2254       }
2255           
2256       if (C == 0 || C == 1) {
2257         cost = target.getInstrInfo()->minLatency(V9::ADDr);
2258         unsigned Zero = target.getRegInfo()->getZeroRegNum();
2259         MachineInstr* M;
2260         if (C == 0)
2261           M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
2262         else
2263           M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
2264         mvec.push_back(M);
2265       } else if (isPowerOf2(C, pow)) {
2266         unsigned opSize = target.getTargetData().getTypeSize(resultType);
2267         MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
2268         CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
2269                                 destVal, mvec, mcfi);
2270       }
2271           
2272       if (mvec.size() > 0 && needNeg) {
2273         // insert <reg = SUB 0, reg> after the instr to flip the sign
2274         MachineInstr* M = CreateIntNegInstruction(target, destVal);
2275         mvec.push_back(M);
2276       }
2277     }
2278   } else {
2279     if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2280       double dval = FPC->getValue();
2281       if (fabs(dval) == 1) {
2282         MachineOpCode opCode =  (dval < 0)
2283           ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2284           : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2285         mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
2286       } 
2287     }
2288   }
2289   
2290   if (firstNewInstr < mvec.size()) {
2291     cost = 0;
2292     for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
2293       cost += target.getInstrInfo()->minLatency(mvec[i]->getOpcode());
2294   }
2295   
2296   return cost;
2297 }
2298
2299 /// CreateCheapestMulConstInstruction - Does not create any instructions
2300 /// if we cannot exploit constant to create a cheaper instruction.
2301 ///
2302 static inline void
2303 CreateCheapestMulConstInstruction(const TargetMachine &target, Function* F,
2304                                   Value* lval, Value* rval,
2305                                   Instruction* destVal,
2306                                   std::vector<MachineInstr*>& mvec,
2307                                   MachineCodeForInstruction& mcfi) {
2308   Value* constOp;
2309   if (isa<Constant>(lval) && isa<Constant>(rval)) {
2310     // both operands are constant: evaluate and "set" in dest
2311     Constant* P = ConstantExpr::get(Instruction::Mul,
2312                                     cast<Constant>(lval),
2313                                     cast<Constant>(rval));
2314     CreateCodeToLoadConst (target, F, P, destVal, mvec, mcfi);
2315   }
2316   else if (isa<Constant>(rval))         // rval is constant, but not lval
2317     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2318   else if (isa<Constant>(lval))         // lval is constant, but not rval
2319     CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2320   
2321   // else neither is constant
2322   return;
2323 }
2324
2325 /// CreateMulInstruction - Returns NULL if we cannot exploit constant
2326 /// to create a cheaper instruction.
2327 /// 
2328 static inline void
2329 CreateMulInstruction(const TargetMachine &target, Function* F,
2330                      Value* lval, Value* rval, Instruction* destVal,
2331                      std::vector<MachineInstr*>& mvec,
2332                      MachineCodeForInstruction& mcfi,
2333                      MachineOpCode forceMulOp = -1) {
2334   unsigned L = mvec.size();
2335   CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
2336   if (mvec.size() == L) {
2337     // no instructions were added so create MUL reg, reg, reg.
2338     // Use FSMULD if both operands are actually floats cast to doubles.
2339     // Otherwise, use the default opcode for the appropriate type.
2340     MachineOpCode mulOp = ((forceMulOp != -1)
2341                            ? forceMulOp 
2342                            : ChooseMulInstructionByType(destVal->getType()));
2343     mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
2344                    .addRegDef(destVal));
2345   }
2346 }
2347
2348 /// ChooseDivInstruction - Generate a divide instruction for Div or Rem.
2349 /// For Rem, this assumes that the operand type will be signed if the result
2350 /// type is signed.  This is correct because they must have the same sign.
2351 /// 
2352 static inline MachineOpCode 
2353 ChooseDivInstruction(TargetMachine &target, const InstructionNode* instrNode) {
2354   MachineOpCode opCode = V9::INVALID_OPCODE;
2355   
2356   const Type* resultType = instrNode->getInstruction()->getType();
2357   
2358   if (resultType->isInteger())
2359     opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
2360   else
2361     switch(resultType->getTypeID()) {
2362       case Type::FloatTyID:  opCode = V9::FDIVS; break;
2363       case Type::DoubleTyID: opCode = V9::FDIVD; break;
2364       default: assert(0 && "Invalid type for DIV instruction"); break; 
2365       }
2366   
2367   return opCode;
2368 }
2369
2370 /// CreateDivConstInstruction - Return if we cannot exploit constant to create
2371 /// a cheaper instruction.
2372 /// 
2373 static void CreateDivConstInstruction(TargetMachine &target,
2374                                       const InstructionNode* instrNode,
2375                                       std::vector<MachineInstr*>& mvec) {
2376   Value* LHS  = instrNode->leftChild()->getValue();
2377   Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2378   if (!isa<Constant>(constOp))
2379     return;
2380
2381   Instruction* destVal = instrNode->getInstruction();
2382   unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
2383   
2384   // Cases worth optimizing are:
2385   // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
2386   // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
2387   const Type* resultType = instrNode->getInstruction()->getType();
2388  
2389   if (resultType->isInteger()) {
2390     unsigned pow;
2391     bool isValidConst;
2392     int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2393                                                    constOp->getType(),
2394                                                    isValidConst);
2395     if (isValidConst) {
2396       bool needNeg = false;
2397       if (C < 0) {
2398         needNeg = true;
2399         C = -C;
2400       }
2401       
2402       if (C == 1) {
2403         mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
2404                        .addRegDef(destVal));
2405       } else if (isPowerOf2(C, pow)) {
2406         unsigned opCode;
2407         Value* shiftOperand;
2408         unsigned opSize = target.getTargetData().getTypeSize(resultType);
2409
2410         if (resultType->isSigned()) {
2411           // For N / 2^k, if the operand N is negative,
2412           // we need to add (2^k - 1) before right-shifting by k, i.e.,
2413           // 
2414           //    (N / 2^k) = N >> k,               if N >= 0;
2415           //                (N + 2^k - 1) >> k,   if N < 0
2416           // 
2417           // If N is <= 32 bits, use:
2418           //    sra N, 31, t1           // t1 = ~0,         if N < 0,  0 else
2419           //    srl t1, 32-k, t2        // t2 = 2^k - 1,    if N < 0,  0 else
2420           //    add t2, N, t3           // t3 = N + 2^k -1, if N < 0,  N else
2421           //    sra t3, k, result       // result = N / 2^k
2422           // 
2423           // If N is 64 bits, use:
2424           //    srax N,  k-1,  t1       // t1 = sign bit in high k positions
2425           //    srlx t1, 64-k, t2       // t2 = 2^k - 1,    if N < 0,  0 else
2426           //    add t2, N, t3           // t3 = N + 2^k -1, if N < 0,  N else
2427           //    sra t3, k, result       // result = N / 2^k
2428           TmpInstruction *sraTmp, *srlTmp, *addTmp;
2429           MachineCodeForInstruction& mcfi
2430             = MachineCodeForInstruction::get(destVal);
2431           sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
2432           srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
2433           addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
2434
2435           // Create the SRA or SRAX instruction to get the sign bit
2436           mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
2437                          .addReg(LHS)
2438                          .addSImm((resultType==Type::LongTy)? pow-1 : 31)
2439                          .addRegDef(sraTmp));
2440
2441           // Create the SRL or SRLX instruction to get the sign bit
2442           mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
2443                          .addReg(sraTmp)
2444                          .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
2445                          .addRegDef(srlTmp));
2446
2447           // Create the ADD instruction to add 2^pow-1 for negative values
2448           mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
2449                          .addRegDef(addTmp));
2450
2451           // Get the shift operand and "right-shift" opcode to do the divide
2452           shiftOperand = addTmp;
2453           opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
2454         } else {
2455           // Get the shift operand and "right-shift" opcode to do the divide
2456           shiftOperand = LHS;
2457           opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
2458         }
2459
2460         // Now do the actual shift!
2461         mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
2462                        .addRegDef(destVal));
2463       }
2464           
2465       if (needNeg && (C == 1 || isPowerOf2(C, pow))) {
2466         // insert <reg = SUB 0, reg> after the instr to flip the sign
2467         mvec.push_back(CreateIntNegInstruction(target, destVal));
2468       }
2469     }
2470   } else {
2471     if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2472       double dval = FPC->getValue();
2473       if (fabs(dval) == 1) {
2474         unsigned opCode = 
2475           (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2476           : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2477               
2478         mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
2479       } 
2480     }
2481   }
2482 }
2483
2484 static void CreateCodeForVariableSizeAlloca(const TargetMachine& target,
2485                                             Instruction* result, unsigned tsize,
2486                                             Value* numElementsVal,
2487                                             std::vector<MachineInstr*>& getMvec)
2488 {
2489   Value* totalSizeVal;
2490   MachineInstr* M;
2491   MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
2492   Function *F = result->getParent()->getParent();
2493
2494   // Enforce the alignment constraints on the stack pointer at
2495   // compile time if the total size is a known constant.
2496   if (isa<Constant>(numElementsVal)) {
2497     bool isValid;
2498     int64_t numElem = (int64_t)
2499       ConvertConstantToIntType(target, numElementsVal,
2500                                numElementsVal->getType(), isValid);
2501     assert(isValid && "Unexpectedly large array dimension in alloca!");
2502     int64_t total = numElem * tsize;
2503     if (int extra= total % SparcV9FrameInfo::StackFrameSizeAlignment)
2504       total += SparcV9FrameInfo::StackFrameSizeAlignment - extra;
2505     totalSizeVal = ConstantSInt::get(Type::IntTy, total);
2506   } else {
2507     // The size is not a constant.  Generate code to compute it and
2508     // code to pad the size for stack alignment.
2509     // Create a Value to hold the (constant) element size
2510     Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
2511
2512     // Create temporary values to hold the result of MUL, SLL, SRL
2513     // To pad `size' to next smallest multiple of 16:
2514     //          size = (size + 15) & (-16 = 0xfffffffffffffff0)
2515     TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
2516     TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
2517     TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
2518
2519     // Instruction 1: mul numElements, typeSize -> tmpProd
2520     // This will optimize the MUL as far as possible.
2521     CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
2522                          mcfi, -1);
2523
2524     // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
2525     getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
2526                       .addReg(tmpAdd15, MachineOperand::Def));
2527
2528     // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
2529     getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
2530                       .addReg(tmpAndf0, MachineOperand::Def));
2531
2532     totalSizeVal = tmpAndf0;
2533   }
2534
2535   // Get the constant offset from SP for dynamically allocated storage
2536   // and create a temporary Value to hold it.
2537   MachineFunction& mcInfo = MachineFunction::get(F);
2538   bool growUp;
2539   ConstantSInt* dynamicAreaOffset =
2540     ConstantSInt::get(Type::IntTy,
2541                     target.getFrameInfo()->getDynamicAreaOffset(mcInfo,growUp));
2542   assert(! growUp && "Has SPARC v9 stack frame convention changed?");
2543
2544   unsigned SPReg = target.getRegInfo()->getStackPointer();
2545
2546   // Instruction 2: sub %sp, totalSizeVal -> %sp
2547   getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
2548                     .addMReg(SPReg,MachineOperand::Def));
2549
2550   // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
2551   getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
2552                     .addRegDef(result));
2553 }        
2554
2555 static void
2556 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
2557                              Instruction* result, unsigned tsize,
2558                              unsigned numElements,
2559                              std::vector<MachineInstr*>& getMvec) {
2560   assert(result && result->getParent() &&
2561          "Result value is not part of a function?");
2562   Function *F = result->getParent()->getParent();
2563   MachineFunction &mcInfo = MachineFunction::get(F);
2564
2565   // If the alloca is of zero bytes (which is perfectly legal) we bump it up to
2566   // one byte.  This is unnecessary, but I really don't want to break any
2567   // fragile logic in this code.  FIXME.
2568   if (tsize == 0)
2569     tsize = 1;
2570
2571   // Put the variable in the dynamically sized area of the frame if either:
2572   // (a) The offset is too large to use as an immediate in load/stores
2573   //     (check LDX because all load/stores have the same-size immed. field).
2574   // (b) The object is "large", so it could cause many other locals,
2575   //     spills, and temporaries to have large offsets.
2576   //     NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
2577   // You've gotta love having only 13 bits for constant offset values :-|.
2578   // 
2579   unsigned paddedSize;
2580   int offsetFromFP = mcInfo.getInfo<SparcV9FunctionInfo>()->computeOffsetforLocalVar(result,
2581                                                                 paddedSize,
2582                                                          tsize * numElements);
2583
2584   if (((int)paddedSize) > 8 * SparcV9FrameInfo::SizeOfEachArgOnStack ||
2585       !target.getInstrInfo()->constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
2586     CreateCodeForVariableSizeAlloca(target, result, tsize, 
2587                                     ConstantSInt::get(Type::IntTy,numElements),
2588                                     getMvec);
2589     return;
2590   }
2591   
2592   // else offset fits in immediate field so go ahead and allocate it.
2593   offsetFromFP = mcInfo.getInfo<SparcV9FunctionInfo>()->allocateLocalVar(result, tsize *numElements);
2594   
2595   // Create a temporary Value to hold the constant offset.
2596   // This is needed because it may not fit in the immediate field.
2597   ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
2598   
2599   // Instruction 1: add %fp, offsetFromFP -> result
2600   unsigned FPReg = target.getRegInfo()->getFramePointer();
2601   getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
2602                     .addRegDef(result));
2603 }
2604
2605 /// SetOperandsForMemInstr - Choose addressing mode for the given load or store
2606 /// instruction.  Use [reg+reg] if it is an indexed reference, and the index
2607 /// offset is not a constant or if it cannot fit in the offset field.  Use
2608 /// [reg+offset] in all other cases.  This assumes that all array refs are
2609 /// "lowered" to one of these forms:
2610 ///    %x = load (subarray*) ptr, constant      ; single constant offset
2611 ///    %x = load (subarray*) ptr, offsetVal     ; single non-constant offset
2612 /// Generally, this should happen via strength reduction + LICM.  Also, strength
2613 /// reduction should take care of using the same register for the loop index
2614 /// variable and an array index, when that is profitable.
2615 ///
2616 static void SetOperandsForMemInstr(unsigned Opcode,
2617                                    std::vector<MachineInstr*>& mvec,
2618                                    InstructionNode* vmInstrNode,
2619                                    const TargetMachine& target) {
2620   Instruction* memInst = vmInstrNode->getInstruction();
2621   // Index vector, ptr value, and flag if all indices are const.
2622   std::vector<Value*> idxVec;
2623   bool allConstantIndices;
2624   Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
2625
2626   // Now create the appropriate operands for the machine instruction.
2627   // First, initialize so we default to storing the offset in a register.
2628   int64_t smallConstOffset = 0;
2629   Value* valueForRegOffset = NULL;
2630   MachineOperand::MachineOperandType offsetOpType =
2631     MachineOperand::MO_VirtualRegister;
2632
2633   // Check if there is an index vector and if so, compute the
2634   // right offset for structures and for arrays 
2635   if (!idxVec.empty()) {
2636     const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
2637       
2638     // If all indices are constant, compute the combined offset directly.
2639     if (allConstantIndices) {
2640       // Compute the offset value using the index vector. Create a
2641       // virtual reg. for it since it may not fit in the immed field.
2642       uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
2643       valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
2644     } else {
2645       // There is at least one non-constant offset.  Therefore, this must
2646       // be an array ref, and must have been lowered to a single non-zero
2647       // offset.  (An extra leading zero offset, if any, can be ignored.)
2648       // Generate code sequence to compute address from index.
2649       bool firstIdxIsZero = IsZero(idxVec[0]);
2650       assert(idxVec.size() == 1U + firstIdxIsZero 
2651              && "Array refs must be lowered before Instruction Selection");
2652
2653       Value* idxVal = idxVec[firstIdxIsZero];
2654
2655       std::vector<MachineInstr*> mulVec;
2656       Instruction* addr =
2657         new TmpInstruction(MachineCodeForInstruction::get(memInst),
2658                            Type::ULongTy, memInst);
2659
2660       // Get the array type indexed by idxVal, and compute its element size.
2661       // The call to getTypeSize() will fail if size is not constant.
2662       const Type* vecType = (firstIdxIsZero
2663                              ? GetElementPtrInst::getIndexedType(ptrType,
2664                                            std::vector<Value*>(1U, idxVec[0]),
2665                                            /*AllowCompositeLeaf*/ true)
2666                                  : ptrType);
2667       const Type* eltType = cast<SequentialType>(vecType)->getElementType();
2668       ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
2669                                    target.getTargetData().getTypeSize(eltType));
2670
2671       // CreateMulInstruction() folds constants intelligently enough.
2672       CreateMulInstruction(target, memInst->getParent()->getParent(),
2673                            idxVal,         /* lval, not likely to be const*/
2674                            eltSizeVal,     /* rval, likely to be constant */
2675                            addr,           /* result */
2676                            mulVec, MachineCodeForInstruction::get(memInst),
2677                            -1);
2678
2679       assert(mulVec.size() > 0 && "No multiply code created?");
2680       mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
2681       
2682       valueForRegOffset = addr;
2683     }
2684   } else {
2685     offsetOpType = MachineOperand::MO_SignExtendedImmed;
2686     smallConstOffset = 0;
2687   }
2688
2689   // For STORE:
2690   //   Operand 0 is value, operand 1 is ptr, operand 2 is offset
2691   // For LOAD or GET_ELEMENT_PTR,
2692   //   Operand 0 is ptr, operand 1 is offset, operand 2 is result.
2693   unsigned offsetOpNum, ptrOpNum;
2694   MachineInstr *MI;
2695   if (memInst->getOpcode() == Instruction::Store) {
2696     if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2697       MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2698                              .addReg(ptrVal).addReg(valueForRegOffset);
2699     } else {
2700       Opcode = convertOpcodeFromRegToImm(Opcode);
2701       MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2702                              .addReg(ptrVal).addSImm(smallConstOffset);
2703     }
2704   } else {
2705     if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2706       MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
2707                              .addRegDef(memInst);
2708     } else {
2709       Opcode = convertOpcodeFromRegToImm(Opcode);
2710       MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
2711                              .addRegDef(memInst);
2712     }
2713   }
2714   mvec.push_back(MI);
2715 }
2716
2717 /// ForwardOperand - Substitute operand `operandNum' of the instruction in
2718 /// node `treeNode' in place of the use(s) of that instruction in node `parent'.
2719 /// Check both explicit and implicit operands!  Also make sure to skip over a
2720 /// parent who: (1) is a list node in the Burg tree, or (2) itself had its
2721 /// results forwarded to its parent.
2722 /// 
2723 static void ForwardOperand (InstructionNode *treeNode, InstrTreeNode *parent,
2724                             int operandNum) {
2725   assert(treeNode && parent && "Invalid invocation of ForwardOperand");
2726   
2727   Instruction* unusedOp = treeNode->getInstruction();
2728   Value* fwdOp = unusedOp->getOperand(operandNum);
2729
2730   // The parent itself may be a list node, so find the real parent instruction
2731   while (parent->getNodeType() != InstrTreeNode::NTInstructionNode) {
2732     parent = parent->parent();
2733     assert(parent && "ERROR: Non-instruction node has no parent in tree.");
2734   }
2735   InstructionNode* parentInstrNode = (InstructionNode*) parent;
2736   
2737   Instruction* userInstr = parentInstrNode->getInstruction();
2738   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
2739
2740   // The parent's mvec would be empty if it was itself forwarded.
2741   // Recursively call ForwardOperand in that case...
2742   //
2743   if (mvec.size() == 0) {
2744     assert(parent->parent() != NULL &&
2745            "Parent could not have been forwarded, yet has no instructions?");
2746     ForwardOperand(treeNode, parent->parent(), operandNum);
2747   } else {
2748     for (unsigned i=0, N=mvec.size(); i < N; i++) {
2749       MachineInstr* minstr = mvec[i];
2750       for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
2751         const MachineOperand& mop = minstr->getOperand(i);
2752         if (mop.getType() == MachineOperand::MO_VirtualRegister &&
2753             mop.getVRegValue() == unusedOp) {
2754           minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
2755                                        fwdOp);
2756         }
2757       }
2758           
2759       for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
2760         if (minstr->getImplicitRef(i) == unusedOp)
2761           minstr->setImplicitRef(i, fwdOp);
2762     }
2763   }
2764 }
2765
2766 /// AllUsesAreBranches - Returns true if all the uses of I are
2767 /// Branch instructions, false otherwise.
2768 /// 
2769 inline bool AllUsesAreBranches(const Instruction* I) {
2770   for (Value::use_const_iterator UI=I->use_begin(), UE=I->use_end();
2771        UI != UE; ++UI)
2772     if (! isa<TmpInstruction>(*UI)     // ignore tmp instructions here
2773         && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
2774       return false;
2775   return true;
2776 }
2777
2778 /// CodeGenIntrinsic - Generate code for any intrinsic that needs a special
2779 /// code sequence instead of a regular call.  If not that kind of intrinsic, do
2780 /// nothing. Returns true if code was generated, otherwise false.
2781 /// 
2782 static bool CodeGenIntrinsic(Intrinsic::ID iid, CallInst &callInstr,
2783                              TargetMachine &target,
2784                              std::vector<MachineInstr*>& mvec) {
2785   switch (iid) {
2786   default:
2787     assert(0 && "Unknown intrinsic function call should have been lowered!");
2788   case Intrinsic::vastart: {
2789     // Get the address of the first incoming vararg argument on the stack
2790     Function* func = cast<Function>(callInstr.getParent()->getParent());
2791     int numFixedArgs   = func->getFunctionType()->getNumParams();
2792     int fpReg          = SparcV9::i6;
2793     int firstVarArgOff = numFixedArgs * 8 + 
2794                          SparcV9FrameInfo::FirstIncomingArgOffsetFromFP;
2795     mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).
2796                    addRegDef(&callInstr));
2797     return true;
2798   }
2799
2800   case Intrinsic::vaend:
2801     return true;                        // no-op on SparcV9
2802
2803   case Intrinsic::vacopy:
2804     // Simple copy of current va_list (arg1) to new va_list (result)
2805     mvec.push_back(BuildMI(V9::ORr, 3).
2806                    addMReg(target.getRegInfo()->getZeroRegNum()).
2807                    addReg(callInstr.getOperand(1)).
2808                    addRegDef(&callInstr));
2809     return true;
2810   }
2811 }
2812
2813 /// ThisIsAChainRule - returns true if the given  BURG rule is a chain rule.
2814 /// 
2815 extern bool ThisIsAChainRule(int eruleno) {
2816   switch(eruleno) {
2817     case 111:   // stmt:  reg
2818     case 123:
2819     case 124:
2820     case 125:
2821     case 126:
2822     case 127:
2823     case 128:
2824     case 129:
2825     case 130:
2826     case 131:
2827     case 132:
2828     case 133:
2829     case 155:
2830     case 221:
2831     case 222:
2832     case 241:
2833     case 242:
2834     case 243:
2835     case 244:
2836     case 245:
2837     case 321:
2838       return true; break;
2839
2840     default:
2841       return false; break;
2842     }
2843 }
2844
2845 /// GetInstructionsByRule - Choose machine instructions for the
2846 /// SPARC V9 according to the patterns chosen by the BURG-generated parser.
2847 /// This is where most of the work in the V9 instruction selector gets done.
2848 /// 
2849 void GetInstructionsByRule(InstructionNode* subtreeRoot, int ruleForNode,
2850                            short* nts, TargetMachine &target,
2851                            std::vector<MachineInstr*>& mvec) {
2852   bool checkCast = false;               // initialize here to use fall-through
2853   bool maskUnsignedResult = false;
2854   int nextRule;
2855   int forwardOperandNum = -1;
2856   unsigned allocaSize = 0;
2857   MachineInstr* M, *M2;
2858   unsigned L;
2859   bool foldCase = false;
2860
2861   mvec.clear(); 
2862   
2863   // If the code for this instruction was folded into the parent (user),
2864   // then do nothing!
2865   if (subtreeRoot->isFoldedIntoParent())
2866     return;
2867   
2868   // Let's check for chain rules outside the switch so that we don't have
2869   // to duplicate the list of chain rule production numbers here again
2870   if (ThisIsAChainRule(ruleForNode)) {
2871     // Chain rules have a single nonterminal on the RHS.
2872     // Get the rule that matches the RHS non-terminal and use that instead.
2873     assert(nts[0] && ! nts[1]
2874            && "A chain rule should have only one RHS non-terminal!");
2875     nextRule = burm_rule(subtreeRoot->state, nts[0]);
2876     nts = burm_nts[nextRule];
2877     GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
2878   } else {
2879     switch(ruleForNode) {
2880       case 1:   // stmt:   Ret
2881       case 2:   // stmt:   RetValue(reg)
2882       {         // NOTE: Prepass of register allocation is responsible
2883                 //       for moving return value to appropriate register.
2884                 // Copy the return value to the required return register.
2885                 // Mark the return Value as an implicit ref of the RET instr..
2886                 // Mark the return-address register as a hidden virtual reg.
2887                 // Finally put a NOP in the delay slot.
2888         ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
2889         Value* retVal = returnInstr->getReturnValue();
2890         MachineCodeForInstruction& mcfi =
2891           MachineCodeForInstruction::get(returnInstr);
2892
2893         // Create a hidden virtual reg to represent the return address register
2894         // used by the machine instruction but not represented in LLVM.
2895         Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
2896
2897         MachineInstr* retMI = 
2898           BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
2899           .addMReg(target.getRegInfo()->getZeroRegNum(), MachineOperand::Def);
2900       
2901         // If there is a value to return, we need to:
2902         // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
2903         // (b) Insert a copy to copy the return value to the appropriate reg.
2904         //     -- For FP values, create a FMOVS or FMOVD instruction
2905         //     -- For non-FP values, create an add-with-0 instruction
2906         if (retVal != NULL) {
2907           const SparcV9RegInfo& regInfo =
2908             (SparcV9RegInfo&) *target.getRegInfo();
2909           const Type* retType = retVal->getType();
2910           unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2911           unsigned retRegNum = (retType->isFloatingPoint()
2912                                 ? (unsigned) SparcV9FloatRegClass::f0
2913                                 : (unsigned) SparcV9IntRegClass::i0);
2914           retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
2915
2916           // Insert sign-extension instructions for small signed values.
2917           Value* retValToUse = retVal;
2918           if (retType->isIntegral() && retType->isSigned()) {
2919             unsigned retSize = target.getTargetData().getTypeSize(retType);
2920             if (retSize <= 4) {
2921               // Create a temporary virtual reg. to hold the sign-extension.
2922               retValToUse = new TmpInstruction(mcfi, retVal);
2923
2924               // Sign-extend retVal and put the result in the temporary reg.
2925               CreateSignExtensionInstructions
2926                 (target, returnInstr->getParent()->getParent(),
2927                  retVal, retValToUse, 8*retSize, mvec, mcfi);
2928             }
2929           }
2930
2931           // (b) Now, insert a copy to to the appropriate register:
2932           //     -- For FP values, create a FMOVS or FMOVD instruction
2933           //     -- For non-FP values, create an add-with-0 instruction
2934           // First, create a virtual register to represent the register and
2935           // mark this vreg as being an implicit operand of the ret MI.
2936           TmpInstruction* retVReg = 
2937             new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
2938           
2939           retMI->addImplicitRef(retVReg);
2940           
2941           if (retType->isFloatingPoint())
2942             M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
2943                  .addReg(retValToUse).addReg(retVReg, MachineOperand::Def));
2944           else
2945             M = (BuildMI(ChooseAddInstructionByType(retType), 3)
2946                  .addReg(retValToUse).addSImm((int64_t) 0)
2947                  .addReg(retVReg, MachineOperand::Def));
2948
2949           // Mark the operand with the register it should be assigned
2950           M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
2951           retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
2952
2953           mvec.push_back(M);
2954         }
2955         
2956         // Now insert the RET instruction and a NOP for the delay slot
2957         mvec.push_back(retMI);
2958         mvec.push_back(BuildMI(V9::NOP, 0));
2959         
2960         break;
2961       }  
2962         
2963       case 3:   // stmt:   Store(reg,reg)
2964       case 4:   // stmt:   Store(reg,ptrreg)
2965         SetOperandsForMemInstr(ChooseStoreInstruction(
2966                         subtreeRoot->leftChild()->getValue()->getType()),
2967                                mvec, subtreeRoot, target);
2968         break;
2969
2970       case 5:   // stmt:   BrUncond
2971         {
2972           BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
2973           mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
2974         
2975           // delay slot
2976           mvec.push_back(BuildMI(V9::NOP, 0));
2977           break;
2978         }
2979
2980       case 206: // stmt:   BrCond(setCCconst)
2981       { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
2982         // If the constant is ZERO, we can use the branch-on-integer-register
2983         // instructions and avoid the SUBcc instruction entirely.
2984         // Otherwise this is just the same as case 5, so just fall through.
2985         // 
2986         InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
2987         assert(constNode &&
2988                constNode->getNodeType() ==InstrTreeNode::NTConstNode);
2989         Constant *constVal = cast<Constant>(constNode->getValue());
2990         bool isValidConst;
2991         
2992         if ((constVal->getType()->isInteger()
2993              || isa<PointerType>(constVal->getType()))
2994             && ConvertConstantToIntType(target,
2995                              constVal, constVal->getType(), isValidConst) == 0
2996             && isValidConst)
2997           {
2998             // That constant is a zero after all...
2999             // Use the left child of setCC as the first argument!
3000             // Mark the setCC node so that no code is generated for it.
3001             InstructionNode* setCCNode = (InstructionNode*)
3002                                          subtreeRoot->leftChild();
3003             assert(setCCNode->getOpLabel() == SetCCOp);
3004             setCCNode->markFoldedIntoParent();
3005             
3006             BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
3007             
3008             M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
3009                                 .addReg(setCCNode->leftChild()->getValue())
3010                                 .addPCDisp(brInst->getSuccessor(0));
3011             mvec.push_back(M);
3012             
3013             // delay slot
3014             mvec.push_back(BuildMI(V9::NOP, 0));
3015
3016             // false branch
3017             mvec.push_back(BuildMI(V9::BA, 1)
3018                            .addPCDisp(brInst->getSuccessor(1)));
3019             
3020             // delay slot
3021             mvec.push_back(BuildMI(V9::NOP, 0));
3022             break;
3023           }
3024         // ELSE FALL THROUGH
3025       }
3026
3027       case 6:   // stmt:   BrCond(setCC)
3028       { // bool => boolean was computed with SetCC.
3029         // The branch to use depends on whether it is FP, signed, or unsigned.
3030         // If it is an integer CC, we also need to find the unique
3031         // TmpInstruction representing that CC.
3032         // 
3033         BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
3034         const Type* setCCType;
3035         unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
3036         Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
3037                                      brInst->getParent()->getParent(),
3038                                      setCCType,
3039                                      MachineCodeForInstruction::get(brInst));
3040         M = BuildMI(Opcode, 2).addCCReg(ccValue)
3041                               .addPCDisp(brInst->getSuccessor(0));
3042         mvec.push_back(M);
3043
3044         // delay slot
3045         mvec.push_back(BuildMI(V9::NOP, 0));
3046
3047         // false branch
3048         mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
3049
3050         // delay slot
3051         mvec.push_back(BuildMI(V9::NOP, 0));
3052         break;
3053       }
3054         
3055       case 208: // stmt:   BrCond(boolconst)
3056       {
3057         // boolconst => boolean is a constant; use BA to first or second label
3058         Constant* constVal = 
3059           cast<Constant>(subtreeRoot->leftChild()->getValue());
3060         unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
3061         
3062         M = BuildMI(V9::BA, 1).addPCDisp(
3063           cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
3064         mvec.push_back(M);
3065         
3066         // delay slot
3067         mvec.push_back(BuildMI(V9::NOP, 0));
3068         break;
3069       }
3070         
3071       case   8: // stmt:   BrCond(boolreg)
3072       { // boolreg   => boolean is recorded in an integer register.
3073         //              Use branch-on-integer-register instruction.
3074         // 
3075         BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
3076         M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
3077           .addPCDisp(BI->getSuccessor(0));
3078         mvec.push_back(M);
3079
3080         // delay slot
3081         mvec.push_back(BuildMI(V9::NOP, 0));
3082
3083         // false branch
3084         mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
3085         
3086         // delay slot
3087         mvec.push_back(BuildMI(V9::NOP, 0));
3088         break;
3089       }  
3090       
3091       case 9:   // stmt:   Switch(reg)
3092         assert(0 && "*** SWITCH instruction is not implemented yet.");
3093         break;
3094
3095       case 10:  // reg:   VRegList(reg, reg)
3096         assert(0 && "VRegList should never be the topmost non-chain rule");
3097         break;
3098
3099       case 21:  // bool:  Not(bool,reg): Compute with a conditional-move-on-reg
3100       { // First find the unary operand. It may be left or right, usually right.
3101         Instruction* notI = subtreeRoot->getInstruction();
3102         Value* notArg = BinaryOperator::getNotArgument(
3103                            cast<BinaryOperator>(subtreeRoot->getInstruction()));
3104         unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3105
3106         // Unconditionally set register to 0
3107         mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
3108
3109         // Now conditionally move 1 into the register.
3110         // Mark the register as a use (as well as a def) because the old
3111         // value will be retained if the condition is false.
3112         mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
3113                        .addReg(notI, MachineOperand::UseAndDef));
3114
3115         break;
3116       }
3117
3118       case 421: // reg:   BNot(reg,reg): Compute as reg = reg XOR-NOT 0
3119       { // First find the unary operand. It may be left or right, usually right.
3120         Value* notArg = BinaryOperator::getNotArgument(
3121                            cast<BinaryOperator>(subtreeRoot->getInstruction()));
3122         unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3123         mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
3124                                        .addRegDef(subtreeRoot->getValue()));
3125         break;
3126       }
3127
3128       case 322: // reg:   Not(tobool, reg):
3129         // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
3130         foldCase = true;
3131         // Just fall through!
3132
3133       case 22:  // reg:   ToBoolTy(reg):
3134       {
3135         Instruction* castI = subtreeRoot->getInstruction();
3136         Value* opVal = subtreeRoot->leftChild()->getValue();
3137         assert(opVal->getType()->isIntegral() ||
3138                isa<PointerType>(opVal->getType()));
3139
3140         // Unconditionally set register to 0
3141         mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
3142
3143         // Now conditionally move 1 into the register.
3144         // Mark the register as a use (as well as a def) because the old
3145         // value will be retained if the condition is false.
3146         MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
3147         mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
3148                        .addReg(castI, MachineOperand::UseAndDef));
3149
3150         break;
3151       }
3152       
3153       case 23:  // reg:   ToUByteTy(reg)
3154       case 24:  // reg:   ToSByteTy(reg)
3155       case 25:  // reg:   ToUShortTy(reg)
3156       case 26:  // reg:   ToShortTy(reg)
3157       case 27:  // reg:   ToUIntTy(reg)
3158       case 28:  // reg:   ToIntTy(reg)
3159       case 29:  // reg:   ToULongTy(reg)
3160       case 30:  // reg:   ToLongTy(reg)
3161       {
3162         //======================================================================
3163         // Rules for integer conversions:
3164         // 
3165         //--------
3166         // From ISO 1998 C++ Standard, Sec. 4.7:
3167         //
3168         // 2. If the destination type is unsigned, the resulting value is
3169         // the least unsigned integer congruent to the source integer
3170         // (modulo 2n where n is the number of bits used to represent the
3171         // unsigned type). [Note: In a two s complement representation,
3172         // this conversion is conceptual and there is no change in the
3173         // bit pattern (if there is no truncation). ]
3174         // 
3175         // 3. If the destination type is signed, the value is unchanged if
3176         // it can be represented in the destination type (and bitfield width);
3177         // otherwise, the value is implementation-defined.
3178         //--------
3179         // 
3180         // Since we assume 2s complement representations, this implies:
3181         // 
3182         // -- If operand is smaller than destination, zero-extend or sign-extend
3183         //    according to the signedness of the *operand*: source decides:
3184         //    (1) If operand is signed, sign-extend it.
3185         //        If dest is unsigned, zero-ext the result!
3186         //    (2) If operand is unsigned, our current invariant is that
3187         //        it's high bits are correct, so zero-extension is not needed.
3188         // 
3189         // -- If operand is same size as or larger than destination,
3190         //    zero-extend or sign-extend according to the signedness of
3191         //    the *destination*: destination decides:
3192         //    (1) If destination is signed, sign-extend (truncating if needed)
3193         //        This choice is implementation defined.  We sign-extend the
3194         //        operand, which matches both Sun's cc and gcc3.2.
3195         //    (2) If destination is unsigned, zero-extend (truncating if needed)
3196         //======================================================================
3197
3198         Instruction* destI =  subtreeRoot->getInstruction();
3199         Function* currentFunc = destI->getParent()->getParent();
3200         MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
3201
3202         Value* opVal = subtreeRoot->leftChild()->getValue();
3203         const Type* opType = opVal->getType();
3204         const Type* destType = destI->getType();
3205         unsigned opSize   = target.getTargetData().getTypeSize(opType);
3206         unsigned destSize = target.getTargetData().getTypeSize(destType);
3207         
3208         bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
3209
3210         if (opType == Type::BoolTy ||
3211             opType == destType ||
3212             isIntegral && opSize == destSize && opSize == 8) {
3213           // nothing to do in all these cases
3214           forwardOperandNum = 0;          // forward first operand to user
3215
3216         } else if (opType->isFloatingPoint()) {
3217
3218           CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
3219           if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
3220             maskUnsignedResult = true; // not handled by fp->int code
3221
3222         } else if (isIntegral) {
3223
3224           bool opSigned     = opType->isSigned();
3225           bool destSigned   = destType->isSigned();
3226           unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
3227
3228           assert(! (opSize == destSize && opSigned == destSigned) &&
3229                  "How can different int types have same size and signedness?");
3230
3231           bool signExtend = (opSize <  destSize && opSigned ||
3232                              opSize >= destSize && destSigned);
3233
3234           bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
3235                                     opSigned && !destSigned);
3236           assert(!signAndZeroExtend || signExtend);
3237
3238           bool zeroExtendOnly = opSize >= destSize && !destSigned;
3239           assert(!zeroExtendOnly || !signExtend);
3240
3241           if (signExtend) {
3242             Value* signExtDest = (signAndZeroExtend
3243                                   ? new TmpInstruction(mcfi, destType, opVal)
3244                                   : destI);
3245
3246             CreateSignExtensionInstructions
3247               (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
3248
3249             if (signAndZeroExtend)
3250               CreateZeroExtensionInstructions
3251               (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
3252           }
3253           else if (zeroExtendOnly) {
3254             CreateZeroExtensionInstructions
3255               (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
3256           }
3257           else
3258             forwardOperandNum = 0;          // forward first operand to user
3259
3260         } else
3261           assert(0 && "Unrecognized operand type for convert-to-integer");
3262
3263         break;
3264       }
3265       
3266       case  31: // reg:   ToFloatTy(reg):
3267       case  32: // reg:   ToDoubleTy(reg):
3268       case 232: // reg:   ToDoubleTy(Constant):
3269       
3270         // If this instruction has a parent (a user) in the tree 
3271         // and the user is translated as an FsMULd instruction,
3272         // then the cast is unnecessary.  So check that first.
3273         // In the future, we'll want to do the same for the FdMULq instruction,
3274         // so do the check here instead of only for ToFloatTy(reg).
3275         // 
3276         if (subtreeRoot->parent() != NULL) {
3277           const MachineCodeForInstruction& mcfi =
3278             MachineCodeForInstruction::get(
3279                 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
3280           if (mcfi.size() == 0 || mcfi.front()->getOpcode() == V9::FSMULD)
3281             forwardOperandNum = 0;    // forward first operand to user
3282         }
3283
3284         if (forwardOperandNum != 0) {    // we do need the cast
3285           Value* leftVal = subtreeRoot->leftChild()->getValue();
3286           const Type* opType = leftVal->getType();
3287           MachineOpCode opCode=ChooseConvertToFloatInstr(target,
3288                                        subtreeRoot->getOpLabel(), opType);
3289           if (opCode == V9::NOP) {      // no conversion needed
3290             forwardOperandNum = 0;      // forward first operand to user
3291           } else {
3292             // If the source operand is a non-FP type it must be
3293             // first copied from int to float register via memory!
3294             Instruction *dest = subtreeRoot->getInstruction();
3295             Value* srcForCast;
3296             int n = 0;
3297             if (! opType->isFloatingPoint()) {
3298               // Create a temporary to represent the FP register
3299               // into which the integer will be copied via memory.
3300               // The type of this temporary will determine the FP
3301               // register used: single-prec for a 32-bit int or smaller,
3302               // double-prec for a 64-bit int.
3303               // 
3304               uint64_t srcSize =
3305                 target.getTargetData().getTypeSize(leftVal->getType());
3306               Type* tmpTypeToUse =
3307                 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
3308               MachineCodeForInstruction &destMCFI = 
3309                 MachineCodeForInstruction::get(dest);
3310               srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
3311
3312               CreateCodeToCopyIntToFloat(target,
3313                          dest->getParent()->getParent(),
3314                          leftVal, cast<Instruction>(srcForCast),
3315                          mvec, destMCFI);
3316             } else
3317               srcForCast = leftVal;
3318
3319             M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
3320             mvec.push_back(M);
3321           }
3322         }
3323         break;
3324
3325       case 19:  // reg:   ToArrayTy(reg):
3326       case 20:  // reg:   ToPointerTy(reg):
3327         forwardOperandNum = 0;          // forward first operand to user
3328         break;
3329
3330       case 233: // reg:   Add(reg, Constant)
3331         maskUnsignedResult = true;
3332         M = CreateAddConstInstruction(subtreeRoot);
3333         if (M != NULL) {
3334           mvec.push_back(M);
3335           break;
3336         }
3337         // ELSE FALL THROUGH
3338         
3339       case 33:  // reg:   Add(reg, reg)
3340         maskUnsignedResult = true;
3341         Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
3342         break;
3343
3344       case 234: // reg:   Sub(reg, Constant)
3345         maskUnsignedResult = true;
3346         M = CreateSubConstInstruction(subtreeRoot);
3347         if (M != NULL) {
3348           mvec.push_back(M);
3349           break;
3350         }
3351         // ELSE FALL THROUGH
3352         
3353       case 34:  // reg:   Sub(reg, reg)
3354         maskUnsignedResult = true;
3355         Add3OperandInstr(ChooseSubInstructionByType(
3356                                    subtreeRoot->getInstruction()->getType()),
3357                          subtreeRoot, mvec);
3358         break;
3359
3360       case 135: // reg:   Mul(todouble, todouble)
3361         checkCast = true;
3362         // FALL THROUGH 
3363
3364       case 35:  // reg:   Mul(reg, reg)
3365       {
3366         maskUnsignedResult = true;
3367         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3368                                  ? (MachineOpCode)V9::FSMULD
3369                                  : -1);
3370         Instruction* mulInstr = subtreeRoot->getInstruction();
3371         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3372                              subtreeRoot->leftChild()->getValue(),
3373                              subtreeRoot->rightChild()->getValue(),
3374                              mulInstr, mvec,
3375                              MachineCodeForInstruction::get(mulInstr),forceOp);
3376         break;
3377       }
3378       case 335: // reg:   Mul(todouble, todoubleConst)
3379         checkCast = true;
3380         // FALL THROUGH 
3381
3382       case 235: // reg:   Mul(reg, Constant)
3383       {
3384         maskUnsignedResult = true;
3385         MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3386                                  ? (MachineOpCode)V9::FSMULD
3387                                  : -1);
3388         Instruction* mulInstr = subtreeRoot->getInstruction();
3389         CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3390                              subtreeRoot->leftChild()->getValue(),
3391                              subtreeRoot->rightChild()->getValue(),
3392                              mulInstr, mvec,
3393                              MachineCodeForInstruction::get(mulInstr),
3394                              forceOp);
3395         break;
3396       }
3397       case 236: // reg:   Div(reg, Constant)
3398         maskUnsignedResult = true;
3399         L = mvec.size();
3400         CreateDivConstInstruction(target, subtreeRoot, mvec);
3401         if (mvec.size() > L)
3402           break;
3403         // ELSE FALL THROUGH
3404       
3405       case 36:  // reg:   Div(reg, reg)
3406       {
3407         maskUnsignedResult = true;
3408
3409         // If either operand of divide is smaller than 64 bits, we have
3410         // to make sure the unused top bits are correct because they affect
3411         // the result.  These bits are already correct for unsigned values.
3412         // They may be incorrect for signed values, so sign extend to fill in.
3413         Instruction* divI = subtreeRoot->getInstruction();
3414         Value* divOp1 = subtreeRoot->leftChild()->getValue();
3415         Value* divOp2 = subtreeRoot->rightChild()->getValue();
3416         Value* divOp1ToUse = divOp1;
3417         Value* divOp2ToUse = divOp2;
3418         if (divI->getType()->isSigned()) {
3419           unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
3420           if (opSize < 8) {
3421             MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
3422             divOp1ToUse = new TmpInstruction(mcfi, divOp1);
3423             divOp2ToUse = new TmpInstruction(mcfi, divOp2);
3424             CreateSignExtensionInstructions(target,
3425                                               divI->getParent()->getParent(),
3426                                               divOp1, divOp1ToUse,
3427                                               8*opSize, mvec, mcfi);
3428             CreateSignExtensionInstructions(target,
3429                                               divI->getParent()->getParent(),
3430                                               divOp2, divOp2ToUse,
3431                                               8*opSize, mvec, mcfi);
3432           }
3433         }
3434
3435         mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3436                        .addReg(divOp1ToUse)
3437                        .addReg(divOp2ToUse)
3438                        .addRegDef(divI));
3439
3440         break;
3441       }
3442
3443       case  37: // reg:   Rem(reg, reg)
3444       case 237: // reg:   Rem(reg, Constant)
3445       {
3446         maskUnsignedResult = true;
3447
3448         Instruction* remI   = subtreeRoot->getInstruction();
3449         Value* divOp1 = subtreeRoot->leftChild()->getValue();
3450         Value* divOp2 = subtreeRoot->rightChild()->getValue();
3451
3452         MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
3453         
3454         // If second operand of divide is smaller than 64 bits, we have
3455         // to make sure the unused top bits are correct because they affect
3456         // the result.  These bits are already correct for unsigned values.
3457         // They may be incorrect for signed values, so sign extend to fill in.
3458         // 
3459         Value* divOpToUse = divOp2;
3460         if (divOp2->getType()->isSigned()) {
3461           unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
3462           if (opSize < 8) {
3463             divOpToUse = new TmpInstruction(mcfi, divOp2);
3464             CreateSignExtensionInstructions(target,
3465                                               remI->getParent()->getParent(),
3466                                               divOp2, divOpToUse,
3467                                               8*opSize, mvec, mcfi);
3468           }
3469         }
3470
3471         // Now compute: result = rem V1, V2 as:
3472         //      result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
3473         // 
3474         TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
3475         TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
3476
3477         mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3478                        .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
3479         
3480         mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
3481                        .addReg(quot).addReg(divOpToUse).addRegDef(prod));
3482         
3483         mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
3484                        .addReg(divOp1).addReg(prod).addRegDef(remI));
3485         
3486         break;
3487       }
3488       
3489       case  38: // bool:   And(bool, bool)
3490       case 138: // bool:   And(bool, not)
3491       case 238: // bool:   And(bool, boolconst)
3492       case 338: // reg :   BAnd(reg, reg)
3493       case 538: // reg :   BAnd(reg, Constant)
3494         Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
3495         break;
3496
3497       case 438: // bool:   BAnd(bool, bnot)
3498       { // Use the argument of NOT as the second argument!
3499         // Mark the NOT node so that no code is generated for it.
3500         // If the type is boolean, set 1 or 0 in the result register.
3501         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3502         Value* notArg = BinaryOperator::getNotArgument(
3503                            cast<BinaryOperator>(notNode->getInstruction()));
3504         notNode->markFoldedIntoParent();
3505         Value *lhs = subtreeRoot->leftChild()->getValue();
3506         Value *dest = subtreeRoot->getValue();
3507         mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
3508                                        .addReg(dest, MachineOperand::Def));
3509
3510         if (notArg->getType() == Type::BoolTy) {
3511           // set 1 in result register if result of above is non-zero
3512           mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3513                          .addReg(dest, MachineOperand::UseAndDef));
3514         }
3515
3516         break;
3517       }
3518
3519       case  39: // bool:   Or(bool, bool)
3520       case 139: // bool:   Or(bool, not)
3521       case 239: // bool:   Or(bool, boolconst)
3522       case 339: // reg :   BOr(reg, reg)
3523       case 539: // reg :   BOr(reg, Constant)
3524         Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
3525         break;
3526
3527       case 439: // bool:   BOr(bool, bnot)
3528       { // Use the argument of NOT as the second argument!
3529         // Mark the NOT node so that no code is generated for it.
3530         // If the type is boolean, set 1 or 0 in the result register.
3531         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3532         Value* notArg = BinaryOperator::getNotArgument(
3533                            cast<BinaryOperator>(notNode->getInstruction()));
3534         notNode->markFoldedIntoParent();
3535         Value *lhs = subtreeRoot->leftChild()->getValue();
3536         Value *dest = subtreeRoot->getValue();
3537
3538         mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
3539                        .addReg(dest, MachineOperand::Def));
3540
3541         if (notArg->getType() == Type::BoolTy) {
3542           // set 1 in result register if result of above is non-zero
3543           mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3544                          .addReg(dest, MachineOperand::UseAndDef));
3545         }
3546
3547         break;
3548       }
3549
3550       case  40: // bool:   Xor(bool, bool)
3551       case 140: // bool:   Xor(bool, not)
3552       case 240: // bool:   Xor(bool, boolconst)
3553       case 340: // reg :   BXor(reg, reg)
3554       case 540: // reg :   BXor(reg, Constant)
3555         Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
3556         break;
3557
3558       case 440: // bool:   BXor(bool, bnot)
3559       { // Use the argument of NOT as the second argument!
3560         // Mark the NOT node so that no code is generated for it.
3561         // If the type is boolean, set 1 or 0 in the result register.
3562         InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3563         Value* notArg = BinaryOperator::getNotArgument(
3564                            cast<BinaryOperator>(notNode->getInstruction()));
3565         notNode->markFoldedIntoParent();
3566         Value *lhs = subtreeRoot->leftChild()->getValue();
3567         Value *dest = subtreeRoot->getValue();
3568         mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
3569                        .addReg(dest, MachineOperand::Def));
3570
3571         if (notArg->getType() == Type::BoolTy) {
3572           // set 1 in result register if result of above is non-zero
3573           mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3574                          .addReg(dest, MachineOperand::UseAndDef));
3575         }
3576         break;
3577       }
3578
3579       case 41:  // setCCconst:   SetCC(reg, Constant)
3580       { // Comparison is with a constant:
3581         // 
3582         // If the bool result must be computed into a register (see below),
3583         // and the constant is int ZERO, we can use the MOVR[op] instructions
3584         // and avoid the SUBcc instruction entirely.
3585         // Otherwise this is just the same as case 42, so just fall through.
3586         // 
3587         // The result of the SetCC must be computed and stored in a register if
3588         // it is used outside the current basic block (so it must be computed
3589         // as a boolreg) or it is used by anything other than a branch.
3590         // We will use a conditional move to do this.
3591         // 
3592         Instruction* setCCInstr = subtreeRoot->getInstruction();
3593         bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3594                                ! AllUsesAreBranches(setCCInstr));
3595
3596         if (computeBoolVal) {
3597           InstrTreeNode* constNode = subtreeRoot->rightChild();
3598           assert(constNode &&
3599                  constNode->getNodeType() ==InstrTreeNode::NTConstNode);
3600           Constant *constVal = cast<Constant>(constNode->getValue());
3601           bool isValidConst;
3602           
3603           if ((constVal->getType()->isInteger()
3604                || isa<PointerType>(constVal->getType()))
3605               && ConvertConstantToIntType(target,
3606                              constVal, constVal->getType(), isValidConst) == 0
3607               && isValidConst)
3608           {
3609             // That constant is an integer zero after all...
3610             // Use a MOVR[op] to compute the boolean result
3611             // Unconditionally set register to 0
3612             mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
3613                            .addRegDef(setCCInstr));
3614                 
3615             // Now conditionally move 1 into the register.
3616             // Mark the register as a use (as well as a def) because the old
3617             // value will be retained if the condition is false.
3618             MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
3619             mvec.push_back(BuildMI(movOpCode, 3)
3620                            .addReg(subtreeRoot->leftChild()->getValue())
3621                            .addZImm(1)
3622                            .addReg(setCCInstr, MachineOperand::UseAndDef));
3623                 
3624             break;
3625           }
3626         }
3627         // ELSE FALL THROUGH
3628       }
3629
3630       case 42:  // bool:   SetCC(reg, reg):
3631       {
3632         // This generates a SUBCC instruction, putting the difference in a
3633         // result reg. if needed, and/or setting a condition code if needed.
3634         // 
3635         Instruction* setCCInstr = subtreeRoot->getInstruction();
3636         Value* leftVal  = subtreeRoot->leftChild()->getValue();
3637         Value* rightVal = subtreeRoot->rightChild()->getValue();
3638         const Type* opType = leftVal->getType();
3639         bool isFPCompare = opType->isFloatingPoint();
3640         
3641         // If the boolean result of the SetCC is used outside the current basic
3642         // block (so it must be computed as a boolreg) or is used by anything
3643         // other than a branch, the boolean must be computed and stored
3644         // in a result register.  We will use a conditional move to do this.
3645         // 
3646         bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3647                                ! AllUsesAreBranches(setCCInstr));
3648         
3649         // A TmpInstruction is created to represent the CC "result".
3650         // Unlike other instances of TmpInstruction, this one is used
3651         // by machine code of multiple LLVM instructions, viz.,
3652         // the SetCC and the branch.  Make sure to get the same one!
3653         // Note that we do this even for FP CC registers even though they
3654         // are explicit operands, because the type of the operand
3655         // needs to be a floating point condition code, not an integer
3656         // condition code.  Think of this as casting the bool result to
3657         // a FP condition code register.
3658         // Later, we mark the 4th operand as being a CC register, and as a def.
3659         // 
3660         TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
3661                                     setCCInstr->getParent()->getParent(),
3662                                     leftVal->getType(),
3663                                     MachineCodeForInstruction::get(setCCInstr));
3664
3665         // If the operands are signed values smaller than 4 bytes, then they
3666         // must be sign-extended in order to do a valid 32-bit comparison
3667         // and get the right result in the 32-bit CC register (%icc).
3668         // 
3669         Value* leftOpToUse  = leftVal;
3670         Value* rightOpToUse = rightVal;
3671         if (opType->isIntegral() && opType->isSigned()) {
3672           unsigned opSize = target.getTargetData().getTypeSize(opType);
3673           if (opSize < 4) {
3674             MachineCodeForInstruction& mcfi =
3675               MachineCodeForInstruction::get(setCCInstr); 
3676
3677             // create temporary virtual regs. to hold the sign-extensions
3678             leftOpToUse  = new TmpInstruction(mcfi, leftVal);
3679             rightOpToUse = new TmpInstruction(mcfi, rightVal);
3680             
3681             // sign-extend each operand and put the result in the temporary reg.
3682             CreateSignExtensionInstructions
3683               (target, setCCInstr->getParent()->getParent(),
3684                leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
3685             CreateSignExtensionInstructions
3686               (target, setCCInstr->getParent()->getParent(),
3687                rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
3688           }
3689         }
3690
3691         if (! isFPCompare) {
3692           // Integer condition: set CC and discard result.
3693           mvec.push_back(BuildMI(V9::SUBccr, 4)
3694                          .addReg(leftOpToUse)
3695                          .addReg(rightOpToUse)
3696                          .addMReg(target.getRegInfo()->
3697                                    getZeroRegNum(), MachineOperand::Def)
3698                          .addCCReg(tmpForCC, MachineOperand::Def));
3699         } else {
3700           // FP condition: dest of FCMP should be some FCCn register
3701           mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
3702                          .addCCReg(tmpForCC, MachineOperand::Def)
3703                          .addReg(leftOpToUse)
3704                          .addReg(rightOpToUse));
3705         }
3706         
3707         if (computeBoolVal) {
3708           MachineOpCode movOpCode = (isFPCompare
3709                                      ? ChooseMovFpcciInstruction(subtreeRoot)
3710                                      : ChooseMovpcciForSetCC(subtreeRoot));
3711
3712           // Unconditionally set register to 0
3713           M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
3714           mvec.push_back(M);
3715           
3716           // Now conditionally move 1 into the register.
3717           // Mark the register as a use (as well as a def) because the old
3718           // value will be retained if the condition is false.
3719           M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
3720                .addReg(setCCInstr, MachineOperand::UseAndDef));
3721           mvec.push_back(M);
3722         }
3723         break;
3724       }    
3725       
3726       case 51:  // reg:   Load(reg)
3727       case 52:  // reg:   Load(ptrreg)
3728         SetOperandsForMemInstr(ChooseLoadInstruction(
3729                                    subtreeRoot->getValue()->getType()),
3730                                mvec, subtreeRoot, target);
3731         break;
3732
3733       case 55:  // reg:   GetElemPtr(reg)
3734       case 56:  // reg:   GetElemPtrIdx(reg,reg)
3735         // If the GetElemPtr was folded into the user (parent), it will be
3736         // caught above.  For other cases, we have to compute the address.
3737         SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
3738         break;
3739
3740       case 57:  // reg:  Alloca: Implement as 1 instruction:
3741       {         //          add %fp, offsetFromFP -> result
3742         AllocationInst* instr =
3743           cast<AllocationInst>(subtreeRoot->getInstruction());
3744         unsigned tsize =
3745           target.getTargetData().getTypeSize(instr->getAllocatedType());
3746         assert(tsize != 0);
3747         CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
3748         break;
3749       }
3750
3751       case 58:  // reg:   Alloca(reg): Implement as 3 instructions:
3752                 //      mul num, typeSz -> tmp
3753                 //      sub %sp, tmp    -> %sp
3754       {         //      add %sp, frameSizeBelowDynamicArea -> result
3755         AllocationInst* instr =
3756           cast<AllocationInst>(subtreeRoot->getInstruction());
3757         const Type* eltType = instr->getAllocatedType();
3758         
3759         // If #elements is constant, use simpler code for fixed-size allocas
3760         int tsize = (int) target.getTargetData().getTypeSize(eltType);
3761         Value* numElementsVal = NULL;
3762         bool isArray = instr->isArrayAllocation();
3763         
3764         if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
3765           // total size is constant: generate code for fixed-size alloca
3766           unsigned numElements = isArray? 
3767             cast<ConstantUInt>(numElementsVal)->getValue() : 1;
3768           CreateCodeForFixedSizeAlloca(target, instr, tsize,
3769                                        numElements, mvec);
3770         } else {
3771           // total size is not constant.
3772           CreateCodeForVariableSizeAlloca(target, instr, tsize,
3773                                           numElementsVal, mvec);
3774         }
3775         break;
3776       }
3777
3778       case 61:  // reg:   Call
3779       {         // Generate a direct (CALL) or indirect (JMPL) call.
3780                 // Mark the return-address register, the indirection
3781                 // register (for indirect calls), the operands of the Call,
3782                 // and the return value (if any) as implicit operands
3783                 // of the machine instruction.
3784                 // 
3785                 // If this is a varargs function, floating point arguments
3786                 // have to passed in integer registers so insert
3787                 // copy-float-to-int instructions for each float operand.
3788                 // 
3789         CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
3790         Value *callee = callInstr->getCalledValue();
3791         Function* calledFunc = dyn_cast<Function>(callee);
3792
3793         // Check if this is an intrinsic function that needs a special code
3794         // sequence (e.g., va_start).  Indirect calls cannot be special.
3795         // 
3796         bool specialIntrinsic = false;
3797         Intrinsic::ID iid;
3798         if (calledFunc && (iid=(Intrinsic::ID)calledFunc->getIntrinsicID()))
3799           specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
3800
3801         // If not, generate the normal call sequence for the function.
3802         // This can also handle any intrinsics that are just function calls.
3803         // 
3804         if (! specialIntrinsic) {
3805           Function* currentFunc = callInstr->getParent()->getParent();
3806           MachineFunction& MF = MachineFunction::get(currentFunc);
3807           MachineCodeForInstruction& mcfi =
3808             MachineCodeForInstruction::get(callInstr); 
3809           const SparcV9RegInfo& regInfo =
3810             (SparcV9RegInfo&) *target.getRegInfo();
3811           const TargetFrameInfo& frameInfo = *target.getFrameInfo();
3812
3813           // Create hidden virtual register for return address with type void*
3814           TmpInstruction* retAddrReg =
3815             new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
3816
3817           // Generate the machine instruction and its operands.
3818           // Use CALL for direct function calls; this optimistically assumes
3819           // the PC-relative address fits in the CALL address field (22 bits).
3820           // Use JMPL for indirect calls.
3821           // This will be added to mvec later, after operand copies.
3822           // 
3823           MachineInstr* callMI;
3824           if (calledFunc)             // direct function call
3825             callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
3826           else                        // indirect function call
3827             callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
3828                       .addSImm((int64_t)0).addRegDef(retAddrReg));
3829
3830           const FunctionType* funcType =
3831             cast<FunctionType>(cast<PointerType>(callee->getType())
3832                                ->getElementType());
3833           bool isVarArgs = funcType->isVarArg();
3834           bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
3835         
3836           // Use a descriptor to pass information about call arguments
3837           // to the register allocator.  This descriptor will be "owned"
3838           // and freed automatically when the MachineCodeForInstruction
3839           // object for the callInstr goes away.
3840           CallArgsDescriptor* argDesc =
3841             new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
3842           assert(callInstr->getOperand(0) == callee
3843                  && "This is assumed in the loop below!");
3844
3845           // Insert sign-extension instructions for small signed values,
3846           // if this is an unknown function (i.e., called via a funcptr)
3847           // or an external one (i.e., which may not be compiled by llc).
3848           // 
3849           if (calledFunc == NULL || calledFunc->isExternal()) {
3850             for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3851               Value* argVal = callInstr->getOperand(i);
3852               const Type* argType = argVal->getType();
3853               if (argType->isIntegral() && argType->isSigned()) {
3854                 unsigned argSize = target.getTargetData().getTypeSize(argType);
3855                 if (argSize <= 4) {
3856                   // create a temporary virtual reg. to hold the sign-extension
3857                   TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
3858
3859                   // sign-extend argVal and put the result in the temporary reg.
3860                   CreateSignExtensionInstructions
3861                     (target, currentFunc, argVal, argExtend,
3862                      8*argSize, mvec, mcfi);
3863
3864                   // replace argVal with argExtend in CallArgsDescriptor
3865                   argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
3866                 }
3867               }
3868             }
3869           }
3870
3871           // Insert copy instructions to get all the arguments into
3872           // all the places that they need to be.
3873           // 
3874           for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3875             int argNo = i-1;
3876             CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
3877             Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
3878             const Type* argType = argVal->getType();
3879             unsigned regType = regInfo.getRegTypeForDataType(argType);
3880             unsigned argSize = target.getTargetData().getTypeSize(argType);
3881             int regNumForArg = SparcV9RegInfo::getInvalidRegNum();
3882             unsigned regClassIDOfArgReg;
3883
3884             // Check for FP arguments to varargs functions.
3885             // Any such argument in the first $K$ args must be passed in an
3886             // integer register.  If there is no prototype, it must also
3887             // be passed as an FP register.
3888             // K = #integer argument registers.
3889             bool isFPArg = argVal->getType()->isFloatingPoint();
3890             if (isVarArgs && isFPArg) {
3891
3892               if (noPrototype) {
3893                 // It is a function with no prototype: pass value
3894                 // as an FP value as well as a varargs value.  The FP value
3895                 // may go in a register or on the stack.  The copy instruction
3896                 // to the outgoing reg/stack is created by the normal argument
3897                 // handling code since this is the "normal" passing mode.
3898                 // 
3899                 regNumForArg = regInfo.regNumForFPArg(regType,
3900                                                       false, false, argNo,
3901                                                       regClassIDOfArgReg);
3902                 if (regNumForArg == regInfo.getInvalidRegNum())
3903                   argInfo.setUseStackSlot();
3904                 else
3905                   argInfo.setUseFPArgReg();
3906               }
3907               
3908               // If this arg. is in the first $K$ regs, add special copy-
3909               // float-to-int instructions to pass the value as an int.
3910               // To check if it is in the first $K$, get the register
3911               // number for the arg #i.  These copy instructions are
3912               // generated here because they are extra cases and not needed
3913               // for the normal argument handling (some code reuse is
3914               // possible though -- later).
3915               // 
3916               int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
3917                                                        regClassIDOfArgReg);
3918               if (copyRegNum != regInfo.getInvalidRegNum()) {
3919                 // Create a virtual register to represent copyReg. Mark
3920                 // this vreg as being an implicit operand of the call MI
3921                 const Type* loadTy = (argType == Type::FloatTy
3922                                       ? Type::IntTy : Type::LongTy);
3923                 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
3924                                                              argVal, NULL,
3925                                                              "argRegCopy");
3926                 callMI->addImplicitRef(argVReg);
3927                 
3928                 // Get a temp stack location to use to copy
3929                 // float-to-int via the stack.
3930                 // 
3931                 // FIXME: For now, we allocate permanent space because
3932                 // the stack frame manager does not allow locals to be
3933                 // allocated (e.g., for alloca) after a temp is
3934                 // allocated!
3935                 // 
3936                 // int tmpOffset = MF.getInfo<SparcV9FunctionInfo>()->pushTempValue(argSize);
3937                 int tmpOffset = MF.getInfo<SparcV9FunctionInfo>()->allocateLocalVar(argVReg);
3938                     
3939                 // Generate the store from FP reg to stack
3940                 unsigned StoreOpcode = ChooseStoreInstruction(argType);
3941                 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
3942                   .addReg(argVal).addMReg(regInfo.getFramePointer())
3943                   .addSImm(tmpOffset);
3944                 mvec.push_back(M);
3945                         
3946                 // Generate the load from stack to int arg reg
3947                 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
3948                 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
3949                   .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
3950                   .addReg(argVReg, MachineOperand::Def);
3951
3952                 // Mark operand with register it should be assigned
3953                 // both for copy and for the callMI
3954                 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
3955                 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
3956                                              copyRegNum);
3957                 mvec.push_back(M);
3958
3959                 // Add info about the argument to the CallArgsDescriptor
3960                 argInfo.setUseIntArgReg();
3961                 argInfo.setArgCopy(copyRegNum);
3962               } else {
3963                 // Cannot fit in first $K$ regs so pass arg on stack
3964                 argInfo.setUseStackSlot();
3965               }
3966             } else if (isFPArg) {
3967               // Get the outgoing arg reg to see if there is one.
3968               regNumForArg = regInfo.regNumForFPArg(regType, false, false,
3969                                                     argNo, regClassIDOfArgReg);
3970               if (regNumForArg == regInfo.getInvalidRegNum())
3971                 argInfo.setUseStackSlot();
3972               else {
3973                 argInfo.setUseFPArgReg();
3974                 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
3975                                                        regNumForArg);
3976               }
3977             } else {
3978               // Get the outgoing arg reg to see if there is one.
3979               regNumForArg = regInfo.regNumForIntArg(false,false,
3980                                                      argNo, regClassIDOfArgReg);
3981               if (regNumForArg == regInfo.getInvalidRegNum())
3982                 argInfo.setUseStackSlot();
3983               else {
3984                 argInfo.setUseIntArgReg();
3985                 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
3986                                                        regNumForArg);
3987               }
3988             }                
3989
3990             // 
3991             // Now insert copy instructions to stack slot or arg. register
3992             // 
3993             if (argInfo.usesStackSlot()) {
3994               // Get the stack offset for this argument slot.
3995               // FP args on stack are right justified so adjust offset!
3996               // int arguments are also right justified but they are
3997               // always loaded as a full double-word so the offset does
3998               // not need to be adjusted.
3999               int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
4000               if (argType->isFloatingPoint()) {
4001                 unsigned slotSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
4002                 assert(argSize <= slotSize && "Insufficient slot size!");
4003                 argOffset += slotSize - argSize;
4004               }
4005
4006               // Now generate instruction to copy argument to stack
4007               MachineOpCode storeOpCode =
4008                 (argType->isFloatingPoint()
4009                  ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
4010
4011               M = BuildMI(storeOpCode, 3).addReg(argVal)
4012                 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
4013               mvec.push_back(M);
4014             }
4015             else if (regNumForArg != regInfo.getInvalidRegNum()) {
4016
4017               // Create a virtual register to represent the arg reg. Mark
4018               // this vreg as being an implicit operand of the call MI.
4019               TmpInstruction* argVReg = 
4020                 new TmpInstruction(mcfi, argVal, NULL, "argReg");
4021
4022               callMI->addImplicitRef(argVReg);
4023               
4024               // Generate the reg-to-reg copy into the outgoing arg reg.
4025               // -- For FP values, create a FMOVS or FMOVD instruction
4026               // -- For non-FP values, create an add-with-0 instruction
4027               if (argType->isFloatingPoint())
4028                 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
4029                    .addReg(argVal).addReg(argVReg, MachineOperand::Def));
4030               else
4031                 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
4032                      .addReg(argVal).addSImm((int64_t) 0)
4033                      .addReg(argVReg, MachineOperand::Def));
4034               
4035               // Mark the operand with the register it should be assigned
4036               M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
4037               callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
4038                                            regNumForArg);
4039
4040               mvec.push_back(M);
4041             }
4042             else
4043               assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
4044                      "Arg. not in stack slot, primary or secondary register?");
4045           }
4046
4047           // add call instruction and delay slot before copying return value
4048           mvec.push_back(callMI);
4049           mvec.push_back(BuildMI(V9::NOP, 0));
4050
4051           // Add the return value as an implicit ref.  The call operands
4052           // were added above.  Also, add code to copy out the return value.
4053           // This is always register-to-register for int or FP return values.
4054           // 
4055           if (callInstr->getType() != Type::VoidTy) { 
4056             // Get the return value reg.
4057             const Type* retType = callInstr->getType();
4058
4059             int regNum = (retType->isFloatingPoint()
4060                           ? (unsigned) SparcV9FloatRegClass::f0 
4061                           : (unsigned) SparcV9IntRegClass::o0);
4062             unsigned regClassID = regInfo.getRegClassIDOfType(retType);
4063             regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
4064
4065             // Create a virtual register to represent it and mark
4066             // this vreg as being an implicit operand of the call MI
4067             TmpInstruction* retVReg = 
4068               new TmpInstruction(mcfi, callInstr, NULL, "argReg");
4069
4070             callMI->addImplicitRef(retVReg, /*isDef*/ true);
4071
4072             // Generate the reg-to-reg copy from the return value reg.
4073             // -- For FP values, create a FMOVS or FMOVD instruction
4074             // -- For non-FP values, create an add-with-0 instruction
4075             if (retType->isFloatingPoint())
4076               M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
4077                    .addReg(retVReg).addReg(callInstr, MachineOperand::Def));
4078             else
4079               M = (BuildMI(ChooseAddInstructionByType(retType), 3)
4080                    .addReg(retVReg).addSImm((int64_t) 0)
4081                    .addReg(callInstr, MachineOperand::Def));
4082
4083             // Mark the operand with the register it should be assigned
4084             // Also mark the implicit ref of the call defining this operand
4085             M->SetRegForOperand(0, regNum);
4086             callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
4087
4088             mvec.push_back(M);
4089           }
4090
4091           // For the CALL instruction, the ret. addr. reg. is also implicit
4092           if (isa<Function>(callee))
4093             callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
4094
4095           MF.getInfo<SparcV9FunctionInfo>()->popAllTempValues();  // free temps used for this inst
4096         }
4097
4098         break;
4099       }
4100       
4101       case 62:  // reg:   Shl(reg, reg)
4102       {
4103         Value* argVal1 = subtreeRoot->leftChild()->getValue();
4104         Value* argVal2 = subtreeRoot->rightChild()->getValue();
4105         Instruction* shlInstr = subtreeRoot->getInstruction();
4106         
4107         const Type* opType = argVal1->getType();
4108         assert((opType->isInteger() || isa<PointerType>(opType)) &&
4109                "Shl unsupported for other types");
4110         unsigned opSize = target.getTargetData().getTypeSize(opType);
4111         
4112         CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
4113                                 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
4114                                 argVal1, argVal2, 0, shlInstr, mvec,
4115                                 MachineCodeForInstruction::get(shlInstr));
4116         break;
4117       }
4118       
4119       case 63:  // reg:   Shr(reg, reg)
4120       { 
4121         const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
4122         assert((opType->isInteger() || isa<PointerType>(opType)) &&
4123                "Shr unsupported for other types");
4124         unsigned opSize = target.getTargetData().getTypeSize(opType);
4125         Add3OperandInstr(opType->isSigned()
4126                          ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
4127                          : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
4128                          subtreeRoot, mvec);
4129         break;
4130       }
4131       
4132       case 64:  // reg:   Phi(reg,reg)
4133         break;                          // don't forward the value
4134
4135       case 65:  // reg:   VANext(reg):  the va_next(va_list, type) instruction
4136       { // Increment the va_list pointer register according to the type.
4137         // All LLVM argument types are <= 64 bits, so use one doubleword.
4138         Instruction* vaNextI = subtreeRoot->getInstruction();
4139         assert(target.getTargetData().getTypeSize(vaNextI->getType()) <= 8 &&
4140                "We assumed that all LLVM parameter types <= 8 bytes!");
4141         unsigned argSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
4142         mvec.push_back(BuildMI(V9::ADDi, 3).addReg(vaNextI->getOperand(0)).
4143                        addSImm(argSize).addRegDef(vaNextI));
4144         break;
4145       }
4146
4147       case 66:  // reg:   VAArg (reg): the va_arg instruction
4148       { // Load argument from stack using current va_list pointer value.
4149         // Use 64-bit load for all non-FP args, and LDDF or double for FP.
4150         Instruction* vaArgI = subtreeRoot->getInstruction();
4151         MachineOpCode loadOp = (vaArgI->getType()->isFloatingPoint()
4152                                 ? (vaArgI->getType() == Type::FloatTy
4153                                    ? V9::LDFi : V9::LDDFi)
4154                                 : V9::LDXi);
4155         mvec.push_back(BuildMI(loadOp, 3).addReg(vaArgI->getOperand(0)).
4156                        addSImm(0).addRegDef(vaArgI));
4157         break;
4158       }
4159       
4160       case 71:  // reg:     VReg
4161       case 72:  // reg:     Constant
4162         break;                          // don't forward the value
4163
4164       default:
4165         assert(0 && "Unrecognized BURG rule");
4166         break;
4167       }
4168     }
4169
4170   if (forwardOperandNum >= 0) {
4171     // We did not generate a machine instruction but need to use operand.
4172     // If user is in the same tree, replace Value in its machine operand.
4173     // If not, insert a copy instruction which should get coalesced away
4174     // by register allocation.
4175     if (subtreeRoot->parent() != NULL)
4176       ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
4177     else {
4178       std::vector<MachineInstr*> minstrVec;
4179       Instruction* instr = subtreeRoot->getInstruction();
4180       CreateCopyInstructionsByType(target,
4181                                      instr->getParent()->getParent(),
4182                                      instr->getOperand(forwardOperandNum),
4183                                      instr, minstrVec,
4184                                      MachineCodeForInstruction::get(instr));
4185       assert(minstrVec.size() > 0);
4186       mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4187     }
4188   }
4189
4190   if (maskUnsignedResult) {
4191     // If result is unsigned and smaller than int reg size,
4192     // we need to clear high bits of result value.
4193     assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
4194     Instruction* dest = subtreeRoot->getInstruction();
4195     if (dest->getType()->isUnsigned()) {
4196       unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
4197       if (destSize <= 4) {
4198         // Mask high 64 - N bits, where N = 4*destSize.
4199         
4200         // Use a TmpInstruction to represent the
4201         // intermediate result before masking.  Since those instructions
4202         // have already been generated, go back and substitute tmpI
4203         // for dest in the result position of each one of them.
4204         // 
4205         MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
4206         TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
4207                                                   dest, NULL, "maskHi");
4208         Value* srlArgToUse = tmpI;
4209
4210         unsigned numSubst = 0;
4211         for (unsigned i=0, N=mvec.size(); i < N; ++i) {
4212
4213           // Make sure we substitute all occurrences of dest in these instrs.
4214           // Otherwise, we will have bogus code.
4215           bool someArgsWereIgnored = false;
4216
4217           // Make sure not to substitute an upwards-exposed use -- that would
4218           // introduce a use of `tmpI' with no preceding def.  Therefore,
4219           // substitute a use or def-and-use operand only if a previous def
4220           // operand has already been substituted (i.e., numSubst > 0).
4221           // 
4222           numSubst += mvec[i]->substituteValue(dest, tmpI,
4223                                                /*defsOnly*/ numSubst == 0,
4224                                                /*notDefsAndUses*/ numSubst > 0,
4225                                                someArgsWereIgnored);
4226           assert(!someArgsWereIgnored &&
4227                  "Operand `dest' exists but not replaced: probably bogus!");
4228         }
4229         assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
4230
4231         // Left shift 32-N if size (N) is less than 32 bits.
4232         // Use another tmp. virtual register to represent this result.
4233         if (destSize < 4) {
4234           srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
4235                                            tmpI, NULL, "maskHi2");
4236           mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
4237                          .addZImm(8*(4-destSize))
4238                          .addReg(srlArgToUse, MachineOperand::Def));
4239         }
4240
4241         // Logical right shift 32-N to get zero extension in top 64-N bits.
4242         mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
4243                          .addZImm(8*(4-destSize))
4244                          .addReg(dest, MachineOperand::Def));
4245
4246       } else if (destSize < 8) {
4247         assert(0 && "Unsupported type size: 32 < size < 64 bits");
4248       }
4249     }
4250   }
4251 }
4252
4253 } // End llvm namespace
4254
4255 //==------------------------------------------------------------------------==//
4256 //                     Class V9ISel Implementation
4257 //==------------------------------------------------------------------------==//
4258
4259 bool V9ISel::runOnFunction(Function &F) {
4260   // First pass - Walk the function, lowering any calls to intrinsic functions
4261   // which the instruction selector cannot handle.
4262   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
4263     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
4264       if (CallInst *CI = dyn_cast<CallInst>(I++))
4265         if (Function *F = CI->getCalledFunction())
4266           switch (F->getIntrinsicID()) {
4267           case Intrinsic::not_intrinsic:
4268           case Intrinsic::vastart:
4269           case Intrinsic::vacopy:
4270           case Intrinsic::vaend:
4271             // We directly implement these intrinsics.  Note that this knowledge
4272             // is incestuously entangled with the code in
4273             // SparcInstrSelection.cpp and must be updated when it is updated.
4274             // Since ALL of the code in this library is incestuously intertwined
4275             // with it already and sparc specific, we will live with this.
4276             break;
4277           default:
4278             // All other intrinsic calls we must lower.
4279             Instruction *Before = CI->getPrev();
4280             Target.getIntrinsicLowering().LowerIntrinsicCall(CI);
4281             if (Before) {        // Move iterator to instruction after call
4282               I = Before;  ++I;
4283             } else {
4284               I = BB->begin();
4285             }
4286           }
4287
4288   // Build the instruction trees to be given as inputs to BURG.
4289   InstrForest instrForest(&F);
4290   if (SelectDebugLevel >= Select_DebugInstTrees) {
4291     std::cerr << "\n\n*** Input to instruction selection for function "
4292               << F.getName() << "\n\n" << F
4293               << "\n\n*** Instruction trees for function "
4294               << F.getName() << "\n\n";
4295     instrForest.dump();
4296   }
4297   
4298   // Invoke BURG instruction selection for each tree
4299   for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
4300        RI != instrForest.roots_end(); ++RI) {
4301     InstructionNode* basicNode = *RI;
4302     assert(basicNode->parent() == NULL && "A `root' node has a parent?"); 
4303       
4304     // Invoke BURM to label each tree node with a state
4305     burm_label(basicNode);
4306     if (SelectDebugLevel >= Select_DebugBurgTrees) {
4307       printcover(basicNode, 1, 0);
4308       std::cerr << "\nCover cost == " << treecost(basicNode, 1, 0) <<"\n\n";
4309       printMatches(basicNode);
4310     }
4311       
4312     // Then recursively walk the tree to select instructions
4313     SelectInstructionsForTree(basicNode, /*goalnt*/1);
4314   }
4315   
4316   // Create the MachineBasicBlocks and add all of the MachineInstrs
4317   // defined in the MachineCodeForInstruction objects to the MachineBasicBlocks.
4318   MachineFunction &MF = MachineFunction::get(&F);
4319   std::map<const BasicBlock *, MachineBasicBlock *> MBBMap;
4320   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
4321     MachineBasicBlock *MBB = new MachineBasicBlock(BI);
4322     MF.getBasicBlockList().push_back(MBB);
4323     MBBMap[BI] = MBB;
4324
4325     for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
4326       MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
4327       MBB->insert(MBB->end(), mvec.begin(), mvec.end());
4328     }
4329   }
4330
4331   // Initialize Machine-CFG for the function.
4332   for (MachineFunction::iterator i = MF.begin (), e = MF.end (); i != e; ++i) {
4333     MachineBasicBlock &MBB = *i;
4334     const BasicBlock *BB = MBB.getBasicBlock ();
4335     // for each successor S of BB, add MBBMap[S] as a successor of MBB.
4336     for (succ_const_iterator si = succ_begin(BB), se = succ_end(BB); si != se;
4337          ++si) {
4338       MachineBasicBlock *succMBB = MBBMap[*si];
4339       assert (succMBB && "Can't find MachineBasicBlock for this successor");
4340       MBB.addSuccessor (succMBB);
4341     }
4342   }
4343
4344   // Insert phi elimination code
4345   InsertCodeForPhis(F);
4346   
4347   if (SelectDebugLevel >= Select_PrintMachineCode) {
4348     std::cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
4349     MachineFunction::get(&F).dump();
4350   }
4351   
4352   return true;
4353 }
4354
4355 /// InsertCodeForPhis - This method inserts Phi elimination code for
4356 /// all Phi nodes in the given function.  After this method is called,
4357 /// the Phi nodes still exist in the LLVM code, but copies are added to the
4358 /// machine code.
4359 ///
4360 void V9ISel::InsertCodeForPhis(Function &F) {
4361   // Iterate over every Phi node PN in F:
4362   MachineFunction &MF = MachineFunction::get(&F);
4363   for (MachineFunction::iterator BB = MF.begin(); BB != MF.end(); ++BB) {
4364     for (BasicBlock::const_iterator IIt = BB->getBasicBlock()->begin();
4365          const PHINode *PN = dyn_cast<PHINode>(IIt); ++IIt) {
4366       // Create a new temporary register to hold the result of the Phi copy.
4367       // The leak detector shouldn't track these nodes.  They are not garbage,
4368       // even though their parent field is never filled in.
4369       Value *PhiCpRes = new PHINode(PN->getType(), PN->getName() + ":PhiCp");
4370       LeakDetector::removeGarbageObject(PhiCpRes);
4371
4372       // For each of PN's incoming values, insert a copy in the corresponding
4373       // predecessor block.
4374       MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get (PN);
4375       for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
4376         std::vector<MachineInstr*> mvec, CpVec;
4377         Target.getRegInfo()->cpValue2Value(PN->getIncomingValue(i), 
4378                                            PhiCpRes, mvec);
4379         for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
4380              MI != mvec.end(); ++MI) {
4381           std::vector<MachineInstr*> CpVec2 =
4382             FixConstantOperandsForInstr(const_cast<PHINode*>(PN), *MI, Target);
4383           CpVec2.push_back(*MI);
4384           CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
4385         }
4386         // Insert the copy instructions into the predecessor BB.        
4387         InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
4388         MCforPN.insert (MCforPN.end (), CpVec.begin (), CpVec.end ());
4389       }
4390       // Insert a copy instruction from PhiCpRes to PN.
4391       std::vector<MachineInstr*> mvec;
4392       Target.getRegInfo()->cpValue2Value(PhiCpRes, const_cast<PHINode*>(PN),
4393                                         mvec);
4394       BB->insert(BB->begin(), mvec.begin(), mvec.end());
4395       MCforPN.insert (MCforPN.end (), mvec.begin (), mvec.end ());
4396     }  // for each Phi Instr in BB
4397   } // for all BBs in function
4398 }
4399
4400 /// InsertPhiElimInstructions - Inserts the instructions in CpVec into the
4401 /// MachineBasicBlock corresponding to BB, just before its terminator
4402 /// instruction. This is used by InsertCodeForPhis() to insert copies, above.
4403 ///
4404 void V9ISel::InsertPhiElimInstructions(BasicBlock *BB,
4405                                        const std::vector<MachineInstr*>& CpVec)
4406
4407   Instruction *TermInst = (Instruction*)BB->getTerminator();
4408   MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
4409   MachineInstr *FirstMIOfTerm = MC4Term.front();
4410   assert (FirstMIOfTerm && "No Machine Instrs for terminator");
4411
4412   MachineBasicBlock *MBB = FirstMIOfTerm->getParent();
4413   assert(MBB && "Machine BB for predecessor's terminator not found");
4414   MachineBasicBlock::iterator MCIt = FirstMIOfTerm;
4415   assert(MCIt != MBB->end() && "Start inst of terminator not found");
4416   
4417   // Insert the copy instructions just before the first machine instruction
4418   // generated for the terminator.
4419   MBB->insert(MCIt, CpVec.begin(), CpVec.end());
4420 }
4421
4422 /// SelectInstructionsForTree - Recursively walk the tree to select
4423 /// instructions. Do this top-down so that child instructions can exploit
4424 /// decisions made at the child instructions.
4425 /// 
4426 /// E.g., if br(setle(reg,const)) decides the constant is 0 and uses
4427 /// a branch-on-integer-register instruction, then the setle node
4428 /// can use that information to avoid generating the SUBcc instruction.
4429 ///
4430 /// Note that this cannot be done bottom-up because setle must do this
4431 /// only if it is a child of the branch (otherwise, the result of setle
4432 /// may be used by multiple instructions).
4433 ///
4434 void V9ISel::SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt) {
4435   // Get the rule that matches this node.
4436   int ruleForNode = burm_rule(treeRoot->state, goalnt);
4437   
4438   if (ruleForNode == 0) {
4439     std::cerr << "Could not match instruction tree for instr selection\n";
4440     abort();
4441   }
4442   
4443   // Get this rule's non-terminals and the corresponding child nodes (if any)
4444   short *nts = burm_nts[ruleForNode];
4445   
4446   // First, select instructions for the current node and rule.
4447   // (If this is a list node, not an instruction, then skip this step).
4448   // This function is specific to the target architecture.
4449   if (treeRoot->opLabel != VRegListOp) {
4450     std::vector<MachineInstr*> minstrVec;
4451     InstructionNode* instrNode = (InstructionNode*)treeRoot;
4452     assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
4453     GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
4454     MachineCodeForInstruction &mvec = 
4455       MachineCodeForInstruction::get(instrNode->getInstruction());
4456     mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4457   }
4458   
4459   // Then, recursively compile the child nodes, if any.
4460   // 
4461   if (nts[0]) {
4462     // i.e., there is at least one kid
4463     InstrTreeNode* kids[2];
4464     int currentRule = ruleForNode;
4465     burm_kids(treeRoot, currentRule, kids);
4466     
4467     // First skip over any chain rules so that we don't visit
4468     // the current node again.
4469     while (ThisIsAChainRule(currentRule)) {
4470       currentRule = burm_rule(treeRoot->state, nts[0]);
4471       nts = burm_nts[currentRule];
4472       burm_kids(treeRoot, currentRule, kids);
4473     }
4474       
4475     // Now we have the first non-chain rule so we have found
4476     // the actual child nodes.  Recursively compile them.
4477     for (unsigned i = 0; nts[i]; i++) {
4478       assert(i < 2);
4479       InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
4480       if (nodeType == InstrTreeNode::NTVRegListNode ||
4481           nodeType == InstrTreeNode::NTInstructionNode)
4482         SelectInstructionsForTree(kids[i], nts[i]);
4483     }
4484   }
4485   
4486   // Finally, do any post-processing on this node after its children
4487   // have been translated.
4488   if (treeRoot->opLabel != VRegListOp)
4489     PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
4490 }
4491
4492 /// PostprocessMachineCodeForTree - Apply any final cleanups to
4493 /// machine code for the root of a subtree after selection for all its
4494 /// children has been completed.
4495 ///
4496 void V9ISel::PostprocessMachineCodeForTree(InstructionNode *instrNode,
4497                                            int ruleForNode, short *nts) {
4498   // Fix up any constant operands in the machine instructions to either
4499   // use an immediate field or to load the constant into a register.
4500   // Walk backwards and use direct indexes to allow insertion before current.
4501   Instruction* vmInstr = instrNode->getInstruction();
4502   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
4503   for (unsigned i = mvec.size(); i != 0; --i) {
4504     std::vector<MachineInstr*> loadConstVec =
4505       FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
4506     mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
4507   }
4508 }
4509
4510 /// createSparcV9BurgInstSelector - Creates and returns a new SparcV9
4511 /// BURG-based instruction selection pass.
4512 ///
4513 FunctionPass *llvm::createSparcV9BurgInstSelector(TargetMachine &TM) {
4514   return new V9ISel(TM);
4515 }