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