2 //***************************************************************************
4 // InstrSelectionSupport.h
7 // Target-independent instruction selection code.
8 // See SparcInstrSelection.cpp for usage.
11 // 10/10/01 - Vikram Adve - Created
12 //**************************************************************************/
14 #include "llvm/CodeGen/InstrSelectionSupport.h"
15 #include "llvm/CodeGen/InstrSelection.h"
16 #include "llvm/CodeGen/MachineCodeForInstruction.h"
17 #include "llvm/CodeGen/MachineCodeForMethod.h"
18 #include "llvm/CodeGen/InstrForest.h"
19 #include "llvm/Target/TargetMachine.h"
20 #include "llvm/Target/MachineRegInfo.h"
21 #include "llvm/Constants.h"
22 #include "llvm/Function.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/Type.h"
25 #include "llvm/iMemory.h"
28 //*************************** Local Functions ******************************/
31 static TmpInstruction*
32 InsertCodeToLoadConstant(Function *F,
35 vector<MachineInstr*>& loadConstVec,
36 TargetMachine& target)
38 vector<TmpInstruction*> tempVec;
40 // Create a tmp virtual register to hold the constant.
41 TmpInstruction* tmpReg = new TmpInstruction(opValue);
42 MachineCodeForInstruction &MCFI = MachineCodeForInstruction::get(vmInstr);
45 target.getInstrInfo().CreateCodeToLoadConst(F, opValue, tmpReg,
46 loadConstVec, tempVec);
48 // Register the new tmp values created for this m/c instruction sequence
49 for (unsigned i=0; i < tempVec.size(); i++)
50 MCFI.addTemp(tempVec[i]);
52 // Record the mapping from the tmp VM instruction to machine instruction.
53 // Do this for all machine instructions that were not mapped to any
54 // other temp values created by
55 // tmpReg->addMachineInstruction(loadConstVec.back());
61 //---------------------------------------------------------------------------
62 // Function GetConstantValueAsSignedInt
64 // Convenience function to get the value of an integer constant, for an
65 // appropriate integer or non-integer type that can be held in an integer.
66 // The type of the argument must be the following:
67 // Signed or unsigned integer
71 // isValidConstant is set to true if a valid constant was found.
72 //---------------------------------------------------------------------------
75 GetConstantValueAsSignedInt(const Value *V,
76 bool &isValidConstant)
78 if (!isa<Constant>(V))
80 isValidConstant = false;
84 isValidConstant = true;
86 if (V->getType() == Type::BoolTy)
87 return (int64_t) cast<ConstantBool>(V)->getValue();
89 if (V->getType()->isIntegral())
91 if (V->getType()->isSigned())
92 return cast<ConstantSInt>(V)->getValue();
94 assert(V->getType()->isUnsigned());
95 uint64_t Val = cast<ConstantUInt>(V)->getValue();
96 if (Val < INT64_MAX) // then safe to cast to signed
100 isValidConstant = false;
105 //---------------------------------------------------------------------------
106 // Function: FoldGetElemChain
109 // Fold a chain of GetElementPtr instructions containing only
110 // structure offsets into an equivalent (Pointer, IndexVector) pair.
111 // Returns the pointer Value, and stores the resulting IndexVector
112 // in argument chainIdxVec.
113 //---------------------------------------------------------------------------
116 FoldGetElemChain(const InstructionNode* getElemInstrNode,
117 vector<Value*>& chainIdxVec)
119 MemAccessInst* getElemInst = (MemAccessInst*)
120 getElemInstrNode->getInstruction();
122 // Return NULL if we don't fold any instructions in.
123 Value* ptrVal = NULL;
125 // The incoming index vector must be for the user of the chain.
126 // Its leading index must be [0] and we insert indices after that.
127 assert(chainIdxVec.size() > 0 &&
128 isa<ConstantUInt>(chainIdxVec.front()) &&
129 cast<ConstantUInt>(chainIdxVec.front())->getValue() == 0);
131 // Now chase the chain of getElementInstr instructions, if any.
132 // Check for any array indices and stop there.
134 const InstrTreeNode* ptrChild = getElemInstrNode;
135 while (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
136 ptrChild->getOpLabel() == GetElemPtrIdx)
138 // Child is a GetElemPtr instruction
139 getElemInst = (MemAccessInst*)
140 ((InstructionNode*) ptrChild)->getInstruction();
141 const vector<Value*>& idxVec = getElemInst->copyIndices();
142 bool allStructureOffsets = true;
144 // If it is a struct* access, the first offset must be array index [0],
145 // and all other offsets must be structure (not array) offsets
146 if (!isa<ConstantUInt>(idxVec.front()) ||
147 cast<ConstantUInt>(idxVec.front())->getValue() != 0)
148 allStructureOffsets = false;
150 if (allStructureOffsets)
151 for (unsigned int i=1; i < idxVec.size(); i++)
152 if (idxVec[i]->getType() == Type::UIntTy)
154 allStructureOffsets = false;
158 if (allStructureOffsets)
159 { // Get pointer value out of ptrChild.
160 ptrVal = getElemInst->getPointerOperand();
162 // Insert its index vector at the start, but after the leading [0]
163 chainIdxVec.insert(chainIdxVec.begin()+1,
164 idxVec.begin()+1, idxVec.end());
166 // Mark the folded node so no code is generated for it.
167 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
169 else // cannot fold this getElementPtr instr. or any further ones
172 ptrChild = ptrChild->leftChild();
179 //------------------------------------------------------------------------
180 // Function Set2OperandsFromInstr
181 // Function Set3OperandsFromInstr
183 // For the common case of 2- and 3-operand arithmetic/logical instructions,
184 // set the m/c instr. operands directly from the VM instruction's operands.
185 // Check whether the first or second operand is 0 and can use a dedicated "0"
187 // Check whether the second operand should use an immediate field or register.
188 // (First and third operands are never immediates for such instructions.)
191 // canDiscardResult: Specifies that the result operand can be discarded
192 // by using the dedicated "0"
194 // op1position, op2position and resultPosition: Specify in which position
195 // in the machine instruction the 3 operands (arg1, arg2
196 // and result) should go.
198 // RETURN VALUE: unsigned int flags, where
199 // flags & 0x01 => operand 1 is constant and needs a register
200 // flags & 0x02 => operand 2 is constant and needs a register
201 //------------------------------------------------------------------------
204 Set2OperandsFromInstr(MachineInstr* minstr,
205 InstructionNode* vmInstrNode,
206 const TargetMachine& target,
207 bool canDiscardResult,
211 Set3OperandsFromInstr(minstr, vmInstrNode, target,
212 canDiscardResult, op1Position,
213 /*op2Position*/ -1, resultPosition);
218 Set3OperandsFromInstr(MachineInstr* minstr,
219 InstructionNode* vmInstrNode,
220 const TargetMachine& target,
221 bool canDiscardResult,
226 assert(op1Position >= 0);
227 assert(resultPosition >= 0);
230 minstr->SetMachineOperandVal(op1Position, MachineOperand::MO_VirtualRegister,
231 vmInstrNode->leftChild()->getValue());
233 // operand 2 (if any)
234 if (op2Position >= 0)
235 minstr->SetMachineOperandVal(op2Position, MachineOperand::MO_VirtualRegister,
236 vmInstrNode->rightChild()->getValue());
238 // result operand: if it can be discarded, use a dead register if one exists
239 if (canDiscardResult && target.getRegInfo().getZeroRegNum() >= 0)
240 minstr->SetMachineOperandReg(resultPosition,
241 target.getRegInfo().getZeroRegNum());
243 minstr->SetMachineOperandVal(resultPosition,
244 MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
248 MachineOperand::MachineOperandType
249 ChooseRegOrImmed(Value* val,
250 MachineOpCode opCode,
251 const TargetMachine& target,
253 unsigned int& getMachineRegNum,
254 int64_t& getImmedValue)
256 MachineOperand::MachineOperandType opType =
257 MachineOperand::MO_VirtualRegister;
258 getMachineRegNum = 0;
261 // Check for the common case first: argument is not constant
263 Constant *CPV = dyn_cast<Constant>(val);
264 if (!CPV) return opType;
266 if (ConstantBool *CPB = dyn_cast<ConstantBool>(CPV))
268 if (!CPB->getValue() && target.getRegInfo().getZeroRegNum() >= 0)
270 getMachineRegNum = target.getRegInfo().getZeroRegNum();
271 return MachineOperand::MO_MachineRegister;
275 return MachineOperand::MO_SignExtendedImmed;
278 // Otherwise it needs to be an integer or a NULL pointer
279 if (! CPV->getType()->isIntegral() &&
280 ! (CPV->getType()->isPointerType() &&
284 // Now get the constant value and check if it fits in the IMMED field.
285 // Take advantage of the fact that the max unsigned value will rarely
286 // fit into any IMMED field and ignore that case (i.e., cast smaller
287 // unsigned constants to signed).
290 if (CPV->getType()->isPointerType())
294 else if (CPV->getType()->isSigned())
296 intValue = cast<ConstantSInt>(CPV)->getValue();
300 uint64_t V = cast<ConstantUInt>(CPV)->getValue();
301 if (V >= INT64_MAX) return opType;
302 intValue = (int64_t)V;
305 if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
307 opType = MachineOperand::MO_MachineRegister;
308 getMachineRegNum = target.getRegInfo().getZeroRegNum();
310 else if (canUseImmed &&
311 target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
313 opType = MachineOperand::MO_SignExtendedImmed;
314 getImmedValue = intValue;
321 //---------------------------------------------------------------------------
322 // Function: FixConstantOperandsForInstr
325 // Special handling for constant operands of a machine instruction
326 // -- if the constant is 0, use the hardwired 0 register, if any;
327 // -- if the constant fits in the IMMEDIATE field, use that field;
328 // -- else create instructions to put the constant into a register, either
329 // directly or by loading explicitly from the constant pool.
331 // In the first 2 cases, the operand of `minstr' is modified in place.
332 // Returns a vector of machine instructions generated for operands that
333 // fall under case 3; these must be inserted before `minstr'.
334 //---------------------------------------------------------------------------
336 vector<MachineInstr*>
337 FixConstantOperandsForInstr(Instruction* vmInstr,
338 MachineInstr* minstr,
339 TargetMachine& target)
341 vector<MachineInstr*> loadConstVec;
343 const MachineInstrDescriptor& instrDesc =
344 target.getInstrInfo().getDescriptor(minstr->getOpCode());
346 Function *F = vmInstr->getParent()->getParent();
348 for (unsigned op=0; op < minstr->getNumOperands(); op++)
350 const MachineOperand& mop = minstr->getOperand(op);
352 // skip the result position (for efficiency below) and any other
353 // positions already marked as not a virtual register
354 if (instrDesc.resultPos == (int) op ||
355 mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
356 mop.getVRegValue() == NULL)
361 Value* opValue = mop.getVRegValue();
362 bool constantThatMustBeLoaded = false;
364 if (Constant *opConst = dyn_cast<Constant>(opValue))
366 unsigned int machineRegNum;
368 MachineOperand::MachineOperandType opType =
369 ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
370 (target.getInstrInfo().getImmedConstantPos(minstr->getOpCode()) == (int) op),
371 machineRegNum, immedValue);
373 if (opType == MachineOperand::MO_MachineRegister)
374 minstr->SetMachineOperandReg(op, machineRegNum);
375 else if (opType == MachineOperand::MO_VirtualRegister)
376 constantThatMustBeLoaded = true; // load is generated below
378 minstr->SetMachineOperandConst(op, opType, immedValue);
381 if (constantThatMustBeLoaded || isa<GlobalValue>(opValue))
382 { // opValue is a constant that must be explicitly loaded into a reg.
383 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
386 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
392 // Also, check for implicit operands used (not those defined) by the
393 // machine instruction. These include:
394 // -- arguments to a Call
395 // -- return value of a Return
396 // Any such operand that is a constant value needs to be fixed also.
397 // The current instructions with implicit refs (viz., Call and Return)
398 // have no immediate fields, so the constant always needs to be loaded
401 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
402 if (isa<Constant>(minstr->getImplicitRef(i)) ||
403 isa<GlobalValue>(minstr->getImplicitRef(i)))
405 Value* oldVal = minstr->getImplicitRef(i);
406 TmpInstruction* tmpReg =
407 InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
408 minstr->setImplicitRef(i, tmpReg);