Adjust to change in TII ctor arguments
[oota-llvm.git] / lib / Target / SparcV9 / SparcV9InstrInfo.cpp
1 //===-- SparcV9InstrInfo.cpp ------------------------------------------------===//
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 //===----------------------------------------------------------------------===//
11
12 #include "llvm/Constants.h"
13 #include "llvm/DerivedTypes.h"
14 #include "llvm/Function.h"
15 #include "llvm/iTerminators.h"
16 #include "llvm/CodeGen/InstrSelection.h"
17 #include "llvm/CodeGen/InstrSelectionSupport.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineFunctionInfo.h"
21 #include "llvm/CodeGen/MachineCodeForInstruction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "SparcV9Internals.h"
24 #include "SparcV9InstrSelectionSupport.h"
25 #include "SparcV9InstrInfo.h"
26
27 namespace llvm {
28
29 static const uint32_t MAXLO   = (1 << 10) - 1; // set bits set by %lo(*)
30 static const uint32_t MAXSIMM = (1 << 12) - 1; // set bits in simm13 field of OR
31
32 //---------------------------------------------------------------------------
33 // Function ConvertConstantToIntType
34 // 
35 // Function to get the value of an integral constant in the form
36 // that must be put into the machine register.  The specified constant is
37 // interpreted as (i.e., converted if necessary to) the specified destination
38 // type.  The result is always returned as an uint64_t, since the representation
39 // of int64_t and uint64_t are identical.  The argument can be any known const.
40 // 
41 // isValidConstant is set to true if a valid constant was found.
42 //---------------------------------------------------------------------------
43
44 uint64_t
45 SparcV9InstrInfo::ConvertConstantToIntType(const TargetMachine &target,
46                                               const Value *V,
47                                               const Type *destType,
48                                               bool  &isValidConstant) const
49 {
50   isValidConstant = false;
51   uint64_t C = 0;
52
53   if (! destType->isIntegral() && ! isa<PointerType>(destType))
54     return C;
55
56   if (! isa<Constant>(V))
57     return C;
58
59   // ConstantPointerRef: no conversions needed: get value and return it
60   if (const ConstantPointerRef* CPR = dyn_cast<ConstantPointerRef>(V)) {
61     // A ConstantPointerRef is just a reference to GlobalValue.
62     isValidConstant = true;             // may be overwritten by recursive call
63     return (CPR->isNullValue()? 0
64             : ConvertConstantToIntType(target, CPR->getValue(), destType,
65                                        isValidConstant));
66   }
67
68   // ConstantBool: no conversions needed: get value and return it
69   if (const ConstantBool *CB = dyn_cast<ConstantBool>(V)) {
70     isValidConstant = true;
71     return (uint64_t) CB->getValue();
72   }
73
74   // For other types of constants, some conversion may be needed.
75   // First, extract the constant operand according to its own type
76   if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
77     switch(CE->getOpcode()) {
78     case Instruction::Cast:             // recursively get the value as cast
79       C = ConvertConstantToIntType(target, CE->getOperand(0), CE->getType(),
80                                    isValidConstant);
81       break;
82     default:                            // not simplifying other ConstantExprs
83       break;
84     }
85   else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
86     isValidConstant = true;
87     C = CI->getRawValue();
88   }
89   else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
90     isValidConstant = true;
91     double fC = CFP->getValue();
92     C = (destType->isSigned()? (uint64_t) (int64_t) fC
93                              : (uint64_t)           fC);
94   }
95
96   // Now if a valid value was found, convert it to destType.
97   if (isValidConstant) {
98     unsigned opSize   = target.getTargetData().getTypeSize(V->getType());
99     unsigned destSize = target.getTargetData().getTypeSize(destType);
100     uint64_t maskHi   = (destSize < 8)? (1U << 8*destSize) - 1 : ~0;
101     assert(opSize <= 8 && destSize <= 8 && ">8-byte int type unexpected");
102     
103     if (destType->isSigned()) {
104       if (opSize > destSize)            // operand is larger than dest:
105         C = C & maskHi;                 // mask high bits
106
107       if (opSize > destSize ||
108           (opSize == destSize && ! V->getType()->isSigned()))
109         if (C & (1U << (8*destSize - 1)))
110           C =  C | ~maskHi;             // sign-extend from destSize to 64 bits
111     }
112     else {
113       if (opSize > destSize || (V->getType()->isSigned() && destSize < 8)) {
114         // operand is larger than dest,
115         //    OR both are equal but smaller than the full register size
116         //       AND operand is signed, so it may have extra sign bits:
117         // mask high bits
118         C = C & maskHi;
119       }
120     }
121   }
122
123   return C;
124 }
125
126
127 //----------------------------------------------------------------------------
128 // Function: CreateSETUWConst
129 // 
130 // Set a 32-bit unsigned constant in the register `dest', using
131 // SETHI, OR in the worst case.  This function correctly emulates
132 // the SETUW pseudo-op for SPARC v9 (if argument isSigned == false).
133 //
134 // The isSigned=true case is used to implement SETSW without duplicating code.
135 // 
136 // Optimize some common cases:
137 // (1) Small value that fits in simm13 field of OR: don't need SETHI.
138 // (2) isSigned = true and C is a small negative signed value, i.e.,
139 //     high bits are 1, and the remaining bits fit in simm13(OR).
140 //----------------------------------------------------------------------------
141
142 static inline void
143 CreateSETUWConst(const TargetMachine& target, uint32_t C,
144                  Instruction* dest, std::vector<MachineInstr*>& mvec,
145                  bool isSigned = false)
146 {
147   MachineInstr *miSETHI = NULL, *miOR = NULL;
148
149   // In order to get efficient code, we should not generate the SETHI if
150   // all high bits are 1 (i.e., this is a small signed value that fits in
151   // the simm13 field of OR).  So we check for and handle that case specially.
152   // NOTE: The value C = 0x80000000 is bad: sC < 0 *and* -sC < 0.
153   //       In fact, sC == -sC, so we have to check for this explicitly.
154   int32_t sC = (int32_t) C;
155   bool smallNegValue =isSigned && sC < 0 && sC != -sC && -sC < (int32_t)MAXSIMM;
156
157   // Set the high 22 bits in dest if non-zero and simm13 field of OR not enough
158   if (!smallNegValue && (C & ~MAXLO) && C > MAXSIMM) {
159     miSETHI = BuildMI(V9::SETHI, 2).addZImm(C).addRegDef(dest);
160     miSETHI->setOperandHi32(0);
161     mvec.push_back(miSETHI);
162   }
163   
164   // Set the low 10 or 12 bits in dest.  This is necessary if no SETHI
165   // was generated, or if the low 10 bits are non-zero.
166   if (miSETHI==NULL || C & MAXLO) {
167     if (miSETHI) {
168       // unsigned value with high-order bits set using SETHI
169       miOR = BuildMI(V9::ORi,3).addReg(dest).addZImm(C).addRegDef(dest);
170       miOR->setOperandLo32(1);
171     } else {
172       // unsigned or small signed value that fits in simm13 field of OR
173       assert(smallNegValue || (C & ~MAXSIMM) == 0);
174       miOR = BuildMI(V9::ORi, 3).addMReg(target.getRegInfo()
175                                         .getZeroRegNum())
176         .addSImm(sC).addRegDef(dest);
177     }
178     mvec.push_back(miOR);
179   }
180   
181   assert((miSETHI || miOR) && "Oops, no code was generated!");
182 }
183
184
185 //----------------------------------------------------------------------------
186 // Function: CreateSETSWConst
187 // 
188 // Set a 32-bit signed constant in the register `dest', with sign-extension
189 // to 64 bits.  This uses SETHI, OR, SRA in the worst case.
190 // This function correctly emulates the SETSW pseudo-op for SPARC v9.
191 //
192 // Optimize the same cases as SETUWConst, plus:
193 // (1) SRA is not needed for positive or small negative values.
194 //----------------------------------------------------------------------------
195
196 static inline void
197 CreateSETSWConst(const TargetMachine& target, int32_t C,
198                  Instruction* dest, std::vector<MachineInstr*>& mvec)
199 {
200   // Set the low 32 bits of dest
201   CreateSETUWConst(target, (uint32_t) C,  dest, mvec, /*isSigned*/true);
202
203   // Sign-extend to the high 32 bits if needed.
204   // NOTE: The value C = 0x80000000 is bad: -C == C and so -C is < MAXSIMM
205   if (C < 0 && (C == -C || -C > (int32_t) MAXSIMM))
206     mvec.push_back(BuildMI(V9::SRAi5,3).addReg(dest).addZImm(0).addRegDef(dest));
207 }
208
209
210 //----------------------------------------------------------------------------
211 // Function: CreateSETXConst
212 // 
213 // Set a 64-bit signed or unsigned constant in the register `dest'.
214 // Use SETUWConst for each 32 bit word, plus a left-shift-by-32 in between.
215 // This function correctly emulates the SETX pseudo-op for SPARC v9.
216 //
217 // Optimize the same cases as SETUWConst for each 32 bit word.
218 //----------------------------------------------------------------------------
219
220 static inline void
221 CreateSETXConst(const TargetMachine& target, uint64_t C,
222                 Instruction* tmpReg, Instruction* dest,
223                 std::vector<MachineInstr*>& mvec)
224 {
225   assert(C > (unsigned int) ~0 && "Use SETUW/SETSW for 32-bit values!");
226   
227   MachineInstr* MI;
228   
229   // Code to set the upper 32 bits of the value in register `tmpReg'
230   CreateSETUWConst(target, (C >> 32), tmpReg, mvec);
231   
232   // Shift tmpReg left by 32 bits
233   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
234                  .addRegDef(tmpReg));
235   
236   // Code to set the low 32 bits of the value in register `dest'
237   CreateSETUWConst(target, C, dest, mvec);
238   
239   // dest = OR(tmpReg, dest)
240   mvec.push_back(BuildMI(V9::ORr,3).addReg(dest).addReg(tmpReg).addRegDef(dest));
241 }
242
243
244 //----------------------------------------------------------------------------
245 // Function: CreateSETUWLabel
246 // 
247 // Set a 32-bit constant (given by a symbolic label) in the register `dest'.
248 //----------------------------------------------------------------------------
249
250 static inline void
251 CreateSETUWLabel(const TargetMachine& target, Value* val,
252                  Instruction* dest, std::vector<MachineInstr*>& mvec)
253 {
254   MachineInstr* MI;
255   
256   // Set the high 22 bits in dest
257   MI = BuildMI(V9::SETHI, 2).addReg(val).addRegDef(dest);
258   MI->setOperandHi32(0);
259   mvec.push_back(MI);
260   
261   // Set the low 10 bits in dest
262   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(val).addRegDef(dest);
263   MI->setOperandLo32(1);
264   mvec.push_back(MI);
265 }
266
267
268 //----------------------------------------------------------------------------
269 // Function: CreateSETXLabel
270 // 
271 // Set a 64-bit constant (given by a symbolic label) in the register `dest'.
272 //----------------------------------------------------------------------------
273
274 static inline void
275 CreateSETXLabel(const TargetMachine& target,
276                 Value* val, Instruction* tmpReg, Instruction* dest,
277                 std::vector<MachineInstr*>& mvec)
278 {
279   assert(isa<Constant>(val) || isa<GlobalValue>(val) &&
280          "I only know about constant values and global addresses");
281   
282   MachineInstr* MI;
283   
284   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg);
285   MI->setOperandHi64(0);
286   mvec.push_back(MI);
287   
288   MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addPCDisp(val).addRegDef(tmpReg);
289   MI->setOperandLo64(1);
290   mvec.push_back(MI);
291   
292   mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
293                  .addRegDef(tmpReg));
294   MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(dest);
295   MI->setOperandHi32(0);
296   mvec.push_back(MI);
297   
298   MI = BuildMI(V9::ORr, 3).addReg(dest).addReg(tmpReg).addRegDef(dest);
299   mvec.push_back(MI);
300   
301   MI = BuildMI(V9::ORi, 3).addReg(dest).addPCDisp(val).addRegDef(dest);
302   MI->setOperandLo32(1);
303   mvec.push_back(MI);
304 }
305
306
307 //----------------------------------------------------------------------------
308 // Function: CreateUIntSetInstruction
309 // 
310 // Create code to Set an unsigned constant in the register `dest'.
311 // Uses CreateSETUWConst, CreateSETSWConst or CreateSETXConst as needed.
312 // CreateSETSWConst is an optimization for the case that the unsigned value
313 // has all ones in the 33 high bits (so that sign-extension sets them all).
314 //----------------------------------------------------------------------------
315
316 static inline void
317 CreateUIntSetInstruction(const TargetMachine& target,
318                          uint64_t C, Instruction* dest,
319                          std::vector<MachineInstr*>& mvec,
320                          MachineCodeForInstruction& mcfi)
321 {
322   static const uint64_t lo32 = (uint32_t) ~0;
323   if (C <= lo32)                        // High 32 bits are 0.  Set low 32 bits.
324     CreateSETUWConst(target, (uint32_t) C, dest, mvec);
325   else if ((C & ~lo32) == ~lo32 && (C & (1U << 31))) {
326     // All high 33 (not 32) bits are 1s: sign-extension will take care
327     // of high 32 bits, so use the sequence for signed int
328     CreateSETSWConst(target, (int32_t) C, dest, mvec);
329   } else if (C > lo32) {
330     // C does not fit in 32 bits
331     TmpInstruction* tmpReg = new TmpInstruction(mcfi, Type::IntTy);
332     CreateSETXConst(target, C, tmpReg, dest, mvec);
333   }
334 }
335
336
337 //----------------------------------------------------------------------------
338 // Function: CreateIntSetInstruction
339 // 
340 // Create code to Set a signed constant in the register `dest'.
341 // Really the same as CreateUIntSetInstruction.
342 //----------------------------------------------------------------------------
343
344 static inline void
345 CreateIntSetInstruction(const TargetMachine& target,
346                         int64_t C, Instruction* dest,
347                         std::vector<MachineInstr*>& mvec,
348                         MachineCodeForInstruction& mcfi)
349 {
350   CreateUIntSetInstruction(target, (uint64_t) C, dest, mvec, mcfi);
351 }
352
353
354 //---------------------------------------------------------------------------
355 // Create a table of LLVM opcode -> max. immediate constant likely to
356 // be usable for that operation.
357 //---------------------------------------------------------------------------
358
359 // Entry == 0 ==> no immediate constant field exists at all.
360 // Entry >  0 ==> abs(immediate constant) <= Entry
361 // 
362 std::vector<int> MaxConstantsTable(Instruction::OtherOpsEnd);
363
364 static int
365 MaxConstantForInstr(unsigned llvmOpCode)
366 {
367   int modelOpCode = -1;
368
369   if (llvmOpCode >= Instruction::BinaryOpsBegin &&
370       llvmOpCode <  Instruction::BinaryOpsEnd)
371     modelOpCode = V9::ADDi;
372   else
373     switch(llvmOpCode) {
374     case Instruction::Ret:   modelOpCode = V9::JMPLCALLi; break;
375
376     case Instruction::Malloc:         
377     case Instruction::Alloca:         
378     case Instruction::GetElementPtr:  
379     case Instruction::PHI:       
380     case Instruction::Cast:
381     case Instruction::Call:  modelOpCode = V9::ADDi; break;
382
383     case Instruction::Shl:
384     case Instruction::Shr:   modelOpCode = V9::SLLXi6; break;
385
386     default: break;
387     };
388
389   return (modelOpCode < 0)? 0: SparcV9MachineInstrDesc[modelOpCode].maxImmedConst;
390 }
391
392 static void
393 InitializeMaxConstantsTable()
394 {
395   unsigned op;
396   assert(MaxConstantsTable.size() == Instruction::OtherOpsEnd &&
397          "assignments below will be illegal!");
398   for (op = Instruction::TermOpsBegin; op < Instruction::TermOpsEnd; ++op)
399     MaxConstantsTable[op] = MaxConstantForInstr(op);
400   for (op = Instruction::BinaryOpsBegin; op < Instruction::BinaryOpsEnd; ++op)
401     MaxConstantsTable[op] = MaxConstantForInstr(op);
402   for (op = Instruction::MemoryOpsBegin; op < Instruction::MemoryOpsEnd; ++op)
403     MaxConstantsTable[op] = MaxConstantForInstr(op);
404   for (op = Instruction::OtherOpsBegin; op < Instruction::OtherOpsEnd; ++op)
405     MaxConstantsTable[op] = MaxConstantForInstr(op);
406 }
407
408
409 //---------------------------------------------------------------------------
410 // class SparcV9InstrInfo 
411 // 
412 // Purpose:
413 //   Information about individual instructions.
414 //   Most information is stored in the SparcV9MachineInstrDesc array above.
415 //   Other information is computed on demand, and most such functions
416 //   default to member functions in base class TargetInstrInfo. 
417 //---------------------------------------------------------------------------
418
419 SparcV9InstrInfo::SparcV9InstrInfo()
420   : TargetInstrInfo(SparcV9MachineInstrDesc, V9::NUM_TOTAL_OPCODES) {
421   InitializeMaxConstantsTable();
422 }
423
424 bool
425 SparcV9InstrInfo::ConstantMayNotFitInImmedField(const Constant* CV,
426                                                    const Instruction* I) const
427 {
428   if (I->getOpcode() >= MaxConstantsTable.size()) // user-defined op (or bug!)
429     return true;
430
431   if (isa<ConstantPointerNull>(CV))               // can always use %g0
432     return false;
433
434   if (isa<SwitchInst>(I)) // Switch instructions will be lowered!
435     return false;
436
437   if (const ConstantInt* CI = dyn_cast<ConstantInt>(CV))
438     return labs((int64_t)CI->getRawValue()) > MaxConstantsTable[I->getOpcode()];
439
440   if (isa<ConstantBool>(CV))
441     return 1 > MaxConstantsTable[I->getOpcode()];
442
443   return true;
444 }
445
446 // 
447 // Create an instruction sequence to put the constant `val' into
448 // the virtual register `dest'.  `val' may be a Constant or a
449 // GlobalValue, viz., the constant address of a global variable or function.
450 // The generated instructions are returned in `mvec'.
451 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
452 // Any stack space required is allocated via MachineFunction.
453 // 
454 void
455 SparcV9InstrInfo::CreateCodeToLoadConst(const TargetMachine& target,
456                                       Function* F,
457                                       Value* val,
458                                       Instruction* dest,
459                                       std::vector<MachineInstr*>& mvec,
460                                       MachineCodeForInstruction& mcfi) const
461 {
462   assert(isa<Constant>(val) || isa<GlobalValue>(val) &&
463          "I only know about constant values and global addresses");
464   
465   // Use a "set" instruction for known constants or symbolic constants (labels)
466   // that can go in an integer reg.
467   // We have to use a "load" instruction for all other constants,
468   // in particular, floating point constants.
469   // 
470   const Type* valType = val->getType();
471   
472   // A ConstantPointerRef is just a reference to GlobalValue.
473   while (isa<ConstantPointerRef>(val))
474     val = cast<ConstantPointerRef>(val)->getValue();
475
476   if (isa<GlobalValue>(val)) {
477       TmpInstruction* tmpReg =
478         new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
479       CreateSETXLabel(target, val, tmpReg, dest, mvec);
480       return;
481   }
482
483   bool isValid;
484   uint64_t C = ConvertConstantToIntType(target, val, dest->getType(), isValid);
485   if (isValid) {
486     if (dest->getType()->isSigned())
487       CreateUIntSetInstruction(target, C, dest, mvec, mcfi);
488     else
489       CreateIntSetInstruction(target, (int64_t) C, dest, mvec, mcfi);
490
491   } else {
492     // Make an instruction sequence to load the constant, viz:
493     //            SETX <addr-of-constant>, tmpReg, addrReg
494     //            LOAD  /*addr*/ addrReg, /*offset*/ 0, dest
495       
496     // First, create a tmp register to be used by the SETX sequence.
497     TmpInstruction* tmpReg =
498       new TmpInstruction(mcfi, PointerType::get(val->getType()));
499       
500     // Create another TmpInstruction for the address register
501     TmpInstruction* addrReg =
502       new TmpInstruction(mcfi, PointerType::get(val->getType()));
503     
504     // Get the constant pool index for this constant
505     MachineConstantPool *CP = MachineFunction::get(F).getConstantPool();
506     Constant *C = cast<Constant>(val);
507     unsigned CPI = CP->getConstantPoolIndex(C);
508
509     // Put the address of the constant into a register
510     MachineInstr* MI;
511   
512     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(tmpReg);
513     MI->setOperandHi64(0);
514     mvec.push_back(MI);
515   
516     MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addConstantPoolIndex(CPI)
517       .addRegDef(tmpReg);
518     MI->setOperandLo64(1);
519     mvec.push_back(MI);
520   
521     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
522                    .addRegDef(tmpReg));
523     MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(addrReg);
524     MI->setOperandHi32(0);
525     mvec.push_back(MI);
526   
527     MI = BuildMI(V9::ORr, 3).addReg(addrReg).addReg(tmpReg).addRegDef(addrReg);
528     mvec.push_back(MI);
529   
530     MI = BuildMI(V9::ORi, 3).addReg(addrReg).addConstantPoolIndex(CPI)
531       .addRegDef(addrReg);
532     MI->setOperandLo32(1);
533     mvec.push_back(MI);
534
535     // Now load the constant from out ConstantPool label
536     unsigned Opcode = ChooseLoadInstruction(val->getType());
537     Opcode = convertOpcodeFromRegToImm(Opcode);
538     mvec.push_back(BuildMI(Opcode, 3)
539                    .addReg(addrReg).addSImm((int64_t)0).addRegDef(dest));
540   }
541 }
542
543
544 // Create an instruction sequence to copy an integer register `val'
545 // to a floating point register `dest' by copying to memory and back.
546 // val must be an integral type.  dest must be a Float or Double.
547 // The generated instructions are returned in `mvec'.
548 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
549 // Any stack space required is allocated via MachineFunction.
550 // 
551 void
552 SparcV9InstrInfo::CreateCodeToCopyIntToFloat(const TargetMachine& target,
553                                         Function* F,
554                                         Value* val,
555                                         Instruction* dest,
556                                         std::vector<MachineInstr*>& mvec,
557                                         MachineCodeForInstruction& mcfi) const
558 {
559   assert((val->getType()->isIntegral() || isa<PointerType>(val->getType()))
560          && "Source type must be integral (integer or bool) or pointer");
561   assert(dest->getType()->isFloatingPoint()
562          && "Dest type must be float/double");
563
564   // Get a stack slot to use for the copy
565   int offset = MachineFunction::get(F).getInfo()->allocateLocalVar(val);
566
567   // Get the size of the source value being copied. 
568   size_t srcSize = target.getTargetData().getTypeSize(val->getType());
569
570   // Store instruction stores `val' to [%fp+offset].
571   // The store and load opCodes are based on the size of the source value.
572   // If the value is smaller than 32 bits, we must sign- or zero-extend it
573   // to 32 bits since the load-float will load 32 bits.
574   // Note that the store instruction is the same for signed and unsigned ints.
575   const Type* storeType = (srcSize <= 4)? Type::IntTy : Type::LongTy;
576   Value* storeVal = val;
577   if (srcSize < target.getTargetData().getTypeSize(Type::FloatTy)) {
578     // sign- or zero-extend respectively
579     storeVal = new TmpInstruction(mcfi, storeType, val);
580     if (val->getType()->isSigned())
581       CreateSignExtensionInstructions(target, F, val, storeVal, 8*srcSize,
582                                       mvec, mcfi);
583     else
584       CreateZeroExtensionInstructions(target, F, val, storeVal, 8*srcSize,
585                                       mvec, mcfi);
586   }
587
588   unsigned FPReg = target.getRegInfo().getFramePointer();
589   unsigned StoreOpcode = ChooseStoreInstruction(storeType);
590   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
591   mvec.push_back(BuildMI(StoreOpcode, 3)
592                  .addReg(storeVal).addMReg(FPReg).addSImm(offset));
593
594   // Load instruction loads [%fp+offset] to `dest'.
595   // The type of the load opCode is the floating point type that matches the
596   // stored type in size:
597   // On SparcV9: float for int or smaller, double for long.
598   // 
599   const Type* loadType = (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
600   unsigned LoadOpcode = ChooseLoadInstruction(loadType);
601   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
602   mvec.push_back(BuildMI(LoadOpcode, 3)
603                  .addMReg(FPReg).addSImm(offset).addRegDef(dest));
604 }
605
606 // Similarly, create an instruction sequence to copy an FP register
607 // `val' to an integer register `dest' by copying to memory and back.
608 // The generated instructions are returned in `mvec'.
609 // Any temp. virtual registers (TmpInstruction) created are recorded in mcfi.
610 // Temporary stack space required is allocated via MachineFunction.
611 // 
612 void
613 SparcV9InstrInfo::CreateCodeToCopyFloatToInt(const TargetMachine& target,
614                                         Function* F,
615                                         Value* val,
616                                         Instruction* dest,
617                                         std::vector<MachineInstr*>& mvec,
618                                         MachineCodeForInstruction& mcfi) const
619 {
620   const Type* opTy   = val->getType();
621   const Type* destTy = dest->getType();
622
623   assert(opTy->isFloatingPoint() && "Source type must be float/double");
624   assert((destTy->isIntegral() || isa<PointerType>(destTy))
625          && "Dest type must be integer, bool or pointer");
626
627   // FIXME: For now, we allocate permanent space because the stack frame
628   // manager does not allow locals to be allocated (e.g., for alloca) after
629   // a temp is allocated!
630   // 
631   int offset = MachineFunction::get(F).getInfo()->allocateLocalVar(val); 
632
633   unsigned FPReg = target.getRegInfo().getFramePointer();
634
635   // Store instruction stores `val' to [%fp+offset].
636   // The store opCode is based only the source value being copied.
637   // 
638   unsigned StoreOpcode = ChooseStoreInstruction(opTy);
639   StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);  
640   mvec.push_back(BuildMI(StoreOpcode, 3)
641                  .addReg(val).addMReg(FPReg).addSImm(offset));
642
643   // Load instruction loads [%fp+offset] to `dest'.
644   // The type of the load opCode is the integer type that matches the
645   // source type in size:
646   // On SparcV9: int for float, long for double.
647   // Note that we *must* use signed loads even for unsigned dest types, to
648   // ensure correct sign-extension for UByte, UShort or UInt:
649   // 
650   const Type* loadTy = (opTy == Type::FloatTy)? Type::IntTy : Type::LongTy;
651   unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
652   LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
653   mvec.push_back(BuildMI(LoadOpcode, 3).addMReg(FPReg)
654                  .addSImm(offset).addRegDef(dest));
655 }
656
657
658 // Create instruction(s) to copy src to dest, for arbitrary types
659 // The generated instructions are returned in `mvec'.
660 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
661 // Any stack space required is allocated via MachineFunction.
662 // 
663 void
664 SparcV9InstrInfo::CreateCopyInstructionsByType(const TargetMachine& target,
665                                              Function *F,
666                                              Value* src,
667                                              Instruction* dest,
668                                              std::vector<MachineInstr*>& mvec,
669                                           MachineCodeForInstruction& mcfi) const
670 {
671   bool loadConstantToReg = false;
672   
673   const Type* resultType = dest->getType();
674   
675   MachineOpCode opCode = ChooseAddInstructionByType(resultType);
676   if (opCode == V9::INVALID_OPCODE) {
677     assert(0 && "Unsupported result type in CreateCopyInstructionsByType()");
678     return;
679   }
680   
681   // if `src' is a constant that doesn't fit in the immed field or if it is
682   // a global variable (i.e., a constant address), generate a load
683   // instruction instead of an add
684   // 
685   if (isa<Constant>(src)) {
686     unsigned int machineRegNum;
687     int64_t immedValue;
688     MachineOperand::MachineOperandType opType =
689       ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
690                        machineRegNum, immedValue);
691       
692     if (opType == MachineOperand::MO_VirtualRegister)
693       loadConstantToReg = true;
694   }
695   else if (isa<GlobalValue>(src))
696     loadConstantToReg = true;
697   
698   if (loadConstantToReg) { 
699     // `src' is constant and cannot fit in immed field for the ADD
700     // Insert instructions to "load" the constant into a register
701     target.getInstrInfo().CreateCodeToLoadConst(target, F, src, dest,
702                                                 mvec, mcfi);
703   } else { 
704     // Create a reg-to-reg copy instruction for the given type:
705     // -- For FP values, create a FMOVS or FMOVD instruction
706     // -- For non-FP values, create an add-with-0 instruction (opCode as above)
707     // Make `src' the second operand, in case it is a small constant!
708     // 
709     MachineInstr* MI;
710     if (resultType->isFloatingPoint())
711       MI = (BuildMI(resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
712             .addReg(src).addRegDef(dest));
713     else {
714         const Type* Ty =isa<PointerType>(resultType)? Type::ULongTy :resultType;
715         MI = (BuildMI(opCode, 3)
716               .addSImm((int64_t) 0).addReg(src).addRegDef(dest));
717     }
718     mvec.push_back(MI);
719   }
720 }
721
722
723 // Helper function for sign-extension and zero-extension.
724 // For SPARC v9, we sign-extend the given operand using SLL; SRA/SRL.
725 inline void
726 CreateBitExtensionInstructions(bool signExtend,
727                                const TargetMachine& target,
728                                Function* F,
729                                Value* srcVal,
730                                Value* destVal,
731                                unsigned int numLowBits,
732                                std::vector<MachineInstr*>& mvec,
733                                MachineCodeForInstruction& mcfi)
734 {
735   MachineInstr* M;
736
737   assert(numLowBits <= 32 && "Otherwise, nothing should be done here!");
738
739   if (numLowBits < 32) {
740     // SLL is needed since operand size is < 32 bits.
741     TmpInstruction *tmpI = new TmpInstruction(mcfi, destVal->getType(),
742                                               srcVal, destVal, "make32");
743     mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(srcVal)
744                    .addZImm(32-numLowBits).addRegDef(tmpI));
745     srcVal = tmpI;
746   }
747
748   mvec.push_back(BuildMI(signExtend? V9::SRAi5 : V9::SRLi5, 3)
749                  .addReg(srcVal).addZImm(32-numLowBits).addRegDef(destVal));
750 }
751
752
753 // Create instruction sequence to produce a sign-extended register value
754 // from an arbitrary-sized integer value (sized in bits, not bytes).
755 // The generated instructions are returned in `mvec'.
756 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
757 // Any stack space required is allocated via MachineFunction.
758 // 
759 void
760 SparcV9InstrInfo::CreateSignExtensionInstructions(
761                                         const TargetMachine& target,
762                                         Function* F,
763                                         Value* srcVal,
764                                         Value* destVal,
765                                         unsigned int numLowBits,
766                                         std::vector<MachineInstr*>& mvec,
767                                         MachineCodeForInstruction& mcfi) const
768 {
769   CreateBitExtensionInstructions(/*signExtend*/ true, target, F, srcVal,
770                                  destVal, numLowBits, mvec, mcfi);
771 }
772
773
774 // Create instruction sequence to produce a zero-extended register value
775 // from an arbitrary-sized integer value (sized in bits, not bytes).
776 // For SPARC v9, we sign-extend the given operand using SLL; SRL.
777 // The generated instructions are returned in `mvec'.
778 // Any temp. registers (TmpInstruction) created are recorded in mcfi.
779 // Any stack space required is allocated via MachineFunction.
780 // 
781 void
782 SparcV9InstrInfo::CreateZeroExtensionInstructions(
783                                         const TargetMachine& target,
784                                         Function* F,
785                                         Value* srcVal,
786                                         Value* destVal,
787                                         unsigned int numLowBits,
788                                         std::vector<MachineInstr*>& mvec,
789                                         MachineCodeForInstruction& mcfi) const
790 {
791   CreateBitExtensionInstructions(/*signExtend*/ false, target, F, srcVal,
792                                  destVal, numLowBits, mvec, mcfi);
793 }
794
795 } // End llvm namespace