1 //===- SparcV9BurgISel.cpp - SparcV9 BURG-based Instruction Selector ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // SparcV9 BURG-based instruction selector. It uses the SSA graph to
11 // construct a forest of BURG instruction trees (class InstrForest) and then
12 // uses the BURG-generated tree grammar (BURM) to find the optimal instruction
13 // sequences for the SparcV9.
15 //===----------------------------------------------------------------------===//
17 #include "MachineInstrAnnot.h"
18 #include "SparcV9BurgISel.h"
19 #include "SparcV9InstrForest.h"
20 #include "SparcV9Internals.h"
21 #include "SparcV9TmpInstr.h"
22 #include "SparcV9FrameInfo.h"
23 #include "SparcV9RegisterInfo.h"
24 #include "MachineFunctionInfo.h"
25 #include "llvm/CodeGen/IntrinsicLowering.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/CodeGen/MachineInstrBuilder.h"
30 #include "llvm/Constants.h"
31 #include "llvm/DerivedTypes.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Intrinsics.h"
34 #include "llvm/Module.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CFG.h"
37 #include "llvm/Target/TargetInstrInfo.h"
38 #include "llvm/Target/TargetMachine.h"
39 #include "llvm/Type.h"
40 #include "llvm/Config/alloca.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/LeakDetector.h"
43 #include "llvm/Support/MathExtras.h"
44 #include "llvm/ADT/STLExtras.h"
45 #include "llvm/ADT/hash_map"
51 //==------------------------------------------------------------------------==//
52 // InstrForest (V9ISel BURG instruction trees) implementation
53 //==------------------------------------------------------------------------==//
57 class InstructionNode : public InstrTreeNode {
58 bool codeIsFoldedIntoParent;
61 InstructionNode(Instruction *_instr);
63 Instruction *getInstruction() const {
64 assert(treeNodeType == NTInstructionNode);
65 return cast<Instruction>(val);
68 void markFoldedIntoParent() { codeIsFoldedIntoParent = true; }
69 bool isFoldedIntoParent() { return codeIsFoldedIntoParent; }
71 // Methods to support type inquiry through isa, cast, and dyn_cast:
72 static inline bool classof(const InstructionNode *N) { return true; }
73 static inline bool classof(const InstrTreeNode *N) {
74 return N->getNodeType() == InstrTreeNode::NTInstructionNode;
78 virtual void dumpNode(int indent) const;
81 class VRegListNode : public InstrTreeNode {
83 VRegListNode() : InstrTreeNode(NTVRegListNode, 0) { opLabel = VRegListOp; }
84 // Methods to support type inquiry through isa, cast, and dyn_cast:
85 static inline bool classof(const VRegListNode *N) { return true; }
86 static inline bool classof(const InstrTreeNode *N) {
87 return N->getNodeType() == InstrTreeNode::NTVRegListNode;
90 virtual void dumpNode(int indent) const;
93 class VRegNode : public InstrTreeNode {
95 VRegNode(Value* _val) : InstrTreeNode(NTVRegNode, _val) {
98 // Methods to support type inquiry through isa, cast, and dyn_cast:
99 static inline bool classof(const VRegNode *N) { return true; }
100 static inline bool classof(const InstrTreeNode *N) {
101 return N->getNodeType() == InstrTreeNode::NTVRegNode;
104 virtual void dumpNode(int indent) const;
107 class ConstantNode : public InstrTreeNode {
109 ConstantNode(Constant *constVal)
110 : InstrTreeNode(NTConstNode, (Value*)constVal) {
111 opLabel = ConstantNodeOp;
113 Constant *getConstVal() const { return (Constant*) val;}
114 // Methods to support type inquiry through isa, cast, and dyn_cast:
115 static inline bool classof(const ConstantNode *N) { return true; }
116 static inline bool classof(const InstrTreeNode *N) {
117 return N->getNodeType() == InstrTreeNode::NTConstNode;
120 virtual void dumpNode(int indent) const;
123 class LabelNode : public InstrTreeNode {
125 LabelNode(BasicBlock* BB) : InstrTreeNode(NTLabelNode, (Value*)BB) {
126 opLabel = LabelNodeOp;
128 BasicBlock *getBasicBlock() const { return (BasicBlock*)val;}
129 // Methods to support type inquiry through isa, cast, and dyn_cast:
130 static inline bool classof(const LabelNode *N) { return true; }
131 static inline bool classof(const InstrTreeNode *N) {
132 return N->getNodeType() == InstrTreeNode::NTLabelNode;
135 virtual void dumpNode(int indent) const;
138 /// InstrForest - A forest of instruction trees for a single function.
139 /// The goal of InstrForest is to group instructions into a single
140 /// tree if one or more of them might be potentially combined into a
141 /// single complex instruction in the target machine. We group two
142 /// instructions O and I if: (1) Instruction O computes an operand used
143 /// by instruction I, and (2) O and I are part of the same basic block,
144 /// and (3) O has only a single use, viz., I.
146 class InstrForest : private hash_map<const Instruction *, InstructionNode*> {
148 // Use a vector for the root set to get a deterministic iterator
149 // for stable code generation. Even though we need to erase nodes
150 // during forest construction, a vector should still be efficient
151 // because the elements to erase are nearly always near the end.
152 typedef std::vector<InstructionNode*> RootSet;
153 typedef RootSet:: iterator root_iterator;
154 typedef RootSet::const_iterator const_root_iterator;
160 /*ctor*/ InstrForest (Function *F);
161 /*dtor*/ ~InstrForest ();
163 /// getTreeNodeForInstr - Returns the tree node for an Instruction.
165 inline InstructionNode *getTreeNodeForInstr(Instruction* instr) {
166 return (*this)[instr];
169 /// Iterators for the root nodes for all the trees.
171 const_root_iterator roots_begin() const { return treeRoots.begin(); }
172 root_iterator roots_begin() { return treeRoots.begin(); }
173 const_root_iterator roots_end () const { return treeRoots.end(); }
174 root_iterator roots_end () { return treeRoots.end(); }
179 // Methods used to build the instruction forest.
180 void eraseRoot (InstructionNode* node);
181 void setLeftChild (InstrTreeNode* parent, InstrTreeNode* child);
182 void setRightChild(InstrTreeNode* parent, InstrTreeNode* child);
183 void setParent (InstrTreeNode* child, InstrTreeNode* parent);
184 void noteTreeNodeForInstr(Instruction* instr, InstructionNode* treeNode);
185 InstructionNode* buildTreeForInstruction(Instruction* instr);
188 void InstrTreeNode::dump(int dumpChildren, int indent) const {
193 LeftChild->dump(dumpChildren, indent+1);
195 RightChild->dump(dumpChildren, indent+1);
199 InstructionNode::InstructionNode(Instruction* I)
200 : InstrTreeNode(NTInstructionNode, I), codeIsFoldedIntoParent(false) {
201 opLabel = I->getOpcode();
203 // Distinguish special cases of some instructions such as Ret and Br
205 if (opLabel == Instruction::Ret && cast<ReturnInst>(I)->getReturnValue()) {
206 opLabel = RetValueOp; // ret(value) operation
208 else if (opLabel ==Instruction::Br && !cast<BranchInst>(I)->isUnconditional())
210 opLabel = BrCondOp; // br(cond) operation
211 } else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT) {
212 opLabel = SetCCOp; // common label for all SetCC ops
213 } else if (opLabel == Instruction::Alloca && I->getNumOperands() > 0) {
214 opLabel = AllocaN; // Alloca(ptr, N) operation
215 } else if (opLabel == Instruction::GetElementPtr &&
216 cast<GetElementPtrInst>(I)->hasIndices()) {
217 opLabel = opLabel + 100; // getElem with index vector
218 } else if (opLabel == Instruction::Xor &&
219 BinaryOperator::isNot(I)) {
220 opLabel = (I->getType() == Type::BoolTy)? NotOp // boolean Not operator
221 : BNotOp; // bitwise Not operator
222 } else if (opLabel == Instruction::And || opLabel == Instruction::Or ||
223 opLabel == Instruction::Xor) {
224 // Distinguish bitwise operators from logical operators!
225 if (I->getType() != Type::BoolTy)
226 opLabel = opLabel + 100; // bitwise operator
227 } else if (opLabel == Instruction::Cast) {
228 const Type *ITy = I->getType();
229 switch(ITy->getTypeID())
231 case Type::BoolTyID: opLabel = ToBoolTy; break;
232 case Type::UByteTyID: opLabel = ToUByteTy; break;
233 case Type::SByteTyID: opLabel = ToSByteTy; break;
234 case Type::UShortTyID: opLabel = ToUShortTy; break;
235 case Type::ShortTyID: opLabel = ToShortTy; break;
236 case Type::UIntTyID: opLabel = ToUIntTy; break;
237 case Type::IntTyID: opLabel = ToIntTy; break;
238 case Type::ULongTyID: opLabel = ToULongTy; break;
239 case Type::LongTyID: opLabel = ToLongTy; break;
240 case Type::FloatTyID: opLabel = ToFloatTy; break;
241 case Type::DoubleTyID: opLabel = ToDoubleTy; break;
242 case Type::ArrayTyID: opLabel = ToArrayTy; break;
243 case Type::PointerTyID: opLabel = ToPointerTy; break;
245 // Just use `Cast' opcode otherwise. It's probably ignored.
251 void InstructionNode::dumpNode(int indent) const {
252 for (int i=0; i < indent; i++)
254 std::cerr << getInstruction()->getOpcodeName()
255 << " [label " << getOpLabel() << "]" << "\n";
258 void VRegListNode::dumpNode(int indent) const {
259 for (int i=0; i < indent; i++)
262 std::cerr << "List" << "\n";
265 void VRegNode::dumpNode(int indent) const {
266 for (int i=0; i < indent; i++)
268 std::cerr << "VReg " << *getValue() << "\n";
271 void ConstantNode::dumpNode(int indent) const {
272 for (int i=0; i < indent; i++)
274 std::cerr << "Constant " << *getValue() << "\n";
277 void LabelNode::dumpNode(int indent) const {
278 for (int i=0; i < indent; i++)
281 std::cerr << "Label " << *getValue() << "\n";
284 /// InstrForest ctor - Create a forest of instruction trees for a
287 InstrForest::InstrForest(Function *F) {
288 for (Function::iterator BB = F->begin(), FE = F->end(); BB != FE; ++BB) {
289 for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
290 buildTreeForInstruction(I);
294 InstrForest::~InstrForest() {
295 for_each(treeRoots.begin(), treeRoots.end(), deleter<InstructionNode>);
298 void InstrForest::dump() const {
299 for (const_root_iterator I = roots_begin(); I != roots_end(); ++I)
300 (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
303 inline void InstrForest::eraseRoot(InstructionNode* node) {
304 for (RootSet::reverse_iterator RI=treeRoots.rbegin(), RE=treeRoots.rend();
307 treeRoots.erase(RI.base()-1);
310 inline void InstrForest::noteTreeNodeForInstr(Instruction *instr,
311 InstructionNode *treeNode) {
312 (*this)[instr] = treeNode;
313 treeRoots.push_back(treeNode); // mark node as root of a new tree
316 inline void InstrForest::setLeftChild(InstrTreeNode *parent,
317 InstrTreeNode *child) {
318 parent->LeftChild = child;
319 child->Parent = parent;
320 if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
321 eraseRoot(instrNode); // no longer a tree root
324 inline void InstrForest::setRightChild(InstrTreeNode *parent,
325 InstrTreeNode *child) {
326 parent->RightChild = child;
327 child->Parent = parent;
328 if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
329 eraseRoot(instrNode); // no longer a tree root
332 InstructionNode* InstrForest::buildTreeForInstruction(Instruction *instr) {
333 InstructionNode *treeNode = getTreeNodeForInstr(instr);
335 // treeNode has already been constructed for this instruction
336 assert(treeNode->getInstruction() == instr);
340 // Otherwise, create a new tree node for this instruction.
341 treeNode = new InstructionNode(instr);
342 noteTreeNodeForInstr(instr, treeNode);
344 if (instr->getOpcode() == Instruction::Call) {
345 // Operands of call instruction
349 // If the instruction has more than 2 instruction operands,
350 // then we need to create artificial list nodes to hold them.
351 // (Note that we only count operands that get tree nodes, and not
352 // others such as branch labels for a branch or switch instruction.)
353 // To do this efficiently, we'll walk all operands, build treeNodes
354 // for all appropriate operands and save them in an array. We then
355 // insert children at the end, creating list nodes where needed.
356 // As a performance optimization, allocate a child array only
357 // if a fixed array is too small.
359 InstrTreeNode** childArray = new InstrTreeNode*[instr->getNumOperands()];
361 // Walk the operands of the instruction
362 for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end();
366 // Check if the operand is a data value, not an branch label, type,
367 // method or module. If the operand is an address type (i.e., label
368 // or method) that is used in an non-branching operation, e.g., `add'.
369 // that should be considered a data value.
370 // Check latter condition here just to simplify the next IF.
371 bool includeAddressOperand =
372 (isa<BasicBlock>(operand) || isa<Function>(operand))
373 && !instr->isTerminator();
375 if (includeAddressOperand || isa<Instruction>(operand) ||
376 isa<Constant>(operand) || isa<Argument>(operand)) {
377 // This operand is a data value.
378 // An instruction that computes the incoming value is added as a
379 // child of the current instruction if:
380 // the value has only a single use
381 // AND both instructions are in the same basic block.
382 // AND the current instruction is not a PHI (because the incoming
383 // value is conceptually in a predecessor block,
384 // even though it may be in the same static block)
385 // (Note that if the value has only a single use (viz., `instr'),
386 // the def of the value can be safely moved just before instr
387 // and therefore it is safe to combine these two instructions.)
388 // In all other cases, the virtual register holding the value
389 // is used directly, i.e., made a child of the instruction node.
390 InstrTreeNode* opTreeNode;
391 if (isa<Instruction>(operand) && operand->hasOneUse() &&
392 cast<Instruction>(operand)->getParent() == instr->getParent() &&
393 instr->getOpcode() != Instruction::PHI &&
394 instr->getOpcode() != Instruction::Call) {
395 // Recursively create a treeNode for it.
396 opTreeNode = buildTreeForInstruction((Instruction*)operand);
397 } else if (Constant *CPV = dyn_cast<Constant>(operand)) {
398 if (isa<GlobalValue>(CPV))
399 opTreeNode = new VRegNode(operand);
400 else if (isa<UndefValue>(CPV)) {
402 ConstantNode(Constant::getNullValue(CPV->getType()));
404 // Create a leaf node for a constant
405 opTreeNode = new ConstantNode(CPV);
408 // Create a leaf node for the virtual register
409 opTreeNode = new VRegNode(operand);
412 childArray[numChildren++] = opTreeNode;
416 // Add any selected operands as children in the tree.
417 // Certain instructions can have more than 2 in some instances (viz.,
418 // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
419 // array or struct). Make the operands of every such instruction into
420 // a right-leaning binary tree with the operand nodes at the leaves
421 // and VRegList nodes as internal nodes.
422 InstrTreeNode *parent = treeNode;
424 if (numChildren > 2) {
425 unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
426 assert(instrOpcode == Instruction::PHI ||
427 instrOpcode == Instruction::Call ||
428 instrOpcode == Instruction::Load ||
429 instrOpcode == Instruction::Store ||
430 instrOpcode == Instruction::GetElementPtr);
433 // Insert the first child as a direct child
434 if (numChildren >= 1)
435 setLeftChild(parent, childArray[0]);
439 // Create a list node for children 2 .. N-1, if any
440 for (n = numChildren-1; n >= 2; n--) {
441 // We have more than two children
442 InstrTreeNode *listNode = new VRegListNode();
443 setRightChild(parent, listNode);
444 setLeftChild(listNode, childArray[numChildren - n]);
448 // Now insert the last remaining child (if any).
449 if (numChildren >= 2) {
451 setRightChild(parent, childArray[numChildren - 1]);
454 delete [] childArray;
457 //==------------------------------------------------------------------------==//
458 // V9ISel Command-line options and declarations
459 //==------------------------------------------------------------------------==//
462 /// Allow the user to select the amount of debugging information printed
465 enum SelectDebugLevel_t {
467 Select_PrintMachineCode,
468 Select_DebugInstTrees,
469 Select_DebugBurgTrees,
471 cl::opt<SelectDebugLevel_t>
472 SelectDebugLevel("dselect", cl::Hidden,
473 cl::desc("enable instruction selection debug information"),
475 clEnumValN(Select_NoDebugInfo, "n", "disable debug output"),
476 clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
477 clEnumValN(Select_DebugInstTrees, "i",
478 "print debugging info for instruction selection"),
479 clEnumValN(Select_DebugBurgTrees, "b", "print burg trees"),
483 /// V9ISel - This is the FunctionPass that drives the instruction selection
484 /// process on the SparcV9 target.
486 class V9ISel : public FunctionPass {
487 TargetMachine &Target;
488 void InsertCodeForPhis(Function &F);
489 void InsertPhiElimInstructions(BasicBlock *BB,
490 const std::vector<MachineInstr*>& CpVec);
491 void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
492 void PostprocessMachineCodeForTree(InstructionNode* instrNode,
493 int ruleForNode, short* nts);
495 V9ISel(TargetMachine &TM) : Target(TM) {}
497 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
498 AU.setPreservesCFG();
501 bool runOnFunction(Function &F);
502 virtual const char *getPassName() const {
503 return "SparcV9 BURG Instruction Selector";
509 //==------------------------------------------------------------------------==//
510 // Various V9ISel helper functions
511 //==------------------------------------------------------------------------==//
513 static const uint32_t MAXLO = (1 << 10) - 1; // set bits set by %lo(*)
514 static const uint32_t MAXSIMM = (1 << 12) - 1; // set bits in simm13 field of OR
516 /// ConvertConstantToIntType - Function to get the value of an integral
517 /// constant in the form that must be put into the machine register. The
518 /// specified constant is interpreted as (i.e., converted if necessary to) the
519 /// specified destination type. The result is always returned as an uint64_t,
520 /// since the representation of int64_t and uint64_t are identical. The
521 /// argument can be any known const. isValidConstant is set to true if a valid
522 /// constant was found.
524 uint64_t ConvertConstantToIntType(const TargetMachine &target, const Value *V,
525 const Type *destType, bool &isValidConstant) {
526 isValidConstant = false;
529 if (! destType->isIntegral() && ! isa<PointerType>(destType))
532 if (! isa<Constant>(V) || isa<GlobalValue>(V))
535 // GlobalValue: no conversions needed: get value and return it
536 if (const GlobalValue* GV = dyn_cast<GlobalValue>(V)) {
537 isValidConstant = true; // may be overwritten by recursive call
538 return ConvertConstantToIntType(target, GV, destType, isValidConstant);
541 // ConstantBool: no conversions needed: get value and return it
542 if (const ConstantBool *CB = dyn_cast<ConstantBool>(V)) {
543 isValidConstant = true;
544 return (uint64_t) CB->getValue();
547 // ConstantPointerNull: it's really just a big, shiny version of zero.
548 if (isa<ConstantPointerNull>(V)) {
549 isValidConstant = true;
553 // For other types of constants, some conversion may be needed.
554 // First, extract the constant operand according to its own type
555 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
556 switch(CE->getOpcode()) {
557 case Instruction::Cast: // recursively get the value as cast
558 C = ConvertConstantToIntType(target, CE->getOperand(0), CE->getType(),
561 default: // not simplifying other ConstantExprs
564 else if (const ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
565 isValidConstant = true;
566 C = CI->getRawValue();
567 } else if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
568 isValidConstant = true;
569 double fC = CFP->getValue();
570 C = (destType->isSigned()? (uint64_t) (int64_t) fC
572 } else if (isa<UndefValue>(V)) {
573 isValidConstant = true;
577 // Now if a valid value was found, convert it to destType.
578 if (isValidConstant) {
579 unsigned opSize = target.getTargetData().getTypeSize(V->getType());
580 unsigned destSize = target.getTargetData().getTypeSize(destType);
581 uint64_t maskHi = (destSize < 8)? (1U << 8*destSize) - 1 : ~0;
582 assert(opSize <= 8 && destSize <= 8 && ">8-byte int type unexpected");
584 if (destType->isSigned()) {
585 if (opSize > destSize) // operand is larger than dest:
586 C = C & maskHi; // mask high bits
588 if (opSize > destSize ||
589 (opSize == destSize && ! V->getType()->isSigned()))
590 if (C & (1U << (8*destSize - 1)))
591 C = C | ~maskHi; // sign-extend from destSize to 64 bits
594 if (opSize > destSize || (V->getType()->isSigned() && destSize < 8)) {
595 // operand is larger than dest,
596 // OR both are equal but smaller than the full register size
597 // AND operand is signed, so it may have extra sign bits:
607 /// CreateSETUWConst - Copy a 32-bit unsigned constant into the register
608 /// `dest', using SETHI, OR in the worst case. This function correctly emulates
609 /// the SETUW pseudo-op for SPARC v9 (if argument isSigned == false). The
610 /// isSigned=true case is used to implement SETSW without duplicating code. It
611 /// optimizes some common cases:
612 /// (1) Small value that fits in simm13 field of OR: don't need SETHI.
613 /// (2) isSigned = true and C is a small negative signed value, i.e.,
614 /// high bits are 1, and the remaining bits fit in simm13(OR).
616 CreateSETUWConst(uint32_t C,
617 Instruction* dest, std::vector<MachineInstr*>& mvec,
618 MachineCodeForInstruction& mcfi, Value* val, bool isSigned = false) {
619 MachineInstr *miSETHI = NULL, *miOR = NULL;
621 // In order to get efficient code, we should not generate the SETHI if
622 // all high bits are 1 (i.e., this is a small signed value that fits in
623 // the simm13 field of OR). So we check for and handle that case specially.
624 // NOTE: The value C = 0x80000000 is bad: sC < 0 *and* -sC < 0.
625 // In fact, sC == -sC, so we have to check for this explicitly.
626 int32_t sC = (int32_t) C;
627 bool smallNegValue =isSigned && sC < 0 && sC != -sC && -sC < (int32_t)MAXSIMM;
629 //Create TmpInstruction for intermediate values
630 TmpInstruction *tmpReg = 0;
632 // Set the high 22 bits in dest if non-zero and simm13 field of OR not enough
633 if (!smallNegValue && (C & ~MAXLO) && C > MAXSIMM) {
634 tmpReg = new TmpInstruction(mcfi, PointerType::get(val->getType()), (Instruction*) val);
635 miSETHI = BuildMI(V9::SETHI, 2).addZImm(C).addRegDef(tmpReg);
636 miSETHI->getOperand(0).markHi32();
637 mvec.push_back(miSETHI);
640 // Set the low 10 or 12 bits in dest. This is necessary if no SETHI
641 // was generated, or if the low 10 bits are non-zero.
642 if (miSETHI==NULL || C & MAXLO) {
644 // unsigned value with high-order bits set using SETHI
645 miOR = BuildMI(V9::ORi,3).addReg(tmpReg).addZImm(C).addRegDef(dest);
646 miOR->getOperand(1).markLo32();
648 // unsigned or small signed value that fits in simm13 field of OR
649 assert(smallNegValue || (C & ~MAXSIMM) == 0);
650 miOR = BuildMI(V9::ORi, 3).addMReg(SparcV9::g0)
651 .addSImm(sC).addRegDef(dest);
653 mvec.push_back(miOR);
656 mvec.push_back(BuildMI(V9::ORr,3).addReg(tmpReg).addMReg(SparcV9::g0).addRegDef(dest));
658 assert((miSETHI || miOR) && "Oops, no code was generated!");
661 /// CreateSETSWConst - Set a 32-bit signed constant in the register `dest',
662 /// with sign-extension to 64 bits. This uses SETHI, OR, SRA in the worst case.
663 /// This function correctly emulates the SETSW pseudo-op for SPARC v9. It
664 /// optimizes the same cases as SETUWConst, plus:
665 /// (1) SRA is not needed for positive or small negative values.
668 CreateSETSWConst(int32_t C,
669 Instruction* dest, std::vector<MachineInstr*>& mvec,
670 MachineCodeForInstruction& mcfi, Value* val) {
672 //TmpInstruction for intermediate values
673 TmpInstruction *tmpReg = new TmpInstruction(mcfi, (Instruction*) val);
675 // Set the low 32 bits of dest
676 CreateSETUWConst((uint32_t) C, tmpReg, mvec, mcfi, val, /*isSigned*/true);
678 // Sign-extend to the high 32 bits if needed.
679 // NOTE: The value C = 0x80000000 is bad: -C == C and so -C is < MAXSIMM
680 if (C < 0 && (C == -C || -C > (int32_t) MAXSIMM))
681 mvec.push_back(BuildMI(V9::SRAi5,3).addReg(tmpReg).addZImm(0).addRegDef(dest));
683 mvec.push_back(BuildMI(V9::ORr,3).addReg(tmpReg).addMReg(SparcV9::g0).addRegDef(dest));
686 /// CreateSETXConst - Set a 64-bit signed or unsigned constant in the
687 /// register `dest'. Use SETUWConst for each 32 bit word, plus a
688 /// left-shift-by-32 in between. This function correctly emulates the SETX
689 /// pseudo-op for SPARC v9. It optimizes the same cases as SETUWConst for each
693 CreateSETXConst(uint64_t C,
694 Instruction* tmpReg, Instruction* dest,
695 std::vector<MachineInstr*>& mvec,
696 MachineCodeForInstruction& mcfi, Value* val) {
697 assert(C > (unsigned int) ~0 && "Use SETUW/SETSW for 32-bit values!");
701 // Code to set the upper 32 bits of the value in register `tmpReg'
702 CreateSETUWConst((C >> 32), tmpReg, mvec, mcfi, val);
704 //TmpInstruction for intermediate values
705 TmpInstruction *tmpReg2 = new TmpInstruction(mcfi, (Instruction*) val);
707 // Shift tmpReg left by 32 bits
708 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg).addZImm(32)
709 .addRegDef(tmpReg2));
711 //TmpInstruction for intermediate values
712 TmpInstruction *tmpReg3 = new TmpInstruction(mcfi, (Instruction*) val);
714 // Code to set the low 32 bits of the value in register `dest'
715 CreateSETUWConst(C, tmpReg3, mvec, mcfi, val);
717 // dest = OR(tmpReg, dest)
718 mvec.push_back(BuildMI(V9::ORr,3).addReg(tmpReg3).addReg(tmpReg2).addRegDef(dest));
721 /// CreateSETUWLabel - Set a 32-bit constant (given by a symbolic label) in
722 /// the register `dest'.
725 CreateSETUWLabel(Value* val,
726 Instruction* dest, std::vector<MachineInstr*>& mvec) {
729 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get((Instruction*) val);
730 TmpInstruction* tmpReg = new TmpInstruction(mcfi, val);
732 // Set the high 22 bits in dest
733 MI = BuildMI(V9::SETHI, 2).addReg(val).addRegDef(tmpReg);
734 MI->getOperand(0).markHi32();
737 // Set the low 10 bits in dest
738 MI = BuildMI(V9::ORr, 3).addReg(tmpReg).addReg(val).addRegDef(dest);
739 MI->getOperand(1).markLo32();
743 /// CreateSETXLabel - Set a 64-bit constant (given by a symbolic label) in the
747 CreateSETXLabel(Value* val, Instruction* tmpReg,
748 Instruction* dest, std::vector<MachineInstr*>& mvec,
749 MachineCodeForInstruction& mcfi) {
750 assert(isa<Constant>(val) &&
751 "I only know about constant values and global addresses");
755 MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg);
756 MI->getOperand(0).markHi64();
759 TmpInstruction* tmpReg2 =
760 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
762 MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addPCDisp(val).addRegDef(tmpReg2);
763 MI->getOperand(1).markLo64();
767 TmpInstruction* tmpReg3 =
768 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
770 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg2).addZImm(32)
771 .addRegDef(tmpReg3));
774 TmpInstruction* tmpReg4 =
775 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
776 MI = BuildMI(V9::SETHI, 2).addPCDisp(val).addRegDef(tmpReg4);
777 MI->getOperand(0).markHi32();
780 TmpInstruction* tmpReg5 =
781 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
782 MI = BuildMI(V9::ORr, 3).addReg(tmpReg4).addReg(tmpReg3).addRegDef(tmpReg5);
785 MI = BuildMI(V9::ORi, 3).addReg(tmpReg5).addPCDisp(val).addRegDef(dest);
786 MI->getOperand(1).markLo32();
790 /// CreateUIntSetInstruction - Create code to Set an unsigned constant in the
791 /// register `dest'. Uses CreateSETUWConst, CreateSETSWConst or CreateSETXConst
792 /// as needed. CreateSETSWConst is an optimization for the case that the
793 /// unsigned value has all ones in the 33 high bits (so that sign-extension sets
797 CreateUIntSetInstruction(uint64_t C, Instruction* dest,
798 std::vector<MachineInstr*>& mvec,
799 MachineCodeForInstruction& mcfi, Value* val) {
800 static const uint64_t lo32 = (uint32_t) ~0;
801 if (C <= lo32) // High 32 bits are 0. Set low 32 bits.
802 CreateSETUWConst((uint32_t) C, dest, mvec, mcfi, val);
803 else if ((C & ~lo32) == ~lo32 && (C & (1U << 31))) {
804 // All high 33 (not 32) bits are 1s: sign-extension will take care
805 // of high 32 bits, so use the sequence for signed int
806 CreateSETSWConst((int32_t) C, dest, mvec, mcfi, val);
807 } else if (C > lo32) {
808 // C does not fit in 32 bits
809 TmpInstruction* tmpReg = new TmpInstruction(mcfi, Type::IntTy);
810 CreateSETXConst(C, tmpReg, dest, mvec, mcfi, val);
814 /// CreateIntSetInstruction - Create code to Set a signed constant in the
815 /// register `dest'. Really the same as CreateUIntSetInstruction.
818 CreateIntSetInstruction(int64_t C, Instruction* dest,
819 std::vector<MachineInstr*>& mvec,
820 MachineCodeForInstruction& mcfi, Value* val) {
821 CreateUIntSetInstruction((uint64_t) C, dest, mvec, mcfi, val);
824 /// MaxConstantsTableTy - Table mapping LLVM opcodes to the max. immediate
825 /// constant usable for that operation in the SparcV9 backend. Used by
826 /// ConstantMayNotFitInImmedField().
828 struct MaxConstantsTableTy {
829 // Entry == 0 ==> no immediate constant field exists at all.
830 // Entry > 0 ==> abs(immediate constant) <= Entry
831 std::vector<int> tbl;
833 int getMaxConstantForInstr (unsigned llvmOpCode);
834 MaxConstantsTableTy ();
835 unsigned size() const { return tbl.size (); }
836 int &operator[] (unsigned index) { return tbl[index]; }
839 int MaxConstantsTableTy::getMaxConstantForInstr(unsigned llvmOpCode) {
840 int modelOpCode = -1;
842 if (llvmOpCode >= Instruction::BinaryOpsBegin &&
843 llvmOpCode < Instruction::BinaryOpsEnd)
844 modelOpCode = V9::ADDi;
847 case Instruction::Ret: modelOpCode = V9::JMPLCALLi; break;
849 case Instruction::Malloc:
850 case Instruction::Alloca:
851 case Instruction::GetElementPtr:
852 case Instruction::PHI:
853 case Instruction::Cast:
854 case Instruction::Call: modelOpCode = V9::ADDi; break;
856 case Instruction::Shl:
857 case Instruction::Shr: modelOpCode = V9::SLLXi6; break;
862 return (modelOpCode < 0)? 0: SparcV9MachineInstrDesc[modelOpCode].maxImmedConst;
865 MaxConstantsTableTy::MaxConstantsTableTy () : tbl (Instruction::OtherOpsEnd) {
867 assert(tbl.size() == Instruction::OtherOpsEnd &&
868 "assignments below will be illegal!");
869 for (op = Instruction::TermOpsBegin; op < Instruction::TermOpsEnd; ++op)
870 tbl[op] = getMaxConstantForInstr(op);
871 for (op = Instruction::BinaryOpsBegin; op < Instruction::BinaryOpsEnd; ++op)
872 tbl[op] = getMaxConstantForInstr(op);
873 for (op = Instruction::MemoryOpsBegin; op < Instruction::MemoryOpsEnd; ++op)
874 tbl[op] = getMaxConstantForInstr(op);
875 for (op = Instruction::OtherOpsBegin; op < Instruction::OtherOpsEnd; ++op)
876 tbl[op] = getMaxConstantForInstr(op);
879 bool ConstantMayNotFitInImmedField(const Constant* CV, const Instruction* I) {
880 // The one and only MaxConstantsTable, used only by this function.
881 static MaxConstantsTableTy MaxConstantsTable;
883 if (I->getOpcode() >= MaxConstantsTable.size()) // user-defined op (or bug!)
886 // can always use %g0
887 if (isa<ConstantPointerNull>(CV) || isa<UndefValue>(CV))
890 if (isa<SwitchInst>(I)) // Switch instructions will be lowered!
893 if (const ConstantInt* CI = dyn_cast<ConstantInt>(CV))
894 return labs((int64_t)CI->getRawValue()) > MaxConstantsTable[I->getOpcode()];
896 if (isa<ConstantBool>(CV))
897 return 1 > MaxConstantsTable[I->getOpcode()];
902 /// ChooseLoadInstruction - Return the appropriate load instruction opcode
903 /// based on the given LLVM value type.
905 static inline MachineOpCode ChooseLoadInstruction(const Type *DestTy) {
906 switch (DestTy->getTypeID()) {
908 case Type::UByteTyID: return V9::LDUBr;
909 case Type::SByteTyID: return V9::LDSBr;
910 case Type::UShortTyID: return V9::LDUHr;
911 case Type::ShortTyID: return V9::LDSHr;
912 case Type::UIntTyID: return V9::LDUWr;
913 case Type::IntTyID: return V9::LDSWr;
914 case Type::PointerTyID:
915 case Type::ULongTyID:
916 case Type::LongTyID: return V9::LDXr;
917 case Type::FloatTyID: return V9::LDFr;
918 case Type::DoubleTyID: return V9::LDDFr;
919 default: assert(0 && "Invalid type for Load instruction");
924 /// ChooseStoreInstruction - Return the appropriate store instruction opcode
925 /// based on the given LLVM value type.
927 static inline MachineOpCode ChooseStoreInstruction(const Type *DestTy) {
928 switch (DestTy->getTypeID()) {
930 case Type::UByteTyID:
931 case Type::SByteTyID: return V9::STBr;
932 case Type::UShortTyID:
933 case Type::ShortTyID: return V9::STHr;
935 case Type::IntTyID: return V9::STWr;
936 case Type::PointerTyID:
937 case Type::ULongTyID:
938 case Type::LongTyID: return V9::STXr;
939 case Type::FloatTyID: return V9::STFr;
940 case Type::DoubleTyID: return V9::STDFr;
941 default: assert(0 && "Invalid type for Store instruction");
946 static inline MachineOpCode ChooseAddInstructionByType(const Type* resultType) {
947 MachineOpCode opCode = V9::INVALID_OPCODE;
948 if (resultType->isIntegral() || isa<PointerType>(resultType)
949 || isa<FunctionType>(resultType) || resultType == Type::LabelTy) {
952 switch(resultType->getTypeID()) {
953 case Type::FloatTyID: opCode = V9::FADDS; break;
954 case Type::DoubleTyID: opCode = V9::FADDD; break;
955 default: assert(0 && "Invalid type for ADD instruction"); break;
961 /// convertOpcodeFromRegToImm - Because the SparcV9 instruction selector likes
962 /// to re-write operands to instructions, making them change from a Value*
963 /// (virtual register) to a Constant* (making an immediate field), we need to
964 /// change the opcode from a register-based instruction to an immediate-based
965 /// instruction, hence this mapping.
967 static unsigned convertOpcodeFromRegToImm(unsigned Opcode) {
970 case V9::ADDr: return V9::ADDi;
971 case V9::ADDccr: return V9::ADDcci;
972 case V9::ADDCr: return V9::ADDCi;
973 case V9::ADDCccr: return V9::ADDCcci;
974 case V9::SUBr: return V9::SUBi;
975 case V9::SUBccr: return V9::SUBcci;
976 case V9::SUBCr: return V9::SUBCi;
977 case V9::SUBCccr: return V9::SUBCcci;
978 case V9::MULXr: return V9::MULXi;
979 case V9::SDIVXr: return V9::SDIVXi;
980 case V9::UDIVXr: return V9::UDIVXi;
983 case V9::ANDr: return V9::ANDi;
984 case V9::ANDccr: return V9::ANDcci;
985 case V9::ANDNr: return V9::ANDNi;
986 case V9::ANDNccr: return V9::ANDNcci;
987 case V9::ORr: return V9::ORi;
988 case V9::ORccr: return V9::ORcci;
989 case V9::ORNr: return V9::ORNi;
990 case V9::ORNccr: return V9::ORNcci;
991 case V9::XORr: return V9::XORi;
992 case V9::XORccr: return V9::XORcci;
993 case V9::XNORr: return V9::XNORi;
994 case V9::XNORccr: return V9::XNORcci;
997 case V9::SLLr5: return V9::SLLi5;
998 case V9::SRLr5: return V9::SRLi5;
999 case V9::SRAr5: return V9::SRAi5;
1000 case V9::SLLXr6: return V9::SLLXi6;
1001 case V9::SRLXr6: return V9::SRLXi6;
1002 case V9::SRAXr6: return V9::SRAXi6;
1004 /* Conditional move on int comparison with zero */
1005 case V9::MOVRZr: return V9::MOVRZi;
1006 case V9::MOVRLEZr: return V9::MOVRLEZi;
1007 case V9::MOVRLZr: return V9::MOVRLZi;
1008 case V9::MOVRNZr: return V9::MOVRNZi;
1009 case V9::MOVRGZr: return V9::MOVRGZi;
1010 case V9::MOVRGEZr: return V9::MOVRGEZi;
1013 /* Conditional move on int condition code */
1014 case V9::MOVAr: return V9::MOVAi;
1015 case V9::MOVNr: return V9::MOVNi;
1016 case V9::MOVNEr: return V9::MOVNEi;
1017 case V9::MOVEr: return V9::MOVEi;
1018 case V9::MOVGr: return V9::MOVGi;
1019 case V9::MOVLEr: return V9::MOVLEi;
1020 case V9::MOVGEr: return V9::MOVGEi;
1021 case V9::MOVLr: return V9::MOVLi;
1022 case V9::MOVGUr: return V9::MOVGUi;
1023 case V9::MOVLEUr: return V9::MOVLEUi;
1024 case V9::MOVCCr: return V9::MOVCCi;
1025 case V9::MOVCSr: return V9::MOVCSi;
1026 case V9::MOVPOSr: return V9::MOVPOSi;
1027 case V9::MOVNEGr: return V9::MOVNEGi;
1028 case V9::MOVVCr: return V9::MOVVCi;
1029 case V9::MOVVSr: return V9::MOVVSi;
1031 /* Conditional move of int reg on fp condition code */
1032 case V9::MOVFAr: return V9::MOVFAi;
1033 case V9::MOVFNr: return V9::MOVFNi;
1034 case V9::MOVFUr: return V9::MOVFUi;
1035 case V9::MOVFGr: return V9::MOVFGi;
1036 case V9::MOVFUGr: return V9::MOVFUGi;
1037 case V9::MOVFLr: return V9::MOVFLi;
1038 case V9::MOVFULr: return V9::MOVFULi;
1039 case V9::MOVFLGr: return V9::MOVFLGi;
1040 case V9::MOVFNEr: return V9::MOVFNEi;
1041 case V9::MOVFEr: return V9::MOVFEi;
1042 case V9::MOVFUEr: return V9::MOVFUEi;
1043 case V9::MOVFGEr: return V9::MOVFGEi;
1044 case V9::MOVFUGEr: return V9::MOVFUGEi;
1045 case V9::MOVFLEr: return V9::MOVFLEi;
1046 case V9::MOVFULEr: return V9::MOVFULEi;
1047 case V9::MOVFOr: return V9::MOVFOi;
1050 case V9::LDSBr: return V9::LDSBi;
1051 case V9::LDSHr: return V9::LDSHi;
1052 case V9::LDSWr: return V9::LDSWi;
1053 case V9::LDUBr: return V9::LDUBi;
1054 case V9::LDUHr: return V9::LDUHi;
1055 case V9::LDUWr: return V9::LDUWi;
1056 case V9::LDXr: return V9::LDXi;
1057 case V9::LDFr: return V9::LDFi;
1058 case V9::LDDFr: return V9::LDDFi;
1059 case V9::LDQFr: return V9::LDQFi;
1060 case V9::LDFSRr: return V9::LDFSRi;
1061 case V9::LDXFSRr: return V9::LDXFSRi;
1064 case V9::STBr: return V9::STBi;
1065 case V9::STHr: return V9::STHi;
1066 case V9::STWr: return V9::STWi;
1067 case V9::STXr: return V9::STXi;
1068 case V9::STFr: return V9::STFi;
1069 case V9::STDFr: return V9::STDFi;
1070 case V9::STFSRr: return V9::STFSRi;
1071 case V9::STXFSRr: return V9::STXFSRi;
1074 case V9::JMPLCALLr: return V9::JMPLCALLi;
1075 case V9::JMPLRETr: return V9::JMPLRETi;
1077 /* save and restore */
1078 case V9::SAVEr: return V9::SAVEi;
1079 case V9::RESTOREr: return V9::RESTOREi;
1082 // It's already in correct format
1083 // Or, it's just not handled yet, but an assert() would break LLC
1085 std::cerr << "Unhandled opcode in convertOpcodeFromRegToImm(): " << Opcode
1092 /// CreateCodeToLoadConst - Create an instruction sequence to put the
1093 /// constant `val' into the virtual register `dest'. `val' may be a Constant or
1094 /// a GlobalValue, viz., the constant address of a global variable or function.
1095 /// The generated instructions are returned in `mvec'. Any temp. registers
1096 /// (TmpInstruction) created are recorded in mcfi. Any stack space required is
1097 /// allocated via MachineFunction.
1099 void CreateCodeToLoadConst(const TargetMachine& target, Function* F,
1100 Value* val, Instruction* dest,
1101 std::vector<MachineInstr*>& mvec,
1102 MachineCodeForInstruction& mcfi) {
1103 assert(isa<Constant>(val) &&
1104 "I only know about constant values and global addresses");
1106 // Use a "set" instruction for known constants or symbolic constants (labels)
1107 // that can go in an integer reg.
1108 // We have to use a "load" instruction for all other constants,
1109 // in particular, floating point constants.
1110 const Type* valType = val->getType();
1112 if (isa<GlobalValue>(val)) {
1113 TmpInstruction* tmpReg =
1114 new TmpInstruction(mcfi, PointerType::get(val->getType()), val);
1115 CreateSETXLabel(val, tmpReg, dest, mvec, mcfi);
1120 uint64_t C = ConvertConstantToIntType(target, val, dest->getType(), isValid);
1122 if (dest->getType()->isSigned())
1123 CreateUIntSetInstruction(C, dest, mvec, mcfi, val);
1125 CreateIntSetInstruction((int64_t) C, dest, mvec, mcfi, val);
1128 // Make an instruction sequence to load the constant, viz:
1129 // SETX <addr-of-constant>, tmpReg, addrReg
1130 // LOAD /*addr*/ addrReg, /*offset*/ 0, dest
1131 // First, create a tmp register to be used by the SETX sequence.
1132 TmpInstruction* tmpReg =
1133 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1135 // Create another TmpInstruction for the address register
1136 TmpInstruction* addrReg =
1137 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1139 // Get the constant pool index for this constant
1140 MachineConstantPool *CP = MachineFunction::get(F).getConstantPool();
1141 Constant *C = cast<Constant>(val);
1142 unsigned CPI = CP->getConstantPoolIndex(C);
1144 // Put the address of the constant into a register
1147 MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(tmpReg);
1148 MI->getOperand(0).markHi64();
1151 //Create another tmp register for the SETX sequence to preserve SSA
1152 TmpInstruction* tmpReg2 =
1153 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1155 MI = BuildMI(V9::ORi, 3).addReg(tmpReg).addConstantPoolIndex(CPI)
1156 .addRegDef(tmpReg2);
1157 MI->getOperand(1).markLo64();
1160 //Create another tmp register for the SETX sequence to preserve SSA
1161 TmpInstruction* tmpReg3 =
1162 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1164 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpReg2).addZImm(32)
1165 .addRegDef(tmpReg3));
1166 MI = BuildMI(V9::SETHI, 2).addConstantPoolIndex(CPI).addRegDef(addrReg);
1167 MI->getOperand(0).markHi32();
1170 // Create another TmpInstruction for the address register
1171 TmpInstruction* addrReg2 =
1172 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1175 MI = BuildMI(V9::ORr, 3).addReg(addrReg).addReg(tmpReg3).addRegDef(addrReg2);
1178 // Create another TmpInstruction for the address register
1179 TmpInstruction* addrReg3 =
1180 new TmpInstruction(mcfi, PointerType::get(val->getType()));
1182 MI = BuildMI(V9::ORi, 3).addReg(addrReg2).addConstantPoolIndex(CPI)
1183 .addRegDef(addrReg3);
1184 MI->getOperand(1).markLo32();
1187 // Now load the constant from out ConstantPool label
1188 unsigned Opcode = ChooseLoadInstruction(val->getType());
1189 Opcode = convertOpcodeFromRegToImm(Opcode);
1190 mvec.push_back(BuildMI(Opcode, 3)
1191 .addReg(addrReg3).addSImm((int64_t)0).addRegDef(dest));
1195 /// CreateCodeToCopyFloatToInt - Similarly, create an instruction sequence
1196 /// to copy an FP register `val' to an integer register `dest' by copying to
1197 /// memory and back. The generated instructions are returned in `mvec'. Any
1198 /// temp. virtual registers (TmpInstruction) created are recorded in mcfi.
1199 /// Temporary stack space required is allocated via MachineFunction.
1201 void CreateCodeToCopyFloatToInt(const TargetMachine& target, Function* F,
1202 Value* val, Instruction* dest,
1203 std::vector<MachineInstr*>& mvec,
1204 MachineCodeForInstruction& mcfi) {
1205 const Type* opTy = val->getType();
1206 const Type* destTy = dest->getType();
1207 assert(opTy->isFloatingPoint() && "Source type must be float/double");
1208 assert((destTy->isIntegral() || isa<PointerType>(destTy))
1209 && "Dest type must be integer, bool or pointer");
1211 // FIXME: For now, we allocate permanent space because the stack frame
1212 // manager does not allow locals to be allocated (e.g., for alloca) after
1213 // a temp is allocated!
1214 int offset = MachineFunction::get(F).getInfo<SparcV9FunctionInfo>()->allocateLocalVar(val);
1216 unsigned FPReg = target.getRegInfo()->getFramePointer();
1218 // Store instruction stores `val' to [%fp+offset].
1219 // The store opCode is based only the source value being copied.
1220 unsigned StoreOpcode = ChooseStoreInstruction(opTy);
1221 StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
1222 mvec.push_back(BuildMI(StoreOpcode, 3)
1223 .addReg(val).addMReg(FPReg).addSImm(offset));
1225 // Load instruction loads [%fp+offset] to `dest'.
1226 // The type of the load opCode is the integer type that matches the
1227 // source type in size:
1228 // On SparcV9: int for float, long for double.
1229 // Note that we *must* use signed loads even for unsigned dest types, to
1230 // ensure correct sign-extension for UByte, UShort or UInt:
1231 const Type* loadTy = (opTy == Type::FloatTy)? Type::IntTy : Type::LongTy;
1232 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
1233 LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1234 mvec.push_back(BuildMI(LoadOpcode, 3).addMReg(FPReg)
1235 .addSImm(offset).addRegDef(dest));
1238 /// CreateBitExtensionInstructions - Helper function for sign-extension and
1239 /// zero-extension. For SPARC v9, we sign-extend the given operand using SLL;
1243 CreateBitExtensionInstructions(bool signExtend, const TargetMachine& target,
1244 Function* F, Value* srcVal, Value* destVal,
1245 unsigned int numLowBits,
1246 std::vector<MachineInstr*>& mvec,
1247 MachineCodeForInstruction& mcfi) {
1250 assert(numLowBits <= 32 && "Otherwise, nothing should be done here!");
1252 if (numLowBits < 32) {
1253 // SLL is needed since operand size is < 32 bits.
1254 TmpInstruction *tmpI = new TmpInstruction(mcfi, destVal->getType(),
1255 srcVal, destVal, "make32");
1256 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(srcVal)
1257 .addZImm(32-numLowBits).addRegDef(tmpI));
1261 mvec.push_back(BuildMI(signExtend? V9::SRAi5 : V9::SRLi5, 3)
1262 .addReg(srcVal).addZImm(32-numLowBits).addRegDef(destVal));
1265 /// CreateSignExtensionInstructions - Create instruction sequence to produce
1266 /// a sign-extended register value from an arbitrary-sized integer value (sized
1267 /// in bits, not bytes). The generated instructions are returned in `mvec'. Any
1268 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1269 /// space required is allocated via MachineFunction.
1271 void CreateSignExtensionInstructions(const TargetMachine& target,
1272 Function* F, Value* srcVal, Value* destVal,
1273 unsigned int numLowBits,
1274 std::vector<MachineInstr*>& mvec,
1275 MachineCodeForInstruction& mcfi) {
1276 CreateBitExtensionInstructions(/*signExtend*/ true, target, F, srcVal,
1277 destVal, numLowBits, mvec, mcfi);
1280 /// CreateZeroExtensionInstructions - Create instruction sequence to produce
1281 /// a zero-extended register value from an arbitrary-sized integer value (sized
1282 /// in bits, not bytes). For SPARC v9, we sign-extend the given operand using
1283 /// SLL; SRL. The generated instructions are returned in `mvec'. Any temp.
1284 /// registers (TmpInstruction) created are recorded in mcfi. Any stack space
1285 /// required is allocated via MachineFunction.
1287 void CreateZeroExtensionInstructions(const TargetMachine& target,
1288 Function* F, Value* srcVal, Value* destVal,
1289 unsigned int numLowBits,
1290 std::vector<MachineInstr*>& mvec,
1291 MachineCodeForInstruction& mcfi) {
1292 CreateBitExtensionInstructions(/*signExtend*/ false, target, F, srcVal,
1293 destVal, numLowBits, mvec, mcfi);
1296 /// CreateCodeToCopyIntToFloat - Create an instruction sequence to copy an
1297 /// integer register `val' to a floating point register `dest' by copying to
1298 /// memory and back. val must be an integral type. dest must be a Float or
1299 /// Double. The generated instructions are returned in `mvec'. Any temp.
1300 /// registers (TmpInstruction) created are recorded in mcfi. Any stack space
1301 /// required is allocated via MachineFunction.
1303 void CreateCodeToCopyIntToFloat(const TargetMachine& target,
1304 Function* F, Value* val, Instruction* dest,
1305 std::vector<MachineInstr*>& mvec,
1306 MachineCodeForInstruction& mcfi) {
1307 assert((val->getType()->isIntegral() || isa<PointerType>(val->getType()))
1308 && "Source type must be integral (integer or bool) or pointer");
1309 assert(dest->getType()->isFloatingPoint()
1310 && "Dest type must be float/double");
1312 // Get a stack slot to use for the copy
1313 int offset = MachineFunction::get(F).getInfo<SparcV9FunctionInfo>()->allocateLocalVar(val);
1315 // Get the size of the source value being copied.
1316 size_t srcSize = target.getTargetData().getTypeSize(val->getType());
1318 // Store instruction stores `val' to [%fp+offset].
1319 // The store and load opCodes are based on the size of the source value.
1320 // If the value is smaller than 32 bits, we must sign- or zero-extend it
1321 // to 32 bits since the load-float will load 32 bits.
1322 // Note that the store instruction is the same for signed and unsigned ints.
1323 const Type* storeType = (srcSize <= 4)? Type::IntTy : Type::LongTy;
1324 Value* storeVal = val;
1325 if (srcSize < target.getTargetData().getTypeSize(Type::FloatTy)) {
1326 // sign- or zero-extend respectively
1327 storeVal = new TmpInstruction(mcfi, storeType, val);
1328 if (val->getType()->isSigned())
1329 CreateSignExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1332 CreateZeroExtensionInstructions(target, F, val, storeVal, 8*srcSize,
1336 unsigned FPReg = target.getRegInfo()->getFramePointer();
1337 unsigned StoreOpcode = ChooseStoreInstruction(storeType);
1338 StoreOpcode = convertOpcodeFromRegToImm(StoreOpcode);
1339 mvec.push_back(BuildMI(StoreOpcode, 3)
1340 .addReg(storeVal).addMReg(FPReg).addSImm(offset));
1342 // Load instruction loads [%fp+offset] to `dest'.
1343 // The type of the load opCode is the floating point type that matches the
1344 // stored type in size:
1345 // On SparcV9: float for int or smaller, double for long.
1346 const Type* loadType = (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
1347 unsigned LoadOpcode = ChooseLoadInstruction(loadType);
1348 LoadOpcode = convertOpcodeFromRegToImm(LoadOpcode);
1349 mvec.push_back(BuildMI(LoadOpcode, 3)
1350 .addMReg(FPReg).addSImm(offset).addRegDef(dest));
1353 /// InsertCodeToLoadConstant - Generates code to load the constant
1354 /// into a TmpInstruction (virtual reg) and returns the virtual register.
1356 static TmpInstruction*
1357 InsertCodeToLoadConstant(Function *F, Value* opValue, Instruction* vmInstr,
1358 std::vector<MachineInstr*>& loadConstVec,
1359 TargetMachine& target) {
1360 // Create a tmp virtual register to hold the constant.
1361 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(vmInstr);
1362 TmpInstruction* tmpReg = new TmpInstruction(mcfi, opValue);
1364 CreateCodeToLoadConst(target, F, opValue, tmpReg, loadConstVec, mcfi);
1366 // Record the mapping from the tmp VM instruction to machine instruction.
1367 // Do this for all machine instructions that were not mapped to any
1368 // other temp values created by
1369 // tmpReg->addMachineInstruction(loadConstVec.back());
1373 MachineOperand::MachineOperandType
1374 ChooseRegOrImmed(int64_t intValue, bool isSigned,
1375 MachineOpCode opCode, const TargetMachine& target,
1376 bool canUseImmed, unsigned int& getMachineRegNum,
1377 int64_t& getImmedValue) {
1378 MachineOperand::MachineOperandType opType=MachineOperand::MO_VirtualRegister;
1379 getMachineRegNum = 0;
1383 target.getInstrInfo()->constantFitsInImmedField(opCode, intValue)) {
1384 opType = isSigned? MachineOperand::MO_SignExtendedImmed
1385 : MachineOperand::MO_UnextendedImmed;
1386 getImmedValue = intValue;
1387 } else if (intValue == 0 &&
1388 target.getRegInfo()->getZeroRegNum() != (unsigned)-1) {
1389 opType = MachineOperand::MO_MachineRegister;
1390 getMachineRegNum = target.getRegInfo()->getZeroRegNum();
1396 MachineOperand::MachineOperandType
1397 ChooseRegOrImmed(Value* val,
1398 MachineOpCode opCode, const TargetMachine& target,
1399 bool canUseImmed, unsigned int& getMachineRegNum,
1400 int64_t& getImmedValue) {
1401 getMachineRegNum = 0;
1404 // To use reg or immed, constant needs to be integer, bool, or a NULL pointer.
1405 // ConvertConstantToIntType() does the right conversions.
1406 bool isValidConstant;
1407 uint64_t valueToUse =
1408 ConvertConstantToIntType(target, val, val->getType(), isValidConstant);
1409 if (! isValidConstant)
1410 return MachineOperand::MO_VirtualRegister;
1412 // Now check if the constant value fits in the IMMED field.
1413 return ChooseRegOrImmed((int64_t) valueToUse, val->getType()->isSigned(),
1414 opCode, target, canUseImmed,
1415 getMachineRegNum, getImmedValue);
1418 /// CreateCopyInstructionsByType - Create instruction(s) to copy src to dest,
1419 /// for arbitrary types. The generated instructions are returned in `mvec'. Any
1420 /// temp. registers (TmpInstruction) created are recorded in mcfi. Any stack
1421 /// space required is allocated via MachineFunction.
1423 void CreateCopyInstructionsByType(const TargetMachine& target,
1424 Function *F, Value* src, Instruction* dest,
1425 std::vector<MachineInstr*>& mvec,
1426 MachineCodeForInstruction& mcfi) {
1427 bool loadConstantToReg = false;
1428 const Type* resultType = dest->getType();
1429 MachineOpCode opCode = ChooseAddInstructionByType(resultType);
1430 assert (opCode != V9::INVALID_OPCODE
1431 && "Unsupported result type in CreateCopyInstructionsByType()");
1433 // If `src' is a constant that doesn't fit in the immed field or if it is
1434 // a global variable (i.e., a constant address), generate a load
1435 // instruction instead of an add.
1436 if (isa<GlobalValue>(src))
1437 loadConstantToReg = true;
1438 else if (isa<Constant>(src)) {
1439 unsigned int machineRegNum;
1441 MachineOperand::MachineOperandType opType =
1442 ChooseRegOrImmed(src, opCode, target, /*canUseImmed*/ true,
1443 machineRegNum, immedValue);
1445 if (opType == MachineOperand::MO_VirtualRegister)
1446 loadConstantToReg = true;
1449 if (loadConstantToReg) {
1450 // `src' is constant and cannot fit in immed field for the ADD.
1451 // Insert instructions to "load" the constant into a register.
1452 CreateCodeToLoadConst(target, F, src, dest, mvec, mcfi);
1454 // Create a reg-to-reg copy instruction for the given type:
1455 // -- For FP values, create a FMOVS or FMOVD instruction
1456 // -- For non-FP values, create an add-with-0 instruction (opCode as above)
1457 // Make `src' the second operand, in case it is a small constant!
1459 if (resultType->isFloatingPoint())
1460 MI = (BuildMI(resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
1461 .addReg(src).addRegDef(dest));
1463 const Type* Ty =isa<PointerType>(resultType)? Type::ULongTy :resultType;
1464 MI = (BuildMI(opCode, 3)
1465 .addSImm((int64_t) 0).addReg(src).addRegDef(dest));
1471 /// FixConstantOperandsForInstr - Make a machine instruction use its constant
1472 /// operands more efficiently. If the constant is 0, then use the hardwired 0
1473 /// register, if any. Else, if the constant fits in the IMMEDIATE field, then
1474 /// use that field. Otherwise, else create instructions to put the constant
1475 /// into a register, either directly or by loading explicitly from the constant
1476 /// pool. In the first 2 cases, the operand of `minstr' is modified in place.
1477 /// Returns a vector of machine instructions generated for operands that fall
1478 /// under case 3; these must be inserted before `minstr'.
1480 std::vector<MachineInstr*>
1481 FixConstantOperandsForInstr(Instruction* vmInstr, MachineInstr* minstr,
1482 TargetMachine& target) {
1483 std::vector<MachineInstr*> MVec;
1485 MachineOpCode opCode = minstr->getOpcode();
1486 const TargetInstrInfo& instrInfo = *target.getInstrInfo();
1487 int resultPos = instrInfo.get(opCode).resultPos;
1488 int immedPos = instrInfo.getImmedConstantPos(opCode);
1490 Function *F = vmInstr->getParent()->getParent();
1492 for (unsigned op=0; op < minstr->getNumOperands(); op++) {
1493 const MachineOperand& mop = minstr->getOperand(op);
1495 // Skip the result position, preallocated machine registers, or operands
1496 // that cannot be constants (CC regs or PC-relative displacements)
1497 if (resultPos == (int)op ||
1498 mop.getType() == MachineOperand::MO_MachineRegister ||
1499 mop.getType() == MachineOperand::MO_CCRegister ||
1500 mop.getType() == MachineOperand::MO_PCRelativeDisp)
1503 bool constantThatMustBeLoaded = false;
1504 unsigned int machineRegNum = 0;
1505 int64_t immedValue = 0;
1506 Value* opValue = NULL;
1507 MachineOperand::MachineOperandType opType =
1508 MachineOperand::MO_VirtualRegister;
1510 // Operand may be a virtual register or a compile-time constant
1511 if (mop.getType() == MachineOperand::MO_VirtualRegister) {
1512 assert(mop.getVRegValue() != NULL);
1513 opValue = mop.getVRegValue();
1514 if (Constant *opConst = dyn_cast<Constant>(opValue))
1515 if (!isa<GlobalValue>(opConst)) {
1516 opType = ChooseRegOrImmed(opConst, opCode, target,
1517 (immedPos == (int)op), machineRegNum,
1519 if (opType == MachineOperand::MO_VirtualRegister)
1520 constantThatMustBeLoaded = true;
1523 // If the operand is from the constant pool, don't try to change it.
1524 if (mop.getType() == MachineOperand::MO_ConstantPoolIndex) {
1527 assert(mop.isImmediate());
1528 bool isSigned = mop.getType() == MachineOperand::MO_SignExtendedImmed;
1530 // Bit-selection flags indicate an instruction that is extracting
1531 // bits from its operand so ignore this even if it is a big constant.
1532 if (mop.isHiBits32() || mop.isLoBits32() ||
1533 mop.isHiBits64() || mop.isLoBits64())
1536 opType = ChooseRegOrImmed(mop.getImmedValue(), isSigned,
1537 opCode, target, (immedPos == (int)op),
1538 machineRegNum, immedValue);
1540 if (opType == MachineOperand::MO_SignExtendedImmed ||
1541 opType == MachineOperand::MO_UnextendedImmed) {
1542 // The optype is an immediate value
1543 // This means we need to change the opcode, e.g. ADDr -> ADDi
1544 unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1545 minstr->setOpcode(newOpcode);
1548 if (opType == mop.getType())
1549 continue; // no change: this is the most common case
1551 if (opType == MachineOperand::MO_VirtualRegister) {
1552 constantThatMustBeLoaded = true;
1554 ? (Value*)ConstantSInt::get(Type::LongTy, immedValue)
1555 : (Value*)ConstantUInt::get(Type::ULongTy,(uint64_t)immedValue);
1559 if (opType == MachineOperand::MO_MachineRegister)
1560 minstr->SetMachineOperandReg(op, machineRegNum);
1561 else if (opType == MachineOperand::MO_SignExtendedImmed ||
1562 opType == MachineOperand::MO_UnextendedImmed) {
1563 minstr->SetMachineOperandConst(op, opType, immedValue);
1564 // The optype is or has become an immediate
1565 // This means we need to change the opcode, e.g. ADDr -> ADDi
1566 unsigned newOpcode = convertOpcodeFromRegToImm(opCode);
1567 minstr->setOpcode(newOpcode);
1568 } else if (constantThatMustBeLoaded ||
1569 (opValue && isa<GlobalValue>(opValue)))
1570 { // opValue is a constant that must be explicitly loaded into a reg
1572 TmpInstruction* tmpReg = InsertCodeToLoadConstant(F, opValue, vmInstr,
1574 minstr->SetMachineOperandVal(op, MachineOperand::MO_VirtualRegister,
1579 // Also, check for implicit operands used by the machine instruction
1580 // (no need to check those defined since they cannot be constants).
1582 // -- arguments to a Call
1583 // -- return value of a Return
1584 // Any such operand that is a constant value needs to be fixed also.
1585 // The current instructions with implicit refs (viz., Call and Return)
1586 // have no immediate fields, so the constant always needs to be loaded
1588 bool isCall = instrInfo.isCall(opCode);
1589 unsigned lastCallArgNum = 0; // unused if not a call
1590 CallArgsDescriptor* argDesc = NULL; // unused if not a call
1592 argDesc = CallArgsDescriptor::get(minstr);
1594 for (unsigned i=0, N=minstr->getNumImplicitRefs(); i < N; ++i)
1595 if (isa<Constant>(minstr->getImplicitRef(i))) {
1596 Value* oldVal = minstr->getImplicitRef(i);
1597 TmpInstruction* tmpReg =
1598 InsertCodeToLoadConstant(F, oldVal, vmInstr, MVec, target);
1599 minstr->setImplicitRef(i, tmpReg);
1602 // find and replace the argument in the CallArgsDescriptor
1603 unsigned i=lastCallArgNum;
1604 while (argDesc->getArgInfo(i).getArgVal() != oldVal)
1606 assert(i < argDesc->getNumArgs() &&
1607 "Constant operands to a call *must* be in the arg list");
1609 argDesc->getArgInfo(i).replaceArgVal(tmpReg);
1616 static inline void Add3OperandInstr(unsigned Opcode, InstructionNode* Node,
1617 std::vector<MachineInstr*>& mvec) {
1618 mvec.push_back(BuildMI(Opcode, 3).addReg(Node->leftChild()->getValue())
1619 .addReg(Node->rightChild()->getValue())
1620 .addRegDef(Node->getValue()));
1623 /// IsZero - Check for a constant 0.
1625 static inline bool IsZero(Value* idx) {
1626 return (isa<Constant>(idx) && cast<Constant>(idx)->isNullValue()) ||
1627 isa<UndefValue>(idx);
1630 /// FoldGetElemChain - Fold a chain of GetElementPtr instructions containing
1631 /// only constant offsets into an equivalent (Pointer, IndexVector) pair.
1632 /// Returns the pointer Value, and stores the resulting IndexVector in argument
1633 /// chainIdxVec. This is a helper function for FoldConstantIndices that does the
1637 FoldGetElemChain(InstrTreeNode* ptrNode, std::vector<Value*>& chainIdxVec,
1638 bool lastInstHasLeadingNonZero) {
1639 InstructionNode* gepNode = dyn_cast<InstructionNode>(ptrNode);
1640 GetElementPtrInst* gepInst =
1641 dyn_cast_or_null<GetElementPtrInst>(gepNode ? gepNode->getInstruction() :0);
1643 // ptr value is not computed in this tree or ptr value does not come from GEP
1645 if (gepInst == NULL)
1648 // Return NULL if we don't fold any instructions in.
1649 Value* ptrVal = NULL;
1651 // Now chase the chain of getElementInstr instructions, if any.
1652 // Check for any non-constant indices and stop there.
1653 // Also, stop if the first index of child is a non-zero array index
1654 // and the last index of the current node is a non-array index:
1655 // in that case, a non-array declared type is being accessed as an array
1656 // which is not type-safe, but could be legal.
1657 InstructionNode* ptrChild = gepNode;
1658 while (ptrChild && (ptrChild->getOpLabel() == Instruction::GetElementPtr ||
1659 ptrChild->getOpLabel() == GetElemPtrIdx)) {
1660 // Child is a GetElemPtr instruction
1661 gepInst = cast<GetElementPtrInst>(ptrChild->getValue());
1662 User::op_iterator OI, firstIdx = gepInst->idx_begin();
1663 User::op_iterator lastIdx = gepInst->idx_end();
1664 bool allConstantOffsets = true;
1666 // The first index of every GEP must be an array index.
1667 assert((*firstIdx)->getType() == Type::LongTy &&
1668 "INTERNAL ERROR: Structure index for a pointer type!");
1670 // If the last instruction had a leading non-zero index, check if the
1671 // current one references a sequential (i.e., indexable) type.
1672 // If not, the code is not type-safe and we would create an illegal GEP
1673 // by folding them, so don't fold any more instructions.
1674 if (lastInstHasLeadingNonZero)
1675 if (! isa<SequentialType>(gepInst->getType()->getElementType()))
1676 break; // cannot fold in any preceding getElementPtr instrs.
1678 // Check that all offsets are constant for this instruction
1679 for (OI = firstIdx; allConstantOffsets && OI != lastIdx; ++OI)
1680 allConstantOffsets = isa<ConstantInt>(*OI);
1682 if (allConstantOffsets) {
1683 // Get pointer value out of ptrChild.
1684 ptrVal = gepInst->getPointerOperand();
1686 // Insert its index vector at the start, skipping any leading [0]
1687 // Remember the old size to check if anything was inserted.
1688 unsigned oldSize = chainIdxVec.size();
1689 int firstIsZero = IsZero(*firstIdx);
1690 chainIdxVec.insert(chainIdxVec.begin(), firstIdx + firstIsZero, lastIdx);
1692 // Remember if it has leading zero index: it will be discarded later.
1693 if (oldSize < chainIdxVec.size())
1694 lastInstHasLeadingNonZero = !firstIsZero;
1696 // Mark the folded node so no code is generated for it.
1697 ((InstructionNode*) ptrChild)->markFoldedIntoParent();
1699 // Get the previous GEP instruction and continue trying to fold
1700 ptrChild = dyn_cast<InstructionNode>(ptrChild->leftChild());
1701 } else // cannot fold this getElementPtr instr. or any preceding ones
1705 // If the first getElementPtr instruction had a leading [0], add it back.
1706 // Note that this instruction is the *last* one that was successfully
1707 // folded *and* contributed any indices, in the loop above.
1708 if (ptrVal && ! lastInstHasLeadingNonZero)
1709 chainIdxVec.insert(chainIdxVec.begin(), ConstantSInt::get(Type::LongTy,0));
1714 /// GetGEPInstArgs - Helper function for GetMemInstArgs that handles the
1715 /// final getElementPtr instruction used by (or same as) the memory operation.
1716 /// Extracts the indices of the current instruction and tries to fold in
1717 /// preceding ones if all indices of the current one are constant.
1719 static Value *GetGEPInstArgs(InstructionNode *gepNode,
1720 std::vector<Value *> &idxVec,
1721 bool &allConstantIndices) {
1722 allConstantIndices = true;
1723 GetElementPtrInst* gepI = cast<GetElementPtrInst>(gepNode->getInstruction());
1725 // Default pointer is the one from the current instruction.
1726 Value* ptrVal = gepI->getPointerOperand();
1727 InstrTreeNode* ptrChild = gepNode->leftChild();
1729 // Extract the index vector of the GEP instruction.
1730 // If all indices are constant and first index is zero, try to fold
1731 // in preceding GEPs with all constant indices.
1732 for (User::op_iterator OI=gepI->idx_begin(), OE=gepI->idx_end();
1733 allConstantIndices && OI != OE; ++OI)
1734 if (! isa<Constant>(*OI))
1735 allConstantIndices = false; // note: this also terminates loop!
1737 // If we have only constant indices, fold chains of constant indices
1738 // in this and any preceding GetElemPtr instructions.
1739 bool foldedGEPs = false;
1740 bool leadingNonZeroIdx = gepI && ! IsZero(*gepI->idx_begin());
1741 if (allConstantIndices && !leadingNonZeroIdx)
1742 if (Value* newPtr = FoldGetElemChain(ptrChild, idxVec, leadingNonZeroIdx)) {
1747 // Append the index vector of the current instruction.
1748 // Skip the leading [0] index if preceding GEPs were folded into this.
1749 idxVec.insert(idxVec.end(),
1750 gepI->idx_begin() + (foldedGEPs && !leadingNonZeroIdx),
1756 /// GetMemInstArgs - Get the pointer value and the index vector for a memory
1757 /// operation (GetElementPtr, Load, or Store). If all indices of the given
1758 /// memory operation are constant, fold in constant indices in a chain of
1759 /// preceding GetElementPtr instructions (if any), and return the pointer value
1760 /// of the first instruction in the chain. All folded instructions are marked so
1761 /// no code is generated for them. Returns the pointer Value to use, and
1762 /// returns the resulting IndexVector in idxVec. Sets allConstantIndices
1763 /// to true/false if all indices are/aren't const.
1765 static Value *GetMemInstArgs(InstructionNode *memInstrNode,
1766 std::vector<Value*> &idxVec,
1767 bool& allConstantIndices) {
1768 allConstantIndices = false;
1769 Instruction* memInst = memInstrNode->getInstruction();
1770 assert(idxVec.size() == 0 && "Need empty vector to return indices");
1772 // If there is a GetElemPtr instruction to fold in to this instr,
1773 // it must be in the left child for Load and GetElemPtr, and in the
1774 // right child for Store instructions.
1775 InstrTreeNode* ptrChild = (memInst->getOpcode() == Instruction::Store
1776 ? memInstrNode->rightChild()
1777 : memInstrNode->leftChild());
1779 // Default pointer is the one from the current instruction.
1780 Value* ptrVal = ptrChild->getValue();
1782 // Find the "last" GetElemPtr instruction: this one or the immediate child.
1783 // There will be none if this is a load or a store from a scalar pointer.
1784 InstructionNode* gepNode = NULL;
1785 if (isa<GetElementPtrInst>(memInst))
1786 gepNode = memInstrNode;
1787 else if (isa<InstructionNode>(ptrChild) && isa<GetElementPtrInst>(ptrVal)) {
1788 // Child of load/store is a GEP and memInst is its only use.
1789 // Use its indices and mark it as folded.
1790 gepNode = cast<InstructionNode>(ptrChild);
1791 gepNode->markFoldedIntoParent();
1794 // If there are no indices, return the current pointer.
1795 // Else extract the pointer from the GEP and fold the indices.
1796 return gepNode ? GetGEPInstArgs(gepNode, idxVec, allConstantIndices)
1800 static inline MachineOpCode
1801 ChooseBprInstruction(const InstructionNode* instrNode) {
1802 MachineOpCode opCode;
1804 Instruction* setCCInstr =
1805 ((InstructionNode*) instrNode->leftChild())->getInstruction();
1807 switch(setCCInstr->getOpcode()) {
1808 case Instruction::SetEQ: opCode = V9::BRZ; break;
1809 case Instruction::SetNE: opCode = V9::BRNZ; break;
1810 case Instruction::SetLE: opCode = V9::BRLEZ; break;
1811 case Instruction::SetGE: opCode = V9::BRGEZ; break;
1812 case Instruction::SetLT: opCode = V9::BRLZ; break;
1813 case Instruction::SetGT: opCode = V9::BRGZ; break;
1815 assert(0 && "Unrecognized VM instruction!");
1816 opCode = V9::INVALID_OPCODE;
1823 static inline MachineOpCode
1824 ChooseBpccInstruction(const InstructionNode* instrNode,
1825 const BinaryOperator* setCCInstr) {
1826 MachineOpCode opCode = V9::INVALID_OPCODE;
1828 bool isSigned = setCCInstr->getOperand(0)->getType()->isSigned();
1831 switch(setCCInstr->getOpcode()) {
1832 case Instruction::SetEQ: opCode = V9::BE; break;
1833 case Instruction::SetNE: opCode = V9::BNE; break;
1834 case Instruction::SetLE: opCode = V9::BLE; break;
1835 case Instruction::SetGE: opCode = V9::BGE; break;
1836 case Instruction::SetLT: opCode = V9::BL; break;
1837 case Instruction::SetGT: opCode = V9::BG; break;
1839 assert(0 && "Unrecognized VM instruction!");
1843 switch(setCCInstr->getOpcode()) {
1844 case Instruction::SetEQ: opCode = V9::BE; break;
1845 case Instruction::SetNE: opCode = V9::BNE; break;
1846 case Instruction::SetLE: opCode = V9::BLEU; break;
1847 case Instruction::SetGE: opCode = V9::BCC; break;
1848 case Instruction::SetLT: opCode = V9::BCS; break;
1849 case Instruction::SetGT: opCode = V9::BGU; break;
1851 assert(0 && "Unrecognized VM instruction!");
1859 static inline MachineOpCode
1860 ChooseBFpccInstruction(const InstructionNode* instrNode,
1861 const BinaryOperator* setCCInstr) {
1862 MachineOpCode opCode = V9::INVALID_OPCODE;
1864 switch(setCCInstr->getOpcode()) {
1865 case Instruction::SetEQ: opCode = V9::FBE; break;
1866 case Instruction::SetNE: opCode = V9::FBNE; break;
1867 case Instruction::SetLE: opCode = V9::FBLE; break;
1868 case Instruction::SetGE: opCode = V9::FBGE; break;
1869 case Instruction::SetLT: opCode = V9::FBL; break;
1870 case Instruction::SetGT: opCode = V9::FBG; break;
1872 assert(0 && "Unrecognized VM instruction!");
1879 // GetTmpForCC - Create a unique TmpInstruction for a boolean value,
1880 // representing the CC register used by a branch on that value.
1881 // For now, hack this using a little static cache of TmpInstructions.
1882 // Eventually the entire BURG instruction selection should be put
1883 // into a separate class that can hold such information.
1884 // The static cache is not too bad because the memory for these
1885 // TmpInstructions will be freed along with the rest of the Function anyway.
1887 static TmpInstruction *GetTmpForCC (Value* boolVal, const Function *F,
1889 MachineCodeForInstruction& mcfi) {
1890 typedef hash_map<const Value*, TmpInstruction*> BoolTmpCache;
1891 static BoolTmpCache boolToTmpCache; // Map boolVal -> TmpInstruction*
1892 static const Function *lastFunction = 0;// Use to flush cache between funcs
1894 assert(boolVal->getType() == Type::BoolTy && "Weird but ok! Delete assert");
1896 if (lastFunction != F) {
1898 boolToTmpCache.clear();
1901 // Look for tmpI and create a new one otherwise. The new value is
1902 // directly written to map using the ref returned by operator[].
1903 TmpInstruction*& tmpI = boolToTmpCache[boolVal];
1905 tmpI = new TmpInstruction(mcfi, ccType, boolVal);
1910 static inline MachineOpCode
1911 ChooseBccInstruction(const InstructionNode* instrNode, const Type*& setCCType) {
1912 InstructionNode* setCCNode = (InstructionNode*) instrNode->leftChild();
1913 assert(setCCNode->getOpLabel() == SetCCOp);
1914 BinaryOperator* setCCInstr =cast<BinaryOperator>(setCCNode->getInstruction());
1915 setCCType = setCCInstr->getOperand(0)->getType();
1917 if (setCCType->isFloatingPoint())
1918 return ChooseBFpccInstruction(instrNode, setCCInstr);
1920 return ChooseBpccInstruction(instrNode, setCCInstr);
1923 /// ChooseMovFpcciInstruction - WARNING: since this function has only one
1924 /// caller, it always returns the opcode that expects an immediate and a
1925 /// register. If this function is ever used in cases where an opcode that takes
1926 /// two registers is required, then modify this function and use
1927 /// convertOpcodeFromRegToImm() where required. It will be necessary to expand
1928 /// convertOpcodeFromRegToImm() to handle the new cases of opcodes.
1930 static inline MachineOpCode
1931 ChooseMovFpcciInstruction(const InstructionNode* instrNode) {
1932 MachineOpCode opCode = V9::INVALID_OPCODE;
1934 switch(instrNode->getInstruction()->getOpcode()) {
1935 case Instruction::SetEQ: opCode = V9::MOVFEi; break;
1936 case Instruction::SetNE: opCode = V9::MOVFNEi; break;
1937 case Instruction::SetLE: opCode = V9::MOVFLEi; break;
1938 case Instruction::SetGE: opCode = V9::MOVFGEi; break;
1939 case Instruction::SetLT: opCode = V9::MOVFLi; break;
1940 case Instruction::SetGT: opCode = V9::MOVFGi; break;
1942 assert(0 && "Unrecognized VM instruction!");
1949 /// ChooseMovpcciForSetCC -- Choose a conditional-move instruction
1950 /// based on the type of SetCC operation.
1952 /// WARNING: like the previous function, this function always returns
1953 /// the opcode that expects an immediate and a register. See above.
1955 static MachineOpCode ChooseMovpcciForSetCC(const InstructionNode* instrNode) {
1956 MachineOpCode opCode = V9::INVALID_OPCODE;
1958 const Type* opType = instrNode->leftChild()->getValue()->getType();
1959 assert(opType->isIntegral() || isa<PointerType>(opType));
1960 bool noSign = opType->isUnsigned() || isa<PointerType>(opType);
1962 switch(instrNode->getInstruction()->getOpcode()) {
1963 case Instruction::SetEQ: opCode = V9::MOVEi; break;
1964 case Instruction::SetLE: opCode = noSign? V9::MOVLEUi : V9::MOVLEi; break;
1965 case Instruction::SetGE: opCode = noSign? V9::MOVCCi : V9::MOVGEi; break;
1966 case Instruction::SetLT: opCode = noSign? V9::MOVCSi : V9::MOVLi; break;
1967 case Instruction::SetGT: opCode = noSign? V9::MOVGUi : V9::MOVGi; break;
1968 case Instruction::SetNE: opCode = V9::MOVNEi; break;
1969 default: assert(0 && "Unrecognized LLVM instr!"); break;
1975 /// ChooseMovpregiForSetCC -- Choose a conditional-move-on-register-value
1976 /// instruction based on the type of SetCC operation. These instructions
1977 /// compare a register with 0 and perform the move is the comparison is true.
1979 /// WARNING: like the previous function, this function it always returns
1980 /// the opcode that expects an immediate and a register. See above.
1982 static MachineOpCode ChooseMovpregiForSetCC(const InstructionNode* instrNode) {
1983 MachineOpCode opCode = V9::INVALID_OPCODE;
1985 switch(instrNode->getInstruction()->getOpcode()) {
1986 case Instruction::SetEQ: opCode = V9::MOVRZi; break;
1987 case Instruction::SetLE: opCode = V9::MOVRLEZi; break;
1988 case Instruction::SetGE: opCode = V9::MOVRGEZi; break;
1989 case Instruction::SetLT: opCode = V9::MOVRLZi; break;
1990 case Instruction::SetGT: opCode = V9::MOVRGZi; break;
1991 case Instruction::SetNE: opCode = V9::MOVRNZi; break;
1992 default: assert(0 && "Unrecognized VM instr!"); break;
1998 static inline MachineOpCode
1999 ChooseConvertToFloatInstr(const TargetMachine& target,
2000 OpLabel vopCode, const Type* opType) {
2001 assert((vopCode == ToFloatTy || vopCode == ToDoubleTy) &&
2002 "Unrecognized convert-to-float opcode!");
2003 assert((opType->isIntegral() || opType->isFloatingPoint() ||
2004 isa<PointerType>(opType))
2005 && "Trying to convert a non-scalar type to FLOAT/DOUBLE?");
2007 MachineOpCode opCode = V9::INVALID_OPCODE;
2009 unsigned opSize = target.getTargetData().getTypeSize(opType);
2011 if (opType == Type::FloatTy)
2012 opCode = (vopCode == ToFloatTy? V9::NOP : V9::FSTOD);
2013 else if (opType == Type::DoubleTy)
2014 opCode = (vopCode == ToFloatTy? V9::FDTOS : V9::NOP);
2015 else if (opSize <= 4)
2016 opCode = (vopCode == ToFloatTy? V9::FITOS : V9::FITOD);
2018 assert(opSize == 8 && "Unrecognized type size > 4 and < 8!");
2019 opCode = (vopCode == ToFloatTy? V9::FXTOS : V9::FXTOD);
2025 static inline MachineOpCode
2026 ChooseConvertFPToIntInstr(const TargetMachine& target,
2027 const Type* destType, const Type* opType) {
2028 assert((opType == Type::FloatTy || opType == Type::DoubleTy)
2029 && "This function should only be called for FLOAT or DOUBLE");
2030 assert((destType->isIntegral() || isa<PointerType>(destType))
2031 && "Trying to convert FLOAT/DOUBLE to a non-scalar type?");
2033 MachineOpCode opCode = V9::INVALID_OPCODE;
2035 unsigned destSize = target.getTargetData().getTypeSize(destType);
2037 if (destType == Type::UIntTy)
2038 assert(destType != Type::UIntTy && "Expand FP-to-uint beforehand.");
2039 else if (destSize <= 4)
2040 opCode = (opType == Type::FloatTy)? V9::FSTOI : V9::FDTOI;
2042 assert(destSize == 8 && "Unrecognized type size > 4 and < 8!");
2043 opCode = (opType == Type::FloatTy)? V9::FSTOX : V9::FDTOX;
2049 static MachineInstr*
2050 CreateConvertFPToIntInstr(const TargetMachine& target, Value* srcVal,
2051 Value* destVal, const Type* destType) {
2052 MachineOpCode opCode = ChooseConvertFPToIntInstr(target, destType,
2054 assert(opCode != V9::INVALID_OPCODE && "Expected to need conversion!");
2055 return BuildMI(opCode, 2).addReg(srcVal).addRegDef(destVal);
2058 /// CreateCodeToConvertFloatToInt: Convert FP value to signed or unsigned
2059 /// integer. The FP value must be converted to the dest type in an FP register,
2060 /// and the result is then copied from FP to int register via memory. SPARC
2061 /// does not have a float-to-uint conversion, only a float-to-int (fdtoi).
2062 /// Since fdtoi converts to signed integers, any FP value V between MAXINT+1 and
2063 /// MAXUNSIGNED (i.e., 2^31 <= V <= 2^32-1) would be converted incorrectly.
2064 /// Therefore, for converting an FP value to uint32_t, we first need to convert
2065 /// to uint64_t and then to uint32_t.
2068 CreateCodeToConvertFloatToInt(const TargetMachine& target,
2069 Value* opVal, Instruction* destI,
2070 std::vector<MachineInstr*>& mvec,
2071 MachineCodeForInstruction& mcfi) {
2072 Function* F = destI->getParent()->getParent();
2074 // Create a temporary to represent the FP register into which the
2075 // int value will placed after conversion. The type of this temporary
2076 // depends on the type of FP register to use: single-prec for a 32-bit
2077 // int or smaller; double-prec for a 64-bit int.
2078 size_t destSize = target.getTargetData().getTypeSize(destI->getType());
2080 const Type* castDestType = destI->getType(); // type for the cast instr result
2081 const Type* castDestRegType; // type for cast instruction result reg
2082 TmpInstruction* destForCast; // dest for cast instruction
2083 Instruction* fpToIntCopyDest = destI; // dest for fp-reg-to-int-reg copy instr
2085 // For converting an FP value to uint32_t, we first need to convert to
2086 // uint64_t and then to uint32_t, as explained above.
2087 if (destI->getType() == Type::UIntTy) {
2088 castDestType = Type::ULongTy; // use this instead of type of destI
2089 castDestRegType = Type::DoubleTy; // uint64_t needs 64-bit FP register.
2090 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
2091 fpToIntCopyDest = new TmpInstruction(mcfi, castDestType, destForCast);
2093 castDestRegType = (destSize > 4)? Type::DoubleTy : Type::FloatTy;
2094 destForCast = new TmpInstruction(mcfi, castDestRegType, opVal);
2097 // Create the fp-to-int conversion instruction (src and dest regs are FP regs)
2098 mvec.push_back(CreateConvertFPToIntInstr(target, opVal, destForCast,
2101 // Create the fpreg-to-intreg copy code
2102 CreateCodeToCopyFloatToInt(target, F, destForCast, fpToIntCopyDest, mvec,
2105 // Create the uint64_t to uint32_t conversion, if needed
2106 if (destI->getType() == Type::UIntTy)
2107 CreateZeroExtensionInstructions(target, F, fpToIntCopyDest, destI,
2108 /*numLowBits*/ 32, mvec, mcfi);
2111 static inline MachineOpCode
2112 ChooseAddInstruction(const InstructionNode* instrNode) {
2113 return ChooseAddInstructionByType(instrNode->getInstruction()->getType());
2116 static inline MachineInstr*
2117 CreateMovFloatInstruction(const InstructionNode* instrNode,
2118 const Type* resultType) {
2119 return BuildMI((resultType == Type::FloatTy) ? V9::FMOVS : V9::FMOVD, 2)
2120 .addReg(instrNode->leftChild()->getValue())
2121 .addRegDef(instrNode->getValue());
2124 static inline MachineInstr*
2125 CreateAddConstInstruction(const InstructionNode* instrNode) {
2126 MachineInstr* minstr = NULL;
2128 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2129 assert(isa<Constant>(constOp));
2131 // Cases worth optimizing are:
2132 // (1) Add with 0 for float or double: use an FMOV of appropriate type,
2133 // instead of an FADD (1 vs 3 cycles). There is no integer MOV.
2134 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2135 double dval = FPC->getValue();
2137 minstr = CreateMovFloatInstruction(instrNode,
2138 instrNode->getInstruction()->getType());
2144 static inline MachineOpCode ChooseSubInstructionByType(const Type* resultType) {
2145 MachineOpCode opCode = V9::INVALID_OPCODE;
2147 if (resultType->isInteger() || isa<PointerType>(resultType)) {
2150 switch(resultType->getTypeID()) {
2151 case Type::FloatTyID: opCode = V9::FSUBS; break;
2152 case Type::DoubleTyID: opCode = V9::FSUBD; break;
2153 default: assert(0 && "Invalid type for SUB instruction"); break;
2160 static inline MachineInstr*
2161 CreateSubConstInstruction(const InstructionNode* instrNode) {
2162 MachineInstr* minstr = NULL;
2164 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2165 assert(isa<Constant>(constOp));
2167 // Cases worth optimizing are:
2168 // (1) Sub with 0 for float or double: use an FMOV of appropriate type,
2169 // instead of an FSUB (1 vs 3 cycles). There is no integer MOV.
2170 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2171 double dval = FPC->getValue();
2173 minstr = CreateMovFloatInstruction(instrNode,
2174 instrNode->getInstruction()->getType());
2180 static inline MachineOpCode
2181 ChooseFcmpInstruction(const InstructionNode* instrNode) {
2182 MachineOpCode opCode = V9::INVALID_OPCODE;
2184 Value* operand = ((InstrTreeNode*) instrNode->leftChild())->getValue();
2185 switch(operand->getType()->getTypeID()) {
2186 case Type::FloatTyID: opCode = V9::FCMPS; break;
2187 case Type::DoubleTyID: opCode = V9::FCMPD; break;
2188 default: assert(0 && "Invalid type for FCMP instruction"); break;
2194 /// BothFloatToDouble - Assumes that leftArg and rightArg of instrNode are both
2195 /// cast instructions. Returns true if both are floats cast to double.
2197 static inline bool BothFloatToDouble(const InstructionNode* instrNode) {
2198 InstrTreeNode* leftArg = instrNode->leftChild();
2199 InstrTreeNode* rightArg = instrNode->rightChild();
2200 InstrTreeNode* leftArgArg = leftArg->leftChild();
2201 InstrTreeNode* rightArgArg = rightArg->leftChild();
2202 assert(leftArg->getValue()->getType() == rightArg->getValue()->getType());
2203 return (leftArg->getValue()->getType() == Type::DoubleTy &&
2204 leftArgArg->getValue()->getType() == Type::FloatTy &&
2205 rightArgArg->getValue()->getType() == Type::FloatTy);
2208 static inline MachineOpCode ChooseMulInstructionByType(const Type* resultType) {
2209 MachineOpCode opCode = V9::INVALID_OPCODE;
2211 if (resultType->isInteger())
2214 switch(resultType->getTypeID()) {
2215 case Type::FloatTyID: opCode = V9::FMULS; break;
2216 case Type::DoubleTyID: opCode = V9::FMULD; break;
2217 default: assert(0 && "Invalid type for MUL instruction"); break;
2223 static inline MachineInstr*
2224 CreateIntNegInstruction(const TargetMachine& target, Value* vreg) {
2225 return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo()->getZeroRegNum())
2226 .addReg(vreg).addRegDef(vreg);
2229 static inline MachineInstr*
2230 CreateIntNegInstruction(const TargetMachine& target, Value* vreg, Value *destreg) {
2231 return BuildMI(V9::SUBr, 3).addMReg(target.getRegInfo()->getZeroRegNum())
2232 .addReg(vreg).addRegDef(destreg);
2235 /// CreateShiftInstructions - Create instruction sequence for any shift
2236 /// operation. SLL or SLLX on an operand smaller than the integer reg. size
2237 /// (64bits) requires a second instruction for explicit sign-extension. Note
2238 /// that we only have to worry about a sign-bit appearing in the most
2239 /// significant bit of the operand after shifting (e.g., bit 32 of Int or bit 16
2240 /// of Short), so we do not have to worry about results that are as large as a
2241 /// normal integer register.
2244 CreateShiftInstructions(const TargetMachine& target, Function* F,
2245 MachineOpCode shiftOpCode, Value* argVal1,
2246 Value* optArgVal2, /* Use optArgVal2 if not NULL */
2247 unsigned optShiftNum, /* else use optShiftNum */
2248 Instruction* destVal, std::vector<MachineInstr*>& mvec,
2249 MachineCodeForInstruction& mcfi) {
2250 assert((optArgVal2 != NULL || optShiftNum <= 64) &&
2251 "Large shift sizes unexpected, but can be handled below: "
2252 "You need to check whether or not it fits in immed field below");
2254 // If this is a logical left shift of a type smaller than the standard
2255 // integer reg. size, we have to extend the sign-bit into upper bits
2256 // of dest, so we need to put the result of the SLL into a temporary.
2257 Value* shiftDest = destVal;
2258 unsigned opSize = target.getTargetData().getTypeSize(argVal1->getType());
2260 if ((shiftOpCode == V9::SLLr5 || shiftOpCode == V9::SLLXr6) && opSize < 8) {
2261 // put SLL result into a temporary
2262 shiftDest = new TmpInstruction(mcfi, argVal1, optArgVal2, "sllTmp");
2265 MachineInstr* M = (optArgVal2 != NULL)
2266 ? BuildMI(shiftOpCode, 3).addReg(argVal1).addReg(optArgVal2)
2267 .addReg(shiftDest, MachineOperand::Def)
2268 : BuildMI(shiftOpCode, 3).addReg(argVal1).addZImm(optShiftNum)
2269 .addReg(shiftDest, MachineOperand::Def);
2272 if (shiftDest != destVal) {
2273 // extend the sign-bit of the result into all upper bits of dest
2274 assert(8*opSize <= 32 && "Unexpected type size > 4 and < IntRegSize?");
2275 CreateSignExtensionInstructions(target, F, shiftDest, destVal, 8*opSize,
2280 /// CreateMulConstInstruction - Does not create any instructions if we
2281 /// cannot exploit constant to create a cheaper instruction. This returns the
2282 /// approximate cost of the instructions generated, which is used to pick the
2283 /// cheapest when both operands are constant.
2286 CreateMulConstInstruction(const TargetMachine &target, Function* F,
2287 Value* lval, Value* rval, Instruction* destVal,
2288 std::vector<MachineInstr*>& mvec,
2289 MachineCodeForInstruction& mcfi) {
2290 // Use max. multiply cost, viz., cost of MULX
2291 unsigned cost = target.getInstrInfo()->minLatency(V9::MULXr);
2292 unsigned firstNewInstr = mvec.size();
2294 Value* constOp = rval;
2295 if (! isa<Constant>(constOp))
2298 // Cases worth optimizing are:
2299 // (1) Multiply by 0 or 1 for any type: replace with copy (ADD or FMOV)
2300 // (2) Multiply by 2^x for integer types: replace with Shift
2301 const Type* resultType = destVal->getType();
2303 if (resultType->isInteger() || isa<PointerType>(resultType)) {
2305 int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2309 bool needNeg = false;
2314 TmpInstruction *tmpNeg = 0;
2316 if (C == 0 || C == 1) {
2317 cost = target.getInstrInfo()->minLatency(V9::ADDr);
2318 unsigned Zero = target.getRegInfo()->getZeroRegNum();
2321 M =BuildMI(V9::ADDr,3).addMReg(Zero).addMReg(Zero).addRegDef(destVal);
2323 M = BuildMI(V9::ADDr,3).addReg(lval).addMReg(Zero).addRegDef(destVal);
2325 } else if (isPowerOf2_64(C)) {
2326 unsigned pow = Log2_64(C);
2328 unsigned opSize = target.getTargetData().getTypeSize(resultType);
2329 MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
2330 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
2331 destVal, mvec, mcfi);
2334 //Create tmp instruction to hold intermeidate value, since we need
2335 //to negate the result
2336 tmpNeg = new TmpInstruction(mcfi, lval);
2337 unsigned opSize = target.getTargetData().getTypeSize(resultType);
2338 MachineOpCode opCode = (opSize <= 32)? V9::SLLr5 : V9::SLLXr6;
2339 CreateShiftInstructions(target, F, opCode, lval, NULL, pow,
2340 tmpNeg, mvec, mcfi);
2345 if (mvec.size() > 0 && needNeg) {
2346 MachineInstr* M = 0;
2348 // insert <reg = SUB 0, reg> after the instr to flip the sign
2349 M = CreateIntNegInstruction(target, tmpNeg, destVal);
2351 M = CreateIntNegInstruction(target, destVal);
2356 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2357 double dval = FPC->getValue();
2358 if (fabs(dval) == 1) {
2359 MachineOpCode opCode = (dval < 0)
2360 ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2361 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2362 mvec.push_back(BuildMI(opCode,2).addReg(lval).addRegDef(destVal));
2367 if (firstNewInstr < mvec.size()) {
2369 for (unsigned i=firstNewInstr; i < mvec.size(); ++i)
2370 cost += target.getInstrInfo()->minLatency(mvec[i]->getOpcode());
2376 /// CreateCheapestMulConstInstruction - Does not create any instructions
2377 /// if we cannot exploit constant to create a cheaper instruction.
2380 CreateCheapestMulConstInstruction(const TargetMachine &target, Function* F,
2381 Value* lval, Value* rval,
2382 Instruction* destVal,
2383 std::vector<MachineInstr*>& mvec,
2384 MachineCodeForInstruction& mcfi) {
2386 if (isa<Constant>(lval) && isa<Constant>(rval)) {
2387 // both operands are constant: evaluate and "set" in dest
2388 Constant* P = ConstantExpr::get(Instruction::Mul,
2389 cast<Constant>(lval),
2390 cast<Constant>(rval));
2391 CreateCodeToLoadConst (target, F, P, destVal, mvec, mcfi);
2393 else if (isa<Constant>(rval)) // rval is constant, but not lval
2394 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2395 else if (isa<Constant>(lval)) // lval is constant, but not rval
2396 CreateMulConstInstruction(target, F, lval, rval, destVal, mvec, mcfi);
2398 // else neither is constant
2402 /// CreateMulInstruction - Returns NULL if we cannot exploit constant
2403 /// to create a cheaper instruction.
2406 CreateMulInstruction(const TargetMachine &target, Function* F,
2407 Value* lval, Value* rval, Instruction* destVal,
2408 std::vector<MachineInstr*>& mvec,
2409 MachineCodeForInstruction& mcfi,
2410 MachineOpCode forceMulOp = -1) {
2411 unsigned L = mvec.size();
2412 CreateCheapestMulConstInstruction(target,F, lval, rval, destVal, mvec, mcfi);
2413 if (mvec.size() == L) {
2414 // no instructions were added so create MUL reg, reg, reg.
2415 // Use FSMULD if both operands are actually floats cast to doubles.
2416 // Otherwise, use the default opcode for the appropriate type.
2417 MachineOpCode mulOp = ((forceMulOp != -1)
2419 : ChooseMulInstructionByType(destVal->getType()));
2420 mvec.push_back(BuildMI(mulOp, 3).addReg(lval).addReg(rval)
2421 .addRegDef(destVal));
2425 /// ChooseDivInstruction - Generate a divide instruction for Div or Rem.
2426 /// For Rem, this assumes that the operand type will be signed if the result
2427 /// type is signed. This is correct because they must have the same sign.
2429 static inline MachineOpCode
2430 ChooseDivInstruction(TargetMachine &target, const InstructionNode* instrNode) {
2431 MachineOpCode opCode = V9::INVALID_OPCODE;
2433 const Type* resultType = instrNode->getInstruction()->getType();
2435 if (resultType->isInteger())
2436 opCode = resultType->isSigned()? V9::SDIVXr : V9::UDIVXr;
2438 switch(resultType->getTypeID()) {
2439 case Type::FloatTyID: opCode = V9::FDIVS; break;
2440 case Type::DoubleTyID: opCode = V9::FDIVD; break;
2441 default: assert(0 && "Invalid type for DIV instruction"); break;
2447 /// CreateDivConstInstruction - Return if we cannot exploit constant to create
2448 /// a cheaper instruction.
2450 static void CreateDivConstInstruction(TargetMachine &target,
2451 const InstructionNode* instrNode,
2452 std::vector<MachineInstr*>& mvec) {
2453 Value* LHS = instrNode->leftChild()->getValue();
2454 Value* constOp = ((InstrTreeNode*) instrNode->rightChild())->getValue();
2455 if (!isa<Constant>(constOp))
2458 Instruction* destVal = instrNode->getInstruction();
2459 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
2461 // Cases worth optimizing are:
2462 // (1) Divide by 1 for any type: replace with copy (ADD or FMOV)
2463 // (2) Divide by 2^x for integer types: replace with SR[L or A]{X}
2464 const Type* resultType = instrNode->getInstruction()->getType();
2466 if (resultType->isInteger()) {
2468 int64_t C = (int64_t) ConvertConstantToIntType(target, constOp,
2472 bool needNeg = false;
2479 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addMReg(ZeroReg)
2480 .addRegDef(destVal));
2481 } else if (isPowerOf2_64(C)) {
2482 unsigned pow = Log2_64(C);
2484 Value* shiftOperand;
2485 unsigned opSize = target.getTargetData().getTypeSize(resultType);
2487 if (resultType->isSigned()) {
2488 // For N / 2^k, if the operand N is negative,
2489 // we need to add (2^k - 1) before right-shifting by k, i.e.,
2491 // (N / 2^k) = N >> k, if N >= 0;
2492 // (N + 2^k - 1) >> k, if N < 0
2494 // If N is <= 32 bits, use:
2495 // sra N, 31, t1 // t1 = ~0, if N < 0, 0 else
2496 // srl t1, 32-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
2497 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
2498 // sra t3, k, result // result = N / 2^k
2500 // If N is 64 bits, use:
2501 // srax N, k-1, t1 // t1 = sign bit in high k positions
2502 // srlx t1, 64-k, t2 // t2 = 2^k - 1, if N < 0, 0 else
2503 // add t2, N, t3 // t3 = N + 2^k -1, if N < 0, N else
2504 // sra t3, k, result // result = N / 2^k
2505 TmpInstruction *sraTmp, *srlTmp, *addTmp;
2506 MachineCodeForInstruction& mcfi
2507 = MachineCodeForInstruction::get(destVal);
2508 sraTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getSign");
2509 srlTmp = new TmpInstruction(mcfi, resultType, LHS, 0, "getPlus2km1");
2510 addTmp = new TmpInstruction(mcfi, resultType, LHS, srlTmp,"incIfNeg");
2512 // Create the SRA or SRAX instruction to get the sign bit
2513 mvec.push_back(BuildMI((opSize > 4)? V9::SRAXi6 : V9::SRAi5, 3)
2515 .addSImm((resultType==Type::LongTy)? pow-1 : 31)
2516 .addRegDef(sraTmp));
2518 // Create the SRL or SRLX instruction to get the sign bit
2519 mvec.push_back(BuildMI((opSize > 4)? V9::SRLXi6 : V9::SRLi5, 3)
2521 .addSImm((resultType==Type::LongTy)? 64-pow : 32-pow)
2522 .addRegDef(srlTmp));
2524 // Create the ADD instruction to add 2^pow-1 for negative values
2525 mvec.push_back(BuildMI(V9::ADDr, 3).addReg(LHS).addReg(srlTmp)
2526 .addRegDef(addTmp));
2528 // Get the shift operand and "right-shift" opcode to do the divide
2529 shiftOperand = addTmp;
2530 opCode = (opSize > 4)? V9::SRAXi6 : V9::SRAi5;
2532 // Get the shift operand and "right-shift" opcode to do the divide
2534 opCode = (opSize > 4)? V9::SRLXi6 : V9::SRLi5;
2537 // Now do the actual shift!
2538 mvec.push_back(BuildMI(opCode, 3).addReg(shiftOperand).addZImm(pow)
2539 .addRegDef(destVal));
2542 if (needNeg && (C == 1 || isPowerOf2_64(C))) {
2543 // insert <reg = SUB 0, reg> after the instr to flip the sign
2544 mvec.push_back(CreateIntNegInstruction(target, destVal));
2548 if (ConstantFP *FPC = dyn_cast<ConstantFP>(constOp)) {
2549 double dval = FPC->getValue();
2550 if (fabs(dval) == 1) {
2552 (dval < 0) ? (resultType == Type::FloatTy? V9::FNEGS : V9::FNEGD)
2553 : (resultType == Type::FloatTy? V9::FMOVS : V9::FMOVD);
2555 mvec.push_back(BuildMI(opCode, 2).addReg(LHS).addRegDef(destVal));
2561 static void CreateCodeForVariableSizeAlloca(const TargetMachine& target,
2562 Instruction* result, unsigned tsize,
2563 Value* numElementsVal,
2564 std::vector<MachineInstr*>& getMvec)
2566 Value* totalSizeVal;
2568 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(result);
2569 Function *F = result->getParent()->getParent();
2571 // Enforce the alignment constraints on the stack pointer at
2572 // compile time if the total size is a known constant.
2573 if (isa<Constant>(numElementsVal)) {
2575 int64_t numElem = (int64_t)
2576 ConvertConstantToIntType(target, numElementsVal,
2577 numElementsVal->getType(), isValid);
2578 assert(isValid && "Unexpectedly large array dimension in alloca!");
2579 int64_t total = numElem * tsize;
2580 if (int extra= total % SparcV9FrameInfo::StackFrameSizeAlignment)
2581 total += SparcV9FrameInfo::StackFrameSizeAlignment - extra;
2582 totalSizeVal = ConstantSInt::get(Type::IntTy, total);
2584 // The size is not a constant. Generate code to compute it and
2585 // code to pad the size for stack alignment.
2586 // Create a Value to hold the (constant) element size
2587 Value* tsizeVal = ConstantSInt::get(Type::IntTy, tsize);
2589 // Create temporary values to hold the result of MUL, SLL, SRL
2590 // To pad `size' to next smallest multiple of 16:
2591 // size = (size + 15) & (-16 = 0xfffffffffffffff0)
2592 TmpInstruction* tmpProd = new TmpInstruction(mcfi,numElementsVal, tsizeVal);
2593 TmpInstruction* tmpAdd15= new TmpInstruction(mcfi,numElementsVal, tmpProd);
2594 TmpInstruction* tmpAndf0= new TmpInstruction(mcfi,numElementsVal, tmpAdd15);
2596 // Instruction 1: mul numElements, typeSize -> tmpProd
2597 // This will optimize the MUL as far as possible.
2598 CreateMulInstruction(target, F, numElementsVal, tsizeVal, tmpProd, getMvec,
2601 // Instruction 2: andn tmpProd, 0x0f -> tmpAndn
2602 getMvec.push_back(BuildMI(V9::ADDi, 3).addReg(tmpProd).addSImm(15)
2603 .addReg(tmpAdd15, MachineOperand::Def));
2605 // Instruction 3: add tmpAndn, 0x10 -> tmpAdd16
2606 getMvec.push_back(BuildMI(V9::ANDi, 3).addReg(tmpAdd15).addSImm(-16)
2607 .addReg(tmpAndf0, MachineOperand::Def));
2609 totalSizeVal = tmpAndf0;
2612 // Get the constant offset from SP for dynamically allocated storage
2613 // and create a temporary Value to hold it.
2614 MachineFunction& mcInfo = MachineFunction::get(F);
2616 ConstantSInt* dynamicAreaOffset =
2617 ConstantSInt::get(Type::IntTy,
2618 target.getFrameInfo()->getDynamicAreaOffset(mcInfo,growUp));
2619 assert(! growUp && "Has SPARC v9 stack frame convention changed?");
2621 unsigned SPReg = target.getRegInfo()->getStackPointer();
2623 // Instruction 2: sub %sp, totalSizeVal -> %sp
2624 getMvec.push_back(BuildMI(V9::SUBr, 3).addMReg(SPReg).addReg(totalSizeVal)
2625 .addMReg(SPReg,MachineOperand::Def));
2627 // Instruction 3: add %sp, frameSizeBelowDynamicArea -> result
2628 getMvec.push_back(BuildMI(V9::ADDr,3).addMReg(SPReg).addReg(dynamicAreaOffset)
2629 .addRegDef(result));
2633 CreateCodeForFixedSizeAlloca(const TargetMachine& target,
2634 Instruction* result, unsigned tsize,
2635 unsigned numElements,
2636 std::vector<MachineInstr*>& getMvec) {
2637 assert(result && result->getParent() &&
2638 "Result value is not part of a function?");
2639 Function *F = result->getParent()->getParent();
2640 MachineFunction &mcInfo = MachineFunction::get(F);
2642 // If the alloca is of zero bytes (which is perfectly legal) we bump it up to
2643 // one byte. This is unnecessary, but I really don't want to break any
2644 // fragile logic in this code. FIXME.
2648 // Put the variable in the dynamically sized area of the frame if either:
2649 // (a) The offset is too large to use as an immediate in load/stores
2650 // (check LDX because all load/stores have the same-size immed. field).
2651 // (b) The object is "large", so it could cause many other locals,
2652 // spills, and temporaries to have large offsets.
2653 // NOTE: We use LARGE = 8 * argSlotSize = 64 bytes.
2654 // You've gotta love having only 13 bits for constant offset values :-|.
2656 unsigned paddedSize;
2657 int offsetFromFP = mcInfo.getInfo<SparcV9FunctionInfo>()->computeOffsetforLocalVar(result,
2659 tsize * numElements);
2661 if (((int)paddedSize) > 8 * SparcV9FrameInfo::SizeOfEachArgOnStack ||
2662 !target.getInstrInfo()->constantFitsInImmedField(V9::LDXi,offsetFromFP)) {
2663 CreateCodeForVariableSizeAlloca(target, result, tsize,
2664 ConstantSInt::get(Type::IntTy,numElements),
2669 // else offset fits in immediate field so go ahead and allocate it.
2670 offsetFromFP = mcInfo.getInfo<SparcV9FunctionInfo>()->allocateLocalVar(result, tsize *numElements);
2672 // Create a temporary Value to hold the constant offset.
2673 // This is needed because it may not fit in the immediate field.
2674 ConstantSInt* offsetVal = ConstantSInt::get(Type::IntTy, offsetFromFP);
2676 // Instruction 1: add %fp, offsetFromFP -> result
2677 unsigned FPReg = target.getRegInfo()->getFramePointer();
2678 getMvec.push_back(BuildMI(V9::ADDr, 3).addMReg(FPReg).addReg(offsetVal)
2679 .addRegDef(result));
2682 /// SetOperandsForMemInstr - Choose addressing mode for the given load or store
2683 /// instruction. Use [reg+reg] if it is an indexed reference, and the index
2684 /// offset is not a constant or if it cannot fit in the offset field. Use
2685 /// [reg+offset] in all other cases. This assumes that all array refs are
2686 /// "lowered" to one of these forms:
2687 /// %x = load (subarray*) ptr, constant ; single constant offset
2688 /// %x = load (subarray*) ptr, offsetVal ; single non-constant offset
2689 /// Generally, this should happen via strength reduction + LICM. Also, strength
2690 /// reduction should take care of using the same register for the loop index
2691 /// variable and an array index, when that is profitable.
2693 static void SetOperandsForMemInstr(unsigned Opcode,
2694 std::vector<MachineInstr*>& mvec,
2695 InstructionNode* vmInstrNode,
2696 const TargetMachine& target) {
2697 Instruction* memInst = vmInstrNode->getInstruction();
2698 // Index vector, ptr value, and flag if all indices are const.
2699 std::vector<Value*> idxVec;
2700 bool allConstantIndices;
2701 Value* ptrVal = GetMemInstArgs(vmInstrNode, idxVec, allConstantIndices);
2703 // Now create the appropriate operands for the machine instruction.
2704 // First, initialize so we default to storing the offset in a register.
2705 int64_t smallConstOffset = 0;
2706 Value* valueForRegOffset = NULL;
2707 MachineOperand::MachineOperandType offsetOpType =
2708 MachineOperand::MO_VirtualRegister;
2710 // Check if there is an index vector and if so, compute the
2711 // right offset for structures and for arrays
2712 if (!idxVec.empty()) {
2713 const PointerType* ptrType = cast<PointerType>(ptrVal->getType());
2715 // If all indices are constant, compute the combined offset directly.
2716 if (allConstantIndices) {
2717 // Compute the offset value using the index vector. Create a
2718 // virtual reg. for it since it may not fit in the immed field.
2719 uint64_t offset = target.getTargetData().getIndexedOffset(ptrType,idxVec);
2720 valueForRegOffset = ConstantSInt::get(Type::LongTy, offset);
2722 // There is at least one non-constant offset. Therefore, this must
2723 // be an array ref, and must have been lowered to a single non-zero
2724 // offset. (An extra leading zero offset, if any, can be ignored.)
2725 // Generate code sequence to compute address from index.
2726 bool firstIdxIsZero = IsZero(idxVec[0]);
2727 assert(idxVec.size() == 1U + firstIdxIsZero
2728 && "Array refs must be lowered before Instruction Selection");
2730 Value* idxVal = idxVec[firstIdxIsZero];
2732 std::vector<MachineInstr*> mulVec;
2734 new TmpInstruction(MachineCodeForInstruction::get(memInst),
2735 Type::ULongTy, memInst);
2737 // Get the array type indexed by idxVal, and compute its element size.
2738 // The call to getTypeSize() will fail if size is not constant.
2739 const Type* vecType = (firstIdxIsZero
2740 ? GetElementPtrInst::getIndexedType(ptrType,
2741 std::vector<Value*>(1U, idxVec[0]),
2742 /*AllowCompositeLeaf*/ true)
2744 const Type* eltType = cast<SequentialType>(vecType)->getElementType();
2745 ConstantUInt* eltSizeVal = ConstantUInt::get(Type::ULongTy,
2746 target.getTargetData().getTypeSize(eltType));
2748 // CreateMulInstruction() folds constants intelligently enough.
2749 CreateMulInstruction(target, memInst->getParent()->getParent(),
2750 idxVal, /* lval, not likely to be const*/
2751 eltSizeVal, /* rval, likely to be constant */
2753 mulVec, MachineCodeForInstruction::get(memInst),
2756 assert(mulVec.size() > 0 && "No multiply code created?");
2757 mvec.insert(mvec.end(), mulVec.begin(), mulVec.end());
2759 valueForRegOffset = addr;
2762 offsetOpType = MachineOperand::MO_SignExtendedImmed;
2763 smallConstOffset = 0;
2767 // Operand 0 is value, operand 1 is ptr, operand 2 is offset
2768 // For LOAD or GET_ELEMENT_PTR,
2769 // Operand 0 is ptr, operand 1 is offset, operand 2 is result.
2770 unsigned offsetOpNum, ptrOpNum;
2772 if (memInst->getOpcode() == Instruction::Store) {
2773 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2774 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2775 .addReg(ptrVal).addReg(valueForRegOffset);
2777 Opcode = convertOpcodeFromRegToImm(Opcode);
2778 MI = BuildMI(Opcode, 3).addReg(vmInstrNode->leftChild()->getValue())
2779 .addReg(ptrVal).addSImm(smallConstOffset);
2782 if (offsetOpType == MachineOperand::MO_VirtualRegister) {
2783 MI = BuildMI(Opcode, 3).addReg(ptrVal).addReg(valueForRegOffset)
2784 .addRegDef(memInst);
2786 Opcode = convertOpcodeFromRegToImm(Opcode);
2787 MI = BuildMI(Opcode, 3).addReg(ptrVal).addSImm(smallConstOffset)
2788 .addRegDef(memInst);
2794 /// ForwardOperand - Substitute operand `operandNum' of the instruction in
2795 /// node `treeNode' in place of the use(s) of that instruction in node `parent'.
2796 /// Check both explicit and implicit operands! Also make sure to skip over a
2797 /// parent who: (1) is a list node in the Burg tree, or (2) itself had its
2798 /// results forwarded to its parent.
2800 static void ForwardOperand (InstructionNode *treeNode, InstrTreeNode *parent,
2802 assert(treeNode && parent && "Invalid invocation of ForwardOperand");
2804 Instruction* unusedOp = treeNode->getInstruction();
2805 Value* fwdOp = unusedOp->getOperand(operandNum);
2807 // The parent itself may be a list node, so find the real parent instruction
2808 while (parent->getNodeType() != InstrTreeNode::NTInstructionNode) {
2809 parent = parent->parent();
2810 assert(parent && "ERROR: Non-instruction node has no parent in tree.");
2812 InstructionNode* parentInstrNode = (InstructionNode*) parent;
2814 Instruction* userInstr = parentInstrNode->getInstruction();
2815 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(userInstr);
2817 // The parent's mvec would be empty if it was itself forwarded.
2818 // Recursively call ForwardOperand in that case...
2820 if (mvec.size() == 0) {
2821 assert(parent->parent() != NULL &&
2822 "Parent could not have been forwarded, yet has no instructions?");
2823 ForwardOperand(treeNode, parent->parent(), operandNum);
2825 for (unsigned i=0, N=mvec.size(); i < N; i++) {
2826 MachineInstr* minstr = mvec[i];
2827 for (unsigned i=0, numOps=minstr->getNumOperands(); i < numOps; ++i) {
2828 const MachineOperand& mop = minstr->getOperand(i);
2829 if (mop.getType() == MachineOperand::MO_VirtualRegister &&
2830 mop.getVRegValue() == unusedOp) {
2831 minstr->SetMachineOperandVal(i, MachineOperand::MO_VirtualRegister,
2836 for (unsigned i=0,numOps=minstr->getNumImplicitRefs(); i<numOps; ++i)
2837 if (minstr->getImplicitRef(i) == unusedOp)
2838 minstr->setImplicitRef(i, fwdOp);
2843 /// AllUsesAreBranches - Returns true if all the uses of I are
2844 /// Branch instructions, false otherwise.
2846 inline bool AllUsesAreBranches(const Instruction* I) {
2847 for (Value::use_const_iterator UI=I->use_begin(), UE=I->use_end();
2849 if (! isa<TmpInstruction>(*UI) // ignore tmp instructions here
2850 && cast<Instruction>(*UI)->getOpcode() != Instruction::Br)
2855 /// CodeGenIntrinsic - Generate code for any intrinsic that needs a special
2856 /// code sequence instead of a regular call. If not that kind of intrinsic, do
2857 /// nothing. Returns true if code was generated, otherwise false.
2859 static bool CodeGenIntrinsic(Intrinsic::ID iid, CallInst &callInstr,
2860 TargetMachine &target,
2861 std::vector<MachineInstr*>& mvec) {
2864 assert(0 && "Unknown intrinsic function call should have been lowered!");
2865 case Intrinsic::vastart: {
2866 // Get the address of the first incoming vararg argument on the stack
2867 Function* func = cast<Function>(callInstr.getParent()->getParent());
2868 int numFixedArgs = func->getFunctionType()->getNumParams();
2869 int fpReg = SparcV9::i6;
2870 int firstVarArgOff = numFixedArgs * 8 +
2871 SparcV9FrameInfo::FirstIncomingArgOffsetFromFP;
2872 //What oh what do we pass to TmpInstruction?
2873 MachineCodeForInstruction& m = MachineCodeForInstruction::get(&callInstr);
2874 TmpInstruction* T = new TmpInstruction(m, callInstr.getOperand(1)->getType());
2875 mvec.push_back(BuildMI(V9::ADDi, 3).addMReg(fpReg).addSImm(firstVarArgOff).addRegDef(T));
2876 mvec.push_back(BuildMI(V9::STXr, 3).addReg(T).addReg(callInstr.getOperand(1)).addSImm(0));
2880 case Intrinsic::vaend:
2881 return true; // no-op on SparcV9
2883 case Intrinsic::vacopy:
2885 MachineCodeForInstruction& m1 = MachineCodeForInstruction::get(&callInstr);
2886 TmpInstruction* VReg =
2887 new TmpInstruction(m1, callInstr.getOperand(1)->getType());
2889 // Simple store of current va_list (arg2) to new va_list (arg1)
2890 mvec.push_back(BuildMI(V9::LDXi, 3).
2891 addReg(callInstr.getOperand(2)).addSImm(0).addRegDef(VReg));
2892 mvec.push_back(BuildMI(V9::STXi, 3).
2893 addReg(VReg).addReg(callInstr.getOperand(1)).addSImm(0));
2899 /// ThisIsAChainRule - returns true if the given BURG rule is a chain rule.
2901 extern bool ThisIsAChainRule(int eruleno) {
2903 case 111: // stmt: reg
2932 /// GetInstructionsByRule - Choose machine instructions for the
2933 /// SPARC V9 according to the patterns chosen by the BURG-generated parser.
2934 /// This is where most of the work in the V9 instruction selector gets done.
2936 void GetInstructionsByRule(InstructionNode* subtreeRoot, int ruleForNode,
2937 short* nts, TargetMachine &target,
2938 std::vector<MachineInstr*>& mvec) {
2939 bool checkCast = false; // initialize here to use fall-through
2940 bool maskUnsignedResult = false;
2942 int forwardOperandNum = -1;
2943 unsigned allocaSize = 0;
2944 MachineInstr* M, *M2;
2946 bool foldCase = false;
2950 // If the code for this instruction was folded into the parent (user),
2952 if (subtreeRoot->isFoldedIntoParent())
2955 // Let's check for chain rules outside the switch so that we don't have
2956 // to duplicate the list of chain rule production numbers here again
2957 if (ThisIsAChainRule(ruleForNode)) {
2958 // Chain rules have a single nonterminal on the RHS.
2959 // Get the rule that matches the RHS non-terminal and use that instead.
2960 assert(nts[0] && ! nts[1]
2961 && "A chain rule should have only one RHS non-terminal!");
2962 nextRule = burm_rule(subtreeRoot->state, nts[0]);
2963 nts = burm_nts[nextRule];
2964 GetInstructionsByRule(subtreeRoot, nextRule, nts, target, mvec);
2966 switch(ruleForNode) {
2967 case 1: // stmt: Ret
2968 case 2: // stmt: RetValue(reg)
2969 { // NOTE: Prepass of register allocation is responsible
2970 // for moving return value to appropriate register.
2971 // Copy the return value to the required return register.
2972 // Mark the return Value as an implicit ref of the RET instr..
2973 // Mark the return-address register as a hidden virtual reg.
2974 // Finally put a NOP in the delay slot.
2975 ReturnInst *returnInstr=cast<ReturnInst>(subtreeRoot->getInstruction());
2976 Value* retVal = returnInstr->getReturnValue();
2977 MachineCodeForInstruction& mcfi =
2978 MachineCodeForInstruction::get(returnInstr);
2980 // Create a hidden virtual reg to represent the return address register
2981 // used by the machine instruction but not represented in LLVM.
2982 Instruction* returnAddrTmp = new TmpInstruction(mcfi, returnInstr);
2984 MachineInstr* retMI =
2985 BuildMI(V9::JMPLRETi, 3).addReg(returnAddrTmp).addSImm(8)
2986 .addMReg(target.getRegInfo()->getZeroRegNum(), MachineOperand::Def);
2988 // If there is a value to return, we need to:
2989 // (a) Sign-extend the value if it is smaller than 8 bytes (reg size)
2990 // (b) Insert a copy to copy the return value to the appropriate reg.
2991 // -- For FP values, create a FMOVS or FMOVD instruction
2992 // -- For non-FP values, create an add-with-0 instruction
2993 if (retVal != NULL) {
2994 const SparcV9RegInfo& regInfo =
2995 (SparcV9RegInfo&) *target.getRegInfo();
2996 const Type* retType = retVal->getType();
2997 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
2998 unsigned retRegNum = (retType->isFloatingPoint()
2999 ? (unsigned) SparcV9FloatRegClass::f0
3000 : (unsigned) SparcV9IntRegClass::i0);
3001 retRegNum = regInfo.getUnifiedRegNum(regClassID, retRegNum);
3003 // Insert sign-extension instructions for small signed values.
3004 Value* retValToUse = retVal;
3005 if (retType->isIntegral() && retType->isSigned()) {
3006 unsigned retSize = target.getTargetData().getTypeSize(retType);
3008 // Create a temporary virtual reg. to hold the sign-extension.
3009 retValToUse = new TmpInstruction(mcfi, retVal);
3011 // Sign-extend retVal and put the result in the temporary reg.
3012 CreateSignExtensionInstructions
3013 (target, returnInstr->getParent()->getParent(),
3014 retVal, retValToUse, 8*retSize, mvec, mcfi);
3018 // (b) Now, insert a copy to to the appropriate register:
3019 // -- For FP values, create a FMOVS or FMOVD instruction
3020 // -- For non-FP values, create an add-with-0 instruction
3021 // First, create a virtual register to represent the register and
3022 // mark this vreg as being an implicit operand of the ret MI.
3023 TmpInstruction* retVReg =
3024 new TmpInstruction(mcfi, retValToUse, NULL, "argReg");
3026 retMI->addImplicitRef(retVReg);
3028 if (retType->isFloatingPoint())
3029 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
3030 .addReg(retValToUse).addReg(retVReg, MachineOperand::Def));
3032 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
3033 .addReg(retValToUse).addSImm((int64_t) 0)
3034 .addReg(retVReg, MachineOperand::Def));
3036 // Mark the operand with the register it should be assigned
3037 M->SetRegForOperand(M->getNumOperands()-1, retRegNum);
3038 retMI->SetRegForImplicitRef(retMI->getNumImplicitRefs()-1, retRegNum);
3043 // Now insert the RET instruction and a NOP for the delay slot
3044 mvec.push_back(retMI);
3045 mvec.push_back(BuildMI(V9::NOP, 0));
3050 case 3: // stmt: Store(reg,reg)
3051 case 4: // stmt: Store(reg,ptrreg)
3052 SetOperandsForMemInstr(ChooseStoreInstruction(
3053 subtreeRoot->leftChild()->getValue()->getType()),
3054 mvec, subtreeRoot, target);
3057 case 5: // stmt: BrUncond
3059 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
3060 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(0)));
3063 mvec.push_back(BuildMI(V9::NOP, 0));
3067 case 206: // stmt: BrCond(setCCconst)
3068 { // setCCconst => boolean was computed with `%b = setCC type reg1 const'
3069 // If the constant is ZERO, we can use the branch-on-integer-register
3070 // instructions and avoid the SUBcc instruction entirely.
3071 // Otherwise this is just the same as case 5, so just fall through.
3073 InstrTreeNode* constNode = subtreeRoot->leftChild()->rightChild();
3075 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
3076 Constant *constVal = cast<Constant>(constNode->getValue());
3079 if ((constVal->getType()->isInteger()
3080 || isa<PointerType>(constVal->getType()))
3081 && ConvertConstantToIntType(target,
3082 constVal, constVal->getType(), isValidConst) == 0
3085 // That constant is a zero after all...
3086 // Use the left child of setCC as the first argument!
3087 // Mark the setCC node so that no code is generated for it.
3088 InstructionNode* setCCNode = (InstructionNode*)
3089 subtreeRoot->leftChild();
3090 assert(setCCNode->getOpLabel() == SetCCOp);
3091 setCCNode->markFoldedIntoParent();
3093 BranchInst* brInst=cast<BranchInst>(subtreeRoot->getInstruction());
3095 M = BuildMI(ChooseBprInstruction(subtreeRoot), 2)
3096 .addReg(setCCNode->leftChild()->getValue())
3097 .addPCDisp(brInst->getSuccessor(0));
3101 mvec.push_back(BuildMI(V9::NOP, 0));
3104 mvec.push_back(BuildMI(V9::BA, 1)
3105 .addPCDisp(brInst->getSuccessor(1)));
3108 mvec.push_back(BuildMI(V9::NOP, 0));
3111 // ELSE FALL THROUGH
3114 case 6: // stmt: BrCond(setCC)
3115 { // bool => boolean was computed with SetCC.
3116 // The branch to use depends on whether it is FP, signed, or unsigned.
3117 // If it is an integer CC, we also need to find the unique
3118 // TmpInstruction representing that CC.
3120 BranchInst* brInst = cast<BranchInst>(subtreeRoot->getInstruction());
3121 const Type* setCCType;
3122 unsigned Opcode = ChooseBccInstruction(subtreeRoot, setCCType);
3123 Value* ccValue = GetTmpForCC(subtreeRoot->leftChild()->getValue(),
3124 brInst->getParent()->getParent(),
3126 MachineCodeForInstruction::get(brInst));
3127 M = BuildMI(Opcode, 2).addCCReg(ccValue)
3128 .addPCDisp(brInst->getSuccessor(0));
3132 mvec.push_back(BuildMI(V9::NOP, 0));
3135 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(brInst->getSuccessor(1)));
3138 mvec.push_back(BuildMI(V9::NOP, 0));
3142 case 208: // stmt: BrCond(boolconst)
3144 // boolconst => boolean is a constant; use BA to first or second label
3145 Constant* constVal =
3146 cast<Constant>(subtreeRoot->leftChild()->getValue());
3147 unsigned dest = cast<ConstantBool>(constVal)->getValue()? 0 : 1;
3149 M = BuildMI(V9::BA, 1).addPCDisp(
3150 cast<BranchInst>(subtreeRoot->getInstruction())->getSuccessor(dest));
3154 mvec.push_back(BuildMI(V9::NOP, 0));
3158 case 8: // stmt: BrCond(boolreg)
3159 { // boolreg => boolean is recorded in an integer register.
3160 // Use branch-on-integer-register instruction.
3162 BranchInst *BI = cast<BranchInst>(subtreeRoot->getInstruction());
3163 M = BuildMI(V9::BRNZ, 2).addReg(subtreeRoot->leftChild()->getValue())
3164 .addPCDisp(BI->getSuccessor(0));
3168 mvec.push_back(BuildMI(V9::NOP, 0));
3171 mvec.push_back(BuildMI(V9::BA, 1).addPCDisp(BI->getSuccessor(1)));
3174 mvec.push_back(BuildMI(V9::NOP, 0));
3178 case 9: // stmt: Switch(reg)
3179 assert(0 && "*** SWITCH instruction is not implemented yet.");
3182 case 10: // reg: VRegList(reg, reg)
3183 assert(0 && "VRegList should never be the topmost non-chain rule");
3186 case 21: // bool: Not(bool,reg): Compute with a conditional-move-on-reg
3187 { // First find the unary operand. It may be left or right, usually right.
3188 Instruction* notI = subtreeRoot->getInstruction();
3189 Value* notArg = BinaryOperator::getNotArgument(
3190 cast<BinaryOperator>(subtreeRoot->getInstruction()));
3191 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3193 // Unconditionally set register to 0
3194 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(notI));
3196 // Now conditionally move 1 into the register.
3197 // Mark the register as a use (as well as a def) because the old
3198 // value will be retained if the condition is false.
3199 mvec.push_back(BuildMI(V9::MOVRZi, 3).addReg(notArg).addZImm(1)
3200 .addReg(notI, MachineOperand::UseAndDef));
3205 case 421: // reg: BNot(reg,reg): Compute as reg = reg XOR-NOT 0
3206 { // First find the unary operand. It may be left or right, usually right.
3207 Value* notArg = BinaryOperator::getNotArgument(
3208 cast<BinaryOperator>(subtreeRoot->getInstruction()));
3209 unsigned ZeroReg = target.getRegInfo()->getZeroRegNum();
3210 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(notArg).addMReg(ZeroReg)
3211 .addRegDef(subtreeRoot->getValue()));
3215 case 322: // reg: Not(tobool, reg):
3216 // Fold CAST-TO-BOOL with NOT by inverting the sense of cast-to-bool
3218 // Just fall through!
3220 case 22: // reg: ToBoolTy(reg):
3222 Instruction* castI = subtreeRoot->getInstruction();
3223 Value* opVal = subtreeRoot->leftChild()->getValue();
3224 MachineCodeForInstruction &mcfi = MachineCodeForInstruction::get(castI);
3225 TmpInstruction* tempReg =
3226 new TmpInstruction(mcfi, opVal);
3230 assert(opVal->getType()->isIntegral() ||
3231 isa<PointerType>(opVal->getType()));
3233 // Unconditionally set register to 0
3234 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(castI));
3236 // Now conditionally move 1 into the register.
3237 // Mark the register as a use (as well as a def) because the old
3238 // value will be retained if the condition is false.
3239 MachineOpCode opCode = foldCase? V9::MOVRZi : V9::MOVRNZi;
3240 mvec.push_back(BuildMI(opCode, 3).addReg(opVal).addZImm(1)
3241 .addReg(castI, MachineOperand::UseAndDef));
3246 case 23: // reg: ToUByteTy(reg)
3247 case 24: // reg: ToSByteTy(reg)
3248 case 25: // reg: ToUShortTy(reg)
3249 case 26: // reg: ToShortTy(reg)
3250 case 27: // reg: ToUIntTy(reg)
3251 case 28: // reg: ToIntTy(reg)
3252 case 29: // reg: ToULongTy(reg)
3253 case 30: // reg: ToLongTy(reg)
3255 //======================================================================
3256 // Rules for integer conversions:
3259 // From ISO 1998 C++ Standard, Sec. 4.7:
3261 // 2. If the destination type is unsigned, the resulting value is
3262 // the least unsigned integer congruent to the source integer
3263 // (modulo 2n where n is the number of bits used to represent the
3264 // unsigned type). [Note: In a two s complement representation,
3265 // this conversion is conceptual and there is no change in the
3266 // bit pattern (if there is no truncation). ]
3268 // 3. If the destination type is signed, the value is unchanged if
3269 // it can be represented in the destination type (and bitfield width);
3270 // otherwise, the value is implementation-defined.
3273 // Since we assume 2s complement representations, this implies:
3275 // -- If operand is smaller than destination, zero-extend or sign-extend
3276 // according to the signedness of the *operand*: source decides:
3277 // (1) If operand is signed, sign-extend it.
3278 // If dest is unsigned, zero-ext the result!
3279 // (2) If operand is unsigned, our current invariant is that
3280 // it's high bits are correct, so zero-extension is not needed.
3282 // -- If operand is same size as or larger than destination,
3283 // zero-extend or sign-extend according to the signedness of
3284 // the *destination*: destination decides:
3285 // (1) If destination is signed, sign-extend (truncating if needed)
3286 // This choice is implementation defined. We sign-extend the
3287 // operand, which matches both Sun's cc and gcc3.2.
3288 // (2) If destination is unsigned, zero-extend (truncating if needed)
3289 //======================================================================
3291 Instruction* destI = subtreeRoot->getInstruction();
3292 Function* currentFunc = destI->getParent()->getParent();
3293 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(destI);
3295 Value* opVal = subtreeRoot->leftChild()->getValue();
3296 const Type* opType = opVal->getType();
3297 const Type* destType = destI->getType();
3298 unsigned opSize = target.getTargetData().getTypeSize(opType);
3299 unsigned destSize = target.getTargetData().getTypeSize(destType);
3301 bool isIntegral = opType->isIntegral() || isa<PointerType>(opType);
3303 if (opType == Type::BoolTy ||
3304 opType == destType ||
3305 isIntegral && opSize == destSize && opSize == 8) {
3306 // nothing to do in all these cases
3307 forwardOperandNum = 0; // forward first operand to user
3309 } else if (opType->isFloatingPoint()) {
3311 CreateCodeToConvertFloatToInt(target, opVal, destI, mvec, mcfi);
3312 if (destI->getType()->isUnsigned() && destI->getType() !=Type::UIntTy)
3313 maskUnsignedResult = true; // not handled by fp->int code
3315 } else if (isIntegral) {
3317 bool opSigned = opType->isSigned();
3318 bool destSigned = destType->isSigned();
3319 unsigned extSourceInBits = 8 * std::min<unsigned>(opSize, destSize);
3321 assert(! (opSize == destSize && opSigned == destSigned) &&
3322 "How can different int types have same size and signedness?");
3324 bool signExtend = (opSize < destSize && opSigned ||
3325 opSize >= destSize && destSigned);
3327 bool signAndZeroExtend = (opSize < destSize && destSize < 8u &&
3328 opSigned && !destSigned);
3329 assert(!signAndZeroExtend || signExtend);
3331 bool zeroExtendOnly = opSize >= destSize && !destSigned;
3332 assert(!zeroExtendOnly || !signExtend);
3335 Value* signExtDest = (signAndZeroExtend
3336 ? new TmpInstruction(mcfi, destType, opVal)
3339 CreateSignExtensionInstructions
3340 (target, currentFunc,opVal,signExtDest,extSourceInBits,mvec,mcfi);
3342 if (signAndZeroExtend)
3343 CreateZeroExtensionInstructions
3344 (target, currentFunc, signExtDest, destI, 8*destSize, mvec, mcfi);
3346 else if (zeroExtendOnly) {
3347 CreateZeroExtensionInstructions
3348 (target, currentFunc, opVal, destI, extSourceInBits, mvec, mcfi);
3351 forwardOperandNum = 0; // forward first operand to user
3354 assert(0 && "Unrecognized operand type for convert-to-integer");
3359 case 31: // reg: ToFloatTy(reg):
3360 case 32: // reg: ToDoubleTy(reg):
3361 case 232: // reg: ToDoubleTy(Constant):
3363 // If this instruction has a parent (a user) in the tree
3364 // and the user is translated as an FsMULd instruction,
3365 // then the cast is unnecessary. So check that first.
3366 // In the future, we'll want to do the same for the FdMULq instruction,
3367 // so do the check here instead of only for ToFloatTy(reg).
3369 if (subtreeRoot->parent() != NULL) {
3370 const MachineCodeForInstruction& mcfi =
3371 MachineCodeForInstruction::get(
3372 cast<InstructionNode>(subtreeRoot->parent())->getInstruction());
3373 if (mcfi.size() == 0 || mcfi.front()->getOpcode() == V9::FSMULD)
3374 forwardOperandNum = 0; // forward first operand to user
3377 if (forwardOperandNum != 0) { // we do need the cast
3378 Value* leftVal = subtreeRoot->leftChild()->getValue();
3379 const Type* opType = leftVal->getType();
3380 MachineOpCode opCode=ChooseConvertToFloatInstr(target,
3381 subtreeRoot->getOpLabel(), opType);
3382 if (opCode == V9::NOP) { // no conversion needed
3383 forwardOperandNum = 0; // forward first operand to user
3385 // If the source operand is a non-FP type it must be
3386 // first copied from int to float register via memory!
3387 Instruction *dest = subtreeRoot->getInstruction();
3390 if (! opType->isFloatingPoint()) {
3391 // Create a temporary to represent the FP register
3392 // into which the integer will be copied via memory.
3393 // The type of this temporary will determine the FP
3394 // register used: single-prec for a 32-bit int or smaller,
3395 // double-prec for a 64-bit int.
3398 target.getTargetData().getTypeSize(leftVal->getType());
3399 Type* tmpTypeToUse =
3400 (srcSize <= 4)? Type::FloatTy : Type::DoubleTy;
3401 MachineCodeForInstruction &destMCFI =
3402 MachineCodeForInstruction::get(dest);
3403 srcForCast = new TmpInstruction(destMCFI, tmpTypeToUse, dest);
3405 CreateCodeToCopyIntToFloat(target,
3406 dest->getParent()->getParent(),
3407 leftVal, cast<Instruction>(srcForCast),
3410 srcForCast = leftVal;
3412 M = BuildMI(opCode, 2).addReg(srcForCast).addRegDef(dest);
3418 case 19: // reg: ToArrayTy(reg):
3419 case 20: // reg: ToPointerTy(reg):
3420 forwardOperandNum = 0; // forward first operand to user
3423 case 233: // reg: Add(reg, Constant)
3424 maskUnsignedResult = true;
3425 M = CreateAddConstInstruction(subtreeRoot);
3430 // ELSE FALL THROUGH
3432 case 33: // reg: Add(reg, reg)
3433 maskUnsignedResult = true;
3434 Add3OperandInstr(ChooseAddInstruction(subtreeRoot), subtreeRoot, mvec);
3437 case 234: // reg: Sub(reg, Constant)
3438 maskUnsignedResult = true;
3439 M = CreateSubConstInstruction(subtreeRoot);
3444 // ELSE FALL THROUGH
3446 case 34: // reg: Sub(reg, reg)
3447 maskUnsignedResult = true;
3448 Add3OperandInstr(ChooseSubInstructionByType(
3449 subtreeRoot->getInstruction()->getType()),
3453 case 135: // reg: Mul(todouble, todouble)
3457 case 35: // reg: Mul(reg, reg)
3459 maskUnsignedResult = true;
3460 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3461 ? (MachineOpCode)V9::FSMULD
3463 Instruction* mulInstr = subtreeRoot->getInstruction();
3464 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3465 subtreeRoot->leftChild()->getValue(),
3466 subtreeRoot->rightChild()->getValue(),
3468 MachineCodeForInstruction::get(mulInstr),forceOp);
3471 case 335: // reg: Mul(todouble, todoubleConst)
3475 case 235: // reg: Mul(reg, Constant)
3477 maskUnsignedResult = true;
3478 MachineOpCode forceOp = ((checkCast && BothFloatToDouble(subtreeRoot))
3479 ? (MachineOpCode)V9::FSMULD
3481 Instruction* mulInstr = subtreeRoot->getInstruction();
3482 CreateMulInstruction(target, mulInstr->getParent()->getParent(),
3483 subtreeRoot->leftChild()->getValue(),
3484 subtreeRoot->rightChild()->getValue(),
3486 MachineCodeForInstruction::get(mulInstr),
3490 case 236: // reg: Div(reg, Constant)
3491 maskUnsignedResult = true;
3493 CreateDivConstInstruction(target, subtreeRoot, mvec);
3494 if (mvec.size() > L)
3496 // ELSE FALL THROUGH
3498 case 36: // reg: Div(reg, reg)
3500 maskUnsignedResult = true;
3502 // If either operand of divide is smaller than 64 bits, we have
3503 // to make sure the unused top bits are correct because they affect
3504 // the result. These bits are already correct for unsigned values.
3505 // They may be incorrect for signed values, so sign extend to fill in.
3506 Instruction* divI = subtreeRoot->getInstruction();
3507 Value* divOp1 = subtreeRoot->leftChild()->getValue();
3508 Value* divOp2 = subtreeRoot->rightChild()->getValue();
3509 Value* divOp1ToUse = divOp1;
3510 Value* divOp2ToUse = divOp2;
3511 if (divI->getType()->isSigned()) {
3512 unsigned opSize=target.getTargetData().getTypeSize(divI->getType());
3514 MachineCodeForInstruction& mcfi=MachineCodeForInstruction::get(divI);
3515 divOp1ToUse = new TmpInstruction(mcfi, divOp1);
3516 divOp2ToUse = new TmpInstruction(mcfi, divOp2);
3517 CreateSignExtensionInstructions(target,
3518 divI->getParent()->getParent(),
3519 divOp1, divOp1ToUse,
3520 8*opSize, mvec, mcfi);
3521 CreateSignExtensionInstructions(target,
3522 divI->getParent()->getParent(),
3523 divOp2, divOp2ToUse,
3524 8*opSize, mvec, mcfi);
3528 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3529 .addReg(divOp1ToUse)
3530 .addReg(divOp2ToUse)
3536 case 37: // reg: Rem(reg, reg)
3537 case 237: // reg: Rem(reg, Constant)
3539 maskUnsignedResult = true;
3541 Instruction* remI = subtreeRoot->getInstruction();
3542 Value* divOp1 = subtreeRoot->leftChild()->getValue();
3543 Value* divOp2 = subtreeRoot->rightChild()->getValue();
3545 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(remI);
3547 // If second operand of divide is smaller than 64 bits, we have
3548 // to make sure the unused top bits are correct because they affect
3549 // the result. These bits are already correct for unsigned values.
3550 // They may be incorrect for signed values, so sign extend to fill in.
3552 Value* divOpToUse = divOp2;
3553 if (divOp2->getType()->isSigned()) {
3554 unsigned opSize=target.getTargetData().getTypeSize(divOp2->getType());
3556 divOpToUse = new TmpInstruction(mcfi, divOp2);
3557 CreateSignExtensionInstructions(target,
3558 remI->getParent()->getParent(),
3560 8*opSize, mvec, mcfi);
3564 // Now compute: result = rem V1, V2 as:
3565 // result = V1 - (V1 / signExtend(V2)) * signExtend(V2)
3567 TmpInstruction* quot = new TmpInstruction(mcfi, divOp1, divOpToUse);
3568 TmpInstruction* prod = new TmpInstruction(mcfi, quot, divOpToUse);
3570 mvec.push_back(BuildMI(ChooseDivInstruction(target, subtreeRoot), 3)
3571 .addReg(divOp1).addReg(divOpToUse).addRegDef(quot));
3573 mvec.push_back(BuildMI(ChooseMulInstructionByType(remI->getType()), 3)
3574 .addReg(quot).addReg(divOpToUse).addRegDef(prod));
3576 mvec.push_back(BuildMI(ChooseSubInstructionByType(remI->getType()), 3)
3577 .addReg(divOp1).addReg(prod).addRegDef(remI));
3582 case 38: // bool: And(bool, bool)
3583 case 138: // bool: And(bool, not)
3584 case 238: // bool: And(bool, boolconst)
3585 case 338: // reg : BAnd(reg, reg)
3586 case 538: // reg : BAnd(reg, Constant)
3587 Add3OperandInstr(V9::ANDr, subtreeRoot, mvec);
3590 case 438: // bool: BAnd(bool, bnot)
3591 { // Use the argument of NOT as the second argument!
3592 // Mark the NOT node so that no code is generated for it.
3593 // If the type is boolean, set 1 or 0 in the result register.
3594 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3595 Value* notArg = BinaryOperator::getNotArgument(
3596 cast<BinaryOperator>(notNode->getInstruction()));
3597 notNode->markFoldedIntoParent();
3598 Value *lhs = subtreeRoot->leftChild()->getValue();
3599 Value *dest = subtreeRoot->getValue();
3600 mvec.push_back(BuildMI(V9::ANDNr, 3).addReg(lhs).addReg(notArg)
3601 .addReg(dest, MachineOperand::Def));
3603 if (notArg->getType() == Type::BoolTy) {
3604 // set 1 in result register if result of above is non-zero
3605 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3606 .addReg(dest, MachineOperand::UseAndDef));
3612 case 39: // bool: Or(bool, bool)
3613 case 139: // bool: Or(bool, not)
3614 case 239: // bool: Or(bool, boolconst)
3615 case 339: // reg : BOr(reg, reg)
3616 case 539: // reg : BOr(reg, Constant)
3617 Add3OperandInstr(V9::ORr, subtreeRoot, mvec);
3620 case 439: // bool: BOr(bool, bnot)
3621 { // Use the argument of NOT as the second argument!
3622 // Mark the NOT node so that no code is generated for it.
3623 // If the type is boolean, set 1 or 0 in the result register.
3624 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3625 Value* notArg = BinaryOperator::getNotArgument(
3626 cast<BinaryOperator>(notNode->getInstruction()));
3627 notNode->markFoldedIntoParent();
3628 Value *lhs = subtreeRoot->leftChild()->getValue();
3629 Value *dest = subtreeRoot->getValue();
3631 mvec.push_back(BuildMI(V9::ORNr, 3).addReg(lhs).addReg(notArg)
3632 .addReg(dest, MachineOperand::Def));
3634 if (notArg->getType() == Type::BoolTy) {
3635 // set 1 in result register if result of above is non-zero
3636 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3637 .addReg(dest, MachineOperand::UseAndDef));
3643 case 40: // bool: Xor(bool, bool)
3644 case 140: // bool: Xor(bool, not)
3645 case 240: // bool: Xor(bool, boolconst)
3646 case 340: // reg : BXor(reg, reg)
3647 case 540: // reg : BXor(reg, Constant)
3648 Add3OperandInstr(V9::XORr, subtreeRoot, mvec);
3651 case 440: // bool: BXor(bool, bnot)
3652 { // Use the argument of NOT as the second argument!
3653 // Mark the NOT node so that no code is generated for it.
3654 // If the type is boolean, set 1 or 0 in the result register.
3655 InstructionNode* notNode = (InstructionNode*) subtreeRoot->rightChild();
3656 Value* notArg = BinaryOperator::getNotArgument(
3657 cast<BinaryOperator>(notNode->getInstruction()));
3658 notNode->markFoldedIntoParent();
3659 Value *lhs = subtreeRoot->leftChild()->getValue();
3660 Value *dest = subtreeRoot->getValue();
3661 mvec.push_back(BuildMI(V9::XNORr, 3).addReg(lhs).addReg(notArg)
3662 .addReg(dest, MachineOperand::Def));
3664 if (notArg->getType() == Type::BoolTy) {
3665 // set 1 in result register if result of above is non-zero
3666 mvec.push_back(BuildMI(V9::MOVRNZi, 3).addReg(dest).addZImm(1)
3667 .addReg(dest, MachineOperand::UseAndDef));
3672 case 41: // setCCconst: SetCC(reg, Constant)
3673 { // Comparison is with a constant:
3675 // If the bool result must be computed into a register (see below),
3676 // and the constant is int ZERO, we can use the MOVR[op] instructions
3677 // and avoid the SUBcc instruction entirely.
3678 // Otherwise this is just the same as case 42, so just fall through.
3680 // The result of the SetCC must be computed and stored in a register if
3681 // it is used outside the current basic block (so it must be computed
3682 // as a boolreg) or it is used by anything other than a branch.
3683 // We will use a conditional move to do this.
3685 Instruction* setCCInstr = subtreeRoot->getInstruction();
3686 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3687 ! AllUsesAreBranches(setCCInstr));
3689 if (computeBoolVal) {
3690 InstrTreeNode* constNode = subtreeRoot->rightChild();
3692 constNode->getNodeType() ==InstrTreeNode::NTConstNode);
3693 Constant *constVal = cast<Constant>(constNode->getValue());
3696 if ((constVal->getType()->isInteger()
3697 || isa<PointerType>(constVal->getType()))
3698 && ConvertConstantToIntType(target,
3699 constVal, constVal->getType(), isValidConst) == 0
3702 // That constant is an integer zero after all...
3703 // Use a MOVR[op] to compute the boolean result
3704 // Unconditionally set register to 0
3705 mvec.push_back(BuildMI(V9::SETHI, 2).addZImm(0)
3706 .addRegDef(setCCInstr));
3708 // Now conditionally move 1 into the register.
3709 // Mark the register as a use (as well as a def) because the old
3710 // value will be retained if the condition is false.
3711 MachineOpCode movOpCode = ChooseMovpregiForSetCC(subtreeRoot);
3712 mvec.push_back(BuildMI(movOpCode, 3)
3713 .addReg(subtreeRoot->leftChild()->getValue())
3715 .addReg(setCCInstr, MachineOperand::UseAndDef));
3720 // ELSE FALL THROUGH
3723 case 42: // bool: SetCC(reg, reg):
3725 // This generates a SUBCC instruction, putting the difference in a
3726 // result reg. if needed, and/or setting a condition code if needed.
3728 Instruction* setCCInstr = subtreeRoot->getInstruction();
3729 Value* leftVal = subtreeRoot->leftChild()->getValue();
3730 Value* rightVal = subtreeRoot->rightChild()->getValue();
3731 const Type* opType = leftVal->getType();
3732 bool isFPCompare = opType->isFloatingPoint();
3734 // If the boolean result of the SetCC is used outside the current basic
3735 // block (so it must be computed as a boolreg) or is used by anything
3736 // other than a branch, the boolean must be computed and stored
3737 // in a result register. We will use a conditional move to do this.
3739 bool computeBoolVal = (subtreeRoot->parent() == NULL ||
3740 ! AllUsesAreBranches(setCCInstr));
3742 // A TmpInstruction is created to represent the CC "result".
3743 // Unlike other instances of TmpInstruction, this one is used
3744 // by machine code of multiple LLVM instructions, viz.,
3745 // the SetCC and the branch. Make sure to get the same one!
3746 // Note that we do this even for FP CC registers even though they
3747 // are explicit operands, because the type of the operand
3748 // needs to be a floating point condition code, not an integer
3749 // condition code. Think of this as casting the bool result to
3750 // a FP condition code register.
3751 // Later, we mark the 4th operand as being a CC register, and as a def.
3753 TmpInstruction* tmpForCC = GetTmpForCC(setCCInstr,
3754 setCCInstr->getParent()->getParent(),
3756 MachineCodeForInstruction::get(setCCInstr));
3758 // If the operands are signed values smaller than 4 bytes, then they
3759 // must be sign-extended in order to do a valid 32-bit comparison
3760 // and get the right result in the 32-bit CC register (%icc).
3762 Value* leftOpToUse = leftVal;
3763 Value* rightOpToUse = rightVal;
3764 if (opType->isIntegral() && opType->isSigned()) {
3765 unsigned opSize = target.getTargetData().getTypeSize(opType);
3767 MachineCodeForInstruction& mcfi =
3768 MachineCodeForInstruction::get(setCCInstr);
3770 // create temporary virtual regs. to hold the sign-extensions
3771 leftOpToUse = new TmpInstruction(mcfi, leftVal);
3772 rightOpToUse = new TmpInstruction(mcfi, rightVal);
3774 // sign-extend each operand and put the result in the temporary reg.
3775 CreateSignExtensionInstructions
3776 (target, setCCInstr->getParent()->getParent(),
3777 leftVal, leftOpToUse, 8*opSize, mvec, mcfi);
3778 CreateSignExtensionInstructions
3779 (target, setCCInstr->getParent()->getParent(),
3780 rightVal, rightOpToUse, 8*opSize, mvec, mcfi);
3784 if (! isFPCompare) {
3785 // Integer condition: set CC and discard result.
3786 mvec.push_back(BuildMI(V9::SUBccr, 4)
3787 .addReg(leftOpToUse)
3788 .addReg(rightOpToUse)
3789 .addMReg(target.getRegInfo()->
3790 getZeroRegNum(), MachineOperand::Def)
3791 .addCCReg(tmpForCC, MachineOperand::Def));
3793 // FP condition: dest of FCMP should be some FCCn register
3794 mvec.push_back(BuildMI(ChooseFcmpInstruction(subtreeRoot), 3)
3795 .addCCReg(tmpForCC, MachineOperand::Def)
3796 .addReg(leftOpToUse)
3797 .addReg(rightOpToUse));
3800 if (computeBoolVal) {
3801 MachineOpCode movOpCode = (isFPCompare
3802 ? ChooseMovFpcciInstruction(subtreeRoot)
3803 : ChooseMovpcciForSetCC(subtreeRoot));
3805 // Unconditionally set register to 0
3806 M = BuildMI(V9::SETHI, 2).addZImm(0).addRegDef(setCCInstr);
3809 // Now conditionally move 1 into the register.
3810 // Mark the register as a use (as well as a def) because the old
3811 // value will be retained if the condition is false.
3812 M = (BuildMI(movOpCode, 3).addCCReg(tmpForCC).addZImm(1)
3813 .addReg(setCCInstr, MachineOperand::UseAndDef));
3819 case 51: // reg: Load(reg)
3820 case 52: // reg: Load(ptrreg)
3821 SetOperandsForMemInstr(ChooseLoadInstruction(
3822 subtreeRoot->getValue()->getType()),
3823 mvec, subtreeRoot, target);
3826 case 55: // reg: GetElemPtr(reg)
3827 case 56: // reg: GetElemPtrIdx(reg,reg)
3828 // If the GetElemPtr was folded into the user (parent), it will be
3829 // caught above. For other cases, we have to compute the address.
3830 SetOperandsForMemInstr(V9::ADDr, mvec, subtreeRoot, target);
3833 case 57: // reg: Alloca: Implement as 1 instruction:
3834 { // add %fp, offsetFromFP -> result
3835 AllocationInst* instr =
3836 cast<AllocationInst>(subtreeRoot->getInstruction());
3838 target.getTargetData().getTypeSize(instr->getAllocatedType());
3840 CreateCodeForFixedSizeAlloca(target, instr, tsize, 1, mvec);
3844 case 58: // reg: Alloca(reg): Implement as 3 instructions:
3845 // mul num, typeSz -> tmp
3846 // sub %sp, tmp -> %sp
3847 { // add %sp, frameSizeBelowDynamicArea -> result
3848 AllocationInst* instr =
3849 cast<AllocationInst>(subtreeRoot->getInstruction());
3850 const Type* eltType = instr->getAllocatedType();
3852 // If #elements is constant, use simpler code for fixed-size allocas
3853 int tsize = (int) target.getTargetData().getTypeSize(eltType);
3854 Value* numElementsVal = NULL;
3855 bool isArray = instr->isArrayAllocation();
3857 if (!isArray || isa<Constant>(numElementsVal = instr->getArraySize())) {
3858 // total size is constant: generate code for fixed-size alloca
3859 unsigned numElements = isArray?
3860 cast<ConstantUInt>(numElementsVal)->getValue() : 1;
3861 CreateCodeForFixedSizeAlloca(target, instr, tsize,
3864 // total size is not constant.
3865 CreateCodeForVariableSizeAlloca(target, instr, tsize,
3866 numElementsVal, mvec);
3871 case 61: // reg: Call
3872 { // Generate a direct (CALL) or indirect (JMPL) call.
3873 // Mark the return-address register, the indirection
3874 // register (for indirect calls), the operands of the Call,
3875 // and the return value (if any) as implicit operands
3876 // of the machine instruction.
3878 // If this is a varargs function, floating point arguments
3879 // have to passed in integer registers so insert
3880 // copy-float-to-int instructions for each float operand.
3882 CallInst *callInstr = cast<CallInst>(subtreeRoot->getInstruction());
3883 Value *callee = callInstr->getCalledValue();
3884 Function* calledFunc = dyn_cast<Function>(callee);
3886 // Check if this is an intrinsic function that needs a special code
3887 // sequence (e.g., va_start). Indirect calls cannot be special.
3889 bool specialIntrinsic = false;
3891 if (calledFunc && (iid=(Intrinsic::ID)calledFunc->getIntrinsicID()))
3892 specialIntrinsic = CodeGenIntrinsic(iid, *callInstr, target, mvec);
3894 // If not, generate the normal call sequence for the function.
3895 // This can also handle any intrinsics that are just function calls.
3897 if (! specialIntrinsic) {
3898 Function* currentFunc = callInstr->getParent()->getParent();
3899 MachineFunction& MF = MachineFunction::get(currentFunc);
3900 MachineCodeForInstruction& mcfi =
3901 MachineCodeForInstruction::get(callInstr);
3902 const SparcV9RegInfo& regInfo =
3903 (SparcV9RegInfo&) *target.getRegInfo();
3904 const TargetFrameInfo& frameInfo = *target.getFrameInfo();
3906 // Create hidden virtual register for return address with type void*
3907 TmpInstruction* retAddrReg =
3908 new TmpInstruction(mcfi, PointerType::get(Type::VoidTy), callInstr);
3910 // Generate the machine instruction and its operands.
3911 // Use CALL for direct function calls; this optimistically assumes
3912 // the PC-relative address fits in the CALL address field (22 bits).
3913 // Use JMPL for indirect calls.
3914 // This will be added to mvec later, after operand copies.
3916 MachineInstr* callMI;
3917 if (calledFunc) // direct function call
3918 callMI = BuildMI(V9::CALL, 1).addPCDisp(callee);
3919 else // indirect function call
3920 callMI = (BuildMI(V9::JMPLCALLi,3).addReg(callee)
3921 .addSImm((int64_t)0).addRegDef(retAddrReg));
3923 const FunctionType* funcType =
3924 cast<FunctionType>(cast<PointerType>(callee->getType())
3925 ->getElementType());
3926 bool isVarArgs = funcType->isVarArg();
3927 bool noPrototype = isVarArgs && funcType->getNumParams() == 0;
3929 // Use a descriptor to pass information about call arguments
3930 // to the register allocator. This descriptor will be "owned"
3931 // and freed automatically when the MachineCodeForInstruction
3932 // object for the callInstr goes away.
3933 CallArgsDescriptor* argDesc =
3934 new CallArgsDescriptor(callInstr, retAddrReg,isVarArgs,noPrototype);
3935 assert(callInstr->getOperand(0) == callee
3936 && "This is assumed in the loop below!");
3938 // Insert sign-extension instructions for small signed values,
3939 // if this is an unknown function (i.e., called via a funcptr)
3940 // or an external one (i.e., which may not be compiled by llc).
3942 if (calledFunc == NULL || calledFunc->isExternal()) {
3943 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3944 Value* argVal = callInstr->getOperand(i);
3945 const Type* argType = argVal->getType();
3946 if (argType->isIntegral() && argType->isSigned()) {
3947 unsigned argSize = target.getTargetData().getTypeSize(argType);
3949 // create a temporary virtual reg. to hold the sign-extension
3950 TmpInstruction* argExtend = new TmpInstruction(mcfi, argVal);
3952 // sign-extend argVal and put the result in the temporary reg.
3953 CreateSignExtensionInstructions
3954 (target, currentFunc, argVal, argExtend,
3955 8*argSize, mvec, mcfi);
3957 // replace argVal with argExtend in CallArgsDescriptor
3958 argDesc->getArgInfo(i-1).replaceArgVal(argExtend);
3964 // Insert copy instructions to get all the arguments into
3965 // all the places that they need to be.
3967 for (unsigned i=1, N=callInstr->getNumOperands(); i < N; ++i) {
3969 CallArgInfo& argInfo = argDesc->getArgInfo(argNo);
3970 Value* argVal = argInfo.getArgVal(); // don't use callInstr arg here
3971 const Type* argType = argVal->getType();
3972 unsigned regType = regInfo.getRegTypeForDataType(argType);
3973 unsigned argSize = target.getTargetData().getTypeSize(argType);
3974 int regNumForArg = SparcV9RegInfo::getInvalidRegNum();
3975 unsigned regClassIDOfArgReg;
3977 // Check for FP arguments to varargs functions.
3978 // Any such argument in the first $K$ args must be passed in an
3979 // integer register. If there is no prototype, it must also
3980 // be passed as an FP register.
3981 // K = #integer argument registers.
3982 bool isFPArg = argVal->getType()->isFloatingPoint();
3983 if (isVarArgs && isFPArg) {
3986 // It is a function with no prototype: pass value
3987 // as an FP value as well as a varargs value. The FP value
3988 // may go in a register or on the stack. The copy instruction
3989 // to the outgoing reg/stack is created by the normal argument
3990 // handling code since this is the "normal" passing mode.
3992 regNumForArg = regInfo.regNumForFPArg(regType,
3993 false, false, argNo,
3994 regClassIDOfArgReg);
3995 if (regNumForArg == regInfo.getInvalidRegNum())
3996 argInfo.setUseStackSlot();
3998 argInfo.setUseFPArgReg();
4001 // If this arg. is in the first $K$ regs, add special copy-
4002 // float-to-int instructions to pass the value as an int.
4003 // To check if it is in the first $K$, get the register
4004 // number for the arg #i. These copy instructions are
4005 // generated here because they are extra cases and not needed
4006 // for the normal argument handling (some code reuse is
4007 // possible though -- later).
4009 int copyRegNum = regInfo.regNumForIntArg(false, false, argNo,
4010 regClassIDOfArgReg);
4011 if (copyRegNum != regInfo.getInvalidRegNum()) {
4012 // Create a virtual register to represent copyReg. Mark
4013 // this vreg as being an implicit operand of the call MI
4014 const Type* loadTy = (argType == Type::FloatTy
4015 ? Type::IntTy : Type::LongTy);
4016 TmpInstruction* argVReg = new TmpInstruction(mcfi, loadTy,
4019 callMI->addImplicitRef(argVReg);
4021 // Get a temp stack location to use to copy
4022 // float-to-int via the stack.
4024 // FIXME: For now, we allocate permanent space because
4025 // the stack frame manager does not allow locals to be
4026 // allocated (e.g., for alloca) after a temp is
4029 // int tmpOffset = MF.getInfo<SparcV9FunctionInfo>()->pushTempValue(argSize);
4030 int tmpOffset = MF.getInfo<SparcV9FunctionInfo>()->allocateLocalVar(argVReg);
4032 // Generate the store from FP reg to stack
4033 unsigned StoreOpcode = ChooseStoreInstruction(argType);
4034 M = BuildMI(convertOpcodeFromRegToImm(StoreOpcode), 3)
4035 .addReg(argVal).addMReg(regInfo.getFramePointer())
4036 .addSImm(tmpOffset);
4039 // Generate the load from stack to int arg reg
4040 unsigned LoadOpcode = ChooseLoadInstruction(loadTy);
4041 M = BuildMI(convertOpcodeFromRegToImm(LoadOpcode), 3)
4042 .addMReg(regInfo.getFramePointer()).addSImm(tmpOffset)
4043 .addReg(argVReg, MachineOperand::Def);
4045 // Mark operand with register it should be assigned
4046 // both for copy and for the callMI
4047 M->SetRegForOperand(M->getNumOperands()-1, copyRegNum);
4048 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
4052 // Add info about the argument to the CallArgsDescriptor
4053 argInfo.setUseIntArgReg();
4054 argInfo.setArgCopy(copyRegNum);
4056 // Cannot fit in first $K$ regs so pass arg on stack
4057 argInfo.setUseStackSlot();
4059 } else if (isFPArg) {
4060 // Get the outgoing arg reg to see if there is one.
4061 regNumForArg = regInfo.regNumForFPArg(regType, false, false,
4062 argNo, regClassIDOfArgReg);
4063 if (regNumForArg == regInfo.getInvalidRegNum())
4064 argInfo.setUseStackSlot();
4066 argInfo.setUseFPArgReg();
4067 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
4071 // Get the outgoing arg reg to see if there is one.
4072 regNumForArg = regInfo.regNumForIntArg(false,false,
4073 argNo, regClassIDOfArgReg);
4074 if (regNumForArg == regInfo.getInvalidRegNum())
4075 argInfo.setUseStackSlot();
4077 argInfo.setUseIntArgReg();
4078 regNumForArg =regInfo.getUnifiedRegNum(regClassIDOfArgReg,
4084 // Now insert copy instructions to stack slot or arg. register
4086 if (argInfo.usesStackSlot()) {
4087 // Get the stack offset for this argument slot.
4088 // FP args on stack are right justified so adjust offset!
4089 // int arguments are also right justified but they are
4090 // always loaded as a full double-word so the offset does
4091 // not need to be adjusted.
4092 int argOffset = frameInfo.getOutgoingArgOffset(MF, argNo);
4093 if (argType->isFloatingPoint()) {
4094 unsigned slotSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
4095 assert(argSize <= slotSize && "Insufficient slot size!");
4096 argOffset += slotSize - argSize;
4099 // Now generate instruction to copy argument to stack
4100 MachineOpCode storeOpCode =
4101 (argType->isFloatingPoint()
4102 ? ((argSize == 4)? V9::STFi : V9::STDFi) : V9::STXi);
4104 M = BuildMI(storeOpCode, 3).addReg(argVal)
4105 .addMReg(regInfo.getStackPointer()).addSImm(argOffset);
4108 else if (regNumForArg != regInfo.getInvalidRegNum()) {
4110 // Create a virtual register to represent the arg reg. Mark
4111 // this vreg as being an implicit operand of the call MI.
4112 TmpInstruction* argVReg =
4113 new TmpInstruction(mcfi, argVal, NULL, "argReg");
4115 callMI->addImplicitRef(argVReg);
4117 // Generate the reg-to-reg copy into the outgoing arg reg.
4118 // -- For FP values, create a FMOVS or FMOVD instruction
4119 // -- For non-FP values, create an add-with-0 instruction
4120 if (argType->isFloatingPoint())
4121 M=(BuildMI(argType==Type::FloatTy? V9::FMOVS :V9::FMOVD,2)
4122 .addReg(argVal).addReg(argVReg, MachineOperand::Def));
4124 M = (BuildMI(ChooseAddInstructionByType(argType), 3)
4125 .addReg(argVal).addSImm((int64_t) 0)
4126 .addReg(argVReg, MachineOperand::Def));
4128 // Mark the operand with the register it should be assigned
4129 M->SetRegForOperand(M->getNumOperands()-1, regNumForArg);
4130 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,
4136 assert(argInfo.getArgCopy() != regInfo.getInvalidRegNum() &&
4137 "Arg. not in stack slot, primary or secondary register?");
4140 // add call instruction and delay slot before copying return value
4141 mvec.push_back(callMI);
4142 mvec.push_back(BuildMI(V9::NOP, 0));
4144 // Add the return value as an implicit ref. The call operands
4145 // were added above. Also, add code to copy out the return value.
4146 // This is always register-to-register for int or FP return values.
4148 if (callInstr->getType() != Type::VoidTy) {
4149 // Get the return value reg.
4150 const Type* retType = callInstr->getType();
4152 int regNum = (retType->isFloatingPoint()
4153 ? (unsigned) SparcV9FloatRegClass::f0
4154 : (unsigned) SparcV9IntRegClass::o0);
4155 unsigned regClassID = regInfo.getRegClassIDOfType(retType);
4156 regNum = regInfo.getUnifiedRegNum(regClassID, regNum);
4158 // Create a virtual register to represent it and mark
4159 // this vreg as being an implicit operand of the call MI
4160 TmpInstruction* retVReg =
4161 new TmpInstruction(mcfi, callInstr, NULL, "argReg");
4163 callMI->addImplicitRef(retVReg, /*isDef*/ true);
4165 // Generate the reg-to-reg copy from the return value reg.
4166 // -- For FP values, create a FMOVS or FMOVD instruction
4167 // -- For non-FP values, create an add-with-0 instruction
4168 if (retType->isFloatingPoint())
4169 M = (BuildMI(retType==Type::FloatTy? V9::FMOVS : V9::FMOVD, 2)
4170 .addReg(retVReg).addReg(callInstr, MachineOperand::Def));
4172 M = (BuildMI(ChooseAddInstructionByType(retType), 3)
4173 .addReg(retVReg).addSImm((int64_t) 0)
4174 .addReg(callInstr, MachineOperand::Def));
4176 // Mark the operand with the register it should be assigned
4177 // Also mark the implicit ref of the call defining this operand
4178 M->SetRegForOperand(0, regNum);
4179 callMI->SetRegForImplicitRef(callMI->getNumImplicitRefs()-1,regNum);
4184 // For the CALL instruction, the ret. addr. reg. is also implicit
4185 if (isa<Function>(callee))
4186 callMI->addImplicitRef(retAddrReg, /*isDef*/ true);
4188 MF.getInfo<SparcV9FunctionInfo>()->popAllTempValues(); // free temps used for this inst
4194 case 62: // reg: Shl(reg, reg)
4196 Value* argVal1 = subtreeRoot->leftChild()->getValue();
4197 Value* argVal2 = subtreeRoot->rightChild()->getValue();
4198 Instruction* shlInstr = subtreeRoot->getInstruction();
4200 const Type* opType = argVal1->getType();
4201 assert((opType->isInteger() || isa<PointerType>(opType)) &&
4202 "Shl unsupported for other types");
4203 unsigned opSize = target.getTargetData().getTypeSize(opType);
4205 CreateShiftInstructions(target, shlInstr->getParent()->getParent(),
4206 (opSize > 4)? V9::SLLXr6:V9::SLLr5,
4207 argVal1, argVal2, 0, shlInstr, mvec,
4208 MachineCodeForInstruction::get(shlInstr));
4212 case 63: // reg: Shr(reg, reg)
4214 const Type* opType = subtreeRoot->leftChild()->getValue()->getType();
4215 assert((opType->isInteger() || isa<PointerType>(opType)) &&
4216 "Shr unsupported for other types");
4217 unsigned opSize = target.getTargetData().getTypeSize(opType);
4218 Add3OperandInstr(opType->isSigned()
4219 ? (opSize > 4? V9::SRAXr6 : V9::SRAr5)
4220 : (opSize > 4? V9::SRLXr6 : V9::SRLr5),
4225 case 64: // reg: Phi(reg,reg)
4226 break; // don't forward the value
4228 case 66: // reg: VAArg (reg): the va_arg instruction
4229 { // Load argument from stack using current va_list pointer value.
4230 // Use 64-bit load for all non-FP args, and LDDF or double for FP.
4231 Instruction* vaArgI = subtreeRoot->getInstruction();
4232 //but first load the va_list pointer
4233 // Create a virtual register to represent it
4234 //What oh what do we pass to TmpInstruction?
4235 MachineCodeForInstruction& m1 = MachineCodeForInstruction::get(vaArgI);
4236 TmpInstruction* VReg = new TmpInstruction(m1, vaArgI->getOperand(0)->getType());
4237 mvec.push_back(BuildMI(V9::LDXi, 3).addReg(vaArgI->getOperand(0))
4238 .addSImm(0).addRegDef(VReg));
4239 //OK, now do the load
4240 MachineOpCode loadOp = (vaArgI->getType()->isFloatingPoint()
4241 ? (vaArgI->getType() == Type::FloatTy
4242 ? V9::LDFi : V9::LDDFi)
4244 mvec.push_back(BuildMI(loadOp, 3).addReg(VReg).
4245 addSImm(0).addRegDef(vaArgI));
4246 //Also increment the pointer
4247 MachineCodeForInstruction& m2 = MachineCodeForInstruction::get(vaArgI);
4248 TmpInstruction* VRegA = new TmpInstruction(m2, vaArgI->getOperand(0)->getType());
4249 unsigned argSize = SparcV9FrameInfo::SizeOfEachArgOnStack;
4250 mvec.push_back(BuildMI(V9::ADDi, 3).addReg(VReg).
4251 addSImm(argSize).addRegDef(VRegA));
4253 mvec.push_back(BuildMI(V9::STXr, 3).addReg(VRegA).
4254 addReg(vaArgI->getOperand(0)).addSImm(0));
4258 case 71: // reg: VReg
4259 case 72: // reg: Constant
4260 break; // don't forward the value
4263 assert(0 && "Unrecognized BURG rule");
4268 if (forwardOperandNum >= 0) {
4269 // We did not generate a machine instruction but need to use operand.
4270 // If user is in the same tree, replace Value in its machine operand.
4271 // If not, insert a copy instruction which should get coalesced away
4272 // by register allocation.
4273 if (subtreeRoot->parent() != NULL)
4274 ForwardOperand(subtreeRoot, subtreeRoot->parent(), forwardOperandNum);
4276 std::vector<MachineInstr*> minstrVec;
4277 Instruction* instr = subtreeRoot->getInstruction();
4278 CreateCopyInstructionsByType(target,
4279 instr->getParent()->getParent(),
4280 instr->getOperand(forwardOperandNum),
4282 MachineCodeForInstruction::get(instr));
4283 assert(minstrVec.size() > 0);
4284 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4288 if (maskUnsignedResult) {
4289 // If result is unsigned and smaller than int reg size,
4290 // we need to clear high bits of result value.
4291 assert(forwardOperandNum < 0 && "Need mask but no instruction generated");
4292 Instruction* dest = subtreeRoot->getInstruction();
4293 if (dest->getType()->isUnsigned()) {
4294 unsigned destSize=target.getTargetData().getTypeSize(dest->getType());
4295 if (destSize <= 4) {
4296 // Mask high 64 - N bits, where N = 4*destSize.
4298 // Use a TmpInstruction to represent the
4299 // intermediate result before masking. Since those instructions
4300 // have already been generated, go back and substitute tmpI
4301 // for dest in the result position of each one of them.
4303 MachineCodeForInstruction& mcfi = MachineCodeForInstruction::get(dest);
4304 TmpInstruction *tmpI = new TmpInstruction(mcfi, dest->getType(),
4305 dest, NULL, "maskHi");
4306 Value* srlArgToUse = tmpI;
4308 unsigned numSubst = 0;
4309 for (unsigned i=0, N=mvec.size(); i < N; ++i) {
4311 // Make sure we substitute all occurrences of dest in these instrs.
4312 // Otherwise, we will have bogus code.
4313 bool someArgsWereIgnored = false;
4315 // Make sure not to substitute an upwards-exposed use -- that would
4316 // introduce a use of `tmpI' with no preceding def. Therefore,
4317 // substitute a use or def-and-use operand only if a previous def
4318 // operand has already been substituted (i.e., numSubst > 0).
4320 numSubst += mvec[i]->substituteValue(dest, tmpI,
4321 /*defsOnly*/ numSubst == 0,
4322 /*notDefsAndUses*/ numSubst > 0,
4323 someArgsWereIgnored);
4324 assert(!someArgsWereIgnored &&
4325 "Operand `dest' exists but not replaced: probably bogus!");
4327 assert(numSubst > 0 && "Operand `dest' not replaced: probably bogus!");
4329 // Left shift 32-N if size (N) is less than 32 bits.
4330 // Use another tmp. virtual register to represent this result.
4332 srlArgToUse = new TmpInstruction(mcfi, dest->getType(),
4333 tmpI, NULL, "maskHi2");
4334 mvec.push_back(BuildMI(V9::SLLXi6, 3).addReg(tmpI)
4335 .addZImm(8*(4-destSize))
4336 .addReg(srlArgToUse, MachineOperand::Def));
4339 // Logical right shift 32-N to get zero extension in top 64-N bits.
4340 mvec.push_back(BuildMI(V9::SRLi5, 3).addReg(srlArgToUse)
4341 .addZImm(8*(4-destSize))
4342 .addReg(dest, MachineOperand::Def));
4344 } else if (destSize < 8) {
4345 assert(0 && "Unsupported type size: 32 < size < 64 bits");
4351 } // End llvm namespace
4353 //==------------------------------------------------------------------------==//
4354 // Class V9ISel Implementation
4355 //==------------------------------------------------------------------------==//
4357 bool V9ISel::runOnFunction(Function &F) {
4358 // First pass - Walk the function, lowering any calls to intrinsic functions
4359 // which the instruction selector cannot handle.
4360 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
4361 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; )
4362 if (CallInst *CI = dyn_cast<CallInst>(I++))
4363 if (Function *F = CI->getCalledFunction())
4364 switch (F->getIntrinsicID()) {
4365 case Intrinsic::not_intrinsic:
4366 case Intrinsic::vastart:
4367 case Intrinsic::vacopy:
4368 case Intrinsic::vaend:
4369 // We directly implement these intrinsics. Note that this knowledge
4370 // is incestuously entangled with the code in
4371 // SparcInstrSelection.cpp and must be updated when it is updated.
4372 // Since ALL of the code in this library is incestuously intertwined
4373 // with it already and sparc specific, we will live with this.
4376 // All other intrinsic calls we must lower.
4377 Instruction *Before = CI->getPrev();
4378 Target.getIntrinsicLowering().LowerIntrinsicCall(CI);
4379 if (Before) { // Move iterator to instruction after call
4386 // Build the instruction trees to be given as inputs to BURG.
4387 InstrForest instrForest(&F);
4388 if (SelectDebugLevel >= Select_DebugInstTrees) {
4389 std::cerr << "\n\n*** Input to instruction selection for function "
4390 << F.getName() << "\n\n" << F
4391 << "\n\n*** Instruction trees for function "
4392 << F.getName() << "\n\n";
4396 // Invoke BURG instruction selection for each tree
4397 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
4398 RI != instrForest.roots_end(); ++RI) {
4399 InstructionNode* basicNode = *RI;
4400 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
4402 // Invoke BURM to label each tree node with a state
4403 burm_label(basicNode);
4404 if (SelectDebugLevel >= Select_DebugBurgTrees) {
4405 printcover(basicNode, 1, 0);
4406 std::cerr << "\nCover cost == " << treecost(basicNode, 1, 0) <<"\n\n";
4407 printMatches(basicNode);
4410 // Then recursively walk the tree to select instructions
4411 SelectInstructionsForTree(basicNode, /*goalnt*/1);
4414 // Create the MachineBasicBlocks and add all of the MachineInstrs
4415 // defined in the MachineCodeForInstruction objects to the MachineBasicBlocks.
4416 MachineFunction &MF = MachineFunction::get(&F);
4417 std::map<const BasicBlock *, MachineBasicBlock *> MBBMap;
4418 for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
4419 MachineBasicBlock *MBB = new MachineBasicBlock(BI);
4420 MF.getBasicBlockList().push_back(MBB);
4423 for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
4424 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
4425 MBB->insert(MBB->end(), mvec.begin(), mvec.end());
4429 // Initialize Machine-CFG for the function.
4430 for (MachineFunction::iterator i = MF.begin (), e = MF.end (); i != e; ++i) {
4431 MachineBasicBlock &MBB = *i;
4432 const BasicBlock *BB = MBB.getBasicBlock ();
4433 // for each successor S of BB, add MBBMap[S] as a successor of MBB.
4434 for (succ_const_iterator si = succ_begin(BB), se = succ_end(BB); si != se;
4436 MachineBasicBlock *succMBB = MBBMap[*si];
4437 assert (succMBB && "Can't find MachineBasicBlock for this successor");
4438 MBB.addSuccessor (succMBB);
4442 // Insert phi elimination code
4443 InsertCodeForPhis(F);
4445 if (SelectDebugLevel >= Select_PrintMachineCode) {
4446 std::cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
4447 MachineFunction::get(&F).dump();
4453 /// InsertCodeForPhis - This method inserts Phi elimination code for
4454 /// all Phi nodes in the given function. After this method is called,
4455 /// the Phi nodes still exist in the LLVM code, but copies are added to the
4458 void V9ISel::InsertCodeForPhis(Function &F) {
4459 // Iterate over every Phi node PN in F:
4460 MachineFunction &MF = MachineFunction::get(&F);
4461 for (MachineFunction::iterator BB = MF.begin(); BB != MF.end(); ++BB) {
4462 for (BasicBlock::const_iterator IIt = BB->getBasicBlock()->begin();
4463 const PHINode *PN = dyn_cast<PHINode>(IIt); ++IIt) {
4464 // Create a new temporary register to hold the result of the Phi copy.
4465 // The leak detector shouldn't track these nodes. They are not garbage,
4466 // even though their parent field is never filled in.
4467 Value *PhiCpRes = new PHINode(PN->getType(), PN->getName() + ":PhiCp");
4468 LeakDetector::removeGarbageObject(PhiCpRes);
4470 // For each of PN's incoming values, insert a copy in the corresponding
4471 // predecessor block.
4472 MachineCodeForInstruction &MCforPN = MachineCodeForInstruction::get (PN);
4473 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
4474 std::vector<MachineInstr*> mvec, CpVec;
4475 Target.getRegInfo()->cpValue2Value(PN->getIncomingValue(i),
4477 for (std::vector<MachineInstr*>::iterator MI=mvec.begin();
4478 MI != mvec.end(); ++MI) {
4479 std::vector<MachineInstr*> CpVec2 =
4480 FixConstantOperandsForInstr(const_cast<PHINode*>(PN), *MI, Target);
4481 CpVec2.push_back(*MI);
4482 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
4484 // Insert the copy instructions into the predecessor BB.
4485 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
4486 MCforPN.insert (MCforPN.end (), CpVec.begin (), CpVec.end ());
4488 // Insert a copy instruction from PhiCpRes to PN.
4489 std::vector<MachineInstr*> mvec;
4490 Target.getRegInfo()->cpValue2Value(PhiCpRes, const_cast<PHINode*>(PN),
4492 BB->insert(BB->begin(), mvec.begin(), mvec.end());
4493 MCforPN.insert (MCforPN.end (), mvec.begin (), mvec.end ());
4494 } // for each Phi Instr in BB
4495 } // for all BBs in function
4498 /// InsertPhiElimInstructions - Inserts the instructions in CpVec into the
4499 /// MachineBasicBlock corresponding to BB, just before its terminator
4500 /// instruction. This is used by InsertCodeForPhis() to insert copies, above.
4502 void V9ISel::InsertPhiElimInstructions(BasicBlock *BB,
4503 const std::vector<MachineInstr*>& CpVec)
4505 Instruction *TermInst = (Instruction*)BB->getTerminator();
4506 MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
4507 MachineInstr *FirstMIOfTerm = MC4Term.front();
4508 assert (FirstMIOfTerm && "No Machine Instrs for terminator");
4510 MachineBasicBlock *MBB = FirstMIOfTerm->getParent();
4511 assert(MBB && "Machine BB for predecessor's terminator not found");
4512 MachineBasicBlock::iterator MCIt = FirstMIOfTerm;
4513 assert(MCIt != MBB->end() && "Start inst of terminator not found");
4515 // Insert the copy instructions just before the first machine instruction
4516 // generated for the terminator.
4517 MBB->insert(MCIt, CpVec.begin(), CpVec.end());
4520 /// SelectInstructionsForTree - Recursively walk the tree to select
4521 /// instructions. Do this top-down so that child instructions can exploit
4522 /// decisions made at the child instructions.
4524 /// E.g., if br(setle(reg,const)) decides the constant is 0 and uses
4525 /// a branch-on-integer-register instruction, then the setle node
4526 /// can use that information to avoid generating the SUBcc instruction.
4528 /// Note that this cannot be done bottom-up because setle must do this
4529 /// only if it is a child of the branch (otherwise, the result of setle
4530 /// may be used by multiple instructions).
4532 void V9ISel::SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt) {
4533 // Get the rule that matches this node.
4534 int ruleForNode = burm_rule(treeRoot->state, goalnt);
4536 if (ruleForNode == 0) {
4537 std::cerr << "Could not match instruction tree for instr selection\n";
4541 // Get this rule's non-terminals and the corresponding child nodes (if any)
4542 short *nts = burm_nts[ruleForNode];
4544 // First, select instructions for the current node and rule.
4545 // (If this is a list node, not an instruction, then skip this step).
4546 // This function is specific to the target architecture.
4547 if (treeRoot->opLabel != VRegListOp) {
4548 std::vector<MachineInstr*> minstrVec;
4549 InstructionNode* instrNode = (InstructionNode*)treeRoot;
4550 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
4551 GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
4552 MachineCodeForInstruction &mvec =
4553 MachineCodeForInstruction::get(instrNode->getInstruction());
4554 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
4557 // Then, recursively compile the child nodes, if any.
4560 // i.e., there is at least one kid
4561 InstrTreeNode* kids[2];
4562 int currentRule = ruleForNode;
4563 burm_kids(treeRoot, currentRule, kids);
4565 // First skip over any chain rules so that we don't visit
4566 // the current node again.
4567 while (ThisIsAChainRule(currentRule)) {
4568 currentRule = burm_rule(treeRoot->state, nts[0]);
4569 nts = burm_nts[currentRule];
4570 burm_kids(treeRoot, currentRule, kids);
4573 // Now we have the first non-chain rule so we have found
4574 // the actual child nodes. Recursively compile them.
4575 for (unsigned i = 0; nts[i]; i++) {
4577 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
4578 if (nodeType == InstrTreeNode::NTVRegListNode ||
4579 nodeType == InstrTreeNode::NTInstructionNode)
4580 SelectInstructionsForTree(kids[i], nts[i]);
4584 // Finally, do any post-processing on this node after its children
4585 // have been translated.
4586 if (treeRoot->opLabel != VRegListOp)
4587 PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
4590 /// PostprocessMachineCodeForTree - Apply any final cleanups to
4591 /// machine code for the root of a subtree after selection for all its
4592 /// children has been completed.
4594 void V9ISel::PostprocessMachineCodeForTree(InstructionNode *instrNode,
4595 int ruleForNode, short *nts) {
4596 // Fix up any constant operands in the machine instructions to either
4597 // use an immediate field or to load the constant into a register.
4598 // Walk backwards and use direct indexes to allow insertion before current.
4599 Instruction* vmInstr = instrNode->getInstruction();
4600 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
4601 for (unsigned i = mvec.size(); i != 0; --i) {
4602 std::vector<MachineInstr*> loadConstVec =
4603 FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
4604 mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
4608 /// createSparcV9BurgInstSelector - Creates and returns a new SparcV9
4609 /// BURG-based instruction selection pass.
4611 FunctionPass *llvm::createSparcV9BurgInstSelector(TargetMachine &TM) {
4612 return new V9ISel(TM);