1 //===-- SparcInstrSelection.cpp -------------------------------------------===//
3 // BURS instruction selection for SPARC V9 architecture.
5 //===----------------------------------------------------------------------===//
7 #include "SparcInternals.h"
8 #include "SparcInstrSelectionSupport.h"
9 #include "SparcRegClassInfo.h"
10 #include "llvm/CodeGen/InstrSelectionSupport.h"
11 #include "llvm/CodeGen/MachineInstr.h"
12 #include "llvm/CodeGen/MachineInstrAnnot.h"
13 #include "llvm/CodeGen/InstrForest.h"
14 #include "llvm/CodeGen/InstrSelection.h"
15 #include "llvm/CodeGen/MachineCodeForMethod.h"
16 #include "llvm/CodeGen/MachineCodeForInstruction.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/iOther.h"
21 #include "llvm/Function.h"
22 #include "llvm/Constants.h"
23 #include "Support/MathExtras.h"
27 //************************* Forward Declarations ***************************/
30 static void SetMemOperands_Internal (vector<MachineInstr*>& mvec,
31 vector<MachineInstr*>::iterator mvecI,
32 const InstructionNode* vmInstrNode,
34 std::vector<Value*>& idxVec,
35 bool allConstantIndices,
36 const TargetMachine& target);
39 //************************ Internal Functions ******************************/
42 static inline MachineOpCode
43 ChooseBprInstruction(const InstructionNode* instrNode)
47 Instruction* setCCInstr =
48 ((InstructionNode*) instrNode->leftChild())->getInstruction();
50 switch(setCCInstr->getOpcode())
52 case Instruction::SetEQ: opCode = BRZ; break;
53 case Instruction::SetNE: opCode = BRNZ; break;
54 case Instruction::SetLE: opCode = BRLEZ; break;
55 case Instruction::SetGE: opCode = BRGEZ; break;
56 case Instruction::SetLT: opCode = BRLZ; break;
57 case Instruction::SetGT: opCode = BRGZ; break;
59 assert(0 && "Unrecognized VM instruction!");
60 opCode = INVALID_OPCODE;
68 static inline MachineOpCode
69 ChooseBpccInstruction(const InstructionNode* instrNode,
70 const BinaryOperator* setCCInstr)
72 MachineOpCode opCode = INVALID_OPCODE;
74 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
78 switch(setCCInstr->getOpcode())
80 case Instruction::SetEQ: opCode = BE; break;
81 case Instruction::SetNE: opCode = BNE; break;
82 case Instruction::SetLE: opCode = BLE; break;
83 case Instruction::SetGE: opCode = BGE; break;
84 case Instruction::SetLT: opCode = BL; break;
85 case Instruction::SetGT: opCode = BG; break;
87 assert(0 && "Unrecognized VM instruction!");
93 switch(setCCInstr->getOpcode())
95 case Instruction::SetEQ: opCode = BE; break;
96 case Instruction::SetNE: opCode = BNE; break;
97 case Instruction::SetLE: opCode = BLEU; break;
98 case Instruction::SetGE: opCode = BCC; break;
99 case Instruction::SetLT: opCode = BCS; break;
100 case Instruction::SetGT: opCode = BGU; break;
102 assert(0 && "Unrecognized VM instruction!");
110 static inline MachineOpCode
111 ChooseBFpccInstruction(const InstructionNode* instrNode,
112 const BinaryOperator* setCCInstr)
114 MachineOpCode opCode = INVALID_OPCODE;
116 switch(setCCInstr->getOpcode())
118 case Instruction::SetEQ: opCode = FBE; break;
119 case Instruction::SetNE: opCode = FBNE; break;
120 case Instruction::SetLE: opCode = FBLE; break;
121 case Instruction::SetGE: opCode = FBGE; break;
122 case Instruction::SetLT: opCode = FBL; break;
123 case Instruction::SetGT: opCode = FBG; break;
125 assert(0 && "Unrecognized VM instruction!");
133 // Create a unique TmpInstruction for a boolean value,
134 // representing the CC register used by a branch on that value.
135 // For now, hack this using a little static cache of TmpInstructions.
136 // Eventually the entire BURG instruction selection should be put
137 // into a separate class that can hold such information.
138 // The static cache is not too bad because the memory for these
139 // TmpInstructions will be freed along with the rest of the Function anyway.
141 static TmpInstruction*
142 GetTmpForCC(Value* boolVal, const Function *F, const Type* ccType)
144 typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
145 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
146 static const Function *lastFunction = 0;// Use to flush cache between funcs
148 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
150 if (lastFunction != F)
153 boolToTmpCache.clear();
156 // Look for tmpI and create a new one otherwise. The new value is
157 // directly written to map using the ref returned by operator[].
158 TmpInstruction*& tmpI = boolToTmpCache[boolVal];
160 tmpI = new TmpInstruction(ccType, boolVal);
166 static inline MachineOpCode
167 ChooseBccInstruction(const InstructionNode* instrNode,
170 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
171 assert(setCCNode->getOpLabel() == SetCCOp);
172 BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
173 const Type* setCCType = setCCInstr->getOperand(0)->getType();
175 isFPBranch = setCCType->isFloatingPoint(); // Return value: don't delete!
178 return ChooseBFpccInstruction(instrNode, setCCInstr);
180 return ChooseBpccInstruction(instrNode, setCCInstr);
184 static inline MachineOpCode
185 ChooseMovFpccInstruction(const InstructionNode* instrNode)
187 MachineOpCode opCode = INVALID_OPCODE;
189 switch(instrNode->getInstruction()->getOpcode())
191 case Instruction::SetEQ: opCode = MOVFE; break;
192 case Instruction::SetNE: opCode = MOVFNE; break;
193 case Instruction::SetLE: opCode = MOVFLE; break;
194 case Instruction::SetGE: opCode = MOVFGE; break;
195 case Instruction::SetLT: opCode = MOVFL; break;
196 case Instruction::SetGT: opCode = MOVFG; break;
198 assert(0 && "Unrecognized VM instruction!");
206 // Assumes that SUBcc v1, v2 -> v3 has been executed.
207 // In most cases, we want to clear v3 and then follow it by instruction
209 // Set mustClearReg=false if v3 need not be cleared before conditional move.
210 // Set valueToMove=0 if we want to conditionally move 0 instead of 1
211 // (i.e., we want to test inverse of a condition)
212 // (The latter two cases do not seem to arise because SetNE needs nothing.)
215 ChooseMovpccAfterSub(const InstructionNode* instrNode,
219 MachineOpCode opCode = INVALID_OPCODE;
223 switch(instrNode->getInstruction()->getOpcode())
225 case Instruction::SetEQ: opCode = MOVE; break;
226 case Instruction::SetLE: opCode = MOVLE; break;
227 case Instruction::SetGE: opCode = MOVGE; break;
228 case Instruction::SetLT: opCode = MOVL; break;
229 case Instruction::SetGT: opCode = MOVG; break;
230 case Instruction::SetNE: assert(0 && "No move required!"); break;
231 default: assert(0 && "Unrecognized VM instr!"); break;
237 static inline MachineOpCode
238 ChooseConvertToFloatInstr(OpLabel vopCode, const Type* opType)
240 MachineOpCode opCode = INVALID_OPCODE;
245 if (opType == Type::SByteTy || opType == Type::ShortTy || opType == Type::IntTy)
247 else if (opType == Type::LongTy)
249 else if (opType == Type::DoubleTy)
251 else if (opType == Type::FloatTy)
254 assert(0 && "Cannot convert this type to FLOAT on SPARC");
258 // This is usually used in conjunction with CreateCodeToCopyIntToFloat().
259 // Both functions should treat the integer as a 32-bit value for types
260 // of 4 bytes or less, and as a 64-bit value otherwise.
261 if (opType == Type::SByteTy || opType == Type::UByteTy ||
262 opType == Type::ShortTy || opType == Type::UShortTy ||
263 opType == Type::IntTy || opType == Type::UIntTy)
265 else if (opType == Type::LongTy || opType == Type::ULongTy)
267 else if (opType == Type::FloatTy)
269 else if (opType == Type::DoubleTy)
272 assert(0 && "Cannot convert this type to DOUBLE on SPARC");
282 static inline MachineOpCode
283 ChooseConvertToIntInstr(Type::PrimitiveID tid, const Type* opType)
285 MachineOpCode opCode = INVALID_OPCODE;;
287 if (tid==Type::SByteTyID || tid==Type::ShortTyID || tid==Type::IntTyID ||
288 tid==Type::UByteTyID || tid==Type::UShortTyID || tid==Type::UIntTyID)
290 switch (opType->getPrimitiveID())
292 case Type::FloatTyID: opCode = FSTOI; break;
293 case Type::DoubleTyID: opCode = FDTOI; break;
295 assert(0 && "Non-numeric non-bool type cannot be converted to Int");
299 else if (tid==Type::LongTyID || tid==Type::ULongTyID)
301 switch (opType->getPrimitiveID())
303 case Type::FloatTyID: opCode = FSTOX; break;
304 case Type::DoubleTyID: opCode = FDTOX; break;
306 assert(0 && "Non-numeric non-bool type cannot be converted to Long");
311 assert(0 && "Should not get here, Mo!");
317 CreateConvertToIntInstr(Type::PrimitiveID destTID, Value* srcVal,Value* destVal)
319 MachineOpCode opCode = ChooseConvertToIntInstr(destTID, srcVal->getType());
320 assert(opCode != INVALID_OPCODE && "Expected to need conversion!");
322 MachineInstr* M = new MachineInstr(opCode);
323 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister, srcVal);
324 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, destVal);
328 // CreateCodeToConvertIntToFloat: Convert FP value to signed or unsigned integer
329 // The FP value must be converted to the dest type in an FP register,
330 // and the result is then copied from FP to int register via memory.
332 CreateCodeToConvertIntToFloat (const TargetMachine& target,
335 std::vector<MachineInstr*>& mvec,
336 MachineCodeForInstruction& mcfi)
338 // Create a temporary to represent the FP register into which the
339 // int value will placed after conversion. The type of this temporary
340 // depends on the type of FP register to use: single-prec for a 32-bit
341 // int or smaller; double-prec for a 64-bit int.
343 const Type* destTypeToUse = (destI->getType() == Type::LongTy)? Type::DoubleTy
345 Value* destForCast = new TmpInstruction(destTypeToUse, opVal);
346 mcfi.addTemp(destForCast);
348 // Create the fp-to-int conversion code
349 MachineInstr* M = CreateConvertToIntInstr(destI->getType()->getPrimitiveID(),
353 // Create the fpreg-to-intreg copy code
354 target.getInstrInfo().
355 CreateCodeToCopyFloatToInt(target, destI->getParent()->getParent(),
356 (TmpInstruction*)destForCast, destI, mvec, mcfi);
360 static inline MachineOpCode
361 ChooseAddInstruction(const InstructionNode* instrNode)
363 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
367 static inline MachineInstr*
368 CreateMovFloatInstruction(const InstructionNode* instrNode,
369 const Type* resultType)
371 MachineInstr* minstr = new MachineInstr((resultType == Type::FloatTy)
373 minstr->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
374 instrNode->leftChild()->getValue());
375 minstr->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,
376 instrNode->getValue());
380 static inline MachineInstr*
381 CreateAddConstInstruction(const InstructionNode* instrNode)
383 MachineInstr* minstr = NULL;
385 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
386 assert(isa<Constant>(constOp));
388 // Cases worth optimizing are:
389 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
390 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
392 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
393 double dval = FPC->getValue();
395 minstr = CreateMovFloatInstruction(instrNode,
396 instrNode->getInstruction()->getType());
403 static inline MachineOpCode
404 ChooseSubInstructionByType(const Type* resultType)
406 MachineOpCode opCode = INVALID_OPCODE;
408 if (resultType->isIntegral() || isa<PointerType>(resultType))
413 switch(resultType->getPrimitiveID())
415 case Type::FloatTyID: opCode = FSUBS; break;
416 case Type::DoubleTyID: opCode = FSUBD; break;
417 default: assert(0 && "Invalid type for SUB instruction"); break;
424 static inline MachineInstr*
425 CreateSubConstInstruction(const InstructionNode* instrNode)
427 MachineInstr* minstr = NULL;
429 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
430 assert(isa<Constant>(constOp));
432 // Cases worth optimizing are:
433 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
434 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
436 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
437 double dval = FPC->getValue();
439 minstr = CreateMovFloatInstruction(instrNode,
440 instrNode->getInstruction()->getType());
447 static inline MachineOpCode
448 ChooseFcmpInstruction(const InstructionNode* instrNode)
450 MachineOpCode opCode = INVALID_OPCODE;
452 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
453 switch(operand->getType()->getPrimitiveID()) {
454 case Type::FloatTyID: opCode = FCMPS; break;
455 case Type::DoubleTyID: opCode = FCMPD; break;
456 default: assert(0 && "Invalid type for FCMP instruction"); break;
463 // Assumes that leftArg and rightArg are both cast instructions.
466 BothFloatToDouble(const InstructionNode* instrNode)
468 InstrTreeNode* leftArg = instrNode->leftChild();
469 InstrTreeNode* rightArg = instrNode->rightChild();
470 InstrTreeNode* leftArgArg = leftArg->leftChild();
471 InstrTreeNode* rightArgArg = rightArg->leftChild();
472 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
474 // Check if both arguments are floats cast to double
475 return (leftArg->getValue()->getType() == Type::DoubleTy &&
476 leftArgArg->getValue()->getType() == Type::FloatTy &&
477 rightArgArg->getValue()->getType() == Type::FloatTy);
481 static inline MachineOpCode
482 ChooseMulInstructionByType(const Type* resultType)
484 MachineOpCode opCode = INVALID_OPCODE;
486 if (resultType->isIntegral())
489 switch(resultType->getPrimitiveID())
491 case Type::FloatTyID: opCode = FMULS; break;
492 case Type::DoubleTyID: opCode = FMULD; break;
493 default: assert(0 && "Invalid type for MUL instruction"); break;
501 static inline MachineInstr*
502 CreateIntNegInstruction(const TargetMachine& target,
505 MachineInstr* minstr = new MachineInstr(SUB);
506 minstr->SetMachineOperandReg(0, target.getRegInfo().getZeroRegNum());
507 minstr->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, vreg);
508 minstr->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, vreg);
513 // Create instruction sequence for any shift operation.
514 // SLL or SLLX on an operand smaller than the integer reg. size (64bits)
515 // requires a second instruction for explicit sign-extension.
516 // Note that we only have to worry about a sign-bit appearing in the
517 // most significant bit of the operand after shifting (e.g., bit 32 of
518 // Int or bit 16 of Short), so we do not have to worry about results
519 // that are as large as a normal integer register.
522 CreateShiftInstructions(const TargetMachine& target,
524 MachineOpCode shiftOpCode,
526 Value* optArgVal2, /* Use optArgVal2 if not NULL */
527 unsigned int optShiftNum, /* else use optShiftNum */
528 Instruction* destVal,
529 vector<MachineInstr*>& mvec,
530 MachineCodeForInstruction& mcfi)
532 assert((optArgVal2 != NULL || optShiftNum <= 64) &&
533 "Large shift sizes unexpected, but can be handled below: "
534 "You need to check whether or not it fits in immed field below");
536 // If this is a logical left shift of a type smaller than the standard
537 // integer reg. size, we have to extend the sign-bit into upper bits
538 // of dest, so we need to put the result of the SLL into a temporary.
540 Value* shiftDest = destVal;
541 const Type* opType = argVal1->getType();
542 unsigned opSize = target.DataLayout.getTypeSize(argVal1->getType());
543 if ((shiftOpCode == SLL || shiftOpCode == SLLX)
544 && opSize < target.DataLayout.getIntegerRegize())
545 { // put SLL result into a temporary
546 shiftDest = new TmpInstruction(argVal1, optArgVal2, "sllTmp");
547 mcfi.addTemp(shiftDest);
550 MachineInstr* M = (optArgVal2 != NULL)
551 ? Create3OperandInstr(shiftOpCode, argVal1, optArgVal2, shiftDest)
552 : Create3OperandInstr_UImmed(shiftOpCode, argVal1, optShiftNum, shiftDest);
555 if (shiftDest != destVal)
556 { // extend the sign-bit of the result into all upper bits of dest
557 assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
558 target.getInstrInfo().
559 CreateSignExtensionInstructions(target, F, shiftDest, 8*opSize,
560 destVal, mvec, mcfi);
565 // Does not create any instructions if we cannot exploit constant to
566 // create a cheaper instruction.
567 // This returns the approximate cost of the instructions generated,
568 // which is used to pick the cheapest when both operands are constant.
569 static inline unsigned int
570 CreateMulConstInstruction(const TargetMachine &target, Function* F,
571 Value* lval, Value* rval, Instruction* destVal,
572 vector<MachineInstr*>& mvec,
573 MachineCodeForInstruction& mcfi)
575 /* Use max. multiply cost, viz., cost of MULX */
576 unsigned int cost = target.getInstrInfo().minLatency(MULX);
577 unsigned int firstNewInstr = mvec.size();
579 Value* constOp = rval;
580 if (! isa<Constant>(constOp))
583 // Cases worth optimizing are:
584 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
585 // (2) Multiply by 2^x for integer types: replace with Shift
587 const Type* resultType = destVal->getType();
589 if (resultType->isIntegral() || isa<PointerType>(resultType))
592 int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
596 bool needNeg = false;
603 if (C == 0 || C == 1)
605 cost = target.getInstrInfo().minLatency(ADD);
606 MachineInstr* M = (C == 0)
607 ? Create3OperandInstr_Reg(ADD,
608 target.getRegInfo().getZeroRegNum(),
609 target.getRegInfo().getZeroRegNum(),
611 : Create3OperandInstr_Reg(ADD, lval,
612 target.getRegInfo().getZeroRegNum(),
616 else if (isPowerOf2(C, pow))
618 unsigned int opSize = target.DataLayout.getTypeSize(resultType);
619 MachineOpCode opCode = (opSize <= 32)? SLL : SLLX;
620 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
621 destVal, mvec, mcfi);
624 if (mvec.size() > 0 && needNeg)
625 { // insert <reg = SUB 0, reg> after the instr to flip the sign
626 MachineInstr* M = CreateIntNegInstruction(target, destVal);
633 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp))
635 double dval = FPC->getValue();
638 MachineOpCode opCode = (dval < 0)
639 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
640 : (resultType == Type::FloatTy? FMOVS : FMOVD);
641 MachineInstr* M = Create2OperandInstr(opCode, lval, destVal);
647 if (firstNewInstr < mvec.size())
650 for (unsigned int i=firstNewInstr; i < mvec.size(); ++i)
651 cost += target.getInstrInfo().minLatency(mvec[i]->getOpCode());
658 // Does not create any instructions if we cannot exploit constant to
659 // create a cheaper instruction.
662 CreateCheapestMulConstInstruction(const TargetMachine &target,
664 Value* lval, Value* rval,
665 Instruction* destVal,
666 vector<MachineInstr*>& mvec,
667 MachineCodeForInstruction& mcfi)
670 if (isa<Constant>(lval) && isa<Constant>(rval))
671 { // both operands are constant: try both orders!
672 vector<MachineInstr*> mvec1, mvec2;
673 unsigned int lcost = CreateMulConstInstruction(target, F, lval, rval,
674 destVal, mvec1, mcfi);
675 unsigned int rcost = CreateMulConstInstruction(target, F, rval, lval,
676 destVal, mvec2, mcfi);
677 vector<MachineInstr*>& mincostMvec = (lcost <= rcost)? mvec1 : mvec2;
678 vector<MachineInstr*>& maxcostMvec = (lcost <= rcost)? mvec2 : mvec1;
679 mvec.insert(mvec.end(), mincostMvec.begin(), mincostMvec.end());
681 for (unsigned int i=0; i < maxcostMvec.size(); ++i)
682 delete maxcostMvec[i];
684 else if (isa<Constant>(rval)) // rval is constant, but not lval
685 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
686 else if (isa<Constant>(lval)) // lval is constant, but not rval
687 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
689 // else neither is constant
693 // Return NULL if we cannot exploit constant to create a cheaper instruction
695 CreateMulInstruction(const TargetMachine &target, Function* F,
696 Value* lval, Value* rval, Instruction* destVal,
697 vector<MachineInstr*>& mvec,
698 MachineCodeForInstruction& mcfi,
699 MachineOpCode forceMulOp = INVALID_MACHINE_OPCODE)
701 unsigned int L = mvec.size();
702 CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
703 if (mvec.size() == L)
704 { // no instructions were added so create MUL reg, reg, reg.
705 // Use FSMULD if both operands are actually floats cast to doubles.
706 // Otherwise, use the default opcode for the appropriate type.
707 MachineOpCode mulOp = ((forceMulOp != INVALID_MACHINE_OPCODE)
709 : ChooseMulInstructionByType(destVal->getType()));
710 MachineInstr* M = new MachineInstr(mulOp);
711 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister, lval);
712 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, rval);
713 M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, destVal);
719 // Generate a divide instruction for Div or Rem.
720 // For Rem, this assumes that the operand type will be signed if the result
721 // type is signed. This is correct because they must have the same sign.
723 static inline MachineOpCode
724 ChooseDivInstruction(TargetMachine &target,
725 const InstructionNode* instrNode)
727 MachineOpCode opCode = INVALID_OPCODE;
729 const Type* resultType = instrNode->getInstruction()->getType();
731 if (resultType->isIntegral())
732 opCode = resultType->isSigned()? SDIVX : UDIVX;
734 switch(resultType->getPrimitiveID())
736 case Type::FloatTyID: opCode = FDIVS; break;
737 case Type::DoubleTyID: opCode = FDIVD; break;
738 default: assert(0 && "Invalid type for DIV instruction"); break;
745 // Return NULL if we cannot exploit constant to create a cheaper instruction
747 CreateDivConstInstruction(TargetMachine &target,
748 const InstructionNode* instrNode,
749 vector<MachineInstr*>& mvec)
751 MachineInstr* minstr1 = NULL;
752 MachineInstr* minstr2 = NULL;
754 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
755 if (! isa<Constant>(constOp))
758 // Cases worth optimizing are:
759 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
760 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
762 const Type* resultType = instrNode->getInstruction()->getType();
764 if (resultType->isIntegral())
768 int64_t C = GetConstantValueAsSignedInt(constOp, isValidConst);
771 bool needNeg = false;
780 minstr1 = new MachineInstr(ADD);
781 minstr1->SetMachineOperandVal(0,
782 MachineOperand::MO_VirtualRegister,
783 instrNode->leftChild()->getValue());
784 minstr1->SetMachineOperandReg(1,
785 target.getRegInfo().getZeroRegNum());
787 else if (isPowerOf2(C, pow))
789 MachineOpCode opCode= ((resultType->isSigned())
790 ? (resultType==Type::LongTy)? SRAX : SRA
791 : (resultType==Type::LongTy)? SRLX : SRL);
792 minstr1 = new MachineInstr(opCode);
793 minstr1->SetMachineOperandVal(0,
794 MachineOperand::MO_VirtualRegister,
795 instrNode->leftChild()->getValue());
796 minstr1->SetMachineOperandConst(1,
797 MachineOperand::MO_UnextendedImmed,
801 if (minstr1 && needNeg)
802 { // insert <reg = SUB 0, reg> after the instr to flip the sign
803 minstr2 = CreateIntNegInstruction(target,
804 instrNode->getValue());
810 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp))
812 double dval = FPC->getValue();
815 bool needNeg = (dval < 0);
817 MachineOpCode opCode = needNeg
818 ? (resultType == Type::FloatTy? FNEGS : FNEGD)
819 : (resultType == Type::FloatTy? FMOVS : FMOVD);
821 minstr1 = new MachineInstr(opCode);
822 minstr1->SetMachineOperandVal(0,
823 MachineOperand::MO_VirtualRegister,
824 instrNode->leftChild()->getValue());
830 minstr1->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
831 instrNode->getValue());
834 mvec.push_back(minstr1);
836 mvec.push_back(minstr2);
841 CreateCodeForVariableSizeAlloca(const TargetMachine& target,
844 Value* numElementsVal,
845 vector<MachineInstr*>& getMvec)
849 // Create a Value to hold the (constant) element size
850 Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
852 // Get the constant offset from SP for dynamically allocated storage
853 // and create a temporary Value to hold it.
854 assert(result && result->getParent() && "Result value is not part of a fn?");
855 Function *F = result->getParent()->getParent();
856 MachineCodeForMethod& mcInfo = MachineCodeForMethod::get(F);
858 ConstantSInt* dynamicAreaOffset =
859 ConstantSInt::get(Type::IntTy,
860 target.getFrameInfo().getDynamicAreaOffset(mcInfo,growUp));
861 assert(! growUp && "Has SPARC v9 stack frame convention changed?");
863 // Create a temporary value to hold the result of MUL
864 TmpInstruction* tmpProd = new TmpInstruction(numElementsVal, tsizeVal);
865 MachineCodeForInstruction::get(result).addTemp(tmpProd);
867 // Instruction 1: mul numElements, typeSize -> tmpProd
868 M = new MachineInstr(MULX);
869 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister, numElementsVal);
870 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, tsizeVal);
871 M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, tmpProd);
872 getMvec.push_back(M);
874 // Instruction 2: sub %sp, tmpProd -> %sp
875 M = new MachineInstr(SUB);
876 M->SetMachineOperandReg(0, target.getRegInfo().getStackPointer());
877 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, tmpProd);
878 M->SetMachineOperandReg(2, target.getRegInfo().getStackPointer());
879 getMvec.push_back(M);
881 // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
882 M = new MachineInstr(ADD);
883 M->SetMachineOperandReg(0, target.getRegInfo().getStackPointer());
884 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, dynamicAreaOffset);
885 M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, result);
886 getMvec.push_back(M);
891 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
894 unsigned int numElements,
895 vector<MachineInstr*>& getMvec)
897 assert(result && result->getParent() &&
898 "Result value is not part of a function?");
899 Function *F = result->getParent()->getParent();
900 MachineCodeForMethod &mcInfo = MachineCodeForMethod::get(F);
902 // Check if the offset would small enough to use as an immediate in
903 // load/stores (check LDX because all load/stores have the same-size immediate
904 // field). If not, put the variable in the dynamically sized area of the
906 unsigned int paddedSizeIgnored;
907 int offsetFromFP = mcInfo.computeOffsetforLocalVar(target, result,
909 tsize * numElements);
910 if (! target.getInstrInfo().constantFitsInImmedField(LDX, offsetFromFP))
912 CreateCodeForVariableSizeAlloca(target, result, tsize,
913 ConstantSInt::get(Type::IntTy,numElements),
918 // else offset fits in immediate field so go ahead and allocate it.
919 offsetFromFP = mcInfo.allocateLocalVar(target, result, tsize * numElements);
921 // Create a temporary Value to hold the constant offset.
922 // This is needed because it may not fit in the immediate field.
923 ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
925 // Instruction 1: add %fp, offsetFromFP -> result
926 MachineInstr* M = new MachineInstr(ADD);
927 M->SetMachineOperandReg(0, target.getRegInfo().getFramePointer());
928 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister, offsetVal);
929 M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister, result);
931 getMvec.push_back(M);
936 // Check for a constant (uint) 0.
940 return (isa<ConstantInt>(idx) && cast<ConstantInt>(idx)->isNullValue());
944 //------------------------------------------------------------------------
945 // Function SetOperandsForMemInstr
947 // Choose addressing mode for the given load or store instruction.
948 // Use [reg+reg] if it is an indexed reference, and the index offset is
949 // not a constant or if it cannot fit in the offset field.
950 // Use [reg+offset] in all other cases.
952 // This assumes that all array refs are "lowered" to one of these forms:
953 // %x = load (subarray*) ptr, constant ; single constant offset
954 // %x = load (subarray*) ptr, offsetVal ; single non-constant offset
955 // Generally, this should happen via strength reduction + LICM.
956 // Also, strength reduction should take care of using the same register for
957 // the loop index variable and an array index, when that is profitable.
958 //------------------------------------------------------------------------
961 SetOperandsForMemInstr(vector<MachineInstr*>& mvec,
962 vector<MachineInstr*>::iterator mvecI,
963 const InstructionNode* vmInstrNode,
964 const TargetMachine& target)
966 MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
968 // Variables to hold the index vector and ptr value.
969 // The major work here is to extract these for all 3 instruction types
970 // and to try to fold chains of constant indices into a single offset.
971 // After that, we call SetMemOperands_Internal(), which creates the
972 // appropriate operands for the machine instruction.
973 vector<Value*> idxVec;
974 bool allConstantIndices = true;
975 Value* ptrVal = memInst->getPointerOperand();
977 // If there is a GetElemPtr instruction to fold in to this instr,
978 // it must be in the left child for Load and GetElemPtr, and in the
979 // right child for Store instructions.
980 InstrTreeNode* ptrChild = (vmInstrNode->getOpLabel() == Instruction::Store
981 ? vmInstrNode->rightChild()
982 : vmInstrNode->leftChild());
984 // Check if all indices are constant for this instruction
985 for (MemAccessInst::op_iterator OI=memInst->idx_begin(),OE=memInst->idx_end();
986 allConstantIndices && OI != OE; ++OI)
987 if (! isa<Constant>(*OI))
988 allConstantIndices = false;
990 // If we have only constant indices, fold chains of constant indices
991 // in this and any preceding GetElemPtr instructions.
992 bool foldedGEPs = false;
993 if (allConstantIndices &&
994 (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
995 ptrChild->getOpLabel() == GetElemPtrIdx))
996 if (Value* newPtr = FoldGetElemChain((InstructionNode*) ptrChild, idxVec)) {
1001 // Append the index vector of the current instruction, if any.
1002 // Skip the leading [0] index if preceding GEPs were folded into this.
1003 if (memInst->getNumIndices() > 0) {
1004 assert((!foldedGEPs || IsZero(*memInst->idx_begin())) && "1st index not 0");
1005 idxVec.insert(idxVec.end(),
1006 memInst->idx_begin() + foldedGEPs, memInst->idx_end());
1009 // Now create the appropriate operands for the machine instruction
1010 SetMemOperands_Internal(mvec, mvecI, vmInstrNode,
1011 ptrVal, idxVec, allConstantIndices, target);
1015 // Generate the correct operands (and additional instructions if needed)
1016 // for the given pointer and given index vector.
1019 SetMemOperands_Internal(vector<MachineInstr*>& mvec,
1020 vector<MachineInstr*>::iterator mvecI,
1021 const InstructionNode* vmInstrNode,
1023 vector<Value*>& idxVec,
1024 bool allConstantIndices,
1025 const TargetMachine& target)
1027 MemAccessInst* memInst = (MemAccessInst*) vmInstrNode->getInstruction();
1029 // Initialize so we default to storing the offset in a register.
1030 int64_t smallConstOffset = 0;
1031 Value* valueForRegOffset = NULL;
1032 MachineOperand::MachineOperandType offsetOpType =
1033 MachineOperand::MO_VirtualRegister;
1035 // Check if there is an index vector and if so, compute the
1036 // right offset for structures and for arrays
1038 if (idxVec.size() > 0)
1040 const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
1042 // If all indices are constant, compute the combined offset directly.
1043 if (allConstantIndices)
1045 // Compute the offset value using the index vector. Create a
1046 // virtual reg. for it since it may not fit in the immed field.
1047 uint64_t offset = target.DataLayout.getIndexedOffset(ptrType,idxVec);
1048 valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
1052 // There is at least one non-constant offset. Therefore, this must
1053 // be an array ref, and must have been lowered to a single non-zero
1054 // offset. (An extra leading zero offset, if any, can be ignored.)
1055 // Generate code sequence to compute address from index.
1057 assert(idxVec.size() == 1U + IsZero(idxVec[0])
1058 && "Array refs must be lowered before Instruction Selection");
1060 Value* idxVal = idxVec[IsZero(idxVec[0])];
1062 vector<MachineInstr*> mulVec;
1063 Instruction* addr = new TmpInstruction(Type::UIntTy, memInst);
1064 MachineCodeForInstruction::get(memInst).addTemp(addr);
1066 // The call to getTypeSize() will fail if size is not constant.
1067 unsigned int eltSize =
1068 target.DataLayout.getTypeSize(ptrType->getElementType());
1069 assert(eltSize > 0 && "Invalid or non-const array element size");
1070 ConstantUInt* eltVal = ConstantUInt::get(Type::UIntTy, eltSize);
1072 // CreateMulInstruction() folds constants intelligently enough.
1073 CreateMulInstruction(target,
1074 memInst->getParent()->getParent(),
1075 idxVal, /* lval, not likely const */
1076 eltVal, /* rval, likely constant */
1079 MachineCodeForInstruction::get(memInst),
1080 INVALID_MACHINE_OPCODE);
1082 // Insert mulVec[] before *mvecI in mvec[] and update mvecI
1083 // to point to the same instruction it pointed to before.
1084 assert(mulVec.size() > 0 && "No multiply code created?");
1085 vector<MachineInstr*>::iterator oldMvecI = mvecI;
1086 for (unsigned i=0, N=mulVec.size(); i < N; ++i)
1087 mvecI = mvec.insert(mvecI, mulVec[i]) + 1; // pts to mem instr
1089 valueForRegOffset = addr;
1094 offsetOpType = MachineOperand::MO_SignExtendedImmed;
1095 smallConstOffset = 0;
1099 // Operand 0 is value, operand 1 is ptr, operand 2 is offset
1100 // For LOAD or GET_ELEMENT_PTR,
1101 // Operand 0 is ptr, operand 1 is offset, operand 2 is result.
1103 unsigned offsetOpNum, ptrOpNum;
1104 if (memInst->getOpcode() == Instruction::Store)
1106 (*mvecI)->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1107 vmInstrNode->leftChild()->getValue());
1115 (*mvecI)->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
1119 (*mvecI)->SetMachineOperandVal(ptrOpNum, MachineOperand::MO_VirtualRegister,
1122 if (offsetOpType == MachineOperand::MO_VirtualRegister)
1124 assert(valueForRegOffset != NULL);
1125 (*mvecI)->SetMachineOperandVal(offsetOpNum, offsetOpType,
1129 (*mvecI)->SetMachineOperandConst(offsetOpNum, offsetOpType,
1135 // Substitute operand `operandNum' of the instruction in node `treeNode'
1136 // in place of the use(s) of that instruction in node `parent'.
1137 // Check both explicit and implicit operands!
1138 // Also make sure to skip over a parent who:
1139 // (1) is a list node in the Burg tree, or
1140 // (2) itself had its results forwarded to its parent
1143 ForwardOperand(InstructionNode* treeNode,
1144 InstrTreeNode* parent,
1147 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
1149 Instruction* unusedOp = treeNode->getInstruction();
1150 Value* fwdOp = unusedOp->getOperand(operandNum);
1152 // The parent itself may be a list node, so find the real parent instruction
1153 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode)
1155 parent = parent->parent();
1156 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
1158 InstructionNode* parentInstrNode = (InstructionNode*) parent;
1160 Instruction* userInstr = parentInstrNode->getInstruction();
1161 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
1163 // The parent's mvec would be empty if it was itself forwarded.
1164 // Recursively call ForwardOperand in that case...
1166 if (mvec.size() == 0)
1168 assert(parent->parent() != NULL &&
1169 "Parent could not have been forwarded, yet has no instructions?");
1170 ForwardOperand(treeNode, parent->parent(), operandNum);
1174 for (unsigned i=0, N=mvec.size(); i < N; i++)
1176 MachineInstr* minstr = mvec[i];
1177 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i)
1179 const MachineOperand& mop = minstr->getOperand(i);
1180 if (mop.getOperandType() == MachineOperand::MO_VirtualRegister &&
1181 mop.getVRegValue() == unusedOp)
1182 minstr->SetMachineOperandVal(i,
1183 MachineOperand::MO_VirtualRegister, fwdOp);
1186 for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
1187 if (minstr->getImplicitRef(i) == unusedOp)
1188 minstr->setImplicitRef(i, fwdOp,
1189 minstr->implicitRefIsDefined(i),
1190 minstr->implicitRefIsDefinedAndUsed(i));
1197 AllUsesAreBranches(const Instruction* setccI)
1199 for (Value::use_const_iterator UI=setccI->use_begin(), UE=setccI->use_end();
1201 if (! isa<TmpInstruction>(*UI) // ignore tmp instructions here
1202 && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
1207 //******************* Externally Visible Functions *************************/
1209 //------------------------------------------------------------------------
1210 // External Function: ThisIsAChainRule
1213 // Check if a given BURG rule is a chain rule.
1214 //------------------------------------------------------------------------
1217 ThisIsAChainRule(int eruleno)
1221 case 111: // stmt: reg
1245 return false; break;
1250 //------------------------------------------------------------------------
1251 // External Function: GetInstructionsByRule
1254 // Choose machine instructions for the SPARC according to the
1255 // patterns chosen by the BURG-generated parser.
1256 //------------------------------------------------------------------------
1259 GetInstructionsByRule(InstructionNode* subtreeRoot,
1262 TargetMachine &target,
1263 vector<MachineInstr*>& mvec)
1265 bool checkCast = false; // initialize here to use fall-through
1266 bool maskUnsignedResult = false;
1268 int forwardOperandNum = -1;
1269 unsigned int allocaSize = 0;
1270 MachineInstr* M, *M2;
1275 // If the code for this instruction was folded into the parent (user),
1277 if (subtreeRoot->isFoldedIntoParent())
1281 // Let's check for chain rules outside the switch so that we don't have
1282 // to duplicate the list of chain rule production numbers here again
1284 if (ThisIsAChainRule(ruleForNode))
1286 // Chain rules have a single nonterminal on the RHS.
1287 // Get the rule that matches the RHS non-terminal and use that instead.
1289 assert(nts[0] && ! nts[1]
1290 && "A chain rule should have only one RHS non-terminal!");
1291 nextRule = burm_rule(subtreeRoot->state, nts[0]);
1292 nts = burm_nts[nextRule];
1293 GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
1297 switch(ruleForNode) {
1298 case 1: // stmt: Ret
1299 case 2: // stmt: RetValue(reg)
1300 { // NOTE: Prepass of register allocation is responsible
1301 // for moving return value to appropriate register.
1302 // Mark the return-address register as a hidden virtual reg.
1303 // Mark the return value register as an implicit ref of
1304 // the machine instruction.
1305 // Finally put a NOP in the delay slot.
1306 ReturnInst *returnInstr =
1307 cast<ReturnInst>(subtreeRoot->getInstruction());
1308 assert(returnInstr->getOpcode() == Instruction::Ret);
1310 Instruction* returnReg = new TmpInstruction(returnInstr);
1311 MachineCodeForInstruction::get(returnInstr).addTemp(returnReg);
1313 M = new MachineInstr(JMPLRET);
1314 M->SetMachineOperandReg(0, MachineOperand::MO_VirtualRegister,
1316 M->SetMachineOperandConst(1,MachineOperand::MO_SignExtendedImmed,
1318 M->SetMachineOperandReg(2, target.getRegInfo().getZeroRegNum());
1320 if (returnInstr->getReturnValue() != NULL)
1321 M->addImplicitRef(returnInstr->getReturnValue());
1324 mvec.push_back(new MachineInstr(NOP));
1329 case 3: // stmt: Store(reg,reg)
1330 case 4: // stmt: Store(reg,ptrreg)
1331 mvec.push_back(new MachineInstr(
1332 ChooseStoreInstruction(
1333 subtreeRoot->leftChild()->getValue()->getType())));
1334 SetOperandsForMemInstr(mvec, mvec.end()-1, subtreeRoot, target);
1337 case 5: // stmt: BrUncond
1338 M = new MachineInstr(BA);
1339 M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1340 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(0));
1344 mvec.push_back(new MachineInstr(NOP));
1347 case 206: // stmt: BrCond(setCCconst)
1348 { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
1349 // If the constant is ZERO, we can use the branch-on-integer-register
1350 // instructions and avoid the SUBcc instruction entirely.
1351 // Otherwise this is just the same as case 5, so just fall through.
1353 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
1355 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
1356 Constant *constVal = cast<Constant>(constNode->getValue());
1359 if ((constVal->getType()->isIntegral()
1360 || isa<PointerType>(constVal->getType()))
1361 && GetConstantValueAsSignedInt(constVal, isValidConst) == 0
1364 // That constant is a zero after all...
1365 // Use the left child of setCC as the first argument!
1366 // Mark the setCC node so that no code is generated for it.
1367 InstructionNode* setCCNode = (InstructionNode*)
1368 subtreeRoot->leftChild();
1369 assert(setCCNode->getOpLabel() == SetCCOp);
1370 setCCNode->markFoldedIntoParent();
1372 BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
1374 M = new MachineInstr(ChooseBprInstruction(subtreeRoot));
1375 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1376 setCCNode->leftChild()->getValue());
1377 M->SetMachineOperandVal(1, MachineOperand::MO_PCRelativeDisp,
1378 brInst->getSuccessor(0));
1382 mvec.push_back(new MachineInstr(NOP));
1385 M = new MachineInstr(BA);
1386 M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1387 brInst->getSuccessor(1));
1391 mvec.push_back(new MachineInstr(NOP));
1395 // ELSE FALL THROUGH
1398 case 6: // stmt: BrCond(setCC)
1399 { // bool => boolean was computed with SetCC.
1400 // The branch to use depends on whether it is FP, signed, or unsigned.
1401 // If it is an integer CC, we also need to find the unique
1402 // TmpInstruction representing that CC.
1404 BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
1406 M = new MachineInstr(ChooseBccInstruction(subtreeRoot, isFPBranch));
1408 Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
1409 brInst->getParent()->getParent(),
1410 isFPBranch? Type::FloatTy : Type::IntTy);
1412 M->SetMachineOperandVal(0, MachineOperand::MO_CCRegister, ccValue);
1413 M->SetMachineOperandVal(1, MachineOperand::MO_PCRelativeDisp,
1414 brInst->getSuccessor(0));
1418 mvec.push_back(new MachineInstr(NOP));
1421 M = new MachineInstr(BA);
1422 M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1423 brInst->getSuccessor(1));
1427 mvec.push_back(new MachineInstr(NOP));
1431 case 208: // stmt: BrCond(boolconst)
1433 // boolconst => boolean is a constant; use BA to first or second label
1434 Constant* constVal =
1435 cast<Constant>(subtreeRoot->leftChild()->getValue());
1436 unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
1438 M = new MachineInstr(BA);
1439 M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1440 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
1444 mvec.push_back(new MachineInstr(NOP));
1448 case 8: // stmt: BrCond(boolreg)
1449 { // boolreg => boolean is stored in an existing register.
1450 // Just use the branch-on-integer-register instruction!
1452 M = new MachineInstr(BRNZ);
1453 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1454 subtreeRoot->leftChild()->getValue());
1455 M->SetMachineOperandVal(1, MachineOperand::MO_PCRelativeDisp,
1456 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(0));
1460 mvec.push_back(new MachineInstr(NOP));
1463 M = new MachineInstr(BA);
1464 M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
1465 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(1));
1469 mvec.push_back(new MachineInstr(NOP));
1473 case 9: // stmt: Switch(reg)
1474 assert(0 && "*** SWITCH instruction is not implemented yet.");
1477 case 10: // reg: VRegList(reg, reg)
1478 assert(0 && "VRegList should never be the topmost non-chain rule");
1481 case 21: // bool: Not(bool,reg): Both these are implemented as:
1482 case 421: // reg: BNot(reg,reg): reg = reg XOR-NOT 0
1483 { // First find the unary operand. It may be left or right, usually right.
1484 Value* notArg = BinaryOperator::getNotArgument(
1485 cast<BinaryOperator>(subtreeRoot->getInstruction()));
1486 mvec.push_back(Create3OperandInstr_Reg(XNOR, notArg,
1487 target.getRegInfo().getZeroRegNum(),
1488 subtreeRoot->getValue()));
1492 case 22: // reg: ToBoolTy(reg):
1494 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1495 assert(opType->isIntegral() || isa<PointerType>(opType)
1496 || opType == Type::BoolTy);
1497 forwardOperandNum = 0; // forward first operand to user
1501 case 23: // reg: ToUByteTy(reg)
1502 case 25: // reg: ToUShortTy(reg)
1503 case 27: // reg: ToUIntTy(reg)
1504 case 29: // reg: ToULongTy(reg)
1506 Instruction* destI = subtreeRoot->getInstruction();
1507 Value* opVal = subtreeRoot->leftChild()->getValue();
1508 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
1509 if (opType->isIntegral()
1510 || isa<PointerType>(opType)
1511 || opType == Type::BoolTy)
1513 unsigned opSize = target.DataLayout.getTypeSize(opType);
1514 unsigned destSize = target.DataLayout.getTypeSize(destI->getType());
1515 if (opSize > destSize ||
1517 && destSize < target.DataLayout.getIntegerRegize()))
1518 { // operand is larger than dest,
1519 // OR both are equal but smaller than the full register size
1520 // AND operand is signed, so it may have extra sign bits:
1521 // mask high bits using AND
1522 M = Create3OperandInstr(AND, opVal,
1523 ConstantUInt::get(Type::ULongTy,
1524 ((uint64_t) 1 << 8*destSize) - 1),
1529 forwardOperandNum = 0; // forward first operand to user
1531 else if (opType->isFloatingPoint())
1532 CreateCodeToConvertIntToFloat(target, opVal, destI, mvec,
1533 MachineCodeForInstruction::get(destI));
1535 assert(0 && "Unrecognized operand type for convert-to-unsigned");
1540 case 24: // reg: ToSByteTy(reg)
1541 case 26: // reg: ToShortTy(reg)
1542 case 28: // reg: ToIntTy(reg)
1543 case 30: // reg: ToLongTy(reg)
1545 Instruction* destI = subtreeRoot->getInstruction();
1546 Value* opVal = subtreeRoot->leftChild()->getValue();
1547 MachineCodeForInstruction& mcfi =MachineCodeForInstruction::get(destI);
1549 const Type* opType = opVal->getType();
1550 if (opType->isIntegral()
1551 || isa<PointerType>(opType)
1552 || opType == Type::BoolTy)
1554 // These operand types have the same format as the destination,
1555 // but may have different size: add sign bits or mask as needed.
1557 const Type* destType = destI->getType();
1558 unsigned opSize = target.DataLayout.getTypeSize(opType);
1559 unsigned destSize = target.DataLayout.getTypeSize(destType);
1561 if (opSize < destSize ||
1562 (opSize == destSize &&
1563 opSize == target.DataLayout.getIntegerRegize()))
1564 { // operand is smaller or both operand and result fill register
1565 forwardOperandNum = 0; // forward first operand to user
1568 { // need to mask (possibly) and then sign-extend (definitely)
1569 Value* srcForSignExt = opVal;
1570 unsigned srcSizeForSignExt = 8 * opSize;
1571 if (opSize > destSize)
1572 { // operand is larger than dest: mask high bits
1573 TmpInstruction *tmpI = new TmpInstruction(destType, opVal,
1576 M = Create3OperandInstr(AND, opVal,
1577 ConstantUInt::get(Type::ULongTy,
1578 ((uint64_t) 1 << 8*destSize)-1),
1581 srcForSignExt = tmpI;
1582 srcSizeForSignExt = 8 * destSize;
1586 target.getInstrInfo().CreateSignExtensionInstructions(target, destI->getParent()->getParent(), srcForSignExt, srcSizeForSignExt, destI, mvec, mcfi);
1589 else if (opType->isFloatingPoint())
1590 CreateCodeToConvertIntToFloat(target, opVal, destI, mvec, mcfi);
1592 assert(0 && "Unrecognized operand type for convert-to-signed");
1597 case 31: // reg: ToFloatTy(reg):
1598 case 32: // reg: ToDoubleTy(reg):
1599 case 232: // reg: ToDoubleTy(Constant):
1601 // If this instruction has a parent (a user) in the tree
1602 // and the user is translated as an FsMULd instruction,
1603 // then the cast is unnecessary. So check that first.
1604 // In the future, we'll want to do the same for the FdMULq instruction,
1605 // so do the check here instead of only for ToFloatTy(reg).
1607 if (subtreeRoot->parent() != NULL &&
1608 MachineCodeForInstruction::get(((InstructionNode*)subtreeRoot->parent())->getInstruction())[0]->getOpCode() == FSMULD)
1610 forwardOperandNum = 0; // forward first operand to user
1614 Value* leftVal = subtreeRoot->leftChild()->getValue();
1615 const Type* opType = leftVal->getType();
1616 MachineOpCode opCode=ChooseConvertToFloatInstr(
1617 subtreeRoot->getOpLabel(), opType);
1618 if (opCode == INVALID_OPCODE) // no conversion needed
1620 forwardOperandNum = 0; // forward first operand to user
1624 // If the source operand is a non-FP type it must be
1625 // first copied from int to float register via memory!
1626 Instruction *dest = subtreeRoot->getInstruction();
1629 if (! opType->isFloatingPoint())
1631 // Create a temporary to represent the FP register
1632 // into which the integer will be copied via memory.
1633 // The type of this temporary will determine the FP
1634 // register used: single-prec for a 32-bit int or smaller,
1635 // double-prec for a 64-bit int.
1637 const Type* srcTypeToUse =
1638 (leftVal->getType() == Type::LongTy)? Type::DoubleTy
1641 srcForCast = new TmpInstruction(srcTypeToUse, dest);
1642 MachineCodeForInstruction &destMCFI =
1643 MachineCodeForInstruction::get(dest);
1644 destMCFI.addTemp(srcForCast);
1646 target.getInstrInfo().CreateCodeToCopyIntToFloat(target,
1647 dest->getParent()->getParent(),
1648 leftVal, (TmpInstruction*) srcForCast,
1652 srcForCast = leftVal;
1654 M = new MachineInstr(opCode);
1655 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
1657 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,
1664 case 19: // reg: ToArrayTy(reg):
1665 case 20: // reg: ToPointerTy(reg):
1666 forwardOperandNum = 0; // forward first operand to user
1669 case 233: // reg: Add(reg, Constant)
1670 maskUnsignedResult = true;
1671 M = CreateAddConstInstruction(subtreeRoot);
1677 // ELSE FALL THROUGH
1679 case 33: // reg: Add(reg, reg)
1680 maskUnsignedResult = true;
1681 mvec.push_back(new MachineInstr(ChooseAddInstruction(subtreeRoot)));
1682 Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1685 case 234: // reg: Sub(reg, Constant)
1686 maskUnsignedResult = true;
1687 M = CreateSubConstInstruction(subtreeRoot);
1693 // ELSE FALL THROUGH
1695 case 34: // reg: Sub(reg, reg)
1696 maskUnsignedResult = true;
1697 mvec.push_back(new MachineInstr(ChooseSubInstructionByType(
1698 subtreeRoot->getInstruction()->getType())));
1699 Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1702 case 135: // reg: Mul(todouble, todouble)
1706 case 35: // reg: Mul(reg, reg)
1708 maskUnsignedResult = true;
1709 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
1711 : INVALID_MACHINE_OPCODE);
1712 Instruction* mulInstr = subtreeRoot->getInstruction();
1713 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
1714 subtreeRoot->leftChild()->getValue(),
1715 subtreeRoot->rightChild()->getValue(),
1717 MachineCodeForInstruction::get(mulInstr),forceOp);
1720 case 335: // reg: Mul(todouble, todoubleConst)
1724 case 235: // reg: Mul(reg, Constant)
1726 maskUnsignedResult = true;
1727 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
1729 : INVALID_MACHINE_OPCODE);
1730 Instruction* mulInstr = subtreeRoot->getInstruction();
1731 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
1732 subtreeRoot->leftChild()->getValue(),
1733 subtreeRoot->rightChild()->getValue(),
1735 MachineCodeForInstruction::get(mulInstr),
1739 case 236: // reg: Div(reg, Constant)
1740 maskUnsignedResult = true;
1742 CreateDivConstInstruction(target, subtreeRoot, mvec);
1743 if (mvec.size() > L)
1745 // ELSE FALL THROUGH
1747 case 36: // reg: Div(reg, reg)
1748 maskUnsignedResult = true;
1749 mvec.push_back(new MachineInstr(ChooseDivInstruction(target, subtreeRoot)));
1750 Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1753 case 37: // reg: Rem(reg, reg)
1754 case 237: // reg: Rem(reg, Constant)
1756 maskUnsignedResult = true;
1757 Instruction* remInstr = subtreeRoot->getInstruction();
1759 TmpInstruction* quot = new TmpInstruction(
1760 subtreeRoot->leftChild()->getValue(),
1761 subtreeRoot->rightChild()->getValue());
1762 TmpInstruction* prod = new TmpInstruction(
1764 subtreeRoot->rightChild()->getValue());
1765 MachineCodeForInstruction::get(remInstr).addTemp(quot).addTemp(prod);
1767 M = new MachineInstr(ChooseDivInstruction(target, subtreeRoot));
1768 Set3OperandsFromInstr(M, subtreeRoot, target);
1769 M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,quot);
1772 M = Create3OperandInstr(ChooseMulInstructionByType(
1773 subtreeRoot->getInstruction()->getType()),
1774 quot, subtreeRoot->rightChild()->getValue(),
1778 M = new MachineInstr(ChooseSubInstructionByType(
1779 subtreeRoot->getInstruction()->getType()));
1780 Set3OperandsFromInstr(M, subtreeRoot, target);
1781 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,prod);
1787 case 38: // bool: And(bool, bool)
1788 case 238: // bool: And(bool, boolconst)
1789 case 338: // reg : BAnd(reg, reg)
1790 case 538: // reg : BAnd(reg, Constant)
1791 mvec.push_back(new MachineInstr(AND));
1792 Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1795 case 138: // bool: And(bool, not)
1796 case 438: // bool: BAnd(bool, bnot)
1797 { // Use the argument of NOT as the second argument!
1798 // Mark the NOT node so that no code is generated for it.
1799 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
1800 Value* notArg = BinaryOperator::getNotArgument(
1801 cast<BinaryOperator>(notNode->getInstruction()));
1802 notNode->markFoldedIntoParent();
1803 mvec.push_back(Create3OperandInstr(ANDN,
1804 subtreeRoot->leftChild()->getValue(),
1805 notArg, subtreeRoot->getValue()));
1809 case 39: // bool: Or(bool, bool)
1810 case 239: // bool: Or(bool, boolconst)
1811 case 339: // reg : BOr(reg, reg)
1812 case 539: // reg : BOr(reg, Constant)
1813 mvec.push_back(new MachineInstr(OR));
1814 Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1817 case 139: // bool: Or(bool, not)
1818 case 439: // bool: BOr(bool, bnot)
1819 { // Use the argument of NOT as the second argument!
1820 // Mark the NOT node so that no code is generated for it.
1821 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
1822 Value* notArg = BinaryOperator::getNotArgument(
1823 cast<BinaryOperator>(notNode->getInstruction()));
1824 notNode->markFoldedIntoParent();
1825 mvec.push_back(Create3OperandInstr(ORN,
1826 subtreeRoot->leftChild()->getValue(),
1827 notArg, subtreeRoot->getValue()));
1831 case 40: // bool: Xor(bool, bool)
1832 case 240: // bool: Xor(bool, boolconst)
1833 case 340: // reg : BXor(reg, reg)
1834 case 540: // reg : BXor(reg, Constant)
1835 mvec.push_back(new MachineInstr(XOR));
1836 Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
1839 case 140: // bool: Xor(bool, not)
1840 case 440: // bool: BXor(bool, bnot)
1841 { // Use the argument of NOT as the second argument!
1842 // Mark the NOT node so that no code is generated for it.
1843 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
1844 Value* notArg = BinaryOperator::getNotArgument(
1845 cast<BinaryOperator>(notNode->getInstruction()));
1846 notNode->markFoldedIntoParent();
1847 mvec.push_back(Create3OperandInstr(XNOR,
1848 subtreeRoot->leftChild()->getValue(),
1849 notArg, subtreeRoot->getValue()));
1853 case 41: // boolconst: SetCC(reg, Constant)
1855 // If the SetCC was folded into the user (parent), it will be
1856 // caught above. All other cases are the same as case 42,
1857 // so just fall through.
1859 case 42: // bool: SetCC(reg, reg):
1861 // This generates a SUBCC instruction, putting the difference in
1862 // a result register, and setting a condition code.
1864 // If the boolean result of the SetCC is used by anything other
1865 // than a branch instruction, or if it is used outside the current
1866 // basic block, the boolean must be
1867 // computed and stored in the result register. Otherwise, discard
1868 // the difference (by using %g0) and keep only the condition code.
1870 // To compute the boolean result in a register we use a conditional
1871 // move, unless the result of the SUBCC instruction can be used as
1872 // the bool! This assumes that zero is FALSE and any non-zero
1875 InstructionNode* parentNode = (InstructionNode*) subtreeRoot->parent();
1876 Instruction* setCCInstr = subtreeRoot->getInstruction();
1878 bool keepBoolVal = parentNode == NULL ||
1879 ! AllUsesAreBranches(setCCInstr);
1880 bool subValIsBoolVal = setCCInstr->getOpcode() == Instruction::SetNE;
1881 bool keepSubVal = keepBoolVal && subValIsBoolVal;
1882 bool computeBoolVal = keepBoolVal && ! subValIsBoolVal;
1886 MachineOpCode movOpCode = 0;
1888 // Mark the 4th operand as being a CC register, and as a def
1889 // A TmpInstruction is created to represent the CC "result".
1890 // Unlike other instances of TmpInstruction, this one is used
1891 // by machine code of multiple LLVM instructions, viz.,
1892 // the SetCC and the branch. Make sure to get the same one!
1893 // Note that we do this even for FP CC registers even though they
1894 // are explicit operands, because the type of the operand
1895 // needs to be a floating point condition code, not an integer
1896 // condition code. Think of this as casting the bool result to
1897 // a FP condition code register.
1899 Value* leftVal = subtreeRoot->leftChild()->getValue();
1900 bool isFPCompare = leftVal->getType()->isFloatingPoint();
1902 TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
1903 setCCInstr->getParent()->getParent(),
1904 isFPCompare ? Type::FloatTy : Type::IntTy);
1905 MachineCodeForInstruction::get(setCCInstr).addTemp(tmpForCC);
1909 // Integer condition: dest. should be %g0 or an integer register.
1910 // If result must be saved but condition is not SetEQ then we need
1911 // a separate instruction to compute the bool result, so discard
1912 // result of SUBcc instruction anyway.
1914 M = new MachineInstr(SUBcc);
1915 Set3OperandsFromInstr(M, subtreeRoot, target, ! keepSubVal);
1916 M->SetMachineOperandVal(3, MachineOperand::MO_CCRegister,
1917 tmpForCC, /*def*/true);
1921 { // recompute bool using the integer condition codes
1923 ChooseMovpccAfterSub(subtreeRoot,mustClearReg,valueToMove);
1928 // FP condition: dest of FCMP should be some FCCn register
1929 M = new MachineInstr(ChooseFcmpInstruction(subtreeRoot));
1930 M->SetMachineOperandVal(0, MachineOperand::MO_CCRegister,
1932 M->SetMachineOperandVal(1,MachineOperand::MO_VirtualRegister,
1933 subtreeRoot->leftChild()->getValue());
1934 M->SetMachineOperandVal(2,MachineOperand::MO_VirtualRegister,
1935 subtreeRoot->rightChild()->getValue());
1939 {// recompute bool using the FP condition codes
1940 mustClearReg = true;
1942 movOpCode = ChooseMovFpccInstruction(subtreeRoot);
1949 {// Unconditionally set register to 0
1950 M = new MachineInstr(SETHI);
1951 M->SetMachineOperandConst(0,MachineOperand::MO_UnextendedImmed,
1953 M->SetMachineOperandVal(1, MachineOperand::MO_VirtualRegister,
1958 // Now conditionally move `valueToMove' (0 or 1) into the register
1959 // Mark the register as a use (as well as a def) because the old
1960 // value should be retained if the condition is false.
1961 M = new MachineInstr(movOpCode);
1962 M->SetMachineOperandVal(0, MachineOperand::MO_CCRegister,
1964 M->SetMachineOperandConst(1, MachineOperand::MO_UnextendedImmed,
1966 M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
1967 setCCInstr, /*isDef*/ true,
1968 /*isDefAndUse*/ true);
1974 case 51: // reg: Load(reg)
1975 case 52: // reg: Load(ptrreg)
1976 case 53: // reg: LoadIdx(reg,reg)
1977 case 54: // reg: LoadIdx(ptrreg,reg)
1978 mvec.push_back(new MachineInstr(ChooseLoadInstruction(
1979 subtreeRoot->getValue()->getType())));
1980 SetOperandsForMemInstr(mvec, mvec.end()-1, subtreeRoot, target);
1983 case 55: // reg: GetElemPtr(reg)
1984 case 56: // reg: GetElemPtrIdx(reg,reg)
1985 // If the GetElemPtr was folded into the user (parent), it will be
1986 // caught above. For other cases, we have to compute the address.
1987 mvec.push_back(new MachineInstr(ADD));
1988 SetOperandsForMemInstr(mvec, mvec.end()-1, subtreeRoot, target);
1991 case 57: // reg: Alloca: Implement as 1 instruction:
1992 { // add %fp, offsetFromFP -> result
1993 AllocationInst* instr =
1994 cast<AllocationInst>(subtreeRoot->getInstruction());
1995 unsigned int tsize =
1996 target.findOptimalStorageSize(instr->getAllocatedType());
1998 CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
2002 case 58: // reg: Alloca(reg): Implement as 3 instructions:
2003 // mul num, typeSz -> tmp
2004 // sub %sp, tmp -> %sp
2005 { // add %sp, frameSizeBelowDynamicArea -> result
2006 AllocationInst* instr =
2007 cast<AllocationInst>(subtreeRoot->getInstruction());
2008 const Type* eltType = instr->getAllocatedType();
2010 // If #elements is constant, use simpler code for fixed-size allocas
2011 int tsize = (int) target.findOptimalStorageSize(eltType);
2012 Value* numElementsVal = NULL;
2013 bool isArray = instr->isArrayAllocation();
2016 isa<Constant>(numElementsVal = instr->getArraySize()))
2017 { // total size is constant: generate code for fixed-size alloca
2018 unsigned int numElements = isArray?
2019 cast<ConstantUInt>(numElementsVal)->getValue() : 1;
2020 CreateCodeForFixedSizeAlloca(target, instr, tsize,
2023 else // total size is not constant.
2024 CreateCodeForVariableSizeAlloca(target, instr, tsize,
2025 numElementsVal, mvec);
2029 case 61: // reg: Call
2030 { // Generate a direct (CALL) or indirect (JMPL). depending
2031 // Mark the return-address register and the indirection
2032 // register (if any) as hidden virtual registers.
2033 // Also, mark the operands of the Call and return value (if
2034 // any) as implicit operands of the CALL machine instruction.
2036 // If this is a varargs function, floating point arguments
2037 // have to passed in integer registers so insert
2038 // copy-float-to-int instructions for each float operand.
2040 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
2041 Value *callee = callInstr->getCalledValue();
2043 // Create hidden virtual register for return address, with type void*.
2044 TmpInstruction* retAddrReg =
2045 new TmpInstruction(PointerType::get(Type::VoidTy), callInstr);
2046 MachineCodeForInstruction::get(callInstr).addTemp(retAddrReg);
2048 // Generate the machine instruction and its operands.
2049 // Use CALL for direct function calls; this optimistically assumes
2050 // the PC-relative address fits in the CALL address field (22 bits).
2051 // Use JMPL for indirect calls.
2053 if (isa<Function>(callee))
2054 { // direct function call
2055 M = new MachineInstr(CALL);
2056 M->SetMachineOperandVal(0, MachineOperand::MO_PCRelativeDisp,
2060 { // indirect function call
2061 M = new MachineInstr(JMPLCALL);
2062 M->SetMachineOperandVal(0, MachineOperand::MO_VirtualRegister,
2064 M->SetMachineOperandConst(1, MachineOperand::MO_SignExtendedImmed,
2066 M->SetMachineOperandVal(2, MachineOperand::MO_VirtualRegister,
2072 const FunctionType* funcType =
2073 cast<FunctionType>(cast<PointerType>(callee->getType())
2074 ->getElementType());
2075 bool isVarArgs = funcType->isVarArg();
2076 bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
2078 // Use an annotation to pass information about call arguments
2079 // to the register allocator.
2080 CallArgsDescriptor* argDesc = new CallArgsDescriptor(callInstr,
2081 retAddrReg, isVarArgs, noPrototype);
2082 M->addAnnotation(argDesc);
2084 assert(callInstr->getOperand(0) == callee
2085 && "This is assumed in the loop below!");
2087 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i)
2089 Value* argVal = callInstr->getOperand(i);
2090 Instruction* intArgReg = NULL;
2092 // Check for FP arguments to varargs functions.
2093 // Any such argument in the first $K$ args must be passed in an
2094 // integer register, where K = #integer argument registers.
2095 if (isVarArgs && argVal->getType()->isFloatingPoint())
2097 // If it is a function with no prototype, pass value
2098 // as an FP value as well as a varargs value
2100 argDesc->getArgInfo(i-1).setUseFPArgReg();
2102 // If this arg. is in the first $K$ regs, add a copy
2103 // float-to-int instruction to pass the value as an integer.
2104 if (i < target.getRegInfo().GetNumOfIntArgRegs())
2106 MachineCodeForInstruction &destMCFI =
2107 MachineCodeForInstruction::get(callInstr);
2108 intArgReg = new TmpInstruction(Type::IntTy, argVal);
2109 destMCFI.addTemp(intArgReg);
2111 vector<MachineInstr*> copyMvec;
2112 target.getInstrInfo().CreateCodeToCopyFloatToInt(target,
2113 callInstr->getParent()->getParent(),
2114 argVal, (TmpInstruction*) intArgReg,
2115 copyMvec, destMCFI);
2116 mvec.insert(mvec.begin(),copyMvec.begin(),copyMvec.end());
2118 argDesc->getArgInfo(i-1).setUseIntArgReg();
2119 argDesc->getArgInfo(i-1).setArgCopy(intArgReg);
2122 // Cannot fit in first $K$ regs so pass the arg on the stack
2123 argDesc->getArgInfo(i-1).setUseStackSlot();
2127 mvec.back()->addImplicitRef(intArgReg);
2129 mvec.back()->addImplicitRef(argVal);
2132 // Add the return value as an implicit ref. The call operands
2133 // were added above.
2134 if (callInstr->getType() != Type::VoidTy)
2135 mvec.back()->addImplicitRef(callInstr, /*isDef*/ true);
2137 // For the CALL instruction, the ret. addr. reg. is also implicit
2138 if (isa<Function>(callee))
2139 mvec.back()->addImplicitRef(retAddrReg, /*isDef*/ true);
2142 mvec.push_back(new MachineInstr(NOP));
2146 case 62: // reg: Shl(reg, reg)
2148 Value* argVal1 = subtreeRoot->leftChild()->getValue();
2149 Value* argVal2 = subtreeRoot->rightChild()->getValue();
2150 Instruction* shlInstr = subtreeRoot->getInstruction();
2152 const Type* opType = argVal1->getType();
2153 assert(opType->isIntegral()
2154 || opType == Type::BoolTy
2155 || isa<PointerType>(opType)&&"Shl unsupported for other types");
2157 CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
2158 (opType == Type::LongTy)? SLLX : SLL,
2159 argVal1, argVal2, 0, shlInstr, mvec,
2160 MachineCodeForInstruction::get(shlInstr));
2164 case 63: // reg: Shr(reg, reg)
2165 { const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
2166 assert(opType->isIntegral()
2167 || isa<PointerType>(opType)&&"Shr unsupported for other types");
2168 mvec.push_back(new MachineInstr((opType->isSigned()
2169 ? ((opType == Type::LongTy)? SRAX : SRA)
2170 : ((opType == Type::LongTy)? SRLX : SRL))));
2171 Set3OperandsFromInstr(mvec.back(), subtreeRoot, target);
2175 case 64: // reg: Phi(reg,reg)
2176 break; // don't forward the value
2178 case 71: // reg: VReg
2179 case 72: // reg: Constant
2180 break; // don't forward the value
2183 assert(0 && "Unrecognized BURG rule");
2188 if (forwardOperandNum >= 0)
2189 { // We did not generate a machine instruction but need to use operand.
2190 // If user is in the same tree, replace Value in its machine operand.
2191 // If not, insert a copy instruction which should get coalesced away
2192 // by register allocation.
2193 if (subtreeRoot->parent() != NULL)
2194 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
2197 vector<MachineInstr*> minstrVec;
2198 Instruction* instr = subtreeRoot->getInstruction();
2199 target.getInstrInfo().
2200 CreateCopyInstructionsByType(target,
2201 instr->getParent()->getParent(),
2202 instr->getOperand(forwardOperandNum),
2204 MachineCodeForInstruction::get(instr));
2205 assert(minstrVec.size() > 0);
2206 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
2210 if (maskUnsignedResult)
2211 { // If result is unsigned and smaller than int reg size,
2212 // we need to clear high bits of result value.
2213 assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
2214 Instruction* dest = subtreeRoot->getInstruction();
2215 if (! dest->getType()->isSigned())
2217 unsigned destSize = target.DataLayout.getTypeSize(dest->getType());
2218 if (destSize < target.DataLayout.getIntegerRegize())
2219 { // Mask high bits. Use a TmpInstruction to represent the
2220 // intermediate result before masking. Since those instructions
2221 // have already been generated, go back and substitute tmpI
2222 // for dest in the result position of each one of them.
2223 TmpInstruction *tmpI = new TmpInstruction(dest->getType(), dest,
2225 MachineCodeForInstruction::get(dest).addTemp(tmpI);
2227 for (unsigned i=0, N=mvec.size(); i < N; ++i)
2228 mvec[i]->substituteValue(dest, tmpI);
2230 M = Create3OperandInstr(AND, tmpI,
2231 ConstantUInt::get(Type::ULongTy,
2232 ((uint64_t) 1 << 8*destSize) - 1),