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