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/MachineFunction.h"
14 #include "llvm/CodeGen/InstrForest.h"
15 #include "llvm/Target/TargetMachine.h"
16 #include "llvm/Target/TargetRegInfo.h"
17 #include "llvm/Target/TargetInstrInfo.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Function.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/iMemory.h"
24 //*************************** Local Functions ******************************/
27 // Generate code to load the constant into a TmpInstruction (virtual reg) and
28 // returns the virtual register.
30 static TmpInstruction*
31 InsertCodeToLoadConstant(Function *F,
34 vector<MachineInstr*>& loadConstVec,
35 TargetMachine& target)
37 // Create a tmp virtual register to hold the constant.
38 TmpInstruction* tmpReg = new TmpInstruction(opValue);
39 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
42 target.getInstrInfo().CreateCodeToLoadConst(target, F, opValue, tmpReg,
45 // Record the mapping from the tmp VM instruction to machine instruction.
46 // Do this for all machine instructions that were not mapped to any
47 // other temp values created by
48 // tmpReg->addMachineInstruction(loadConstVec.back());
54 //---------------------------------------------------------------------------
55 // Function GetConstantValueAsUnsignedInt
56 // Function GetConstantValueAsSignedInt
58 // Convenience functions to get the value of an integral constant, for an
59 // appropriate integer or non-integer type that can be held in a signed
60 // or unsigned integer respectively. The type of the argument must be
62 // Signed or unsigned integer
66 // isValidConstant is set to true if a valid constant was found.
67 //---------------------------------------------------------------------------
70 GetConstantValueAsUnsignedInt(const Value *V,
71 bool &isValidConstant)
73 isValidConstant = true;
76 if (const ConstantBool *CB = dyn_cast<ConstantBool>(V))
77 return (int64_t)CB->getValue();
78 else if (const ConstantSInt *CS = dyn_cast<ConstantSInt>(V))
79 return (uint64_t)CS->getValue();
80 else if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(V))
81 return CU->getValue();
83 isValidConstant = false;
88 GetConstantValueAsSignedInt(const Value *V,
89 bool &isValidConstant)
91 uint64_t C = GetConstantValueAsUnsignedInt(V, isValidConstant);
92 if (isValidConstant) {
93 if (V->getType()->isSigned() || C < INT64_MAX) // safe to cast to signed
96 isValidConstant = false;
102 //---------------------------------------------------------------------------
103 // Function: FoldGetElemChain
106 // Fold a chain of GetElementPtr instructions containing only
107 // constant offsets into an equivalent (Pointer, IndexVector) pair.
108 // Returns the pointer Value, and stores the resulting IndexVector
109 // in argument chainIdxVec. This is a helper function for
110 // FoldConstantIndices that does the actual folding.
111 //---------------------------------------------------------------------------
114 // Check for a constant 0.
118 return (idx == ConstantSInt::getNullValue(idx->getType()));
122 FoldGetElemChain(InstrTreeNode* ptrNode, vector<Value*>& chainIdxVec,
123 bool lastInstHasLeadingNonZero)
125 InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
126 GetElementPtrInst* gepInst =
127 dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
129 // ptr value is not computed in this tree or ptr value does not come from GEP
134 // Return NULL if we don't fold any instructions in.
135 Value* ptrVal = NULL;
137 // Now chase the chain of getElementInstr instructions, if any.
138 // Check for any non-constant indices and stop there.
139 // Also, stop if the first index of child is a non-zero array index
140 // and the last index of the current node is a non-array index:
141 // in that case, a non-array declared type is being accessed as an array
142 // which is not type-safe, but could be legal.
144 InstructionNode* ptrChild = gepNode;
145 while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
146 ptrChild->getOpLabel() == GetElemPtrIdx))
148 // Child is a GetElemPtr instruction
149 gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
150 User::op_iterator OI, firstIdx = gepInst->idx_begin();
151 User::op_iterator lastIdx = gepInst->idx_end();
152 bool allConstantOffsets = true;
154 // The first index of every GEP must be an array index.
155 assert((*firstIdx)->getType() == Type::LongTy &&
156 "INTERNAL ERROR: Structure index for a pointer type!");
158 // If the last instruction had a leading non-zero index, check if the
159 // current one references a sequential (i.e., indexable) type.
160 // If not, the code is not type-safe and we would create an illegal GEP
161 // by folding them, so don't fold any more instructions.
163 if (lastInstHasLeadingNonZero)
164 if (! isa<SequentialType>(gepInst->getType()->getElementType()))
165 break; // cannot fold in any preceding getElementPtr instrs.
167 // Check that all offsets are constant for this instruction
168 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
169 allConstantOffsets = isa<ConstantInt>(*OI);
171 if (allConstantOffsets)
172 { // Get pointer value out of ptrChild.
173 ptrVal = gepInst->getPointerOperand();
175 // Remember if it has leading zero index: it will be discarded later.
176 lastInstHasLeadingNonZero = ! IsZero(*firstIdx);
178 // Insert its index vector at the start, skipping any leading [0]
179 chainIdxVec.insert(chainIdxVec.begin(),
180 firstIdx + !lastInstHasLeadingNonZero, lastIdx);
182 // Mark the folded node so no code is generated for it.
183 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
185 // Get the previous GEP instruction and continue trying to fold
186 ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
188 else // cannot fold this getElementPtr instr. or any preceding ones
192 // If the first getElementPtr instruction had a leading [0], add it back.
193 // Note that this instruction is the *last* one successfully folded above.
194 if (ptrVal && ! lastInstHasLeadingNonZero)
195 chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
201 //---------------------------------------------------------------------------
202 // Function: GetGEPInstArgs
205 // Helper function for GetMemInstArgs that handles the final getElementPtr
206 // instruction used by (or same as) the memory operation.
207 // Extracts the indices of the current instruction and tries to fold in
208 // preceding ones if all indices of the current one are constant.
209 //---------------------------------------------------------------------------
212 GetGEPInstArgs(InstructionNode* gepNode,
213 vector<Value*>& idxVec,
214 bool& allConstantIndices)
216 allConstantIndices = true;
217 GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
219 // Default pointer is the one from the current instruction.
220 Value* ptrVal = gepI->getPointerOperand();
221 InstrTreeNode* ptrChild = gepNode->leftChild();
223 // Extract the index vector of the GEP instructin.
224 // If all indices are constant and first index is zero, try to fold
225 // in preceding GEPs with all constant indices.
226 for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
227 allConstantIndices && OI != OE; ++OI)
228 if (! isa<Constant>(*OI))
229 allConstantIndices = false; // note: this also terminates loop!
231 // If we have only constant indices, fold chains of constant indices
232 // in this and any preceding GetElemPtr instructions.
233 bool foldedGEPs = false;
234 bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
235 if (allConstantIndices)
236 if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx))
242 // Append the index vector of the current instruction.
243 // Skip the leading [0] index if preceding GEPs were folded into this.
244 idxVec.insert(idxVec.end(),
245 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
251 //---------------------------------------------------------------------------
252 // Function: GetMemInstArgs
255 // Get the pointer value and the index vector for a memory operation
256 // (GetElementPtr, Load, or Store). If all indices of the given memory
257 // operation are constant, fold in constant indices in a chain of
258 // preceding GetElementPtr instructions (if any), and return the
259 // pointer value of the first instruction in the chain.
260 // All folded instructions are marked so no code is generated for them.
263 // Returns the pointer Value to use.
264 // Returns the resulting IndexVector in idxVec.
265 // Returns true/false in allConstantIndices if all indices are/aren't const.
266 //---------------------------------------------------------------------------
269 GetMemInstArgs(InstructionNode* memInstrNode,
270 vector<Value*>& idxVec,
271 bool& allConstantIndices)
273 allConstantIndices = false;
274 Instruction* memInst = memInstrNode->getInstruction();
275 assert(idxVec.size() == 0 && "Need empty vector to return indices");
277 // If there is a GetElemPtr instruction to fold in to this instr,
278 // it must be in the left child for Load and GetElemPtr, and in the
279 // right child for Store instructions.
280 InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
281 ? memInstrNode->rightChild()
282 : memInstrNode->leftChild());
284 // Default pointer is the one from the current instruction.
285 Value* ptrVal = ptrChild->getValue();
287 // Find the "last" GetElemPtr instruction: this one or the immediate child.
288 // There will be none if this is a load or a store from a scalar pointer.
289 InstructionNode* gepNode = NULL;
290 if (isa<GetElementPtrInst>(memInst))
291 gepNode = memInstrNode;
292 else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal))
293 { // Child of load/store is a GEP and memInst is its only use.
294 // Use its indices and mark it as folded.
295 gepNode = cast<InstructionNode>(ptrChild);
296 gepNode->markFoldedIntoParent();
299 // If there are no indices, return the current pointer.
300 // Else extract the pointer from the GEP and fold the indices.
301 return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
305 MachineOperand::MachineOperandType
306 ChooseRegOrImmed(int64_t intValue,
308 MachineOpCode opCode,
309 const TargetMachine& target,
311 unsigned int& getMachineRegNum,
312 int64_t& getImmedValue)
314 MachineOperand::MachineOperandType opType=MachineOperand::MO_VirtualRegister;
315 getMachineRegNum = 0;
319 target.getInstrInfo().constantFitsInImmedField(opCode, intValue))
321 opType = isSigned? MachineOperand::MO_SignExtendedImmed
322 : MachineOperand::MO_UnextendedImmed;
323 getImmedValue = intValue;
325 else if (intValue == 0 && target.getRegInfo().getZeroRegNum() >= 0)
327 opType = MachineOperand::MO_MachineRegister;
328 getMachineRegNum = target.getRegInfo().getZeroRegNum();
335 MachineOperand::MachineOperandType
336 ChooseRegOrImmed(Value* val,
337 MachineOpCode opCode,
338 const TargetMachine& target,
340 unsigned int& getMachineRegNum,
341 int64_t& getImmedValue)
343 getMachineRegNum = 0;
346 // To use reg or immed, constant needs to be integer, bool, or a NULL pointer
347 Constant *CPV = dyn_cast<Constant>(val);
349 (! CPV->getType()->isIntegral() &&
350 ! (isa<PointerType>(CPV->getType()) && CPV->isNullValue())))
351 return MachineOperand::MO_VirtualRegister;
353 // Now get the constant value and check if it fits in the IMMED field.
354 // Take advantage of the fact that the max unsigned value will rarely
355 // fit into any IMMED field and ignore that case (i.e., cast smaller
356 // unsigned constants to signed).
359 if (isa<PointerType>(CPV->getType()))
360 intValue = 0; // We checked above that it is NULL
361 else if (ConstantBool* CB = dyn_cast<ConstantBool>(CPV))
362 intValue = (int64_t) CB->getValue();
363 else if (CPV->getType()->isSigned())
364 intValue = cast<ConstantSInt>(CPV)->getValue();
366 { // get the int value and sign-extend if original was less than 64 bits
367 intValue = (int64_t) cast<ConstantUInt>(CPV)->getValue();
368 switch(CPV->getType()->getPrimitiveID())
370 case Type::UByteTyID: intValue = (int64_t) (int8_t) intValue; break;
371 case Type::UShortTyID: intValue = (int64_t) (short) intValue; break;
372 case Type::UIntTyID: intValue = (int64_t) (int) intValue; break;
377 return ChooseRegOrImmed(intValue, CPV->getType()->isSigned(),
378 opCode, target, canUseImmed,
379 getMachineRegNum, getImmedValue);
384 //---------------------------------------------------------------------------
385 // Function: FixConstantOperandsForInstr
388 // Special handling for constant operands of a machine instruction
389 // -- if the constant is 0, use the hardwired 0 register, if any;
390 // -- if the constant fits in the IMMEDIATE field, use that field;
391 // -- else create instructions to put the constant into a register, either
392 // directly or by loading explicitly from the constant pool.
394 // In the first 2 cases, the operand of `minstr' is modified in place.
395 // Returns a vector of machine instructions generated for operands that
396 // fall under case 3; these must be inserted before `minstr'.
397 //---------------------------------------------------------------------------
399 vector<MachineInstr*>
400 FixConstantOperandsForInstr(Instruction* vmInstr,
401 MachineInstr* minstr,
402 TargetMachine& target)
404 vector<MachineInstr*> MVec;
406 MachineOpCode opCode = minstr->getOpCode();
407 const TargetInstrInfo& instrInfo = target.getInstrInfo();
408 int resultPos = instrInfo.getResultPos(opCode);
409 int immedPos = instrInfo.getImmedConstantPos(opCode);
411 Function *F = vmInstr->getParent()->getParent();
413 for (unsigned op=0; op < minstr->getNumOperands(); op++)
415 const MachineOperand& mop = minstr->getOperand(op);
417 // Skip the result position, preallocated machine registers, or operands
418 // that cannot be constants (CC regs or PC-relative displacements)
419 if (resultPos == (int)op ||
420 mop.getType() == MachineOperand::MO_MachineRegister ||
421 mop.getType() == MachineOperand::MO_CCRegister ||
422 mop.getType() == MachineOperand::MO_PCRelativeDisp)
425 bool constantThatMustBeLoaded = false;
426 unsigned int machineRegNum = 0;
427 int64_t immedValue = 0;
428 Value* opValue = NULL;
429 MachineOperand::MachineOperandType opType =
430 MachineOperand::MO_VirtualRegister;
432 // Operand may be a virtual register or a compile-time constant
433 if (mop.getType() == MachineOperand::MO_VirtualRegister)
435 assert(mop.getVRegValue() != NULL);
436 opValue = mop.getVRegValue();
437 if (Constant *opConst = dyn_cast<Constant>(opValue)) {
438 opType = ChooseRegOrImmed(opConst, opCode, target,
439 (immedPos == (int)op), machineRegNum,
441 if (opType == MachineOperand::MO_VirtualRegister)
442 constantThatMustBeLoaded = true;
447 assert(mop.isImmediate());
448 bool isSigned = mop.getType() == MachineOperand::MO_SignExtendedImmed;
450 // Bit-selection flags indicate an instruction that is extracting
451 // bits from its operand so ignore this even if it is a big constant.
452 if (mop.opHiBits32() || mop.opLoBits32() ||
453 mop.opHiBits64() || mop.opLoBits64())
456 opType = ChooseRegOrImmed(mop.getImmedValue(), isSigned,
457 opCode, target, (immedPos == (int)op),
458 machineRegNum, immedValue);
460 if (opType == mop.getType())
461 continue; // no change: this is the most common case
463 if (opType == MachineOperand::MO_VirtualRegister)
465 constantThatMustBeLoaded = true;
467 ? (Value*)ConstantSInt::get(Type::LongTy, immedValue)
468 : (Value*)ConstantUInt::get(Type::ULongTy,(uint64_t)immedValue);
472 if (opType == MachineOperand::MO_MachineRegister)
473 minstr->SetMachineOperandReg(op, machineRegNum);
474 else if (opType == MachineOperand::MO_SignExtendedImmed ||
475 opType == MachineOperand::MO_UnextendedImmed)
476 minstr->SetMachineOperandConst(op, opType, immedValue);
477 else if (constantThatMustBeLoaded ||
478 (opValue && isa<GlobalValue>(opValue)))
479 { // opValue is a constant that must be explicitly loaded into a reg
481 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
483 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
488 // Also, check for implicit operands used by the machine instruction
489 // (no need to check those defined since they cannot be constants).
491 // -- arguments to a Call
492 // -- return value of a Return
493 // Any such operand that is a constant value needs to be fixed also.
494 // The current instructions with implicit refs (viz., Call and Return)
495 // have no immediate fields, so the constant always needs to be loaded
498 bool isCall = instrInfo.isCall(opCode);
499 unsigned lastCallArgNum = 0; // unused if not a call
500 CallArgsDescriptor* argDesc = NULL; // unused if not a call
502 argDesc = CallArgsDescriptor::get(minstr);
504 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
505 if (isa<Constant>(minstr->getImplicitRef(i)) ||
506 isa<GlobalValue>(minstr->getImplicitRef(i)))
508 Value* oldVal = minstr->getImplicitRef(i);
509 TmpInstruction* tmpReg =
510 InsertCodeToLoadConstant(F, oldVal, vmInstr, MVec, target);
511 minstr->setImplicitRef(i, tmpReg);
514 { // find and replace the argument in the CallArgsDescriptor
515 unsigned i=lastCallArgNum;
516 while (argDesc->getArgInfo(i).getArgVal() != oldVal)
518 assert(i < argDesc->getNumArgs() &&
519 "Constant operands to a call *must* be in the arg list");
521 argDesc->getArgInfo(i).replaceArgVal(tmpReg);