2 //***************************************************************************
4 // SparcInstrSelection.cpp
7 // BURS instruction selection for SPARC V9 architecture.
10 // 7/02/01 - Vikram Adve - Created
11 //**************************************************************************/
13 #include "SparcInternals.h"
14 #include "llvm/CodeGen/InstrSelectionSupport.h"
15 #include "llvm/CodeGen/MachineInstr.h"
16 #include "llvm/CodeGen/InstrForest.h"
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/iTerminators.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iOther.h"
23 #include "llvm/BasicBlock.h"
24 #include "llvm/Method.h"
25 #include "llvm/ConstPoolVals.h"
28 //******************** Internal Data Declarations ************************/
31 struct BranchPattern {
32 bool flipCondition; // should the sense of the test be reversed
33 BasicBlock* targetBB; // which basic block to branch to
34 MachineInstr* extraBranch; // if neither branch is fall-through, then this
35 // BA must be inserted after the cond'l one
38 //************************* Forward Declarations ***************************/
41 static void SetMemOperands_Internal (MachineInstr* minstr,
42 const InstructionNode* vmInstrNode,
44 Value* arrayOffsetVal,
45 const vector<ConstPoolVal*>& idxVec,
46 const TargetMachine& target);
49 //************************ Internal Functions ******************************/
51 // Convenience function to get the value of an integer constant, for an
52 // appropriate integer or non-integer type that can be held in an integer.
53 // The type of the argument must be the following:
54 // Signed or unsigned integer
58 // isValidConstant is set to true if a valid constant was found.
61 GetConstantValueAsSignedInt(const Value *V,
62 bool &isValidConstant)
64 if (!isa<ConstPoolVal>(V))
66 isValidConstant = false;
70 isValidConstant = true;
72 if (V->getType() == Type::BoolTy)
73 return (int64_t) ((ConstPoolBool*)V)->getValue();
75 if (V->getType()->isIntegral())
77 if (V->getType()->isSigned())
78 return ((ConstPoolSInt*)V)->getValue();
80 assert(V->getType()->isUnsigned());
81 uint64_t Val = ((ConstPoolUInt*)V)->getValue();
82 if (Val < INT64_MAX) // then safe to cast to signed
86 isValidConstant = false;
92 //------------------------------------------------------------------------
93 // External Function: ThisIsAChainRule
96 // Check if a given BURG rule is a chain rule.
97 //------------------------------------------------------------------------
100 ThisIsAChainRule(int eruleno)
104 case 111: // stmt: reg
105 case 113: // stmt: bool
132 static inline MachineOpCode
133 ChooseBprInstruction(const InstructionNode* instrNode)
135 MachineOpCode opCode;
137 Instruction* setCCInstr =
138 ((InstructionNode*) instrNode->leftChild())->getInstruction();
140 switch(setCCInstr->getOpcode())
142 case Instruction::SetEQ: opCode = BRZ; break;
143 case Instruction::SetNE: opCode = BRNZ; break;
144 case Instruction::SetLE: opCode = BRLEZ; break;
145 case Instruction::SetGE: opCode = BRGEZ; break;
146 case Instruction::SetLT: opCode = BRLZ; break;
147 case Instruction::SetGT: opCode = BRGZ; break;
149 assert(0 && "Unrecognized VM instruction!");
150 opCode = INVALID_OPCODE;
158 static inline MachineOpCode
159 ChooseBpccInstruction(const InstructionNode* instrNode,
160 const BinaryOperator* setCCInstr)
162 MachineOpCode opCode = INVALID_OPCODE;
164 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
168 switch(setCCInstr->getOpcode())
170 case Instruction::SetEQ: opCode = BE; break;
171 case Instruction::SetNE: opCode = BNE; break;
172 case Instruction::SetLE: opCode = BLE; break;
173 case Instruction::SetGE: opCode = BGE; break;
174 case Instruction::SetLT: opCode = BL; break;
175 case Instruction::SetGT: opCode = BG; break;
177 assert(0 && "Unrecognized VM instruction!");
183 switch(setCCInstr->getOpcode())
185 case Instruction::SetEQ: opCode = BE; break;
186 case Instruction::SetNE: opCode = BNE; break;
187 case Instruction::SetLE: opCode = BLEU; break;
188 case Instruction::SetGE: opCode = BCC; break;
189 case Instruction::SetLT: opCode = BCS; break;
190 case Instruction::SetGT: opCode = BGU; break;
192 assert(0 && "Unrecognized VM instruction!");
200 static inline MachineOpCode
201 ChooseBFpccInstruction(const InstructionNode* instrNode,
202 const BinaryOperator* setCCInstr)
204 MachineOpCode opCode = INVALID_OPCODE;
206 switch(setCCInstr->getOpcode())
208 case Instruction::SetEQ: opCode = FBE; break;
209 case Instruction::SetNE: opCode = FBNE; break;
210 case Instruction::SetLE: opCode = FBLE; break;
211 case Instruction::SetGE: opCode = FBGE; break;
212 case Instruction::SetLT: opCode = FBL; break;
213 case Instruction::SetGT: opCode = FBG; break;
215 assert(0 && "Unrecognized VM instruction!");
223 static inline MachineOpCode
224 ChooseBccInstruction(const InstructionNode* instrNode,
227 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
228 BinaryOperator* setCCInstr = (BinaryOperator*) setCCNode->getInstruction();
229 const Type* setCCType = setCCInstr->getOperand(0)->getType();
231 isFPBranch = (setCCType == Type::FloatTy || setCCType == Type::DoubleTy);
234 return ChooseBFpccInstruction(instrNode, setCCInstr);
236 return ChooseBpccInstruction(instrNode, setCCInstr);
240 static inline MachineOpCode
241 ChooseMovFpccInstruction(const InstructionNode* instrNode)
243 MachineOpCode opCode = INVALID_OPCODE;
245 switch(instrNode->getInstruction()->getOpcode())
247 case Instruction::SetEQ: opCode = MOVFE; break;
248 case Instruction::SetNE: opCode = MOVFNE; break;
249 case Instruction::SetLE: opCode = MOVFLE; break;
250 case Instruction::SetGE: opCode = MOVFGE; break;
251 case Instruction::SetLT: opCode = MOVFL; break;
252 case Instruction::SetGT: opCode = MOVFG; break;
254 assert(0 && "Unrecognized VM instruction!");
262 // Assumes that SUBcc v1, v2 -> v3 has been executed.
263 // In most cases, we want to clear v3 and then follow it by instruction
265 // Set mustClearReg=false if v3 need not be cleared before conditional move.
266 // Set valueToMove=0 if we want to conditionally move 0 instead of 1
267 // (i.e., we want to test inverse of a condition)
268 // (The latter two cases do not seem to arise because SetNE needs nothing.)
271 ChooseMovpccAfterSub(const InstructionNode* instrNode,
275 MachineOpCode opCode = INVALID_OPCODE;
279 switch(instrNode->getInstruction()->getOpcode())
281 case Instruction::SetEQ: opCode = MOVE; break;
282 case Instruction::SetLE: opCode = MOVLE; break;
283 case Instruction::SetGE: opCode = MOVGE; break;
284 case Instruction::SetLT: opCode = MOVL; break;
285 case Instruction::SetGT: opCode = MOVG; break;
286 case Instruction::SetNE: assert(0 && "No move required!"); break;
287 default: assert(0 && "Unrecognized VM instr!"); break;
294 static inline MachineOpCode
295 ChooseConvertToFloatInstr(const InstructionNode* instrNode,
298 MachineOpCode opCode = INVALID_OPCODE;
300 switch(instrNode->getOpLabel())
303 if (opType == Type::SByteTy || opType == Type::ShortTy || opType == Type::IntTy)
305 else if (opType == Type::LongTy)
307 else if (opType == Type::DoubleTy)
309 else if (opType == Type::FloatTy)
312 assert(0 && "Cannot convert this type to FLOAT on SPARC");
316 if (opType == Type::SByteTy || opType == Type::ShortTy || opType == Type::IntTy)
318 else if (opType == Type::LongTy)
320 else if (opType == Type::FloatTy)
322 else if (opType == Type::DoubleTy)
325 assert(0 && "Cannot convert this type to DOUBLE on SPARC");
335 static inline MachineOpCode
336 ChooseConvertToIntInstr(const InstructionNode* instrNode,
339 MachineOpCode opCode = INVALID_OPCODE;;
341 int instrType = (int) instrNode->getOpLabel();
343 if (instrType == ToSByteTy || instrType == ToShortTy || instrType == ToIntTy)
345 switch (opType->getPrimitiveID())
347 case Type::FloatTyID: opCode = FSTOI; break;
348 case Type::DoubleTyID: opCode = FDTOI; break;
350 assert(0 && "Non-numeric non-bool type cannot be converted to Int");
354 else if (instrType == ToLongTy)
356 switch (opType->getPrimitiveID())
358 case Type::FloatTyID: opCode = FSTOX; break;
359 case Type::DoubleTyID: opCode = FDTOX; break;
361 assert(0 && "Non-numeric non-bool type cannot be converted to Long");
366 assert(0 && "Should not get here, Mo!");
372 static inline MachineOpCode
373 ChooseAddInstructionByType(const Type* resultType)
375 MachineOpCode opCode = INVALID_OPCODE;
377 if (resultType->isIntegral() ||
378 isa<PointerType>(resultType) ||
379 isa<MethodType>(resultType) ||
380 resultType->isLabelType() ||
381 resultType == Type::BoolTy)
386 switch(resultType->getPrimitiveID())
388 case Type::FloatTyID: opCode = FADDS; break;
389 case Type::DoubleTyID: opCode = FADDD; break;
390 default: assert(0 && "Invalid type for ADD instruction"); break;
397 static inline MachineOpCode
398 ChooseAddInstruction(const InstructionNode* instrNode)
400 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
404 static inline MachineInstr*
405 CreateMovFloatInstruction(const InstructionNode* instrNode,
406 const Type* resultType)
408 MachineInstr* minstr = new MachineInstr((resultType == Type::FloatTy)
410 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
411 instrNode->leftChild()->getValue());
412 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
413 instrNode->getValue());
417 static inline MachineInstr*
418 CreateAddConstInstruction(const InstructionNode* instrNode)
420 MachineInstr* minstr = NULL;
422 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
423 assert(isa<ConstPoolVal>(constOp));
425 // Cases worth optimizing are:
426 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
427 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
429 const Type* resultType = instrNode->getInstruction()->getType();
431 if (resultType == Type::FloatTy ||
432 resultType == Type::DoubleTy)
434 double dval = ((ConstPoolFP*) constOp)->getValue();
436 minstr = CreateMovFloatInstruction(instrNode, resultType);
443 static inline MachineOpCode
444 ChooseSubInstruction(const InstructionNode* instrNode)
446 MachineOpCode opCode = INVALID_OPCODE;
448 const Type* resultType = instrNode->getInstruction()->getType();
450 if (resultType->isIntegral() ||
451 resultType->isPointerType())
456 switch(resultType->getPrimitiveID())
458 case Type::FloatTyID: opCode = FSUBS; break;
459 case Type::DoubleTyID: opCode = FSUBD; break;
460 default: assert(0 && "Invalid type for SUB instruction"); break;
467 static inline MachineInstr*
468 CreateSubConstInstruction(const InstructionNode* instrNode)
470 MachineInstr* minstr = NULL;
472 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
473 assert(isa<ConstPoolVal>(constOp));
475 // Cases worth optimizing are:
476 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
477 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
479 const Type* resultType = instrNode->getInstruction()->getType();
481 if (resultType == Type::FloatTy ||
482 resultType == Type::DoubleTy)
484 double dval = ((ConstPoolFP*) constOp)->getValue();
486 minstr = CreateMovFloatInstruction(instrNode, resultType);
493 static inline MachineOpCode
494 ChooseFcmpInstruction(const InstructionNode* instrNode)
496 MachineOpCode opCode = INVALID_OPCODE;
498 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
499 switch(operand->getType()->getPrimitiveID()) {
500 case Type::FloatTyID: opCode = FCMPS; break;
501 case Type::DoubleTyID: opCode = FCMPD; break;
502 default: assert(0 && "Invalid type for FCMP instruction"); break;
509 // Assumes that leftArg and rightArg are both cast instructions.
512 BothFloatToDouble(const InstructionNode* instrNode)
514 InstrTreeNode* leftArg = instrNode->leftChild();
515 InstrTreeNode* rightArg = instrNode->rightChild();
516 InstrTreeNode* leftArgArg = leftArg->leftChild();
517 InstrTreeNode* rightArgArg = rightArg->leftChild();
518 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
520 // Check if both arguments are floats cast to double
521 return (leftArg->getValue()->getType() == Type::DoubleTy &&
522 leftArgArg->getValue()->getType() == Type::FloatTy &&
523 rightArgArg->getValue()->getType() == Type::FloatTy);
527 static inline MachineOpCode
528 ChooseMulInstruction(const InstructionNode* instrNode,
531 MachineOpCode opCode = INVALID_OPCODE;
533 if (checkCasts && BothFloatToDouble(instrNode))
535 return opCode = FSMULD;
537 // else fall through and use the regular multiply instructions
539 const Type* resultType = instrNode->getInstruction()->getType();
541 if (resultType->isIntegral())
546 switch(resultType->getPrimitiveID())
548 case Type::FloatTyID: opCode = FMULS; break;
549 case Type::DoubleTyID: opCode = FMULD; break;
550 default: assert(0 && "Invalid type for MUL instruction"); break;
557 static inline MachineInstr*
558 CreateIntNegInstruction(TargetMachine& target,
561 MachineInstr* minstr = new MachineInstr(SUB);
562 minstr->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
563 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, vreg);
564 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister, vreg);
569 static inline MachineInstr*
570 CreateMulConstInstruction(TargetMachine &target,
571 const InstructionNode* instrNode,
572 MachineInstr*& getMinstr2)
574 MachineInstr* minstr = NULL;
576 bool needNeg = false;
578 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
579 assert(isa<ConstPoolVal>(constOp));
581 // Cases worth optimizing are:
582 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
583 // (2) Multiply by 2^x for integer types: replace with Shift
585 const Type* resultType = instrNode->getInstruction()->getType();
587 if (resultType->isIntegral() || resultType->isPointerType())
591 int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
594 bool needNeg = false;
601 if (C == 0 || C == 1)
603 minstr = new MachineInstr(ADD);
606 minstr->SetMachineOperand(0,
607 target.getRegInfo().getZeroRegNum());
609 minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
610 instrNode->leftChild()->getValue());
611 minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
613 else if (IsPowerOf2(C, pow))
615 minstr = new MachineInstr((resultType == Type::LongTy)
617 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
618 instrNode->leftChild()->getValue());
619 minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
623 if (minstr && needNeg)
624 { // insert <reg = SUB 0, reg> after the instr to flip the sign
625 getMinstr2 = CreateIntNegInstruction(target,
626 instrNode->getValue());
632 if (resultType == Type::FloatTy ||
633 resultType == Type::DoubleTy)
636 double dval = ((ConstPoolFP*) constOp)->getValue();
642 minstr = new MachineInstr((resultType == Type::FloatTy)
644 minstr->SetMachineOperand(0,
645 target.getRegInfo().getZeroRegNum());
647 else if (fabs(dval) == 1)
649 bool needNeg = (dval < 0);
651 MachineOpCode opCode = needNeg
652 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
653 : (resultType == Type::FloatTy? FMOVS : FMOVD);
655 minstr = new MachineInstr(opCode);
656 minstr->SetMachineOperand(0,
657 MachineOperand::MO_VirtualRegister,
658 instrNode->leftChild()->getValue());
665 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
666 instrNode->getValue());
672 static inline MachineOpCode
673 ChooseDivInstruction(TargetMachine &target,
674 const InstructionNode* instrNode)
676 MachineOpCode opCode = INVALID_OPCODE;
678 const Type* resultType = instrNode->getInstruction()->getType();
680 if (resultType->isIntegral())
681 opCode = resultType->isSigned()? SDIVX : UDIVX;
683 switch(resultType->getPrimitiveID())
685 case Type::FloatTyID: opCode = FDIVS; break;
686 case Type::DoubleTyID: opCode = FDIVD; break;
687 default: assert(0 && "Invalid type for DIV instruction"); break;
694 static inline MachineInstr*
695 CreateDivConstInstruction(TargetMachine &target,
696 const InstructionNode* instrNode,
697 MachineInstr*& getMinstr2)
699 MachineInstr* minstr = NULL;
702 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
703 assert(isa<ConstPoolVal>(constOp));
705 // Cases worth optimizing are:
706 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
707 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
709 const Type* resultType = instrNode->getInstruction()->getType();
711 if (resultType->isIntegral())
715 int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
718 bool needNeg = false;
727 minstr = new MachineInstr(ADD);
728 minstr->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
729 instrNode->leftChild()->getValue());
730 minstr->SetMachineOperand(1,target.getRegInfo().getZeroRegNum());
732 else if (IsPowerOf2(C, pow))
734 MachineOpCode opCode= ((resultType->isSigned())
735 ? (resultType==Type::LongTy)? SRAX : SRA
736 : (resultType==Type::LongTy)? SRLX : SRL);
737 minstr = new MachineInstr(opCode);
738 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
739 instrNode->leftChild()->getValue());
740 minstr->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
744 if (minstr && needNeg)
745 { // insert <reg = SUB 0, reg> after the instr to flip the sign
746 getMinstr2 = CreateIntNegInstruction(target,
747 instrNode->getValue());
753 if (resultType == Type::FloatTy ||
754 resultType == Type::DoubleTy)
757 double dval = ((ConstPoolFP*) constOp)->getValue();
759 if (isValidConst && fabs(dval) == 1)
761 bool needNeg = (dval < 0);
763 MachineOpCode opCode = needNeg
764 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
765 : (resultType == Type::FloatTy? FMOVS : FMOVD);
767 minstr = new MachineInstr(opCode);
768 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
769 instrNode->leftChild()->getValue());
775 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
776 instrNode->getValue());
782 static inline MachineOpCode
783 ChooseLoadInstruction(const Type *DestTy)
785 switch (DestTy->getPrimitiveID()) {
787 case Type::UByteTyID: return LDUB;
788 case Type::SByteTyID: return LDSB;
789 case Type::UShortTyID: return LDUH;
790 case Type::ShortTyID: return LDSH;
791 case Type::UIntTyID: return LDUW;
792 case Type::IntTyID: return LDSW;
793 case Type::PointerTyID:
794 case Type::ULongTyID:
795 case Type::LongTyID: return LDX;
796 case Type::FloatTyID: return LD;
797 case Type::DoubleTyID: return LDD;
798 default: assert(0 && "Invalid type for Load instruction");
805 static inline MachineOpCode
806 ChooseStoreInstruction(const Type *DestTy)
808 switch (DestTy->getPrimitiveID()) {
810 case Type::UByteTyID:
811 case Type::SByteTyID: return STB;
812 case Type::UShortTyID:
813 case Type::ShortTyID: return STH;
815 case Type::IntTyID: return STW;
816 case Type::PointerTyID:
817 case Type::ULongTyID:
818 case Type::LongTyID: return STX;
819 case Type::FloatTyID: return ST;
820 case Type::DoubleTyID: return STD;
821 default: assert(0 && "Invalid type for Store instruction");
828 //------------------------------------------------------------------------
829 // Function SetOperandsForMemInstr
831 // Choose addressing mode for the given load or store instruction.
832 // Use [reg+reg] if it is an indexed reference, and the index offset is
833 // not a constant or if it cannot fit in the offset field.
834 // Use [reg+offset] in all other cases.
836 // This assumes that all array refs are "lowered" to one of these forms:
837 // %x = load (subarray*) ptr, constant ; single constant offset
838 // %x = load (subarray*) ptr, offsetVal ; single non-constant offset
839 // Generally, this should happen via strength reduction + LICM.
840 // Also, strength reduction should take care of using the same register for
841 // the loop index variable and an array index, when that is profitable.
842 //------------------------------------------------------------------------
845 SetOperandsForMemInstr(MachineInstr* minstr,
846 const InstructionNode* vmInstrNode,
847 const TargetMachine& target)
849 MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
851 // Variables to hold the index vector, ptr value, and offset value.
852 // The major work here is to extract these for all 3 instruction types
853 // and then call the common function SetMemOperands_Internal().
855 const vector<ConstPoolVal*>* idxVec = & memInst->getIndexVec();
856 vector<ConstPoolVal*>* newIdxVec = NULL;
858 Value* arrayOffsetVal = NULL;
860 // Test if a GetElemPtr instruction is being folded into this mem instrn.
861 // If so, it will be in the left child for Load and GetElemPtr,
862 // and in the right child for Store instructions.
864 InstrTreeNode* ptrChild = (vmInstrNode->getOpLabel() == Instruction::Store
865 ? vmInstrNode->rightChild()
866 : vmInstrNode->leftChild());
868 if (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
869 ptrChild->getOpLabel() == GetElemPtrIdx)
871 // There is a GetElemPtr instruction and there may be a chain of
872 // more than one. Use the pointer value of the last one in the chain.
873 // Fold the index vectors from the entire chain and from the mem
874 // instruction into one single index vector.
875 // Finally, we never fold for an array instruction so make that NULL.
877 newIdxVec = new vector<ConstPoolVal*>;
878 ptrVal = FoldGetElemChain((InstructionNode*) ptrChild, *newIdxVec);
880 newIdxVec->insert(newIdxVec->end(), idxVec->begin(), idxVec->end());
883 assert(! ((PointerType*)ptrVal->getType())->getValueType()->isArrayType()
884 && "GetElemPtr cannot be folded into array refs in selection");
888 // There is no GetElemPtr instruction.
889 // Use the pointer value and the index vector from the Mem instruction.
890 // If it is an array reference, get the array offset value.
892 ptrVal = memInst->getPtrOperand();
895 ((const PointerType*) ptrVal->getType())->getValueType();
896 if (opType->isArrayType())
898 assert((memInst->getNumOperands()
899 == (unsigned) 1 + memInst->getFirstOffsetIdx())
900 && "Array refs must be lowered before Instruction Selection");
902 arrayOffsetVal = memInst->getOperand(memInst->getFirstOffsetIdx());
906 SetMemOperands_Internal(minstr, vmInstrNode, ptrVal, arrayOffsetVal,
909 if (newIdxVec != NULL)
915 SetMemOperands_Internal(MachineInstr* minstr,
916 const InstructionNode* vmInstrNode,
918 Value* arrayOffsetVal,
919 const vector<ConstPoolVal*>& idxVec,
920 const TargetMachine& target)
922 MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
924 // Initialize so we default to storing the offset in a register.
925 int64_t smallConstOffset;
926 Value* valueForRegOffset = NULL;
927 MachineOperand::MachineOperandType offsetOpType =MachineOperand::MO_VirtualRegister;
929 // Check if there is an index vector and if so, if it translates to
930 // a small enough constant to fit in the immediate-offset field.
932 if (idxVec.size() > 0)
934 bool isConstantOffset = false;
937 const PointerType* ptrType = (PointerType*) ptrVal->getType();
939 if (ptrType->getValueType()->isStructType())
941 // the offset is always constant for structs
942 isConstantOffset = true;
944 // Compute the offset value using the index vector
945 offset = target.DataLayout.getIndexedOffset(ptrType, idxVec);
949 // It must be an array ref. Check if the offset is a constant,
950 // and that the indexing has been lowered to a single offset.
952 assert(ptrType->getValueType()->isArrayType());
953 assert(arrayOffsetVal != NULL
954 && "Expect to be given Value* for array offsets");
956 if (ConstPoolVal *CPV = dyn_cast<ConstPoolVal>(arrayOffsetVal))
958 isConstantOffset = true; // always constant for structs
959 assert(arrayOffsetVal->getType()->isIntegral());
960 offset = (CPV->getType()->isSigned()
961 ? ((ConstPoolSInt*)CPV)->getValue()
962 : (int64_t) ((ConstPoolUInt*)CPV)->getValue());
966 valueForRegOffset = arrayOffsetVal;
970 if (isConstantOffset)
972 // create a virtual register for the constant
973 valueForRegOffset = ConstPoolSInt::get(Type::IntTy, offset);
978 offsetOpType = MachineOperand::MO_SignExtendedImmed;
979 smallConstOffset = 0;
982 // Operand 0 is value for STORE, ptr for LOAD or GET_ELEMENT_PTR
983 // It is the left child in the instruction tree in all cases.
984 Value* leftVal = vmInstrNode->leftChild()->getValue();
985 minstr->SetMachineOperand(0, MachineOperand::MO_VirtualRegister, leftVal);
987 // Operand 1 is ptr for STORE, offset for LOAD or GET_ELEMENT_PTR
988 // Operand 2 is offset for STORE, result reg for LOAD or GET_ELEMENT_PTR
990 unsigned offsetOpNum = (memInst->getOpcode() == Instruction::Store)? 2 : 1;
991 if (offsetOpType == MachineOperand::MO_VirtualRegister)
993 assert(valueForRegOffset != NULL);
994 minstr->SetMachineOperand(offsetOpNum, offsetOpType, valueForRegOffset);
997 minstr->SetMachineOperand(offsetOpNum, offsetOpType, smallConstOffset);
999 if (memInst->getOpcode() == Instruction::Store)
1000 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, ptrVal);
1002 minstr->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1003 vmInstrNode->getValue());
1007 static inline MachineInstr*
1008 CreateIntSetInstruction(int64_t C, bool isSigned, Value* dest)
1010 MachineInstr* minstr;
1013 minstr = new MachineInstr(SETSW);
1014 minstr->SetMachineOperand(0, MachineOperand::MO_SignExtendedImmed, C);
1018 minstr = new MachineInstr(SETUW);
1019 minstr->SetMachineOperand(0, MachineOperand::MO_UnextendedImmed, C);
1022 minstr->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, dest);
1028 // Create an instruction sequence to load a constant into a register.
1029 // This always creates either one or two instructions.
1030 // If two instructions are created, the second one is returned in getMinstr2
1032 static MachineInstr*
1033 CreateLoadConstInstr(const TargetMachine &target,
1034 Instruction* vmInstr,
1037 MachineInstr*& getMinstr2)
1039 assert(isa<ConstPoolVal>(val));
1041 MachineInstr* minstr1 = NULL;
1045 // Use a "set" instruction for known constants that can go in an integer reg.
1046 // Use a "set" instruction followed by a int-to-float conversion for known
1047 // constants that must go in a floating point reg but have an integer value.
1048 // Use a "load" instruction for all other constants, in particular,
1049 // floating point constants.
1051 const Type* valType = val->getType();
1053 if (valType->isIntegral() || valType == Type::BoolTy)
1055 bool isValidConstant;
1056 int64_t C = GetConstantValueAsSignedInt(val, isValidConstant);
1057 assert(isValidConstant && "Unrecognized constant");
1058 minstr1 = CreateIntSetInstruction(C, valType->isSigned(), dest);
1063 #undef MOVE_INT_TO_FP_REG_AVAILABLE
1064 #ifdef MOVE_INT_TO_FP_REG_AVAILABLE
1066 // This code was written to generate the following sequence:
1067 // SET[SU]W <int-const> <int-reg>
1068 // FITO[SD] <int-reg> <fp-reg>
1069 // (it really should have moved the int-reg to an fp-reg and then FITOS).
1070 // But for now the only way to move a value from an int-reg to an fp-reg
1071 // is via memory. Leave this code here but unused.
1073 assert(valType == Type::FloatTy || valType == Type::DoubleTy);
1074 double dval = ((ConstPoolFP*) val)->getValue();
1075 if (dval == (int64_t) dval)
1077 // The constant actually has an integer value, so use a
1078 // [set; int-to-float] sequence instead of a load instruction.
1080 TmpInstruction* addrReg = NULL;
1082 { // First, create an integer constant of the same value as dval
1083 ConstPoolSInt* ival = ConstPoolSInt::get(Type::IntTy,
1085 // Create another TmpInstruction for the hidden integer register
1086 addrReg = new TmpInstruction(Instruction::UserOp1, ival, NULL);
1087 vmInstr->getMachineInstrVec().addTempValue(addrReg);
1089 // Create the `SET' instruction
1090 minstr1 = CreateIntSetInstruction((int64_t)dval, true, addrReg);
1091 addrReg->addMachineInstruction(minstr1);
1094 // In which variable do we put the second instruction?
1095 MachineInstr*& instr2 = (minstr1)? getMinstr2 : minstr1;
1097 // Create the int-to-float instruction
1098 instr2 = new MachineInstr(valType == Type::FloatTy? FITOS : FITOD);
1101 instr2->SetMachineOperand(0, target.getRegInfo().getZeroRegNum());
1103 instr2->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1106 instr2->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1110 #endif /*MOVE_INT_TO_FP_REG_AVAILABLE*/
1113 // Make an instruction sequence to load the constant, viz:
1114 // SETSW <addr-of-constant>, addrReg
1115 // LOAD /*addr*/ addrReg, /*offset*/ 0, dest
1116 // set the offset field to 0.
1118 int64_t zeroOffset = 0; // to avoid ambiguity with (Value*) 0
1120 // Create another TmpInstruction for the hidden integer register
1121 TmpInstruction* addrReg =
1122 new TmpInstruction(Instruction::UserOp1, val, NULL);
1123 vmInstr->getMachineInstrVec().addTempValue(addrReg);
1125 minstr1 = new MachineInstr(SETUW);
1126 minstr1->SetMachineOperand(0, MachineOperand::MO_PCRelativeDisp,val);
1127 minstr1->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1129 addrReg->addMachineInstruction(minstr1);
1131 getMinstr2 = new MachineInstr(ChooseLoadInstruction(val->getType()));
1132 getMinstr2->SetMachineOperand(0,MachineOperand::MO_VirtualRegister,
1134 getMinstr2->SetMachineOperand(1,MachineOperand::MO_SignExtendedImmed,
1136 getMinstr2->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,
1147 InsertCodeToLoadConstant(ConstPoolVal* opValue,
1148 Instruction* vmInstr,
1149 vector<MachineInstr*>& loadConstVec,
1150 TargetMachine& target)
1152 // value is constant and must be loaded into a register.
1153 // First, create a tmp virtual register (TmpInstruction)
1154 // to hold the constant.
1155 // This will replace the constant operand in `minstr'.
1156 TmpInstruction* tmpReg =
1157 new TmpInstruction(Instruction::UserOp1, opValue, NULL);
1158 vmInstr->getMachineInstrVec().addTempValue(tmpReg);
1160 MachineInstr *minstr1, *minstr2;
1161 minstr1 = CreateLoadConstInstr(target, vmInstr,
1162 opValue, tmpReg, minstr2);
1164 loadConstVec.push_back(minstr1);
1165 if (minstr2 != NULL)
1166 loadConstVec.push_back(minstr2);
1168 tmpReg->addMachineInstruction(loadConstVec.back());
1174 // Special handling for constant operands:
1175 // -- if the constant is 0, use the hardwired 0 register, if any;
1176 // -- if the constant is of float or double type but has an integer value,
1177 // use int-to-float conversion instruction instead of generating a load;
1178 // -- if the constant fits in the IMMEDIATE field, use that field;
1179 // -- else insert instructions to put the constant into a register, either
1180 // directly or by loading explicitly from the constant pool.
1183 FixConstantOperands(const InstructionNode* vmInstrNode,
1184 MachineInstr** mvec,
1186 TargetMachine& target)
1188 vector<MachineInstr*> loadConstVec;
1189 loadConstVec.reserve(MAX_INSTR_PER_VMINSTR);
1191 Instruction* vmInstr = vmInstrNode->getInstruction();
1193 for (unsigned i=0; i < numInstr; i++)
1195 MachineInstr* minstr = mvec[i];
1196 const MachineInstrDescriptor& instrDesc =
1197 target.getInstrInfo().getDescriptor(minstr->getOpCode());
1199 for (unsigned op=0; op < minstr->getNumOperands(); op++)
1201 const MachineOperand& mop = minstr->getOperand(op);
1203 // skip the result position (for efficiency below) and any other
1204 // positions already marked as not a virtual register
1205 if (instrDesc.resultPos == (int) op ||
1206 mop.getOperandType() != MachineOperand::MO_VirtualRegister ||
1207 mop.getVRegValue() == NULL)
1212 Value* opValue = mop.getVRegValue();
1214 if (isa<ConstPoolVal>(opValue))
1216 unsigned int machineRegNum;
1218 MachineOperand::MachineOperandType opType =
1219 ChooseRegOrImmed(opValue, minstr->getOpCode(), target,
1220 /*canUseImmed*/ (op == 1),
1221 machineRegNum, immedValue);
1223 if (opType == MachineOperand::MO_MachineRegister)
1224 minstr->SetMachineOperand(op, machineRegNum);
1225 else if (opType == MachineOperand::MO_VirtualRegister)
1227 TmpInstruction* tmpReg =
1228 InsertCodeToLoadConstant((ConstPoolVal*) opValue,
1229 vmInstr, loadConstVec, target);
1230 minstr->SetMachineOperand(op, opType, tmpReg);
1233 minstr->SetMachineOperand(op, opType, immedValue);
1238 // Also, check for implicit operands used (not those defined) by the
1239 // machine instruction. These include:
1240 // -- arguments to a Call
1241 // -- return value of a Return
1242 // Any such operand that is a constant value needs to be fixed also.
1243 // The current instructions with implicit refs (viz., Call and Return)
1244 // have no immediate fields, so the constant always needs to be loaded
1247 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
1248 if (isa<ConstPoolVal>(minstr->getImplicitRef(i)))
1250 TmpInstruction* tmpReg = InsertCodeToLoadConstant((ConstPoolVal*)
1251 minstr->getImplicitRef(i),
1252 vmInstr, loadConstVec, target);
1253 minstr->setImplicitRef(i, tmpReg);
1258 // Finally, inserted the generated instructions in the vector
1261 unsigned numNew = loadConstVec.size();
1264 // Insert the new instructions *before* the old ones by moving
1265 // the old ones over `numNew' positions (last-to-first, of course!).
1266 // We do check *after* returning that we did not exceed the vector mvec.
1267 for (int i=numInstr-1; i >= 0; i--)
1268 mvec[i+numNew] = mvec[i];
1270 for (unsigned i=0; i < numNew; i++)
1271 mvec[i] = loadConstVec[i];
1274 return (numInstr + numNew);
1279 // Substitute operand `operandNum' of the instruction in node `treeNode'
1280 // in place the use(s) of that instruction in node `parent'.
1283 ForwardOperand(InstructionNode* treeNode,
1284 InstrTreeNode* parent,
1287 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1289 Instruction* unusedOp = treeNode->getInstruction();
1290 Value* fwdOp = unusedOp->getOperand(operandNum);
1292 // The parent itself may be a list node, so find the real parent instruction
1293 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1295 parent = parent->parent();
1296 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1298 InstructionNode* parentInstrNode = (InstructionNode*) parent;
1300 Instruction* userInstr = parentInstrNode->getInstruction();
1301 MachineCodeForVMInstr& mvec = userInstr->getMachineInstrVec();
1302 for (unsigned i=0, N=mvec.size(); i < N; i++)
1304 MachineInstr* minstr = mvec[i];
1305 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; i++)
1307 const MachineOperand& mop = minstr->getOperand(i);
1308 if (mop.getOperandType() == MachineOperand::MO_VirtualRegister &&
1309 mop.getVRegValue() == unusedOp)
1311 minstr->SetMachineOperand(i, MachineOperand::MO_VirtualRegister,
1320 CreateCopyInstructionsByType(const TargetMachine& target,
1323 MachineInstr*& getMinstr2)
1325 getMinstr2 = NULL; // initialize second return value
1327 MachineInstr* minstr1 = NULL;
1329 const Type* resultType = dest->getType();
1331 MachineOpCode opCode = ChooseAddInstructionByType(resultType);
1332 if (opCode == INVALID_OPCODE)
1334 assert(0 && "Unsupported result type in CreateCopyInstructionsByType()");
1338 // if `src' is a constant that doesn't fit in the immed field, generate
1339 // a load instruction instead of an add
1340 if (isa<ConstPoolVal>(src))
1342 unsigned int machineRegNum;
1344 MachineOperand::MachineOperandType opType =
1345 ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
1346 machineRegNum, immedValue);
1348 if (opType == MachineOperand::MO_VirtualRegister)
1349 { // value is constant and cannot fit in immed field for the ADD
1350 minstr1 = CreateLoadConstInstr(target, dest, src, dest, getMinstr2);
1354 if (minstr1 == NULL)
1355 { // Create the appropriate add instruction.
1356 // Make `src' the second operand, in case it is a constant
1357 // Use (unsigned long) 0 for a NULL pointer value.
1359 const Type* nullValueType =
1360 (resultType->getPrimitiveID() == Type::PointerTyID)? Type::ULongTy
1362 minstr1 = new MachineInstr(opCode);
1363 minstr1->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1364 ConstPoolVal::getNullConstant(nullValueType));
1365 minstr1->SetMachineOperand(1, MachineOperand::MO_VirtualRegister, src);
1366 minstr1->SetMachineOperand(2, MachineOperand::MO_VirtualRegister, dest);
1373 // This function is currently unused and incomplete but will be
1374 // used if we have a linear layout of basic blocks in LLVM code.
1375 // It decides which branch should fall-through, and whether an
1376 // extra unconditional branch is needed (when neither falls through).
1379 ChooseBranchPattern(Instruction* vmInstr, BranchPattern& brPattern)
1381 BranchInst* brInstr = (BranchInst*) vmInstr;
1383 brPattern.flipCondition = false;
1384 brPattern.targetBB = brInstr->getSuccessor(0);
1385 brPattern.extraBranch = NULL;
1387 assert(brInstr->getNumSuccessors() > 1 &&
1388 "Unnecessary analysis for unconditional branch");
1390 assert(0 && "Fold branches in peephole optimization");
1394 //******************* Externally Visible Functions *************************/
1397 //------------------------------------------------------------------------
1398 // External Function: GetInstructionsByRule
1401 // Choose machine instructions for the SPARC according to the
1402 // patterns chosen by the BURG-generated parser.
1403 //------------------------------------------------------------------------
1406 GetInstructionsByRule(InstructionNode* subtreeRoot,
1409 TargetMachine &target,
1410 MachineInstr** mvec)
1412 int numInstr = 1; // initialize for common case
1413 bool checkCast = false; // initialize here to use fall-through
1414 Value *leftVal, *rightVal;
1417 int forwardOperandNum = -1;
1418 int64_t s0=0, s8=8; // variables holding constants to avoid
1419 uint64_t u0=0; // overloading ambiguities below
1421 mvec[0] = mvec[1] = mvec[2] = mvec[3] = NULL; // just for safety
1424 // Let's check for chain rules outside the switch so that we don't have
1425 // to duplicate the list of chain rule production numbers here again
1427 if (ThisIsAChainRule(ruleForNode))
1429 // Chain rules have a single nonterminal on the RHS.
1430 // Get the rule that matches the RHS non-terminal and use that instead.
1432 assert(nts[0] && ! nts[1]
1433 && "A chain rule should have only one RHS non-terminal!");
1434 nextRule = burm_rule(subtreeRoot->state, nts[0]);
1435 nts = burm_nts[nextRule];
1436 numInstr = GetInstructionsByRule(subtreeRoot, nextRule, nts,target,mvec);
1440 switch(ruleForNode) {
1441 case 1: // stmt: Ret
1442 case 2: // stmt: RetValue(reg)
1443 // NOTE: Prepass of register allocation is responsible
1444 // for moving return value to appropriate register.
1445 // Mark the return-address register as a hidden virtual reg.
1446 // Mark the return value register as an implicit ref of
1447 // the machine instruction.
1449 ReturnInst* returnInstr = (ReturnInst*) subtreeRoot->getInstruction();
1450 assert(returnInstr->getOpcode() == Instruction::Ret);
1452 Instruction* returnReg = new TmpInstruction(Instruction::UserOp1,
1454 returnInstr->getMachineInstrVec().addTempValue(returnReg);
1456 mvec[0] = new MachineInstr(RETURN);
1457 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1459 mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,s8);
1461 if (returnInstr->getReturnValue() != NULL)
1462 mvec[0]->addImplicitRef(returnInstr->getReturnValue());
1464 returnReg->addMachineInstruction(mvec[0]);
1466 mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1470 case 3: // stmt: Store(reg,reg)
1471 case 4: // stmt: Store(reg,ptrreg)
1472 mvec[0] = new MachineInstr(
1473 ChooseStoreInstruction(
1474 subtreeRoot->leftChild()->getValue()->getType()));
1475 SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1478 case 5: // stmt: BrUncond
1479 mvec[0] = new MachineInstr(BA);
1480 mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1482 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1483 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1486 mvec[numInstr++] = new MachineInstr(NOP);
1489 case 206: // stmt: BrCond(setCCconst)
1490 // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1491 // If the constant is ZERO, we can use the branch-on-integer-register
1492 // instructions and avoid the SUBcc instruction entirely.
1493 // Otherwise this is just the same as case 5, so just fall through.
1495 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1497 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1498 ConstPoolVal* constVal = (ConstPoolVal*) constNode->getValue();
1501 if ((constVal->getType()->isIntegral()
1502 || constVal->getType()->isPointerType())
1503 && GetConstantValueAsSignedInt(constVal, isValidConst) == 0
1506 // That constant is a zero after all...
1507 // Use the left child of setCC as the first argument!
1508 mvec[0] = new MachineInstr(ChooseBprInstruction(subtreeRoot));
1509 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1510 subtreeRoot->leftChild()->leftChild()->getValue());
1511 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1512 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1515 mvec[numInstr++] = new MachineInstr(NOP);
1519 mvec[n] = new MachineInstr(BA);
1520 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1522 mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1523 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1526 mvec[numInstr++] = new MachineInstr(NOP);
1530 // ELSE FALL THROUGH
1533 case 6: // stmt: BrCond(bool)
1534 // bool => boolean was computed with some boolean operator
1535 // (SetCC, Not, ...). We need to check whether the type was a FP,
1536 // signed int or unsigned int, and check the branching condition in
1537 // order to choose the branch to use.
1541 mvec[0] = new MachineInstr(ChooseBccInstruction(subtreeRoot,
1543 mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1544 subtreeRoot->leftChild()->getValue());
1545 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1546 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1549 mvec[numInstr++] = new MachineInstr(NOP);
1553 mvec[n] = new MachineInstr(BA);
1554 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1556 mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1557 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1560 mvec[numInstr++] = new MachineInstr(NOP);
1564 case 208: // stmt: BrCond(boolconst)
1566 // boolconst => boolean is a constant; use BA to first or second label
1567 ConstPoolVal* constVal =
1568 cast<ConstPoolVal>(subtreeRoot->leftChild()->getValue());
1569 unsigned dest = ((ConstPoolBool*) constVal)->getValue()? 0 : 1;
1571 mvec[0] = new MachineInstr(BA);
1572 mvec[0]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1574 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1575 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(dest));
1578 mvec[numInstr++] = new MachineInstr(NOP);
1582 case 8: // stmt: BrCond(boolreg)
1583 // boolreg => boolean is stored in an existing register.
1584 // Just use the branch-on-integer-register instruction!
1587 mvec[0] = new MachineInstr(BRNZ);
1588 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1589 subtreeRoot->leftChild()->getValue());
1590 mvec[0]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1591 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(0));
1594 mvec[numInstr++] = new MachineInstr(NOP); // delay slot
1598 mvec[n] = new MachineInstr(BA);
1599 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1601 mvec[n]->SetMachineOperand(1, MachineOperand::MO_PCRelativeDisp,
1602 ((BranchInst*) subtreeRoot->getInstruction())->getSuccessor(1));
1605 mvec[numInstr++] = new MachineInstr(NOP);
1609 case 9: // stmt: Switch(reg)
1610 assert(0 && "*** SWITCH instruction is not implemented yet.");
1614 case 10: // reg: VRegList(reg, reg)
1615 assert(0 && "VRegList should never be the topmost non-chain rule");
1618 case 21: // reg: Not(reg): Implemented as reg = reg XOR-NOT 0
1619 mvec[0] = new MachineInstr(XNOR);
1620 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
1621 subtreeRoot->leftChild()->getValue());
1622 mvec[0]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
1623 mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1624 subtreeRoot->getValue());
1627 case 322: // reg: ToBoolTy(bool):
1628 case 22: // reg: ToBoolTy(reg):
1629 opType = subtreeRoot->leftChild()->getValue()->getType();
1630 assert(opType->isIntegral() || opType == Type::BoolTy);
1632 forwardOperandNum = 0;
1635 case 23: // reg: ToUByteTy(reg)
1636 case 25: // reg: ToUShortTy(reg)
1637 case 27: // reg: ToUIntTy(reg)
1638 case 29: // reg: ToULongTy(reg)
1639 opType = subtreeRoot->leftChild()->getValue()->getType();
1640 assert(opType->isIntegral() ||
1641 opType->isPointerType() ||
1642 opType == Type::BoolTy && "Cast is illegal for other types");
1644 forwardOperandNum = 0;
1647 case 24: // reg: ToSByteTy(reg)
1648 case 26: // reg: ToShortTy(reg)
1649 case 28: // reg: ToIntTy(reg)
1650 case 30: // reg: ToLongTy(reg)
1651 opType = subtreeRoot->leftChild()->getValue()->getType();
1652 if (opType->isIntegral() || opType == Type::BoolTy)
1655 forwardOperandNum = 0;
1659 mvec[0] = new MachineInstr(ChooseConvertToIntInstr(subtreeRoot,
1661 Set2OperandsFromInstr(mvec[0], subtreeRoot, target);
1665 case 31: // reg: ToFloatTy(reg):
1666 case 32: // reg: ToDoubleTy(reg):
1667 case 232: // reg: ToDoubleTy(Constant):
1669 // If this instruction has a parent (a user) in the tree
1670 // and the user is translated as an FsMULd instruction,
1671 // then the cast is unnecessary. So check that first.
1672 // In the future, we'll want to do the same for the FdMULq instruction,
1673 // so do the check here instead of only for ToFloatTy(reg).
1675 if (subtreeRoot->parent() != NULL &&
1676 ((InstructionNode*) subtreeRoot->parent())->getInstruction()->getMachineInstrVec()[0]->getOpCode() == FSMULD)
1679 forwardOperandNum = 0;
1683 opType = subtreeRoot->leftChild()->getValue()->getType();
1684 MachineOpCode opCode=ChooseConvertToFloatInstr(subtreeRoot,opType);
1685 if (opCode == INVALID_OPCODE) // no conversion needed
1688 forwardOperandNum = 0;
1692 mvec[0] = new MachineInstr(opCode);
1693 Set2OperandsFromInstr(mvec[0], subtreeRoot, target);
1698 case 19: // reg: ToArrayTy(reg):
1699 case 20: // reg: ToPointerTy(reg):
1701 forwardOperandNum = 0;
1704 case 233: // reg: Add(reg, Constant)
1705 mvec[0] = CreateAddConstInstruction(subtreeRoot);
1706 if (mvec[0] != NULL)
1708 // ELSE FALL THROUGH
1710 case 33: // reg: Add(reg, reg)
1711 mvec[0] = new MachineInstr(ChooseAddInstruction(subtreeRoot));
1712 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1715 case 234: // reg: Sub(reg, Constant)
1716 mvec[0] = CreateSubConstInstruction(subtreeRoot);
1717 if (mvec[0] != NULL)
1719 // ELSE FALL THROUGH
1721 case 34: // reg: Sub(reg, reg)
1722 mvec[0] = new MachineInstr(ChooseSubInstruction(subtreeRoot));
1723 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1726 case 135: // reg: Mul(todouble, todouble)
1730 case 35: // reg: Mul(reg, reg)
1731 mvec[0] =new MachineInstr(ChooseMulInstruction(subtreeRoot,checkCast));
1732 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1735 case 335: // reg: Mul(todouble, todoubleConst)
1739 case 235: // reg: Mul(reg, Constant)
1740 mvec[0] = CreateMulConstInstruction(target, subtreeRoot, mvec[1]);
1741 if (mvec[0] == NULL)
1743 mvec[0] = new MachineInstr(ChooseMulInstruction(subtreeRoot,
1745 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1748 if (mvec[1] != NULL)
1752 case 236: // reg: Div(reg, Constant)
1753 mvec[0] = CreateDivConstInstruction(target, subtreeRoot, mvec[1]);
1754 if (mvec[0] != NULL)
1756 if (mvec[1] != NULL)
1760 // ELSE FALL THROUGH
1762 case 36: // reg: Div(reg, reg)
1763 mvec[0] = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1764 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1767 case 37: // reg: Rem(reg, reg)
1768 case 237: // reg: Rem(reg, Constant)
1769 assert(0 && "REM instruction unimplemented for the SPARC.");
1772 case 38: // reg: And(reg, reg)
1773 case 238: // reg: And(reg, Constant)
1774 mvec[0] = new MachineInstr(AND);
1775 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1778 case 138: // reg: And(reg, not)
1779 mvec[0] = new MachineInstr(ANDN);
1780 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1783 case 39: // reg: Or(reg, reg)
1784 case 239: // reg: Or(reg, Constant)
1785 mvec[0] = new MachineInstr(ORN);
1786 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1789 case 139: // reg: Or(reg, not)
1790 mvec[0] = new MachineInstr(ORN);
1791 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1794 case 40: // reg: Xor(reg, reg)
1795 case 240: // reg: Xor(reg, Constant)
1796 mvec[0] = new MachineInstr(XOR);
1797 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1800 case 140: // reg: Xor(reg, not)
1801 mvec[0] = new MachineInstr(XNOR);
1802 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
1805 case 41: // boolconst: SetCC(reg, Constant)
1806 // Check if this is an integer comparison, and
1807 // there is a parent, and the parent decided to use
1808 // a branch-on-integer-register instead of branch-on-condition-code.
1809 // If so, the SUBcc instruction is not required.
1810 // (However, we must still check for constants to be loaded from
1811 // the constant pool so that such a load can be associated with
1812 // this instruction.)
1814 // Otherwise this is just the same as case 42, so just fall through.
1816 if (subtreeRoot->leftChild()->getValue()->getType()->isIntegral() &&
1817 subtreeRoot->parent() != NULL)
1819 InstructionNode* parent = (InstructionNode*) subtreeRoot->parent();
1820 assert(parent->getNodeType() == InstrTreeNode::NTInstructionNode);
1821 const vector<MachineInstr*>&
1822 minstrVec = parent->getInstruction()->getMachineInstrVec();
1823 MachineOpCode parentOpCode;
1824 if (parent->getInstruction()->getOpcode() == Instruction::Br &&
1825 (parentOpCode = minstrVec[0]->getOpCode()) >= BRZ &&
1826 parentOpCode <= BRGEZ)
1828 numInstr = 0; // don't forward the operand!
1832 // ELSE FALL THROUGH
1834 case 42: // bool: SetCC(reg, reg):
1836 // If result of the SetCC is only used for a single branch, we can
1837 // discard the result. Otherwise, the boolean value must go into
1838 // an integer register.
1840 bool keepBoolVal = (subtreeRoot->parent() == NULL ||
1841 ((InstructionNode*) subtreeRoot->parent())
1842 ->getInstruction()->getOpcode() !=Instruction::Br);
1843 bool subValIsBoolVal =
1844 subtreeRoot->getInstruction()->getOpcode() == Instruction::SetNE;
1845 bool keepSubVal = keepBoolVal && subValIsBoolVal;
1846 bool computeBoolVal = keepBoolVal && ! subValIsBoolVal;
1850 MachineOpCode movOpCode;
1852 if (subtreeRoot->leftChild()->getValue()->getType()->isIntegral() ||
1853 subtreeRoot->leftChild()->getValue()->getType()->isPointerType())
1855 // Integer condition: dest. should be %g0 or an integer register.
1856 // If result must be saved but condition is not SetEQ then we need
1857 // a separate instruction to compute the bool result, so discard
1858 // result of SUBcc instruction anyway.
1860 mvec[0] = new MachineInstr(SUBcc);
1861 Set3OperandsFromInstr(mvec[0], subtreeRoot, target, ! keepSubVal);
1863 // mark the 4th operand as being a CC register, and a "result"
1864 mvec[0]->SetMachineOperand(3, MachineOperand::MO_CCRegister,
1865 subtreeRoot->getValue(),/*def*/true);
1868 { // recompute bool using the integer condition codes
1870 ChooseMovpccAfterSub(subtreeRoot,mustClearReg,valueToMove);
1875 // FP condition: dest of FCMP should be some FCCn register
1876 mvec[0] = new MachineInstr(ChooseFcmpInstruction(subtreeRoot));
1877 mvec[0]->SetMachineOperand(0,MachineOperand::MO_CCRegister,
1878 subtreeRoot->getValue());
1879 mvec[0]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1880 subtreeRoot->leftChild()->getValue());
1881 mvec[0]->SetMachineOperand(2,MachineOperand::MO_VirtualRegister,
1882 subtreeRoot->rightChild()->getValue());
1885 {// recompute bool using the FP condition codes
1886 mustClearReg = true;
1888 movOpCode = ChooseMovFpccInstruction(subtreeRoot);
1895 {// Unconditionally set register to 0
1897 mvec[n] = new MachineInstr(SETHI);
1898 mvec[n]->SetMachineOperand(0,MachineOperand::MO_UnextendedImmed,
1900 mvec[n]->SetMachineOperand(1,MachineOperand::MO_VirtualRegister,
1901 subtreeRoot->getValue());
1904 // Now conditionally move `valueToMove' (0 or 1) into the register
1906 mvec[n] = new MachineInstr(movOpCode);
1907 mvec[n]->SetMachineOperand(0, MachineOperand::MO_CCRegister,
1908 subtreeRoot->getValue());
1909 mvec[n]->SetMachineOperand(1, MachineOperand::MO_UnextendedImmed,
1911 mvec[n]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1912 subtreeRoot->getValue());
1917 case 43: // boolreg: VReg
1918 case 44: // boolreg: Constant
1922 case 51: // reg: Load(reg)
1923 case 52: // reg: Load(ptrreg)
1924 case 53: // reg: LoadIdx(reg,reg)
1925 case 54: // reg: LoadIdx(ptrreg,reg)
1926 mvec[0] = new MachineInstr(ChooseLoadInstruction(
1927 subtreeRoot->getValue()->getType()));
1928 SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1931 case 55: // reg: GetElemPtr(reg)
1932 case 56: // reg: GetElemPtrIdx(reg,reg)
1933 if (subtreeRoot->parent() != NULL)
1935 // Check if the parent was an array access.
1936 // If so, we still need to generate this instruction.
1937 MemAccessInst* memInst = (MemAccessInst*)
1938 subtreeRoot->getInstruction();
1939 const PointerType* ptrType =
1940 (const PointerType*) memInst->getPtrOperand()->getType();
1941 if (! ptrType->getValueType()->isArrayType())
1942 {// we don't need a separate instr
1943 numInstr = 0; // don't forward operand!
1947 // else in all other cases we need to a separate ADD instruction
1948 mvec[0] = new MachineInstr(ADD);
1949 SetOperandsForMemInstr(mvec[0], subtreeRoot, target);
1952 case 57: // reg: Alloca: Implement as 2 instructions:
1953 // sub %sp, tmp -> %sp
1954 { // add %sp, 0 -> result
1955 Instruction* instr = subtreeRoot->getInstruction();
1956 const PointerType* instrType = (const PointerType*) instr->getType();
1957 assert(instrType->isPointerType());
1959 target.findOptimalStorageSize(instrType->getValueType());
1960 assert(tsize != 0 && "Just to check when this can happen");
1962 // Create a temporary Value to hold the constant type-size
1963 ConstPoolSInt* valueForTSize = ConstPoolSInt::get(Type::IntTy, tsize);
1965 // Instruction 1: sub %sp, tsize -> %sp
1966 // tsize is always constant, but it may have to be put into a
1967 // register if it doesn't fit in the immediate field.
1969 mvec[0] = new MachineInstr(SUB);
1970 mvec[0]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
1971 mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
1973 mvec[0]->SetMachineOperand(2, /*regNum %sp=o6=r[14]*/(unsigned int)14);
1975 // Instruction 2: add %sp, 0 -> result
1977 mvec[1] = new MachineInstr(ADD);
1978 mvec[1]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
1979 mvec[1]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
1980 mvec[1]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
1985 case 58: // reg: Alloca(reg): Implement as 3 instructions:
1986 // mul num, typeSz -> tmp
1987 // sub %sp, tmp -> %sp
1988 { // add %sp, 0 -> result
1989 Instruction* instr = subtreeRoot->getInstruction();
1990 const PointerType* instrType = (const PointerType*) instr->getType();
1991 assert(instrType->isPointerType() &&
1992 instrType->getValueType()->isArrayType());
1993 const Type* eltType =
1994 ((ArrayType*) instrType->getValueType())->getElementType();
1995 int tsize = (int) target.findOptimalStorageSize(eltType);
1997 assert(tsize != 0 && "Just to check when this can happen");
2003 //else go on to create the instructions needed...
2005 // Create a temporary Value to hold the constant type-size
2006 ConstPoolSInt* valueForTSize = ConstPoolSInt::get(Type::IntTy, tsize);
2008 // Create a temporary value to hold `tmp'
2009 Instruction* tmpInstr = new TmpInstruction(Instruction::UserOp1,
2010 subtreeRoot->leftChild()->getValue(),
2011 NULL /*could insert tsize here*/);
2012 subtreeRoot->getInstruction()->getMachineInstrVec().addTempValue(tmpInstr);
2014 // Instruction 1: mul numElements, typeSize -> tmp
2015 mvec[0] = new MachineInstr(MULX);
2016 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2017 subtreeRoot->leftChild()->getValue());
2018 mvec[0]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
2020 mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
2023 tmpInstr->addMachineInstruction(mvec[0]);
2025 // Instruction 2: sub %sp, tmp -> %sp
2027 mvec[1] = new MachineInstr(SUB);
2028 mvec[1]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
2029 mvec[1]->SetMachineOperand(1, MachineOperand::MO_VirtualRegister,
2031 mvec[1]->SetMachineOperand(2, /*regNum %sp=o6=r[14]*/(unsigned int)14);
2033 // Instruction 3: add %sp, 0 -> result
2035 mvec[2] = new MachineInstr(ADD);
2036 mvec[2]->SetMachineOperand(0, /*regNum %sp=o6=r[14]*/(unsigned int)14);
2037 mvec[2]->SetMachineOperand(1, target.getRegInfo().getZeroRegNum());
2038 mvec[2]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
2043 case 61: // reg: Call
2044 // Generate a call-indirect (i.e., JMPL) for now to expose
2045 // the potential need for registers. If an absolute address
2046 // is available, replace this with a CALL instruction.
2047 // Mark both the indirection register and the return-address
2048 // register as hidden virtual registers.
2049 // Also, mark the operands of the Call and return value (if
2050 // any) as implicit operands of the CALL machine instruction.
2052 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2053 Value *callee = callInstr->getCalledValue();
2055 Instruction* jmpAddrReg = new TmpInstruction(Instruction::UserOp1,
2057 Instruction* retAddrReg = new TmpInstruction(Instruction::UserOp1,
2060 // Note temporary values in the machineInstrVec for the VM instr.
2062 // WARNING: Operands 0..N-1 must go in slots 0..N-1 of implicitUses.
2063 // The result value must go in slot N. This is assumed
2064 // in register allocation.
2066 callInstr->getMachineInstrVec().addTempValue(jmpAddrReg);
2067 callInstr->getMachineInstrVec().addTempValue(retAddrReg);
2069 // Generate the machine instruction and its operands
2070 mvec[0] = new MachineInstr(JMPL);
2071 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2073 mvec[0]->SetMachineOperand(1, MachineOperand::MO_SignExtendedImmed,
2075 mvec[0]->SetMachineOperand(2, MachineOperand::MO_VirtualRegister,
2078 // Add the call operands and return value as implicit refs
2079 for (unsigned i=0, N=callInstr->getNumOperands(); i < N; ++i)
2080 if (callInstr->getOperand(i) != callee)
2081 mvec[0]->addImplicitRef(callInstr->getOperand(i));
2083 if (callInstr->getCalledMethod()->getReturnType() != Type::VoidTy)
2084 mvec[0]->addImplicitRef(callInstr, /*isDef*/ true);
2086 // NOTE: jmpAddrReg will be loaded by a different instruction generated
2087 // by the final code generator, so we just mark the CALL instruction
2088 // as computing that value.
2089 // The retAddrReg is actually computed by the CALL instruction.
2091 jmpAddrReg->addMachineInstruction(mvec[0]);
2092 retAddrReg->addMachineInstruction(mvec[0]);
2094 mvec[numInstr++] = new MachineInstr(NOP); // delay slot
2098 case 62: // reg: Shl(reg, reg)
2099 opType = subtreeRoot->leftChild()->getValue()->getType();
2100 assert(opType->isIntegral()
2101 || opType == Type::BoolTy
2102 || opType->isPointerType()&& "Shl unsupported for other types");
2103 mvec[0] = new MachineInstr((opType == Type::LongTy)? SLLX : SLL);
2104 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
2107 case 63: // reg: Shr(reg, reg)
2108 opType = subtreeRoot->leftChild()->getValue()->getType();
2109 assert(opType->isIntegral()
2110 || opType == Type::BoolTy
2111 || opType->isPointerType() &&"Shr unsupported for other types");
2112 mvec[0] = new MachineInstr((opType->isSigned()
2113 ? ((opType == Type::LongTy)? SRAX : SRA)
2114 : ((opType == Type::LongTy)? SRLX : SRL)));
2115 Set3OperandsFromInstr(mvec[0], subtreeRoot, target);
2118 case 64: // reg: Phi(reg,reg)
2119 { // This instruction has variable #operands, so resultPos is 0.
2120 Instruction* phi = subtreeRoot->getInstruction();
2121 mvec[0] = new MachineInstr(PHI, 1 + phi->getNumOperands());
2122 mvec[0]->SetMachineOperand(0, MachineOperand::MO_VirtualRegister,
2123 subtreeRoot->getValue());
2124 for (unsigned i=0, N=phi->getNumOperands(); i < N; i++)
2125 mvec[0]->SetMachineOperand(i+1, MachineOperand::MO_VirtualRegister,
2126 phi->getOperand(i));
2129 case 71: // reg: VReg
2130 case 72: // reg: Constant
2131 numInstr = 0; // don't forward the value
2135 assert(0 && "Unrecognized BURG rule");
2141 if (forwardOperandNum >= 0)
2142 { // We did not generate a machine instruction but need to use operand.
2143 // If user is in the same tree, replace Value in its machine operand.
2144 // If not, insert a copy instruction which should get coalesced away
2145 // by register allocation.
2146 if (subtreeRoot->parent() != NULL)
2147 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2150 MachineInstr *minstr1 = NULL, *minstr2 = NULL;
2151 minstr1 = CreateCopyInstructionsByType(target,
2152 subtreeRoot->getInstruction()->getOperand(forwardOperandNum),
2153 subtreeRoot->getInstruction(), minstr2);
2155 mvec[numInstr++] = minstr1;
2156 if (minstr2 != NULL)
2157 mvec[numInstr++] = minstr2;
2161 if (! ThisIsAChainRule(ruleForNode))
2162 numInstr = FixConstantOperands(subtreeRoot, mvec, numInstr, target);