1 //===-- InstrSelectionSupport.cpp -----------------------------------------===//
3 // Target-independent instruction selection code. See SparcInstrSelection.cpp
6 //===----------------------------------------------------------------------===//
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"
23 //*************************** Local Functions ******************************/
26 // Generate code to load the constant into a TmpInstruction (virtual reg) and
27 // returns the virtual register.
29 static TmpInstruction*
30 InsertCodeToLoadConstant(Function *F,
33 vector<MachineInstr*>& loadConstVec,
34 TargetMachine& target)
36 // Create a tmp virtual register to hold the constant.
37 TmpInstruction* tmpReg = new TmpInstruction(opValue);
38 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
41 target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
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());
53 //---------------------------------------------------------------------------
54 // Function GetConstantValueAsUnsignedInt
55 // Function GetConstantValueAsSignedInt
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
61 // Signed or unsigned integer
65 // isValidConstant is set to true if a valid constant was found.
66 //---------------------------------------------------------------------------
69 GetConstantValueAsUnsignedInt(const Value *V,
70 bool &isValidConstant)
72 isValidConstant = true;
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());
82 isValidConstant = false;
87 GetConstantValueAsSignedInt(const Value *V,
88 bool &isValidConstant)
90 uint64_t C = GetConstantValueAsUnsignedInt(V, isValidConstant);
91 if (isValidConstant) {
92 if (V->getType()->isSigned() || C < INT64_MAX) // safe to cast to signed
95 isValidConstant = false;
100 //---------------------------------------------------------------------------
101 // Function: FoldGetElemChain
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 //---------------------------------------------------------------------------
111 FoldGetElemChain(const InstructionNode* getElemInstrNode,
112 vector<Value*>& chainIdxVec)
114 GetElementPtrInst* getElemInst =
115 cast<GetElementPtrInst>(getElemInstrNode->getInstruction());
117 // Return NULL if we don't fold any instructions in.
118 Value* ptrVal = NULL;
120 // Remember if the last instruction had a leading [0] index.
121 bool hasLeadingZero = false;
123 // Now chase the chain of getElementInstr instructions, if any.
124 // Check for any non-constant indices and stop there.
126 const InstrTreeNode* ptrChild = getElemInstrNode;
127 while (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
128 ptrChild->getOpLabel() == GetElemPtrIdx)
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;
136 // Check that all offsets are constant for this instruction
137 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
138 allConstantOffsets = isa<ConstantInt>(*OI);
140 if (allConstantOffsets)
141 { // Get pointer value out of ptrChild.
142 ptrVal = getElemInst->getPointerOperand();
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);
148 // Insert its index vector at the start, skipping any leading [0]
149 chainIdxVec.insert(chainIdxVec.begin(),
150 firstIdx + hasLeadingZero, lastIdx);
152 // Mark the folded node so no code is generated for it.
153 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
155 else // cannot fold this getElementPtr instr. or any further ones
158 ptrChild = ptrChild->leftChild();
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));
170 //------------------------------------------------------------------------
171 // Function Set2OperandsFromInstr
172 // Function Set3OperandsFromInstr
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"
178 // Check whether the second operand should use an immediate field or register.
179 // (First and third operands are never immediates for such instructions.)
182 // canDiscardResult: Specifies that the result operand can be discarded
183 // by using the dedicated "0"
185 // op1position, op2position and resultPosition: Specify in which position
186 // in the machine instruction the 3 operands (arg1, arg2
187 // and result) should go.
189 //------------------------------------------------------------------------
192 Set2OperandsFromInstr(MachineInstr* minstr,
193 InstructionNode* vmInstrNode,
194 const TargetMachine& target,
195 bool canDiscardResult,
199 Set3OperandsFromInstr(minstr, vmInstrNode, target,
200 canDiscardResult, op1Position,
201 /*op2Position*/ -1, resultPosition);
206 Set3OperandsFromInstr(MachineInstr* minstr,
207 InstructionNode* vmInstrNode,
208 const TargetMachine& target,
209 bool canDiscardResult,
214 assert(op1Position >= 0);
215 assert(resultPosition >= 0);
218 minstr->SetMachineOperandVal(op1Position, MachineOperand::MO_VirtualRegister,
219 vmInstrNode->leftChild()->getValue());
221 // operand 2 (if any)
222 if (op2Position >= 0)
223 minstr->SetMachineOperandVal(op2Position, MachineOperand::MO_VirtualRegister,
224 vmInstrNode->rightChild()->getValue());
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());
231 minstr->SetMachineOperandVal(resultPosition,
232 MachineOperand::MO_VirtualRegister, vmInstrNode->getValue());
236 MachineOperand::MachineOperandType
237 ChooseRegOrImmed(Value* val,
238 MachineOpCode opCode,
239 const TargetMachine& target,
241 unsigned int& getMachineRegNum,
242 int64_t& getImmedValue)
244 MachineOperand::MachineOperandType opType =
245 MachineOperand::MO_VirtualRegister;
246 getMachineRegNum = 0;
249 // Check for the common case first: argument is not constant
251 Constant *CPV = dyn_cast<Constant>(val);
252 if (!CPV) return opType;
254 if (ConstantBool *CPB = dyn_cast<ConstantBool>(CPV))
256 if (!CPB->getValue() && target.getRegInfo().getZeroRegNum() >= 0)
258 getMachineRegNum = target.getRegInfo().getZeroRegNum();
259 return MachineOperand::MO_MachineRegister;
263 return MachineOperand::MO_SignExtendedImmed;
266 // Otherwise it needs to be an integer or a NULL pointer
267 if (! CPV->getType()->isIntegral() &&
268 ! (isa<PointerType>(CPV->getType()) &&
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).
278 if (isa<PointerType>(CPV->getType()))
282 else if (CPV->getType()->isSigned())
284 intValue = cast<ConstantSInt>(CPV)->getValue();
288 uint64_t V = cast<ConstantUInt>(CPV)->getValue();
289 if (V >= INT64_MAX) return opType;
290 intValue = (int64_t)V;
293 if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
295 opType = MachineOperand::MO_MachineRegister;
296 getMachineRegNum = target.getRegInfo().getZeroRegNum();
298 else if (canUseImmed &&
299 target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
301 opType = CPV->getType()->isSigned()
302 ? MachineOperand::MO_SignExtendedImmed
303 : MachineOperand::MO_UnextendedImmed;
304 getImmedValue = intValue;
311 //---------------------------------------------------------------------------
312 // Function: FixConstantOperandsForInstr
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.
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 //---------------------------------------------------------------------------
326 vector<MachineInstr*>
327 FixConstantOperandsForInstr(Instruction* vmInstr,
328 MachineInstr* minstr,
329 TargetMachine& target)
331 vector<MachineInstr*> loadConstVec;
333 const MachineInstrDescriptor& instrDesc =
334 target.getInstrInfo().getDescriptor(minstr->getOpCode());
336 Function *F = vmInstr->getParent()->getParent();
338 for (unsigned op=0; op < minstr->getNumOperands(); op++)
340 const MachineOperand& mop = minstr->getOperand(op);
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)
351 Value* opValue = mop.getVRegValue();
352 bool constantThatMustBeLoaded = false;
354 if (Constant *opConst = dyn_cast<Constant>(opValue))
356 unsigned int machineRegNum;
358 MachineOperand::MachineOperandType opType =
359 ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
360 (target.getInstrInfo().getImmedConstantPos(minstr->getOpCode()) == (int) op),
361 machineRegNum, immedValue);
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
368 minstr->SetMachineOperandConst(op, opType, immedValue);
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,
376 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
382 // Also, check for implicit operands used by the machine instruction
383 // (no need to check those defined since they cannot be constants).
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
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
396 argDesc = CallArgsDescriptor::get(minstr);
398 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
399 if (isa<Constant>(minstr->getImplicitRef(i)) ||
400 isa<GlobalValue>(minstr->getImplicitRef(i)))
402 Value* oldVal = minstr->getImplicitRef(i);
403 TmpInstruction* tmpReg =
404 InsertCodeToLoadConstant(F, oldVal, vmInstr, loadConstVec, target);
405 minstr->setImplicitRef(i, tmpReg);
408 { // find and replace the argument in the CallArgsDescriptor
409 unsigned i=lastCallArgNum;
410 while (argDesc->getArgInfo(i).getArgVal() != oldVal)
412 assert(i < argDesc->getNumArgs() &&
413 "Constant operands to a call *must* be in the arg list");
415 argDesc->getArgInfo(i).replaceArgVal(tmpReg);