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