1 //===---- IA64ISelDAGToDAG.cpp - IA64 pattern matching inst selector ------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Duraid Madina and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines a pattern matching instruction selector for IA64,
11 // converting a legalized dag to an IA64 dag.
13 //===----------------------------------------------------------------------===//
16 #include "IA64TargetMachine.h"
17 #include "IA64ISelLowering.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Constants.h"
26 #include "llvm/GlobalValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
32 Statistic<> FusedFP ("ia64-codegen", "Number of fused fp operations");
33 Statistic<> FrameOff("ia64-codegen", "Number of frame idx offsets collapsed");
35 //===--------------------------------------------------------------------===//
36 /// IA64DAGToDAGISel - IA64 specific code to select IA64 machine
37 /// instructions for SelectionDAG operations.
39 class IA64DAGToDAGISel : public SelectionDAGISel {
40 IA64TargetLowering IA64Lowering;
41 unsigned GlobalBaseReg;
43 IA64DAGToDAGISel(TargetMachine &TM)
44 : SelectionDAGISel(IA64Lowering), IA64Lowering(TM) {}
46 virtual bool runOnFunction(Function &Fn) {
47 // Make sure we re-emit a set of the global base reg if necessary
49 return SelectionDAGISel::runOnFunction(Fn);
52 /// getI64Imm - Return a target constant with the specified value, of type
54 inline SDOperand getI64Imm(uint64_t Imm) {
55 return CurDAG->getTargetConstant(Imm, MVT::i64);
58 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
59 /// base register. Return the virtual register that holds this value.
60 // SDOperand getGlobalBaseReg(); TODO: hmm
62 // Select - Convert the specified operand from a target-independent to a
63 // target-specific node if it hasn't already been changed.
64 SDOperand Select(SDOperand Op);
66 SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
67 unsigned OCHi, unsigned OCLo,
68 bool IsArithmetic = false,
70 SDNode *SelectBitfieldInsert(SDNode *N);
72 /// SelectCC - Select a comparison of the specified values with the
73 /// specified condition code, returning the CR# of the expression.
74 SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
76 /// SelectAddr - Given the specified address, return the two operands for a
77 /// load/store instruction, and return true if it should be an indexed [r+r]
79 bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
81 SDOperand BuildSDIVSequence(SDNode *N);
82 SDOperand BuildUDIVSequence(SDNode *N);
84 /// InstructionSelectBasicBlock - This callback is invoked by
85 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
86 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
88 virtual const char *getPassName() const {
89 return "IA64 (Itanium) DAG->DAG Instruction Selector";
92 // Include the pieces autogenerated from the target description.
93 #include "IA64GenDAGISel.inc"
96 SDOperand SelectCALL(SDOperand Op);
100 /// InstructionSelectBasicBlock - This callback is invoked by
101 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
102 void IA64DAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
105 // The selection process is inherently a bottom-up recursive process (users
106 // select their uses before themselves). Given infinite stack space, we
107 // could just start selecting on the root and traverse the whole graph. In
108 // practice however, this causes us to run out of stack space on large basic
109 // blocks. To avoid this problem, select the entry node, then all its uses,
110 // iteratively instead of recursively.
111 std::vector<SDOperand> Worklist;
112 Worklist.push_back(DAG.getEntryNode());
114 // Note that we can do this in the IA64 target (scanning forward across token
115 // chain edges) because no nodes ever get folded across these edges. On a
116 // target like X86 which supports load/modify/store operations, this would
117 // have to be more careful.
118 while (!Worklist.empty()) {
119 SDOperand Node = Worklist.back();
122 // Chose from the least deep of the top two nodes.
123 if (!Worklist.empty() &&
124 Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
125 std::swap(Worklist.back(), Node);
127 if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
128 Node.Val->getOpcode() < IA64ISD::FIRST_NUMBER) ||
129 CodeGenMap.count(Node)) continue;
131 for (SDNode::use_iterator UI = Node.Val->use_begin(),
132 E = Node.Val->use_end(); UI != E; ++UI) {
133 // Scan the values. If this use has a value that is a token chain, add it
136 for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
137 if (User->getValueType(i) == MVT::Other) {
138 Worklist.push_back(SDOperand(User, i));
143 // Finally, legalize this node.
147 // Select target instructions for the DAG.
148 DAG.setRoot(Select(DAG.getRoot()));
150 DAG.RemoveDeadNodes();
152 // Emit machine code to BB.
153 ScheduleAndEmitDAG(DAG);
157 SDOperand IA64DAGToDAGISel::SelectCALL(SDOperand Op) {
159 SDOperand Chain = Select(N->getOperand(0));
162 std::vector<SDOperand> CallOperands;
164 // save the current GP, SP and RP : FIXME: do we need to do all 3 always?
165 SDOperand GPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::r1, MVT::i64);
166 Chain = GPBeforeCall.getValue(1);
167 SDOperand SPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::r12, MVT::i64);
168 Chain = SPBeforeCall.getValue(1);
169 SDOperand RPBeforeCall = CurDAG->getCopyFromReg(Chain, IA64::rp, MVT::i64);
170 Chain = RPBeforeCall.getValue(1);
172 // if we can call directly, do so
173 if (GlobalAddressSDNode *GASD =
174 dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
175 CallOpcode = IA64::BRCALL_IPREL;
176 CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
178 } else if (ExternalSymbolSDNode *ESSDN = // FIXME: we currently NEED this
179 // case for correctness, to avoid
180 // "non-pic code with imm reloc.n
181 // against dynamic symbol" errors
182 dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
183 CallOpcode = IA64::BRCALL_IPREL;
184 CallOperands.push_back(N->getOperand(1));
186 // otherwise we need to load the function descriptor,
187 // load the branch target (function)'s entry point and GP,
188 // branch (call) then restore the
191 SDOperand FnDescriptor = Select(N->getOperand(1));
193 // load the branch target's entry point [mem] and
195 SDOperand targetEntryPoint=CurDAG->getLoad(MVT::i64, Chain, FnDescriptor,
196 CurDAG->getSrcValue(0));
197 SDOperand targetGPAddr=CurDAG->getNode(ISD::ADD, MVT::i64, FnDescriptor,
198 CurDAG->getConstant(8, MVT::i64));
199 SDOperand targetGP=CurDAG->getLoad(MVT::i64, Chain, targetGPAddr,
200 CurDAG->getSrcValue(0));
202 // Copy the callee address into the b6 branch register
203 SDOperand B6 = CurDAG->getRegister(IA64::B6, MVT::i64);
204 Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, B6,
207 CallOperands.push_back(B6);
208 CallOpcode = IA64::BRCALL_INDIRECT;
211 // see section 8.5.8 of "Itanium Software Conventions and
212 // Runtime Architecture Guide to see some examples of what's going
213 // on here. (in short: int args get mapped 1:1 'slot-wise' to out0->out7,
214 // while FP args get mapped to F8->F15 as needed)
216 // TODO: support in-memory arguments
218 unsigned used_FPArgs=0; // how many FP args have been used so far?
220 unsigned intArgs[] = {IA64::out0, IA64::out1, IA64::out2, IA64::out3,
221 IA64::out4, IA64::out5, IA64::out6, IA64::out7 };
222 unsigned FPArgs[] = {IA64::F8, IA64::F9, IA64::F10, IA64::F11,
223 IA64::F12, IA64::F13, IA64::F14, IA64::F15 };
225 SDOperand InFlag; // Null incoming flag value.
227 for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
228 unsigned DestReg = 0;
229 MVT::ValueType RegTy = N->getOperand(i).getValueType();
230 if (RegTy == MVT::i64) {
231 assert((i-2) < 8 && "Too many int args");
232 DestReg = intArgs[i-2];
234 assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
235 "Unpromoted integer arg?");
236 assert(used_FPArgs < 8 && "Too many fp args");
237 DestReg = FPArgs[used_FPArgs++];
240 if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
241 SDOperand Val = Select(N->getOperand(i));
242 Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
243 InFlag = Chain.getValue(1);
244 CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
245 // some functions (e.g. printf) want floating point arguments
246 // *also* passed as in-memory representations in integer registers
247 // this is FORTRAN legacy junk which we don't _always_ need
248 // to do, but to be on the safe side, we do.
249 if(MVT::isFloatingPoint(N->getOperand(i).getValueType())) {
250 assert((i-2) < 8 && "FP args alone would fit, but no int regs left");
251 DestReg = intArgs[i-2]; // this FP arg goes in an int reg
252 // GETFD takes an FP reg and writes a GP reg
253 Chain = CurDAG->getTargetNode(IA64::GETFD, MVT::i64, Val, InFlag);
254 // FIXME: this next line is a bit unfortunate
255 Chain = CurDAG->getCopyToReg(Chain, DestReg, Chain, InFlag);
256 InFlag = Chain.getValue(1);
257 CallOperands.push_back(CurDAG->getRegister(DestReg, MVT::i64));
262 // Finally, once everything is in registers to pass to the call, emit the
265 CallOperands.push_back(InFlag); // Strong dep on register copies.
267 CallOperands.push_back(Chain); // Weak dep on whatever occurs before
268 Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
271 // return Chain; // HACK: err, this means that functions never return anything. need to intergrate this with the code immediately below FIXME XXX
273 std::vector<SDOperand> CallResults;
275 // If the call has results, copy the values out of the ret val registers.
276 switch (N->getValueType(0)) {
277 default: assert(0 && "Unexpected ret value!");
278 case MVT::Other: break;
280 Chain = CurDAG->getCopyFromReg(Chain, IA64::r8, MVT::i64,
281 Chain.getValue(1)).getValue(1);
282 CallResults.push_back(Chain.getValue(0));
285 Chain = CurDAG->getCopyFromReg(Chain, IA64::F8, N->getValueType(0),
286 Chain.getValue(1)).getValue(1);
287 CallResults.push_back(Chain.getValue(0));
290 // restore GP, SP and RP
291 Chain = CurDAG->getCopyToReg(Chain, IA64::r1, GPBeforeCall);
292 Chain = CurDAG->getCopyToReg(Chain, IA64::r12, SPBeforeCall);
293 Chain = CurDAG->getCopyToReg(Chain, IA64::rp, RPBeforeCall);
295 CallResults.push_back(Chain);
297 for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
298 CodeGenMap[Op.getValue(i)] = CallResults[i];
300 return CallResults[Op.ResNo];
303 // Select - Convert the specified operand from a target-independent to a
304 // target-specific node if it hasn't already been changed.
305 SDOperand IA64DAGToDAGISel::Select(SDOperand Op) {
307 if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
308 N->getOpcode() < IA64ISD::FIRST_NUMBER)
309 return Op; // Already selected.
311 // If this has already been converted, use it.
312 std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
313 if (CGMI != CodeGenMap.end()) return CGMI->second;
315 switch (N->getOpcode()) {
319 case ISD::TAILCALL: return SelectCALL(Op);
322 * case ISD::DYNAMIC_STACKALLOC:
325 case ISD::FrameIndex: { // TODO: reduce creepyness
326 int FI = cast<FrameIndexSDNode>(N)->getIndex();
327 if (N->hasOneUse()) {
328 CurDAG->SelectNodeTo(N, IA64::MOV, MVT::i64,
329 CurDAG->getTargetFrameIndex(FI, MVT::i64));
330 return SDOperand(N, 0);
332 return CurDAG->getTargetNode(IA64::MOV, MVT::i64,
333 CurDAG->getTargetFrameIndex(FI, MVT::i64));
336 case ISD::ConstantPool: {
337 Constant *C = cast<ConstantPoolSDNode>(N)->get();
338 SDOperand CPI = CurDAG->getTargetConstantPool(C, MVT::i64);
339 return CurDAG->getTargetNode(IA64::ADDL_GA, MVT::i64, // ?
340 CurDAG->getRegister(IA64::r1, MVT::i64), CPI);
343 case ISD::GlobalAddress: {
344 GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
345 SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i64);
346 SDOperand Tmp = CurDAG->getTargetNode(IA64::ADDL_GA, MVT::i64,
347 CurDAG->getRegister(IA64::r1, MVT::i64), GA);
348 return CurDAG->getTargetNode(IA64::LD8, MVT::i64, Tmp);
353 case ISD::ZEXTLOAD: {
354 SDOperand Chain = Select(N->getOperand(0));
355 SDOperand Address = Select(N->getOperand(1));
357 MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
358 N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
360 switch (TypeBeingLoaded) {
361 default: N->dump(); assert(0 && "Cannot load this type!");
362 // FIXME: bools? case MVT::i1:
363 case MVT::i8: Opc = IA64::LD1; break;
364 case MVT::i16: Opc = IA64::LD2; break;
365 case MVT::i32: Opc = IA64::LD4; break;
366 case MVT::i64: Opc = IA64::LD8; break;
368 case MVT::f32: Opc = IA64::LDF4; break;
369 case MVT::f64: Opc = IA64::LDF8; break;
372 CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), MVT::Other,
373 Address, Chain); // TODO: comment this
375 return SDOperand(N, Op.ResNo);
378 case ISD::TRUNCSTORE:
380 SDOperand Address = Select(N->getOperand(2));
383 if (N->getOpcode() == ISD::STORE) {
384 switch (N->getOperand(1).getValueType()) {
385 default: assert(0 && "unknown Type in store");
386 case MVT::i64: Opc = IA64::ST8; break;
387 case MVT::f64: Opc = IA64::STF8; break;
389 } else { //ISD::TRUNCSTORE
390 switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
391 default: assert(0 && "unknown Type in store");
392 case MVT::i8: Opc = IA64::ST1; break;
393 case MVT::i16: Opc = IA64::ST2; break;
394 case MVT::i32: Opc = IA64::ST4; break;
395 case MVT::f32: Opc = IA64::STF4; break;
399 CurDAG->SelectNodeTo(N, Opc, MVT::Other, Select(N->getOperand(2)),
400 Select(N->getOperand(1)), Select(N->getOperand(0)));
401 return SDOperand(N, 0);
405 SDOperand Chain = Select(N->getOperand(0));
406 SDOperand CC = Select(N->getOperand(1));
407 MachineBasicBlock *Dest =
408 cast<BasicBlockSDNode>(N->getOperand(2))->getBasicBlock();
409 //FIXME - we do NOT need long branches all the time
410 CurDAG->SelectNodeTo(N, IA64::BRLCOND_NOTCALL, MVT::Other, CC, CurDAG->getBasicBlock(Dest), Chain);
411 return SDOperand(N, 0);
414 case ISD::CALLSEQ_START:
415 case ISD::CALLSEQ_END: {
416 int64_t Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
417 unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
418 IA64::ADJUSTCALLSTACKDOWN : IA64::ADJUSTCALLSTACKUP;
419 CurDAG->SelectNodeTo(N, Opc, MVT::Other,
420 getI64Imm(Amt), Select(N->getOperand(0)));
421 return SDOperand(N, 0);
425 SDOperand Chain = Select(N->getOperand(0)); // Token chain.
427 switch (N->getNumOperands()) {
429 assert(0 && "Unknown return instruction!");
431 SDOperand RetVal = Select(N->getOperand(1));
432 switch (RetVal.getValueType()) {
433 default: assert(0 && "I don't know how to return this type! (promote?)");
434 // FIXME: do I need to add support for bools here?
435 // (return '0' or '1' in r8, basically...)
437 // FIXME: need to round floats - 80 bits is bad, the tester
440 // we mark r8 as live on exit up above in LowerArguments()
441 // BuildMI(BB, IA64::MOV, 1, IA64::r8).addReg(Tmp1);
442 Chain = CurDAG->getCopyToReg(Chain, IA64::r8, RetVal);
445 // we mark F8 as live on exit up above in LowerArguments()
446 // BuildMI(BB, IA64::FMOV, 1, IA64::F8).addReg(Tmp1);
447 Chain = CurDAG->getCopyToReg(Chain, IA64::F8, RetVal);
456 // we need to copy VirtGPR (the vreg (to become a real reg)) that holds
457 // the output of this function's alloc instruction back into ar.pfs
458 // before we return. this copy must not float up above the last
459 // outgoing call in this function!!!
460 SDOperand AR_PFSVal = CurDAG->getCopyFromReg(Chain, IA64Lowering.VirtGPR,
462 Chain = AR_PFSVal.getValue(1);
463 Chain = CurDAG->getCopyToReg(Chain, IA64::AR_PFS, AR_PFSVal);
465 CurDAG->SelectNodeTo(N, IA64::RET, MVT::Other, Chain); // and then just emit a 'ret' instruction
467 // before returning, restore the ar.pfs register (set by the 'alloc' up top)
468 // BuildMI(BB, IA64::MOV, 1).addReg(IA64::AR_PFS).addReg(IA64Lowering.VirtGPR);
470 return SDOperand(N, 0);
474 // FIXME: we don't need long branches all the time!
475 CurDAG->SelectNodeTo(N, IA64::BRL_NOTCALL, MVT::Other, N->getOperand(1),
476 Select(N->getOperand(0)));
477 return SDOperand(N, 0);
481 return SelectCode(Op);
485 /// createIA64DAGToDAGInstructionSelector - This pass converts a legalized DAG
486 /// into an IA64-specific DAG, ready for instruction scheduling.
488 FunctionPass *llvm::createIA64DAGToDAGInstructionSelector(TargetMachine &TM) {
489 return new IA64DAGToDAGISel(TM);