Eliminated the MemAccessInst class, folding contents into GEP class.
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrSelectionSupport.cpp
1 //===-- InstrSelectionSupport.cpp -----------------------------------------===//
2 //
3 // Target-independent instruction selection code.  See SparcInstrSelection.cpp
4 // for usage.
5 // 
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/CodeGen/InstrSelectionSupport.h"
9 #include "llvm/CodeGen/InstrSelection.h"
10 #include "llvm/CodeGen/MachineInstr.h"
11 #include "llvm/CodeGen/MachineInstrAnnot.h"
12 #include "llvm/CodeGen/MachineCodeForInstruction.h"
13 #include "llvm/CodeGen/MachineCodeForMethod.h"
14 #include "llvm/CodeGen/InstrForest.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/MachineRegInfo.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Function.h"
19 #include "llvm/Type.h"
20 #include "llvm/iMemory.h"
21 using std::vector;
22
23 //*************************** Local Functions ******************************/
24
25
26 // Generate code to load the constant into a TmpInstruction (virtual reg) and
27 // returns the virtual register.
28 // 
29 static TmpInstruction*
30 InsertCodeToLoadConstant(Function *F,
31                          Value* opValue,
32                          Instruction* vmInstr,
33                          vector<MachineInstr*>& loadConstVec,
34                          TargetMachine& target)
35 {
36   // Create a tmp virtual register to hold the constant.
37   TmpInstruction* tmpReg = new TmpInstruction(opValue);
38   MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
39   mcfi.addTemp(tmpReg);
40   
41   target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
42                                               loadConstVec, mcfi);
43   
44   // Record the mapping from the tmp VM instruction to machine instruction.
45   // Do this for all machine instructions that were not mapped to any
46   // other temp values created by 
47   // tmpReg->addMachineInstruction(loadConstVec.back());
48   
49   return tmpReg;
50 }
51
52
53 //---------------------------------------------------------------------------
54 // Function GetConstantValueAsUnsignedInt
55 // Function GetConstantValueAsSignedInt
56 // 
57 // Convenience functions to get the value of an integral constant, for an
58 // appropriate integer or non-integer type that can be held in a signed
59 // or unsigned integer respectively.  The type of the argument must be
60 // the following:
61 //      Signed or unsigned integer
62 //      Boolean
63 //      Pointer
64 // 
65 // isValidConstant is set to true if a valid constant was found.
66 //---------------------------------------------------------------------------
67
68 uint64_t
69 GetConstantValueAsUnsignedInt(const Value *V,
70                               bool &isValidConstant)
71 {
72   isValidConstant = true;
73
74   if (isa<Constant>(V))
75     if (V->getType() == Type::BoolTy)
76       return (int64_t) cast<ConstantBool>(V)->getValue();
77     else if (V->getType()->isIntegral())
78       return (V->getType()->isUnsigned()
79               ? cast<ConstantUInt>(V)->getValue()
80               : (uint64_t) cast<ConstantSInt>(V)->getValue());
81
82   isValidConstant = false;
83   return 0;
84 }
85
86 int64_t
87 GetConstantValueAsSignedInt(const Value *V,
88                             bool &isValidConstant)
89 {
90   uint64_t C = GetConstantValueAsUnsignedInt(V, isValidConstant);
91   if (isValidConstant) {
92     if (V->getType()->isSigned() || C < INT64_MAX) // safe to cast to signed
93       return (int64_t) C;
94     else
95       isValidConstant = false;
96   }
97   return 0;
98 }
99
100 //---------------------------------------------------------------------------
101 // Function: FoldGetElemChain
102 // 
103 // Purpose:
104 //   Fold a chain of GetElementPtr instructions containing only
105 //   constant offsets into an equivalent (Pointer, IndexVector) pair.
106 //   Returns the pointer Value, and stores the resulting IndexVector
107 //   in argument chainIdxVec.
108 //---------------------------------------------------------------------------
109
110 Value*
111 FoldGetElemChain(const InstructionNode* getElemInstrNode,
112                  vector<Value*>& chainIdxVec)
113 {
114   GetElementPtrInst* getElemInst =
115     cast<GetElementPtrInst>(getElemInstrNode->getInstruction());
116   
117   // Return NULL if we don't fold any instructions in.
118   Value* ptrVal = NULL;
119   
120   // Remember if the last instruction had a leading [0] index.
121   bool hasLeadingZero = false;
122   
123   // Now chase the chain of getElementInstr instructions, if any.
124   // Check for any non-constant indices and stop there.
125   // 
126   const InstrTreeNode* ptrChild = getElemInstrNode;
127   while (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
128          ptrChild->getOpLabel() == GetElemPtrIdx)
129     {
130       // Child is a GetElemPtr instruction
131       getElemInst = cast<GetElementPtrInst>(ptrChild->getValue());
132       User::op_iterator OI, firstIdx = getElemInst->idx_begin();
133       User::op_iterator lastIdx = getElemInst->idx_end();
134       bool allConstantOffsets = true;
135
136       // Check that all offsets are constant for this instruction
137       for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
138         allConstantOffsets = isa<ConstantInt>(*OI);
139
140       if (allConstantOffsets)
141         { // Get pointer value out of ptrChild.
142           ptrVal = getElemInst->getPointerOperand();
143
144           // Check for a leading [0] index, if any.  It will be discarded later.
145           ConstantUInt* CV = dyn_cast<ConstantUInt>((Value*) *firstIdx);
146           hasLeadingZero = bool(CV && CV->getValue() == 0);
147
148           // Insert its index vector at the start, skipping any leading [0]
149           chainIdxVec.insert(chainIdxVec.begin(),
150                              firstIdx + hasLeadingZero, lastIdx);
151
152           // Mark the folded node so no code is generated for it.
153           ((InstructionNode*) ptrChild)->markFoldedIntoParent();
154         }
155       else // cannot fold this getElementPtr instr. or any further ones
156         break;
157
158       ptrChild = ptrChild->leftChild();
159     }
160
161   // If the first getElementPtr instruction had a leading [0], add it back.
162   // Note that this instruction is the *last* one successfully folded above.
163   if (ptrVal && hasLeadingZero) 
164     chainIdxVec.insert(chainIdxVec.begin(), ConstantUInt::get(Type::UIntTy,0));
165
166   return ptrVal;
167 }
168
169
170 //------------------------------------------------------------------------ 
171 // Function Set2OperandsFromInstr
172 // Function Set3OperandsFromInstr
173 // 
174 // For the common case of 2- and 3-operand arithmetic/logical instructions,
175 // set the m/c instr. operands directly from the VM instruction's operands.
176 // Check whether the first or second operand is 0 and can use a dedicated "0"
177 // register.
178 // Check whether the second operand should use an immediate field or register.
179 // (First and third operands are never immediates for such instructions.)
180 // 
181 // Arguments:
182 // canDiscardResult: Specifies that the result operand can be discarded
183 //                   by using the dedicated "0"
184 // 
185 // op1position, op2position and resultPosition: Specify in which position
186 //                   in the machine instruction the 3 operands (arg1, arg2
187 //                   and result) should go.
188 // 
189 //------------------------------------------------------------------------ 
190
191 void
192 Set2OperandsFromInstr(MachineInstr* minstr,
193                       InstructionNode* vmInstrNode,
194                       const TargetMachine& target,
195                       bool canDiscardResult,
196                       int op1Position,
197                       int resultPosition)
198 {
199   Set3OperandsFromInstr(minstr, vmInstrNode, target,
200                         canDiscardResult, op1Position,
201                         /*op2Position*/ -1, resultPosition);
202 }
203
204
205 void
206 Set3OperandsFromInstr(MachineInstr* minstr,
207                       InstructionNode* vmInstrNode,
208                       const TargetMachine& target,
209                       bool canDiscardResult,
210                       int op1Position,
211                       int op2Position,
212                       int resultPosition)
213 {
214   assert(op1Position >= 0);
215   assert(resultPosition >= 0);
216   
217   // operand 1
218   minstr->SetMachineOperandVal(op1Position, MachineOperand::MO_VirtualRegister,
219                             vmInstrNode->leftChild()->getValue());   
220   
221   // operand 2 (if any)
222   if (op2Position >= 0)
223     minstr->SetMachineOperandVal(op2Position, MachineOperand::MO_VirtualRegister,
224                               vmInstrNode->rightChild()->getValue());   
225   
226   // result operand: if it can be discarded, use a dead register if one exists
227   if (canDiscardResult && target.getRegInfo().getZeroRegNum() >= 0)
228     minstr->SetMachineOperandReg(resultPosition,
229                               target.getRegInfo().getZeroRegNum());
230   else
231     minstr->SetMachineOperandVal(resultPosition,
232                               MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
233 }
234
235
236 MachineOperand::MachineOperandType
237 ChooseRegOrImmed(Value* val,
238                  MachineOpCode opCode,
239                  const TargetMachine& target,
240                  bool canUseImmed,
241                  unsigned int& getMachineRegNum,
242                  int64_t& getImmedValue)
243 {
244   MachineOperand::MachineOperandType opType =
245     MachineOperand::MO_VirtualRegister;
246   getMachineRegNum = 0;
247   getImmedValue = 0;
248   
249   // Check for the common case first: argument is not constant
250   // 
251   Constant *CPV = dyn_cast<Constant>(val);
252   if (!CPV) return opType;
253
254   if (ConstantBool *CPB = dyn_cast<ConstantBool>(CPV))
255     {
256       if (!CPB->getValue() && target.getRegInfo().getZeroRegNum() >= 0)
257         {
258           getMachineRegNum = target.getRegInfo().getZeroRegNum();
259           return MachineOperand::MO_MachineRegister;
260         }
261
262       getImmedValue = 1;
263       return MachineOperand::MO_SignExtendedImmed;
264     }
265   
266   // Otherwise it needs to be an integer or a NULL pointer
267   if (! CPV->getType()->isIntegral() &&
268       ! (isa<PointerType>(CPV->getType()) &&
269          CPV->isNullValue()))
270     return opType;
271   
272   // Now get the constant value and check if it fits in the IMMED field.
273   // Take advantage of the fact that the max unsigned value will rarely
274   // fit into any IMMED field and ignore that case (i.e., cast smaller
275   // unsigned constants to signed).
276   // 
277   int64_t intValue;
278   if (isa<PointerType>(CPV->getType()))
279     {
280       intValue = 0;
281     }
282   else if (CPV->getType()->isSigned())
283     {
284       intValue = cast<ConstantSInt>(CPV)->getValue();
285     }
286   else
287     {
288       uint64_t V = cast<ConstantUInt>(CPV)->getValue();
289       if (V >= INT64_MAX) return opType;
290       intValue = (int64_t)V;
291     }
292
293   if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
294     {
295       opType = MachineOperand::MO_MachineRegister;
296       getMachineRegNum = target.getRegInfo().getZeroRegNum();
297     }
298   else if (canUseImmed &&
299            target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
300     {
301       opType = CPV->getType()->isSigned()
302         ? MachineOperand::MO_SignExtendedImmed
303         : MachineOperand::MO_UnextendedImmed;
304       getImmedValue = intValue;
305     }
306   
307   return opType;
308 }
309
310
311 //---------------------------------------------------------------------------
312 // Function: FixConstantOperandsForInstr
313 // 
314 // Purpose:
315 // Special handling for constant operands of a machine instruction
316 // -- if the constant is 0, use the hardwired 0 register, if any;
317 // -- if the constant fits in the IMMEDIATE field, use that field;
318 // -- else create instructions to put the constant into a register, either
319 //    directly or by loading explicitly from the constant pool.
320 // 
321 // In the first 2 cases, the operand of `minstr' is modified in place.
322 // Returns a vector of machine instructions generated for operands that
323 // fall under case 3; these must be inserted before `minstr'.
324 //---------------------------------------------------------------------------
325
326 vector<MachineInstr*>
327 FixConstantOperandsForInstr(Instruction* vmInstr,
328                             MachineInstr* minstr,
329                             TargetMachine& target)
330 {
331   vector<MachineInstr*> loadConstVec;
332   
333   const MachineInstrDescriptor& instrDesc =
334     target.getInstrInfo().getDescriptor(minstr->getOpCode());
335   
336   Function *F = vmInstr->getParent()->getParent();
337   
338   for (unsigned op=0; op < minstr->getNumOperands(); op++)
339     {
340       const MachineOperand& mop = minstr->getOperand(op);
341           
342       // skip the result position (for efficiency below) and any other
343       // positions already marked as not a virtual register
344       if (instrDesc.resultPos == (int) op || 
345           mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
346           mop.getVRegValue() == NULL)
347         {
348           continue;
349         }
350           
351       Value* opValue = mop.getVRegValue();
352       bool constantThatMustBeLoaded = false;
353       
354       if (Constant *opConst = dyn_cast<Constant>(opValue))
355         {
356           unsigned int machineRegNum;
357           int64_t immedValue;
358           MachineOperand::MachineOperandType opType =
359             ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
360                              (target.getInstrInfo().getImmedConstantPos(minstr->getOpCode()) == (int) op),
361                              machineRegNum, immedValue);
362           
363           if (opType == MachineOperand::MO_MachineRegister)
364             minstr->SetMachineOperandReg(op, machineRegNum);
365           else if (opType == MachineOperand::MO_VirtualRegister)
366             constantThatMustBeLoaded = true; // load is generated below
367           else
368             minstr->SetMachineOperandConst(op, opType, immedValue);
369         }
370       
371       if (constantThatMustBeLoaded || isa<GlobalValue>(opValue))
372         { // opValue is a constant that must be explicitly loaded into a reg.
373           TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue,vmInstr,
374                                                             loadConstVec,
375                                                             target);
376           minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
377                                        tmpReg);
378         }
379     }
380   
381   // 
382   // Also, check for implicit operands used by the machine instruction
383   // (no need to check those defined since they cannot be constants).
384   // These include:
385   // -- arguments to a Call
386   // -- return value of a Return
387   // Any such operand that is a constant value needs to be fixed also.
388   // The current instructions with implicit refs (viz., Call and Return)
389   // have no immediate fields, so the constant always needs to be loaded
390   // into a register.
391   // 
392   bool isCall = target.getInstrInfo().isCall(minstr->getOpCode());
393   unsigned lastCallArgNum = 0;          // unused if not a call
394   CallArgsDescriptor* argDesc = NULL;   // unused if not a call
395   if (isCall)
396     argDesc = CallArgsDescriptor::get(minstr);
397   
398   for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
399     if (isa<Constant>(minstr->getImplicitRef(i)) ||
400         isa<GlobalValue>(minstr->getImplicitRef(i)))
401       {
402         Value* oldVal = minstr->getImplicitRef(i);
403         TmpInstruction* tmpReg =
404           InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
405         minstr->setImplicitRef(i, tmpReg);
406         
407         if (isCall)
408           { // find and replace the argument in the CallArgsDescriptor
409             unsigned i=lastCallArgNum;
410             while (argDesc->getArgInfo(i).getArgVal() != oldVal)
411               ++i;
412             assert(i < argDesc->getNumArgs() &&
413                    "Constant operands to a call *must* be in the arg list");
414             lastCallArgNum = i;
415             argDesc->getArgInfo(i).replaceArgVal(tmpReg);
416           }
417       }
418   
419   return loadConstVec;
420 }
421
422