1 //===-- X86ISelPattern.cpp - A pattern matching inst selector for X86 -----===//
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 // This file defines a pattern matching instruction selector for X86.
12 //===----------------------------------------------------------------------===//
15 #include "X86InstrBuilder.h"
16 #include "X86RegisterInfo.h"
17 #include "llvm/CallingConv.h"
18 #include "llvm/Constants.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Function.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/CodeGen/SSARegMap.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetLowering.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Support/CommandLine.h"
39 static cl::opt<bool> EnableFastCC("enable-x86-fastcc", cl::Hidden,
40 cl::desc("Enable fastcc on X86"));
43 // X86 Specific DAG Nodes
46 // Start the numbering where the builtin ops leave off.
47 FIRST_NUMBER = ISD::BUILTIN_OP_END,
49 /// FILD64m - This instruction implements SINT_TO_FP with a
50 /// 64-bit source in memory and a FP reg result. This corresponds to
51 /// the X86::FILD64m instruction. It has two inputs (token chain and
52 /// address) and two outputs (FP value and token chain).
55 /// CALL/TAILCALL - These operations represent an abstract X86 call
56 /// instruction, which includes a bunch of information. In particular the
57 /// operands of these node are:
59 /// #0 - The incoming token chain
61 /// #2 - The number of arg bytes the caller pushes on the stack.
62 /// #3 - The number of arg bytes the callee pops off the stack.
63 /// #4 - The value to pass in AL/AX/EAX (optional)
64 /// #5 - The value to pass in DL/DX/EDX (optional)
66 /// The result values of these nodes are:
68 /// #0 - The outgoing token chain
69 /// #1 - The first register result value (optional)
70 /// #2 - The second register result value (optional)
72 /// The CALL vs TAILCALL distinction boils down to whether the callee is
73 /// known not to modify the caller's stack frame, as is standard with
81 //===----------------------------------------------------------------------===//
82 // X86TargetLowering - X86 Implementation of the TargetLowering interface
84 class X86TargetLowering : public TargetLowering {
85 int VarArgsFrameIndex; // FrameIndex for start of varargs area.
86 int ReturnAddrIndex; // FrameIndex for return slot.
87 int BytesToPopOnReturn; // Number of arg bytes ret should pop.
88 int BytesCallerReserves; // Number of arg bytes caller makes.
90 X86TargetLowering(TargetMachine &TM) : TargetLowering(TM) {
91 // Set up the TargetLowering object.
93 // X86 is weird, it always uses i8 for shift amounts and setcc results.
94 setShiftAmountType(MVT::i8);
95 setSetCCResultType(MVT::i8);
96 setSetCCResultContents(ZeroOrOneSetCCResult);
97 setShiftAmountFlavor(Mask); // shl X, 32 == shl X, 0
99 // Set up the register classes.
100 addRegisterClass(MVT::i8, X86::R8RegisterClass);
101 addRegisterClass(MVT::i16, X86::R16RegisterClass);
102 addRegisterClass(MVT::i32, X86::R32RegisterClass);
103 addRegisterClass(MVT::f64, X86::RFPRegisterClass);
105 // FIXME: Eliminate these two classes when legalize can handle promotions
107 /**/ addRegisterClass(MVT::i1, X86::R8RegisterClass);
109 setOperationAction(ISD::SINT_TO_FP , MVT::i64 , Custom);
110 setOperationAction(ISD::BRCONDTWOWAY , MVT::Other, Expand);
111 setOperationAction(ISD::MEMMOVE , MVT::Other, Expand);
112 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16 , Expand);
113 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
114 setOperationAction(ISD::FP_ROUND_INREG , MVT::f32 , Expand);
115 setOperationAction(ISD::SEXTLOAD , MVT::i1 , Expand);
116 setOperationAction(ISD::SREM , MVT::f64 , Expand);
117 setOperationAction(ISD::CTPOP , MVT::i8 , Expand);
118 setOperationAction(ISD::CTTZ , MVT::i8 , Expand);
119 setOperationAction(ISD::CTLZ , MVT::i8 , Expand);
120 setOperationAction(ISD::CTPOP , MVT::i16 , Expand);
121 setOperationAction(ISD::CTTZ , MVT::i16 , Expand);
122 setOperationAction(ISD::CTLZ , MVT::i16 , Expand);
123 setOperationAction(ISD::CTPOP , MVT::i32 , Expand);
124 setOperationAction(ISD::CTTZ , MVT::i32 , Expand);
125 setOperationAction(ISD::CTLZ , MVT::i32 , Expand);
127 setOperationAction(ISD::READIO , MVT::i1 , Expand);
128 setOperationAction(ISD::READIO , MVT::i8 , Expand);
129 setOperationAction(ISD::READIO , MVT::i16 , Expand);
130 setOperationAction(ISD::READIO , MVT::i32 , Expand);
131 setOperationAction(ISD::WRITEIO , MVT::i1 , Expand);
132 setOperationAction(ISD::WRITEIO , MVT::i8 , Expand);
133 setOperationAction(ISD::WRITEIO , MVT::i16 , Expand);
134 setOperationAction(ISD::WRITEIO , MVT::i32 , Expand);
137 setOperationAction(ISD::FSIN , MVT::f64 , Expand);
138 setOperationAction(ISD::FCOS , MVT::f64 , Expand);
141 // These should be promoted to a larger select which is supported.
142 /**/ setOperationAction(ISD::SELECT , MVT::i1 , Promote);
143 setOperationAction(ISD::SELECT , MVT::i8 , Promote);
145 computeRegisterProperties();
147 addLegalFPImmediate(+0.0); // FLD0
148 addLegalFPImmediate(+1.0); // FLD1
149 addLegalFPImmediate(-0.0); // FLD0/FCHS
150 addLegalFPImmediate(-1.0); // FLD1/FCHS
153 // Return the number of bytes that a function should pop when it returns (in
154 // addition to the space used by the return address).
156 unsigned getBytesToPopOnReturn() const { return BytesToPopOnReturn; }
158 // Return the number of bytes that the caller reserves for arguments passed
160 unsigned getBytesCallerReserves() const { return BytesCallerReserves; }
162 /// LowerOperation - Provide custom lowering hooks for some operations.
164 virtual SDOperand LowerOperation(SDOperand Op, SelectionDAG &DAG);
166 /// LowerArguments - This hook must be implemented to indicate how we should
167 /// lower the arguments for the specified function, into the specified DAG.
168 virtual std::vector<SDOperand>
169 LowerArguments(Function &F, SelectionDAG &DAG);
171 /// LowerCallTo - This hook lowers an abstract call to a function into an
173 virtual std::pair<SDOperand, SDOperand>
174 LowerCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg, unsigned CC,
175 bool isTailCall, SDOperand Callee, ArgListTy &Args,
178 virtual SDOperand LowerVAStart(SDOperand Chain, SDOperand VAListP,
179 Value *VAListV, SelectionDAG &DAG);
180 virtual std::pair<SDOperand,SDOperand>
181 LowerVAArg(SDOperand Chain, SDOperand VAListP, Value *VAListV,
182 const Type *ArgTy, SelectionDAG &DAG);
184 virtual std::pair<SDOperand, SDOperand>
185 LowerFrameReturnAddress(bool isFrameAddr, SDOperand Chain, unsigned Depth,
188 SDOperand getReturnAddressFrameIndex(SelectionDAG &DAG);
191 // C Calling Convention implementation.
192 std::vector<SDOperand> LowerCCCArguments(Function &F, SelectionDAG &DAG);
193 std::pair<SDOperand, SDOperand>
194 LowerCCCCallTo(SDOperand Chain, const Type *RetTy, bool isVarArg,
196 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
198 // Fast Calling Convention implementation.
199 std::vector<SDOperand> LowerFastCCArguments(Function &F, SelectionDAG &DAG);
200 std::pair<SDOperand, SDOperand>
201 LowerFastCCCallTo(SDOperand Chain, const Type *RetTy, bool isTailCall,
202 SDOperand Callee, ArgListTy &Args, SelectionDAG &DAG);
206 std::vector<SDOperand>
207 X86TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
208 if (F.getCallingConv() == CallingConv::Fast && EnableFastCC)
209 return LowerFastCCArguments(F, DAG);
210 return LowerCCCArguments(F, DAG);
213 std::pair<SDOperand, SDOperand>
214 X86TargetLowering::LowerCallTo(SDOperand Chain, const Type *RetTy,
215 bool isVarArg, unsigned CallingConv,
217 SDOperand Callee, ArgListTy &Args,
219 assert((!isVarArg || CallingConv == CallingConv::C) &&
220 "Only C takes varargs!");
221 if (CallingConv == CallingConv::Fast && EnableFastCC)
222 return LowerFastCCCallTo(Chain, RetTy, isTailCall, Callee, Args, DAG);
223 return LowerCCCCallTo(Chain, RetTy, isVarArg, isTailCall, Callee, Args, DAG);
226 //===----------------------------------------------------------------------===//
227 // C Calling Convention implementation
228 //===----------------------------------------------------------------------===//
230 std::vector<SDOperand>
231 X86TargetLowering::LowerCCCArguments(Function &F, SelectionDAG &DAG) {
232 std::vector<SDOperand> ArgValues;
234 MachineFunction &MF = DAG.getMachineFunction();
235 MachineFrameInfo *MFI = MF.getFrameInfo();
237 // Add DAG nodes to load the arguments... On entry to a function on the X86,
238 // the stack frame looks like this:
240 // [ESP] -- return address
241 // [ESP + 4] -- first argument (leftmost lexically)
242 // [ESP + 8] -- second argument, if first argument is four bytes in size
245 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
246 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
247 MVT::ValueType ObjectVT = getValueType(I->getType());
248 unsigned ArgIncrement = 4;
251 default: assert(0 && "Unhandled argument type!");
253 case MVT::i8: ObjSize = 1; break;
254 case MVT::i16: ObjSize = 2; break;
255 case MVT::i32: ObjSize = 4; break;
256 case MVT::i64: ObjSize = ArgIncrement = 8; break;
257 case MVT::f32: ObjSize = 4; break;
258 case MVT::f64: ObjSize = ArgIncrement = 8; break;
260 // Create the frame index object for this incoming parameter...
261 int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
263 // Create the SelectionDAG nodes corresponding to a load from this parameter
264 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
266 // Don't codegen dead arguments. FIXME: remove this check when we can nuke
270 ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
271 DAG.getSrcValue(NULL));
273 if (MVT::isInteger(ObjectVT))
274 ArgValue = DAG.getConstant(0, ObjectVT);
276 ArgValue = DAG.getConstantFP(0, ObjectVT);
278 ArgValues.push_back(ArgValue);
280 ArgOffset += ArgIncrement; // Move on to the next argument...
283 // If the function takes variable number of arguments, make a frame index for
284 // the start of the first vararg value... for expansion of llvm.va_start.
286 VarArgsFrameIndex = MFI->CreateFixedObject(1, ArgOffset);
287 ReturnAddrIndex = 0; // No return address slot generated yet.
288 BytesToPopOnReturn = 0; // Callee pops nothing.
289 BytesCallerReserves = ArgOffset;
291 // Finally, inform the code generator which regs we return values in.
292 switch (getValueType(F.getReturnType())) {
293 default: assert(0 && "Unknown type!");
294 case MVT::isVoid: break;
299 MF.addLiveOut(X86::EAX);
302 MF.addLiveOut(X86::EAX);
303 MF.addLiveOut(X86::EDX);
307 MF.addLiveOut(X86::ST0);
313 std::pair<SDOperand, SDOperand>
314 X86TargetLowering::LowerCCCCallTo(SDOperand Chain, const Type *RetTy,
315 bool isVarArg, bool isTailCall,
316 SDOperand Callee, ArgListTy &Args,
318 // Count how many bytes are to be pushed on the stack.
319 unsigned NumBytes = 0;
323 Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
324 DAG.getConstant(0, getPointerTy()));
326 for (unsigned i = 0, e = Args.size(); i != e; ++i)
327 switch (getValueType(Args[i].second)) {
328 default: assert(0 && "Unknown value type!");
342 Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
343 DAG.getConstant(NumBytes, getPointerTy()));
345 // Arguments go on the stack in reverse order, as specified by the ABI.
346 unsigned ArgOffset = 0;
347 SDOperand StackPtr = DAG.getCopyFromReg(X86::ESP, MVT::i32,
349 std::vector<SDOperand> Stores;
351 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
352 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
353 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
355 switch (getValueType(Args[i].second)) {
356 default: assert(0 && "Unexpected ValueType for argument!");
360 // Promote the integer to 32 bits. If the input type is signed use a
361 // sign extend, otherwise use a zero extend.
362 if (Args[i].second->isSigned())
363 Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
365 Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
370 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
371 Args[i].first, PtrOff,
372 DAG.getSrcValue(NULL)));
377 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
378 Args[i].first, PtrOff,
379 DAG.getSrcValue(NULL)));
384 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
387 std::vector<MVT::ValueType> RetVals;
388 MVT::ValueType RetTyVT = getValueType(RetTy);
389 RetVals.push_back(MVT::Other);
391 // The result values produced have to be legal. Promote the result.
393 case MVT::isVoid: break;
395 RetVals.push_back(RetTyVT);
400 RetVals.push_back(MVT::i32);
403 RetVals.push_back(MVT::f64);
406 RetVals.push_back(MVT::i32);
407 RetVals.push_back(MVT::i32);
410 std::vector<SDOperand> Ops;
411 Ops.push_back(Chain);
412 Ops.push_back(Callee);
413 Ops.push_back(DAG.getConstant(NumBytes, getPointerTy()));
414 Ops.push_back(DAG.getConstant(0, getPointerTy()));
415 SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
417 Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
421 case MVT::isVoid: break;
423 ResultVal = TheCall.getValue(1);
428 ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
431 // FIXME: we would really like to remember that this FP_ROUND operation is
432 // okay to eliminate if we allow excess FP precision.
433 ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
436 ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
437 TheCall.getValue(2));
441 return std::make_pair(ResultVal, Chain);
445 X86TargetLowering::LowerVAStart(SDOperand Chain, SDOperand VAListP,
446 Value *VAListV, SelectionDAG &DAG) {
447 // vastart just stores the address of the VarArgsFrameIndex slot.
448 SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
449 return DAG.getNode(ISD::STORE, MVT::Other, Chain, FR, VAListP,
450 DAG.getSrcValue(VAListV));
454 std::pair<SDOperand,SDOperand>
455 X86TargetLowering::LowerVAArg(SDOperand Chain, SDOperand VAListP,
456 Value *VAListV, const Type *ArgTy,
458 MVT::ValueType ArgVT = getValueType(ArgTy);
459 SDOperand Val = DAG.getLoad(MVT::i32, Chain,
460 VAListP, DAG.getSrcValue(VAListV));
461 SDOperand Result = DAG.getLoad(ArgVT, Chain, Val,
462 DAG.getSrcValue(NULL));
464 if (ArgVT == MVT::i32)
467 assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
468 "Other types should have been promoted for varargs!");
471 Val = DAG.getNode(ISD::ADD, Val.getValueType(), Val,
472 DAG.getConstant(Amt, Val.getValueType()));
473 Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain,
474 Val, VAListP, DAG.getSrcValue(VAListV));
475 return std::make_pair(Result, Chain);
478 //===----------------------------------------------------------------------===//
479 // Fast Calling Convention implementation
480 //===----------------------------------------------------------------------===//
482 // The X86 'fast' calling convention passes up to two integer arguments in
483 // registers (an appropriate portion of EAX/EDX), passes arguments in C order,
484 // and requires that the callee pop its arguments off the stack (allowing proper
485 // tail calls), and has the same return value conventions as C calling convs.
487 // This calling convention always arranges for the callee pop value to be 8n+4
488 // bytes, which is needed for tail recursion elimination and stack alignment
491 // Note that this can be enhanced in the future to pass fp vals in registers
492 // (when we have a global fp allocator) and do other tricks.
495 /// AddLiveIn - This helper function adds the specified physical register to the
496 /// MachineFunction as a live in value. It also creates a corresponding virtual
498 static unsigned AddLiveIn(MachineFunction &MF, unsigned PReg,
499 TargetRegisterClass *RC) {
500 assert(RC->contains(PReg) && "Not the correct regclass!");
501 unsigned VReg = MF.getSSARegMap()->createVirtualRegister(RC);
502 MF.addLiveIn(PReg, VReg);
507 std::vector<SDOperand>
508 X86TargetLowering::LowerFastCCArguments(Function &F, SelectionDAG &DAG) {
509 std::vector<SDOperand> ArgValues;
511 MachineFunction &MF = DAG.getMachineFunction();
512 MachineFrameInfo *MFI = MF.getFrameInfo();
514 // Add DAG nodes to load the arguments... On entry to a function the stack
515 // frame looks like this:
517 // [ESP] -- return address
518 // [ESP + 4] -- first nonreg argument (leftmost lexically)
519 // [ESP + 8] -- second nonreg argument, if first argument is 4 bytes in size
521 unsigned ArgOffset = 0; // Frame mechanisms handle retaddr slot
523 // Keep track of the number of integer regs passed so far. This can be either
524 // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
526 unsigned NumIntRegs = 0;
528 for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
529 MVT::ValueType ObjectVT = getValueType(I->getType());
530 unsigned ArgIncrement = 4;
531 unsigned ObjSize = 0;
535 default: assert(0 && "Unhandled argument type!");
538 if (NumIntRegs < 2) {
539 if (!I->use_empty()) {
540 unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DL : X86::AL,
541 X86::R8RegisterClass);
542 ArgValue = DAG.getCopyFromReg(VReg, MVT::i8, DAG.getRoot());
543 DAG.setRoot(ArgValue.getValue(1));
552 if (NumIntRegs < 2) {
553 if (!I->use_empty()) {
554 unsigned VReg = AddLiveIn(MF, NumIntRegs ? X86::DX : X86::AX,
555 X86::R16RegisterClass);
556 ArgValue = DAG.getCopyFromReg(VReg, MVT::i16, DAG.getRoot());
557 DAG.setRoot(ArgValue.getValue(1));
565 if (NumIntRegs < 2) {
566 if (!I->use_empty()) {
567 unsigned VReg = AddLiveIn(MF,NumIntRegs ? X86::EDX : X86::EAX,
568 X86::R32RegisterClass);
569 ArgValue = DAG.getCopyFromReg(VReg, MVT::i32, DAG.getRoot());
570 DAG.setRoot(ArgValue.getValue(1));
578 if (NumIntRegs == 0) {
579 if (!I->use_empty()) {
580 unsigned BotReg = AddLiveIn(MF, X86::EAX, X86::R32RegisterClass);
581 unsigned TopReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
583 SDOperand Low=DAG.getCopyFromReg(BotReg, MVT::i32, DAG.getRoot());
584 SDOperand Hi =DAG.getCopyFromReg(TopReg, MVT::i32, Low.getValue(1));
585 DAG.setRoot(Hi.getValue(1));
587 ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
591 } else if (NumIntRegs == 1) {
592 if (!I->use_empty()) {
593 unsigned BotReg = AddLiveIn(MF, X86::EDX, X86::R32RegisterClass);
594 SDOperand Low = DAG.getCopyFromReg(BotReg, MVT::i32, DAG.getRoot());
595 DAG.setRoot(Low.getValue(1));
597 // Load the high part from memory.
598 // Create the frame index object for this incoming parameter...
599 int FI = MFI->CreateFixedObject(4, ArgOffset);
600 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
601 SDOperand Hi = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
602 DAG.getSrcValue(NULL));
603 ArgValue = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, Low, Hi);
609 ObjSize = ArgIncrement = 8;
611 case MVT::f32: ObjSize = 4; break;
612 case MVT::f64: ObjSize = ArgIncrement = 8; break;
615 // Don't codegen dead arguments. FIXME: remove this check when we can nuke
617 if (ObjSize && !I->use_empty()) {
618 // Create the frame index object for this incoming parameter...
619 int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
621 // Create the SelectionDAG nodes corresponding to a load from this
623 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
625 ArgValue = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
626 DAG.getSrcValue(NULL));
627 } else if (ArgValue.Val == 0) {
628 if (MVT::isInteger(ObjectVT))
629 ArgValue = DAG.getConstant(0, ObjectVT);
631 ArgValue = DAG.getConstantFP(0, ObjectVT);
633 ArgValues.push_back(ArgValue);
636 ArgOffset += ArgIncrement; // Move on to the next argument.
639 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
640 // arguments and the arguments after the retaddr has been pushed are aligned.
641 if ((ArgOffset & 7) == 0)
644 VarArgsFrameIndex = 0xAAAAAAA; // fastcc functions can't have varargs.
645 ReturnAddrIndex = 0; // No return address slot generated yet.
646 BytesToPopOnReturn = ArgOffset; // Callee pops all stack arguments.
647 BytesCallerReserves = 0;
649 // Finally, inform the code generator which regs we return values in.
650 switch (getValueType(F.getReturnType())) {
651 default: assert(0 && "Unknown type!");
652 case MVT::isVoid: break;
657 MF.addLiveOut(X86::EAX);
660 MF.addLiveOut(X86::EAX);
661 MF.addLiveOut(X86::EDX);
665 MF.addLiveOut(X86::ST0);
671 std::pair<SDOperand, SDOperand>
672 X86TargetLowering::LowerFastCCCallTo(SDOperand Chain, const Type *RetTy,
673 bool isTailCall, SDOperand Callee,
674 ArgListTy &Args, SelectionDAG &DAG) {
675 // Count how many bytes are to be pushed on the stack.
676 unsigned NumBytes = 0;
678 // Keep track of the number of integer regs passed so far. This can be either
679 // 0 (neither EAX or EDX used), 1 (EAX is used) or 2 (EAX and EDX are both
681 unsigned NumIntRegs = 0;
683 for (unsigned i = 0, e = Args.size(); i != e; ++i)
684 switch (getValueType(Args[i].second)) {
685 default: assert(0 && "Unknown value type!");
690 if (NumIntRegs < 2) {
699 if (NumIntRegs == 0) {
702 } else if (NumIntRegs == 1) {
714 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
715 // arguments and the arguments after the retaddr has been pushed are aligned.
716 if ((NumBytes & 7) == 0)
719 Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
720 DAG.getConstant(NumBytes, getPointerTy()));
722 // Arguments go on the stack in reverse order, as specified by the ABI.
723 unsigned ArgOffset = 0;
724 SDOperand StackPtr = DAG.getCopyFromReg(X86::ESP, MVT::i32,
727 std::vector<SDOperand> Stores;
728 std::vector<SDOperand> RegValuesToPass;
729 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
730 switch (getValueType(Args[i].second)) {
731 default: assert(0 && "Unexpected ValueType for argument!");
736 if (NumIntRegs < 2) {
737 RegValuesToPass.push_back(Args[i].first);
743 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
744 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
745 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
746 Args[i].first, PtrOff,
747 DAG.getSrcValue(NULL)));
752 if (NumIntRegs < 2) { // Can pass part of it in regs?
753 SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
754 Args[i].first, DAG.getConstant(1, MVT::i32));
755 SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
756 Args[i].first, DAG.getConstant(0, MVT::i32));
757 RegValuesToPass.push_back(Lo);
759 if (NumIntRegs < 2) { // Pass both parts in regs?
760 RegValuesToPass.push_back(Hi);
763 // Pass the high part in memory.
764 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
765 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
766 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
767 Hi, PtrOff, DAG.getSrcValue(NULL)));
774 SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
775 PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
776 Stores.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
777 Args[i].first, PtrOff,
778 DAG.getSrcValue(NULL)));
784 Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, Stores);
786 // Make sure the instruction takes 8n+4 bytes to make sure the start of the
787 // arguments and the arguments after the retaddr has been pushed are aligned.
788 if ((ArgOffset & 7) == 0)
791 std::vector<MVT::ValueType> RetVals;
792 MVT::ValueType RetTyVT = getValueType(RetTy);
794 RetVals.push_back(MVT::Other);
796 // The result values produced have to be legal. Promote the result.
798 case MVT::isVoid: break;
800 RetVals.push_back(RetTyVT);
805 RetVals.push_back(MVT::i32);
808 RetVals.push_back(MVT::f64);
811 RetVals.push_back(MVT::i32);
812 RetVals.push_back(MVT::i32);
816 std::vector<SDOperand> Ops;
817 Ops.push_back(Chain);
818 Ops.push_back(Callee);
819 Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
820 // Callee pops all arg values on the stack.
821 Ops.push_back(DAG.getConstant(ArgOffset, getPointerTy()));
823 // Pass register arguments as needed.
824 Ops.insert(Ops.end(), RegValuesToPass.begin(), RegValuesToPass.end());
826 SDOperand TheCall = DAG.getNode(isTailCall ? X86ISD::TAILCALL : X86ISD::CALL,
828 Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, TheCall);
832 case MVT::isVoid: break;
834 ResultVal = TheCall.getValue(1);
839 ResultVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, TheCall.getValue(1));
842 // FIXME: we would really like to remember that this FP_ROUND operation is
843 // okay to eliminate if we allow excess FP precision.
844 ResultVal = DAG.getNode(ISD::FP_ROUND, MVT::f32, TheCall.getValue(1));
847 ResultVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, TheCall.getValue(1),
848 TheCall.getValue(2));
852 return std::make_pair(ResultVal, Chain);
855 SDOperand X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) {
856 if (ReturnAddrIndex == 0) {
857 // Set up a frame object for the return address.
858 MachineFunction &MF = DAG.getMachineFunction();
859 ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(4, -4);
862 return DAG.getFrameIndex(ReturnAddrIndex, MVT::i32);
867 std::pair<SDOperand, SDOperand> X86TargetLowering::
868 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
871 if (Depth) // Depths > 0 not supported yet!
872 Result = DAG.getConstant(0, getPointerTy());
874 SDOperand RetAddrFI = getReturnAddressFrameIndex(DAG);
876 // Just load the return address
877 Result = DAG.getLoad(MVT::i32, DAG.getEntryNode(), RetAddrFI,
878 DAG.getSrcValue(NULL));
880 Result = DAG.getNode(ISD::SUB, MVT::i32, RetAddrFI,
881 DAG.getConstant(4, MVT::i32));
883 return std::make_pair(Result, Chain);
886 /// LowerOperation - Provide custom lowering hooks for some operations.
888 SDOperand X86TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
889 switch (Op.getOpcode()) {
890 default: assert(0 && "Should not custom lower this!");
891 case ISD::SINT_TO_FP:
892 assert(Op.getValueType() == MVT::f64 &&
893 Op.getOperand(0).getValueType() == MVT::i64 &&
894 "Unknown SINT_TO_FP to lower!");
895 // We lower sint64->FP into a store to a temporary stack slot, followed by a
897 MachineFunction &MF = DAG.getMachineFunction();
898 int SSFI = MF.getFrameInfo()->CreateStackObject(8, 8);
899 SDOperand StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
900 SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
901 Op.getOperand(0), StackSlot, DAG.getSrcValue(NULL));
902 std::vector<MVT::ValueType> RTs;
903 RTs.push_back(MVT::f64);
904 RTs.push_back(MVT::Other);
905 std::vector<SDOperand> Ops;
906 Ops.push_back(Store);
907 Ops.push_back(StackSlot);
908 return DAG.getNode(X86ISD::FILD64m, RTs, Ops);
913 //===----------------------------------------------------------------------===//
914 // Pattern Matcher Implementation
915 //===----------------------------------------------------------------------===//
918 /// X86ISelAddressMode - This corresponds to X86AddressMode, but uses
919 /// SDOperand's instead of register numbers for the leaves of the matched
921 struct X86ISelAddressMode {
927 struct { // This is really a union, discriminated by BaseType!
938 : BaseType(RegBase), Scale(1), IndexReg(), Disp(), GV(0) {
946 NumFPKill("x86-codegen", "Number of FP_REG_KILL instructions added");
948 //===--------------------------------------------------------------------===//
949 /// ISel - X86 specific code to select X86 machine instructions for
950 /// SelectionDAG operations.
952 class ISel : public SelectionDAGISel {
953 /// ContainsFPCode - Every instruction we select that uses or defines a FP
954 /// register should set this to true.
957 /// X86Lowering - This object fully describes how to lower LLVM code to an
958 /// X86-specific SelectionDAG.
959 X86TargetLowering X86Lowering;
961 /// RegPressureMap - This keeps an approximate count of the number of
962 /// registers required to evaluate each node in the graph.
963 std::map<SDNode*, unsigned> RegPressureMap;
965 /// ExprMap - As shared expressions are codegen'd, we keep track of which
966 /// vreg the value is produced in, so we only emit one copy of each compiled
968 std::map<SDOperand, unsigned> ExprMap;
970 /// TheDAG - The DAG being selected during Select* operations.
971 SelectionDAG *TheDAG;
973 ISel(TargetMachine &TM) : SelectionDAGISel(X86Lowering), X86Lowering(TM) {
976 virtual const char *getPassName() const {
977 return "X86 Pattern Instruction Selection";
980 unsigned getRegPressure(SDOperand O) {
981 return RegPressureMap[O.Val];
983 unsigned ComputeRegPressure(SDOperand O);
985 /// InstructionSelectBasicBlock - This callback is invoked by
986 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
987 virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
989 virtual void EmitFunctionEntryCode(Function &Fn, MachineFunction &MF);
991 bool isFoldableLoad(SDOperand Op, SDOperand OtherOp,
992 bool FloatPromoteOk = false);
993 void EmitFoldedLoad(SDOperand Op, X86AddressMode &AM);
994 bool TryToFoldLoadOpStore(SDNode *Node);
995 bool EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg);
996 void EmitCMP(SDOperand LHS, SDOperand RHS, bool isOnlyUse);
997 bool EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain, SDOperand Cond);
998 void EmitSelectCC(SDOperand Cond, MVT::ValueType SVT,
999 unsigned RTrue, unsigned RFalse, unsigned RDest);
1000 unsigned SelectExpr(SDOperand N);
1002 X86AddressMode SelectAddrExprs(const X86ISelAddressMode &IAM);
1003 bool MatchAddress(SDOperand N, X86ISelAddressMode &AM);
1004 void SelectAddress(SDOperand N, X86AddressMode &AM);
1005 bool EmitPotentialTailCall(SDNode *Node);
1006 void EmitFastCCToFastCCTailCall(SDNode *TailCallNode);
1007 void Select(SDOperand N);
1011 /// EmitSpecialCodeForMain - Emit any code that needs to be executed only in
1012 /// the main function.
1013 static void EmitSpecialCodeForMain(MachineBasicBlock *BB,
1014 MachineFrameInfo *MFI) {
1015 // Switch the FPU to 64-bit precision mode for better compatibility and speed.
1016 int CWFrameIdx = MFI->CreateStackObject(2, 2);
1017 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
1019 // Set the high part to be 64-bit precision.
1020 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
1021 CWFrameIdx, 1).addImm(2);
1023 // Reload the modified control word now.
1024 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
1027 void ISel::EmitFunctionEntryCode(Function &Fn, MachineFunction &MF) {
1028 // If this function has live-in values, emit the copies from pregs to vregs at
1029 // the top of the function, before anything else.
1030 MachineBasicBlock *BB = MF.begin();
1031 if (MF.livein_begin() != MF.livein_end()) {
1032 SSARegMap *RegMap = MF.getSSARegMap();
1033 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
1034 E = MF.livein_end(); LI != E; ++LI) {
1035 const TargetRegisterClass *RC = RegMap->getRegClass(LI->second);
1036 if (RC == X86::R8RegisterClass) {
1037 BuildMI(BB, X86::MOV8rr, 1, LI->second).addReg(LI->first);
1038 } else if (RC == X86::R16RegisterClass) {
1039 BuildMI(BB, X86::MOV16rr, 1, LI->second).addReg(LI->first);
1040 } else if (RC == X86::R32RegisterClass) {
1041 BuildMI(BB, X86::MOV32rr, 1, LI->second).addReg(LI->first);
1042 } else if (RC == X86::RFPRegisterClass) {
1043 BuildMI(BB, X86::FpMOV, 1, LI->second).addReg(LI->first);
1045 assert(0 && "Unknown regclass!");
1051 // If this is main, emit special code for main.
1052 if (Fn.hasExternalLinkage() && Fn.getName() == "main")
1053 EmitSpecialCodeForMain(BB, MF.getFrameInfo());
1057 /// InstructionSelectBasicBlock - This callback is invoked by SelectionDAGISel
1058 /// when it has created a SelectionDAG for us to codegen.
1059 void ISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
1060 // While we're doing this, keep track of whether we see any FP code for
1061 // FP_REG_KILL insertion.
1062 ContainsFPCode = false;
1063 MachineFunction *MF = BB->getParent();
1065 // Scan the PHI nodes that already are inserted into this basic block. If any
1066 // of them is a PHI of a floating point value, we need to insert an
1068 SSARegMap *RegMap = MF->getSSARegMap();
1069 if (BB != MF->begin())
1070 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
1072 assert(I->getOpcode() == X86::PHI &&
1073 "Isn't just PHI nodes?");
1074 if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
1075 X86::RFPRegisterClass) {
1076 ContainsFPCode = true;
1081 // Compute the RegPressureMap, which is an approximation for the number of
1082 // registers required to compute each node.
1083 ComputeRegPressure(DAG.getRoot());
1087 // Codegen the basic block.
1088 Select(DAG.getRoot());
1092 // Finally, look at all of the successors of this block. If any contain a PHI
1093 // node of FP type, we need to insert an FP_REG_KILL in this block.
1094 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1095 E = BB->succ_end(); SI != E && !ContainsFPCode; ++SI)
1096 for (MachineBasicBlock::iterator I = (*SI)->begin(), E = (*SI)->end();
1097 I != E && I->getOpcode() == X86::PHI; ++I) {
1098 if (RegMap->getRegClass(I->getOperand(0).getReg()) ==
1099 X86::RFPRegisterClass) {
1100 ContainsFPCode = true;
1105 // Final check, check LLVM BB's that are successors to the LLVM BB
1106 // corresponding to BB for FP PHI nodes.
1107 const BasicBlock *LLVMBB = BB->getBasicBlock();
1109 if (!ContainsFPCode)
1110 for (succ_const_iterator SI = succ_begin(LLVMBB), E = succ_end(LLVMBB);
1111 SI != E && !ContainsFPCode; ++SI)
1112 for (BasicBlock::const_iterator II = SI->begin();
1113 (PN = dyn_cast<PHINode>(II)); ++II)
1114 if (PN->getType()->isFloatingPoint()) {
1115 ContainsFPCode = true;
1120 // Insert FP_REG_KILL instructions into basic blocks that need them. This
1121 // only occurs due to the floating point stackifier not being aggressive
1122 // enough to handle arbitrary global stackification.
1124 // Currently we insert an FP_REG_KILL instruction into each block that uses or
1125 // defines a floating point virtual register.
1127 // When the global register allocators (like linear scan) finally update live
1128 // variable analysis, we can keep floating point values in registers across
1129 // basic blocks. This will be a huge win, but we are waiting on the global
1130 // allocators before we can do this.
1132 if (ContainsFPCode) {
1133 BuildMI(*BB, BB->getFirstTerminator(), X86::FP_REG_KILL, 0);
1137 // Clear state used for selection.
1139 RegPressureMap.clear();
1143 // ComputeRegPressure - Compute the RegPressureMap, which is an approximation
1144 // for the number of registers required to compute each node. This is basically
1145 // computing a generalized form of the Sethi-Ullman number for each node.
1146 unsigned ISel::ComputeRegPressure(SDOperand O) {
1148 unsigned &Result = RegPressureMap[N];
1149 if (Result) return Result;
1151 // FIXME: Should operations like CALL (which clobber lots o regs) have a
1152 // higher fixed cost??
1154 if (N->getNumOperands() == 0) {
1157 unsigned MaxRegUse = 0;
1158 unsigned NumExtraMaxRegUsers = 0;
1159 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
1161 if (N->getOperand(i).getOpcode() == ISD::Constant)
1164 Regs = ComputeRegPressure(N->getOperand(i));
1165 if (Regs > MaxRegUse) {
1167 NumExtraMaxRegUsers = 0;
1168 } else if (Regs == MaxRegUse &&
1169 N->getOperand(i).getValueType() != MVT::Other) {
1170 ++NumExtraMaxRegUsers;
1174 if (O.getOpcode() != ISD::TokenFactor)
1175 Result = MaxRegUse+NumExtraMaxRegUsers;
1177 Result = MaxRegUse == 1 ? 0 : MaxRegUse-1;
1180 //std::cerr << " WEIGHT: " << Result << " "; N->dump(); std::cerr << "\n";
1184 /// NodeTransitivelyUsesValue - Return true if N or any of its uses uses Op.
1185 /// The DAG cannot have cycles in it, by definition, so the visited set is not
1186 /// needed to prevent infinite loops. The DAG CAN, however, have unbounded
1187 /// reuse, so it prevents exponential cases.
1189 static bool NodeTransitivelyUsesValue(SDOperand N, SDOperand Op,
1190 std::set<SDNode*> &Visited) {
1191 if (N == Op) return true; // Found it.
1192 SDNode *Node = N.Val;
1193 if (Node->getNumOperands() == 0 || // Leaf?
1194 Node->getNodeDepth() <= Op.getNodeDepth()) return false; // Can't find it?
1195 if (!Visited.insert(Node).second) return false; // Already visited?
1197 // Recurse for the first N-1 operands.
1198 for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i)
1199 if (NodeTransitivelyUsesValue(Node->getOperand(i), Op, Visited))
1202 // Tail recurse for the last operand.
1203 return NodeTransitivelyUsesValue(Node->getOperand(0), Op, Visited);
1206 X86AddressMode ISel::SelectAddrExprs(const X86ISelAddressMode &IAM) {
1207 X86AddressMode Result;
1209 // If we need to emit two register operands, emit the one with the highest
1210 // register pressure first.
1211 if (IAM.BaseType == X86ISelAddressMode::RegBase &&
1212 IAM.Base.Reg.Val && IAM.IndexReg.Val) {
1213 bool EmitBaseThenIndex;
1214 if (getRegPressure(IAM.Base.Reg) > getRegPressure(IAM.IndexReg)) {
1215 std::set<SDNode*> Visited;
1216 EmitBaseThenIndex = true;
1217 // If Base ends up pointing to Index, we must emit index first. This is
1218 // because of the way we fold loads, we may end up doing bad things with
1220 if (NodeTransitivelyUsesValue(IAM.Base.Reg, IAM.IndexReg, Visited))
1221 EmitBaseThenIndex = false;
1223 std::set<SDNode*> Visited;
1224 EmitBaseThenIndex = false;
1225 // If Base ends up pointing to Index, we must emit index first. This is
1226 // because of the way we fold loads, we may end up doing bad things with
1228 if (NodeTransitivelyUsesValue(IAM.IndexReg, IAM.Base.Reg, Visited))
1229 EmitBaseThenIndex = true;
1232 if (EmitBaseThenIndex) {
1233 Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1234 Result.IndexReg = SelectExpr(IAM.IndexReg);
1236 Result.IndexReg = SelectExpr(IAM.IndexReg);
1237 Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1240 } else if (IAM.BaseType == X86ISelAddressMode::RegBase && IAM.Base.Reg.Val) {
1241 Result.Base.Reg = SelectExpr(IAM.Base.Reg);
1242 } else if (IAM.IndexReg.Val) {
1243 Result.IndexReg = SelectExpr(IAM.IndexReg);
1246 switch (IAM.BaseType) {
1247 case X86ISelAddressMode::RegBase:
1248 Result.BaseType = X86AddressMode::RegBase;
1250 case X86ISelAddressMode::FrameIndexBase:
1251 Result.BaseType = X86AddressMode::FrameIndexBase;
1252 Result.Base.FrameIndex = IAM.Base.FrameIndex;
1255 assert(0 && "Unknown base type!");
1258 Result.Scale = IAM.Scale;
1259 Result.Disp = IAM.Disp;
1264 /// SelectAddress - Pattern match the maximal addressing mode for this node and
1265 /// emit all of the leaf registers.
1266 void ISel::SelectAddress(SDOperand N, X86AddressMode &AM) {
1267 X86ISelAddressMode IAM;
1268 MatchAddress(N, IAM);
1269 AM = SelectAddrExprs(IAM);
1272 /// MatchAddress - Add the specified node to the specified addressing mode,
1273 /// returning true if it cannot be done. This just pattern matches for the
1274 /// addressing mode, it does not cause any code to be emitted. For that, use
1276 bool ISel::MatchAddress(SDOperand N, X86ISelAddressMode &AM) {
1277 switch (N.getOpcode()) {
1279 case ISD::FrameIndex:
1280 if (AM.BaseType == X86ISelAddressMode::RegBase && AM.Base.Reg.Val == 0) {
1281 AM.BaseType = X86ISelAddressMode::FrameIndexBase;
1282 AM.Base.FrameIndex = cast<FrameIndexSDNode>(N)->getIndex();
1286 case ISD::GlobalAddress:
1288 AM.GV = cast<GlobalAddressSDNode>(N)->getGlobal();
1293 AM.Disp += cast<ConstantSDNode>(N)->getValue();
1296 // We might have folded the load into this shift, so don't regen the value
1298 if (ExprMap.count(N)) break;
1300 if (AM.IndexReg.Val == 0 && AM.Scale == 1)
1301 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1))) {
1302 unsigned Val = CN->getValue();
1303 if (Val == 1 || Val == 2 || Val == 3) {
1304 AM.Scale = 1 << Val;
1305 SDOperand ShVal = N.Val->getOperand(0);
1307 // Okay, we know that we have a scale by now. However, if the scaled
1308 // value is an add of something and a constant, we can fold the
1309 // constant into the disp field here.
1310 if (ShVal.Val->getOpcode() == ISD::ADD && ShVal.hasOneUse() &&
1311 isa<ConstantSDNode>(ShVal.Val->getOperand(1))) {
1312 AM.IndexReg = ShVal.Val->getOperand(0);
1313 ConstantSDNode *AddVal =
1314 cast<ConstantSDNode>(ShVal.Val->getOperand(1));
1315 AM.Disp += AddVal->getValue() << Val;
1317 AM.IndexReg = ShVal;
1324 // We might have folded the load into this mul, so don't regen the value if
1326 if (ExprMap.count(N)) break;
1328 // X*[3,5,9] -> X+X*[2,4,8]
1329 if (AM.IndexReg.Val == 0 && AM.BaseType == X86ISelAddressMode::RegBase &&
1330 AM.Base.Reg.Val == 0)
1331 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.Val->getOperand(1)))
1332 if (CN->getValue() == 3 || CN->getValue() == 5 || CN->getValue() == 9) {
1333 AM.Scale = unsigned(CN->getValue())-1;
1335 SDOperand MulVal = N.Val->getOperand(0);
1338 // Okay, we know that we have a scale by now. However, if the scaled
1339 // value is an add of something and a constant, we can fold the
1340 // constant into the disp field here.
1341 if (MulVal.Val->getOpcode() == ISD::ADD && MulVal.hasOneUse() &&
1342 isa<ConstantSDNode>(MulVal.Val->getOperand(1))) {
1343 Reg = MulVal.Val->getOperand(0);
1344 ConstantSDNode *AddVal =
1345 cast<ConstantSDNode>(MulVal.Val->getOperand(1));
1346 AM.Disp += AddVal->getValue() * CN->getValue();
1348 Reg = N.Val->getOperand(0);
1351 AM.IndexReg = AM.Base.Reg = Reg;
1357 // We might have folded the load into this mul, so don't regen the value if
1359 if (ExprMap.count(N)) break;
1361 X86ISelAddressMode Backup = AM;
1362 if (!MatchAddress(N.Val->getOperand(0), AM) &&
1363 !MatchAddress(N.Val->getOperand(1), AM))
1366 if (!MatchAddress(N.Val->getOperand(1), AM) &&
1367 !MatchAddress(N.Val->getOperand(0), AM))
1374 // Is the base register already occupied?
1375 if (AM.BaseType != X86ISelAddressMode::RegBase || AM.Base.Reg.Val) {
1376 // If so, check to see if the scale index register is set.
1377 if (AM.IndexReg.Val == 0) {
1383 // Otherwise, we cannot select it.
1387 // Default, generate it as a register.
1388 AM.BaseType = X86ISelAddressMode::RegBase;
1393 /// Emit2SetCCsAndLogical - Emit the following sequence of instructions,
1394 /// assuming that the temporary registers are in the 8-bit register class.
1398 /// DestReg = logicalop Tmp1, Tmp2
1400 static void Emit2SetCCsAndLogical(MachineBasicBlock *BB, unsigned SetCC1,
1401 unsigned SetCC2, unsigned LogicalOp,
1403 SSARegMap *RegMap = BB->getParent()->getSSARegMap();
1404 unsigned Tmp1 = RegMap->createVirtualRegister(X86::R8RegisterClass);
1405 unsigned Tmp2 = RegMap->createVirtualRegister(X86::R8RegisterClass);
1406 BuildMI(BB, SetCC1, 0, Tmp1);
1407 BuildMI(BB, SetCC2, 0, Tmp2);
1408 BuildMI(BB, LogicalOp, 2, DestReg).addReg(Tmp1).addReg(Tmp2);
1411 /// EmitSetCC - Emit the code to set the specified 8-bit register to 1 if the
1412 /// condition codes match the specified SetCCOpcode. Note that some conditions
1413 /// require multiple instructions to generate the correct value.
1414 static void EmitSetCC(MachineBasicBlock *BB, unsigned DestReg,
1415 ISD::CondCode SetCCOpcode, bool isFP) {
1418 switch (SetCCOpcode) {
1419 default: assert(0 && "Illegal integer SetCC!");
1420 case ISD::SETEQ: Opc = X86::SETEr; break;
1421 case ISD::SETGT: Opc = X86::SETGr; break;
1422 case ISD::SETGE: Opc = X86::SETGEr; break;
1423 case ISD::SETLT: Opc = X86::SETLr; break;
1424 case ISD::SETLE: Opc = X86::SETLEr; break;
1425 case ISD::SETNE: Opc = X86::SETNEr; break;
1426 case ISD::SETULT: Opc = X86::SETBr; break;
1427 case ISD::SETUGT: Opc = X86::SETAr; break;
1428 case ISD::SETULE: Opc = X86::SETBEr; break;
1429 case ISD::SETUGE: Opc = X86::SETAEr; break;
1432 // On a floating point condition, the flags are set as follows:
1434 // 0 | 0 | 0 | X > Y
1435 // 0 | 0 | 1 | X < Y
1436 // 1 | 0 | 0 | X == Y
1437 // 1 | 1 | 1 | unordered
1439 switch (SetCCOpcode) {
1440 default: assert(0 && "Invalid FP setcc!");
1443 Opc = X86::SETEr; // True if ZF = 1
1447 Opc = X86::SETAr; // True if CF = 0 and ZF = 0
1451 Opc = X86::SETAEr; // True if CF = 0
1455 Opc = X86::SETBr; // True if CF = 1
1459 Opc = X86::SETBEr; // True if CF = 1 or ZF = 1
1463 Opc = X86::SETNEr; // True if ZF = 0
1466 Opc = X86::SETPr; // True if PF = 1
1469 Opc = X86::SETNPr; // True if PF = 0
1471 case ISD::SETOEQ: // !PF & ZF
1472 Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETEr, X86::AND8rr, DestReg);
1474 case ISD::SETOLT: // !PF & CF
1475 Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBr, X86::AND8rr, DestReg);
1477 case ISD::SETOLE: // !PF & (CF || ZF)
1478 Emit2SetCCsAndLogical(BB, X86::SETNPr, X86::SETBEr, X86::AND8rr, DestReg);
1480 case ISD::SETUGT: // PF | (!ZF & !CF)
1481 Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAr, X86::OR8rr, DestReg);
1483 case ISD::SETUGE: // PF | !CF
1484 Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETAEr, X86::OR8rr, DestReg);
1486 case ISD::SETUNE: // PF | !ZF
1487 Emit2SetCCsAndLogical(BB, X86::SETPr, X86::SETNEr, X86::OR8rr, DestReg);
1491 BuildMI(BB, Opc, 0, DestReg);
1495 /// EmitBranchCC - Emit code into BB that arranges for control to transfer to
1496 /// the Dest block if the Cond condition is true. If we cannot fold this
1497 /// condition into the branch, return true.
1499 bool ISel::EmitBranchCC(MachineBasicBlock *Dest, SDOperand Chain,
1501 // FIXME: Evaluate whether it would be good to emit code like (X < Y) | (A >
1502 // B) using two conditional branches instead of one condbr, two setcc's, and
1504 if ((Cond.getOpcode() == ISD::OR ||
1505 Cond.getOpcode() == ISD::AND) && Cond.Val->hasOneUse()) {
1506 // And and or set the flags for us, so there is no need to emit a TST of the
1507 // result. It is only safe to do this if there is only a single use of the
1508 // AND/OR though, otherwise we don't know it will be emitted here.
1511 BuildMI(BB, X86::JNE, 1).addMBB(Dest);
1515 // Codegen br not C -> JE.
1516 if (Cond.getOpcode() == ISD::XOR)
1517 if (ConstantSDNode *NC = dyn_cast<ConstantSDNode>(Cond.Val->getOperand(1)))
1518 if (NC->isAllOnesValue()) {
1520 if (getRegPressure(Chain) > getRegPressure(Cond)) {
1522 CondR = SelectExpr(Cond.Val->getOperand(0));
1524 CondR = SelectExpr(Cond.Val->getOperand(0));
1527 BuildMI(BB, X86::TEST8rr, 2).addReg(CondR).addReg(CondR);
1528 BuildMI(BB, X86::JE, 1).addMBB(Dest);
1532 SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Cond);
1534 return true; // Can only handle simple setcc's so far.
1538 // Handle integer conditions first.
1539 if (MVT::isInteger(SetCC->getOperand(0).getValueType())) {
1540 switch (SetCC->getCondition()) {
1541 default: assert(0 && "Illegal integer SetCC!");
1542 case ISD::SETEQ: Opc = X86::JE; break;
1543 case ISD::SETGT: Opc = X86::JG; break;
1544 case ISD::SETGE: Opc = X86::JGE; break;
1545 case ISD::SETLT: Opc = X86::JL; break;
1546 case ISD::SETLE: Opc = X86::JLE; break;
1547 case ISD::SETNE: Opc = X86::JNE; break;
1548 case ISD::SETULT: Opc = X86::JB; break;
1549 case ISD::SETUGT: Opc = X86::JA; break;
1550 case ISD::SETULE: Opc = X86::JBE; break;
1551 case ISD::SETUGE: Opc = X86::JAE; break;
1554 EmitCMP(SetCC->getOperand(0), SetCC->getOperand(1), SetCC->hasOneUse());
1555 BuildMI(BB, Opc, 1).addMBB(Dest);
1559 unsigned Opc2 = 0; // Second branch if needed.
1561 // On a floating point condition, the flags are set as follows:
1563 // 0 | 0 | 0 | X > Y
1564 // 0 | 0 | 1 | X < Y
1565 // 1 | 0 | 0 | X == Y
1566 // 1 | 1 | 1 | unordered
1568 switch (SetCC->getCondition()) {
1569 default: assert(0 && "Invalid FP setcc!");
1571 case ISD::SETEQ: Opc = X86::JE; break; // True if ZF = 1
1573 case ISD::SETGT: Opc = X86::JA; break; // True if CF = 0 and ZF = 0
1575 case ISD::SETGE: Opc = X86::JAE; break; // True if CF = 0
1577 case ISD::SETLT: Opc = X86::JB; break; // True if CF = 1
1579 case ISD::SETLE: Opc = X86::JBE; break; // True if CF = 1 or ZF = 1
1581 case ISD::SETNE: Opc = X86::JNE; break; // True if ZF = 0
1582 case ISD::SETUO: Opc = X86::JP; break; // True if PF = 1
1583 case ISD::SETO: Opc = X86::JNP; break; // True if PF = 0
1584 case ISD::SETUGT: // PF = 1 | (ZF = 0 & CF = 0)
1585 Opc = X86::JA; // ZF = 0 & CF = 0
1586 Opc2 = X86::JP; // PF = 1
1588 case ISD::SETUGE: // PF = 1 | CF = 0
1589 Opc = X86::JAE; // CF = 0
1590 Opc2 = X86::JP; // PF = 1
1592 case ISD::SETUNE: // PF = 1 | ZF = 0
1593 Opc = X86::JNE; // ZF = 0
1594 Opc2 = X86::JP; // PF = 1
1596 case ISD::SETOEQ: // PF = 0 & ZF = 1
1599 return true; // FIXME: Emit more efficient code for this branch.
1600 case ISD::SETOLT: // PF = 0 & CF = 1
1603 return true; // FIXME: Emit more efficient code for this branch.
1604 case ISD::SETOLE: // PF = 0 & (CF = 1 || ZF = 1)
1605 //X86::JNP, X86::JBE
1607 return true; // FIXME: Emit more efficient code for this branch.
1611 EmitCMP(SetCC->getOperand(0), SetCC->getOperand(1), SetCC->hasOneUse());
1612 BuildMI(BB, Opc, 1).addMBB(Dest);
1614 BuildMI(BB, Opc2, 1).addMBB(Dest);
1618 /// EmitSelectCC - Emit code into BB that performs a select operation between
1619 /// the two registers RTrue and RFalse, generating a result into RDest. Return
1620 /// true if the fold cannot be performed.
1622 void ISel::EmitSelectCC(SDOperand Cond, MVT::ValueType SVT,
1623 unsigned RTrue, unsigned RFalse, unsigned RDest) {
1625 EQ, NE, LT, LE, GT, GE, B, BE, A, AE, P, NP,
1627 } CondCode = NOT_SET;
1629 static const unsigned CMOVTAB16[] = {
1630 X86::CMOVE16rr, X86::CMOVNE16rr, X86::CMOVL16rr, X86::CMOVLE16rr,
1631 X86::CMOVG16rr, X86::CMOVGE16rr, X86::CMOVB16rr, X86::CMOVBE16rr,
1632 X86::CMOVA16rr, X86::CMOVAE16rr, X86::CMOVP16rr, X86::CMOVNP16rr,
1634 static const unsigned CMOVTAB32[] = {
1635 X86::CMOVE32rr, X86::CMOVNE32rr, X86::CMOVL32rr, X86::CMOVLE32rr,
1636 X86::CMOVG32rr, X86::CMOVGE32rr, X86::CMOVB32rr, X86::CMOVBE32rr,
1637 X86::CMOVA32rr, X86::CMOVAE32rr, X86::CMOVP32rr, X86::CMOVNP32rr,
1639 static const unsigned CMOVTABFP[] = {
1640 X86::FCMOVE , X86::FCMOVNE, /*missing*/0, /*missing*/0,
1641 /*missing*/0, /*missing*/0, X86::FCMOVB , X86::FCMOVBE,
1642 X86::FCMOVA , X86::FCMOVAE, X86::FCMOVP , X86::FCMOVNP
1645 if (SetCCSDNode *SetCC = dyn_cast<SetCCSDNode>(Cond)) {
1646 if (MVT::isInteger(SetCC->getOperand(0).getValueType())) {
1647 switch (SetCC->getCondition()) {
1648 default: assert(0 && "Unknown integer comparison!");
1649 case ISD::SETEQ: CondCode = EQ; break;
1650 case ISD::SETGT: CondCode = GT; break;
1651 case ISD::SETGE: CondCode = GE; break;
1652 case ISD::SETLT: CondCode = LT; break;
1653 case ISD::SETLE: CondCode = LE; break;
1654 case ISD::SETNE: CondCode = NE; break;
1655 case ISD::SETULT: CondCode = B; break;
1656 case ISD::SETUGT: CondCode = A; break;
1657 case ISD::SETULE: CondCode = BE; break;
1658 case ISD::SETUGE: CondCode = AE; break;
1661 // On a floating point condition, the flags are set as follows:
1663 // 0 | 0 | 0 | X > Y
1664 // 0 | 0 | 1 | X < Y
1665 // 1 | 0 | 0 | X == Y
1666 // 1 | 1 | 1 | unordered
1668 switch (SetCC->getCondition()) {
1669 default: assert(0 && "Unknown FP comparison!");
1671 case ISD::SETEQ: CondCode = EQ; break; // True if ZF = 1
1673 case ISD::SETGT: CondCode = A; break; // True if CF = 0 and ZF = 0
1675 case ISD::SETGE: CondCode = AE; break; // True if CF = 0
1677 case ISD::SETLT: CondCode = B; break; // True if CF = 1
1679 case ISD::SETLE: CondCode = BE; break; // True if CF = 1 or ZF = 1
1681 case ISD::SETNE: CondCode = NE; break; // True if ZF = 0
1682 case ISD::SETUO: CondCode = P; break; // True if PF = 1
1683 case ISD::SETO: CondCode = NP; break; // True if PF = 0
1684 case ISD::SETUGT: // PF = 1 | (ZF = 0 & CF = 0)
1685 case ISD::SETUGE: // PF = 1 | CF = 0
1686 case ISD::SETUNE: // PF = 1 | ZF = 0
1687 case ISD::SETOEQ: // PF = 0 & ZF = 1
1688 case ISD::SETOLT: // PF = 0 & CF = 1
1689 case ISD::SETOLE: // PF = 0 & (CF = 1 || ZF = 1)
1690 // We cannot emit this comparison as a single cmov.
1697 if (CondCode != NOT_SET) {
1699 default: assert(0 && "Cannot select this type!");
1700 case MVT::i16: Opc = CMOVTAB16[CondCode]; break;
1701 case MVT::i32: Opc = CMOVTAB32[CondCode]; break;
1702 case MVT::f64: Opc = CMOVTABFP[CondCode]; break;
1706 // Finally, if we weren't able to fold this, just emit the condition and test
1708 if (CondCode == NOT_SET || Opc == 0) {
1709 // Get the condition into the zero flag.
1710 unsigned CondReg = SelectExpr(Cond);
1711 BuildMI(BB, X86::TEST8rr, 2).addReg(CondReg).addReg(CondReg);
1714 default: assert(0 && "Cannot select this type!");
1715 case MVT::i16: Opc = X86::CMOVE16rr; break;
1716 case MVT::i32: Opc = X86::CMOVE32rr; break;
1717 case MVT::f64: Opc = X86::FCMOVE; break;
1720 // FIXME: CMP R, 0 -> TEST R, R
1721 EmitCMP(Cond.getOperand(0), Cond.getOperand(1), Cond.Val->hasOneUse());
1722 std::swap(RTrue, RFalse);
1724 BuildMI(BB, Opc, 2, RDest).addReg(RTrue).addReg(RFalse);
1727 void ISel::EmitCMP(SDOperand LHS, SDOperand RHS, bool HasOneUse) {
1729 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS)) {
1731 if (HasOneUse && isFoldableLoad(LHS, RHS)) {
1732 switch (RHS.getValueType()) {
1735 case MVT::i8: Opc = X86::CMP8mi; break;
1736 case MVT::i16: Opc = X86::CMP16mi; break;
1737 case MVT::i32: Opc = X86::CMP32mi; break;
1741 EmitFoldedLoad(LHS, AM);
1742 addFullAddress(BuildMI(BB, Opc, 5), AM).addImm(CN->getValue());
1747 switch (RHS.getValueType()) {
1750 case MVT::i8: Opc = X86::CMP8ri; break;
1751 case MVT::i16: Opc = X86::CMP16ri; break;
1752 case MVT::i32: Opc = X86::CMP32ri; break;
1755 unsigned Tmp1 = SelectExpr(LHS);
1756 BuildMI(BB, Opc, 2).addReg(Tmp1).addImm(CN->getValue());
1759 } else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(RHS)) {
1760 if (CN->isExactlyValue(+0.0) ||
1761 CN->isExactlyValue(-0.0)) {
1762 unsigned Reg = SelectExpr(LHS);
1763 BuildMI(BB, X86::FTST, 1).addReg(Reg);
1764 BuildMI(BB, X86::FNSTSW8r, 0);
1765 BuildMI(BB, X86::SAHF, 1);
1771 if (HasOneUse && isFoldableLoad(LHS, RHS)) {
1772 switch (RHS.getValueType()) {
1775 case MVT::i8: Opc = X86::CMP8mr; break;
1776 case MVT::i16: Opc = X86::CMP16mr; break;
1777 case MVT::i32: Opc = X86::CMP32mr; break;
1781 EmitFoldedLoad(LHS, AM);
1782 unsigned Reg = SelectExpr(RHS);
1783 addFullAddress(BuildMI(BB, Opc, 5), AM).addReg(Reg);
1788 switch (LHS.getValueType()) {
1789 default: assert(0 && "Cannot compare this value!");
1791 case MVT::i8: Opc = X86::CMP8rr; break;
1792 case MVT::i16: Opc = X86::CMP16rr; break;
1793 case MVT::i32: Opc = X86::CMP32rr; break;
1794 case MVT::f64: Opc = X86::FUCOMIr; break;
1796 unsigned Tmp1, Tmp2;
1797 if (getRegPressure(LHS) > getRegPressure(RHS)) {
1798 Tmp1 = SelectExpr(LHS);
1799 Tmp2 = SelectExpr(RHS);
1801 Tmp2 = SelectExpr(RHS);
1802 Tmp1 = SelectExpr(LHS);
1804 BuildMI(BB, Opc, 2).addReg(Tmp1).addReg(Tmp2);
1807 /// isFoldableLoad - Return true if this is a load instruction that can safely
1808 /// be folded into an operation that uses it.
1809 bool ISel::isFoldableLoad(SDOperand Op, SDOperand OtherOp, bool FloatPromoteOk){
1810 if (Op.getOpcode() == ISD::LOAD) {
1811 // FIXME: currently can't fold constant pool indexes.
1812 if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
1814 } else if (FloatPromoteOk && Op.getOpcode() == ISD::EXTLOAD &&
1815 cast<MVTSDNode>(Op)->getExtraValueType() == MVT::f32) {
1816 // FIXME: currently can't fold constant pool indexes.
1817 if (isa<ConstantPoolSDNode>(Op.getOperand(1)))
1823 // If this load has already been emitted, we clearly can't fold it.
1824 assert(Op.ResNo == 0 && "Not a use of the value of the load?");
1825 if (ExprMap.count(Op.getValue(1))) return false;
1826 assert(!ExprMap.count(Op.getValue(0)) && "Value in map but not token chain?");
1827 assert(!ExprMap.count(Op.getValue(1))&&"Token lowered but value not in map?");
1829 // If there is not just one use of its value, we cannot fold.
1830 if (!Op.Val->hasNUsesOfValue(1, 0)) return false;
1832 // Finally, we cannot fold the load into the operation if this would induce a
1833 // cycle into the resultant dag. To check for this, see if OtherOp (the other
1834 // operand of the operation we are folding the load into) can possible use the
1835 // chain node defined by the load.
1836 if (OtherOp.Val && !Op.Val->hasNUsesOfValue(0, 1)) { // Has uses of chain?
1837 std::set<SDNode*> Visited;
1838 if (NodeTransitivelyUsesValue(OtherOp, Op.getValue(1), Visited))
1845 /// EmitFoldedLoad - Ensure that the arguments of the load are code generated,
1846 /// and compute the address being loaded into AM.
1847 void ISel::EmitFoldedLoad(SDOperand Op, X86AddressMode &AM) {
1848 SDOperand Chain = Op.getOperand(0);
1849 SDOperand Address = Op.getOperand(1);
1851 if (getRegPressure(Chain) > getRegPressure(Address)) {
1853 SelectAddress(Address, AM);
1855 SelectAddress(Address, AM);
1859 // The chain for this load is now lowered.
1860 assert(ExprMap.count(SDOperand(Op.Val, 1)) == 0 &&
1861 "Load emitted more than once?");
1862 if (!ExprMap.insert(std::make_pair(Op.getValue(1), 1)).second)
1863 assert(0 && "Load emitted more than once!");
1866 // EmitOrOpOp - Pattern match the expression (Op1|Op2), where we know that op1
1867 // and op2 are i8/i16/i32 values with one use each (the or). If we can form a
1868 // SHLD or SHRD, emit the instruction (generating the value into DestReg) and
1870 bool ISel::EmitOrOpOp(SDOperand Op1, SDOperand Op2, unsigned DestReg) {
1871 if (Op1.getOpcode() == ISD::SHL && Op2.getOpcode() == ISD::SRL) {
1873 } else if (Op2.getOpcode() == ISD::SHL && Op1.getOpcode() == ISD::SRL) {
1874 std::swap(Op1, Op2); // Op1 is the SHL now.
1876 return false; // No match
1879 SDOperand ShlVal = Op1.getOperand(0);
1880 SDOperand ShlAmt = Op1.getOperand(1);
1881 SDOperand ShrVal = Op2.getOperand(0);
1882 SDOperand ShrAmt = Op2.getOperand(1);
1884 unsigned RegSize = MVT::getSizeInBits(Op1.getValueType());
1886 // Find out if ShrAmt = 32-ShlAmt or ShlAmt = 32-ShrAmt.
1887 if (ShlAmt.getOpcode() == ISD::SUB && ShlAmt.getOperand(1) == ShrAmt)
1888 if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShlAmt.getOperand(0)))
1889 if (SubCST->getValue() == RegSize) {
1890 // (A >> ShrAmt) | (A << (32-ShrAmt)) ==> ROR A, ShrAmt
1891 // (A >> ShrAmt) | (B << (32-ShrAmt)) ==> SHRD A, B, ShrAmt
1892 if (ShrVal == ShlVal) {
1893 unsigned Reg, ShAmt;
1894 if (getRegPressure(ShrVal) > getRegPressure(ShrAmt)) {
1895 Reg = SelectExpr(ShrVal);
1896 ShAmt = SelectExpr(ShrAmt);
1898 ShAmt = SelectExpr(ShrAmt);
1899 Reg = SelectExpr(ShrVal);
1901 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1902 unsigned Opc = RegSize == 8 ? X86::ROR8rCL :
1903 (RegSize == 16 ? X86::ROR16rCL : X86::ROR32rCL);
1904 BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
1906 } else if (RegSize != 8) {
1907 unsigned AReg, BReg;
1908 if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
1909 BReg = SelectExpr(ShlVal);
1910 AReg = SelectExpr(ShrVal);
1912 AReg = SelectExpr(ShrVal);
1913 BReg = SelectExpr(ShlVal);
1915 unsigned ShAmt = SelectExpr(ShrAmt);
1916 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1917 unsigned Opc = RegSize == 16 ? X86::SHRD16rrCL : X86::SHRD32rrCL;
1918 BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
1923 if (ShrAmt.getOpcode() == ISD::SUB && ShrAmt.getOperand(1) == ShlAmt)
1924 if (ConstantSDNode *SubCST = dyn_cast<ConstantSDNode>(ShrAmt.getOperand(0)))
1925 if (SubCST->getValue() == RegSize) {
1926 // (A << ShlAmt) | (A >> (32-ShlAmt)) ==> ROL A, ShrAmt
1927 // (A << ShlAmt) | (B >> (32-ShlAmt)) ==> SHLD A, B, ShrAmt
1928 if (ShrVal == ShlVal) {
1929 unsigned Reg, ShAmt;
1930 if (getRegPressure(ShrVal) > getRegPressure(ShlAmt)) {
1931 Reg = SelectExpr(ShrVal);
1932 ShAmt = SelectExpr(ShlAmt);
1934 ShAmt = SelectExpr(ShlAmt);
1935 Reg = SelectExpr(ShrVal);
1937 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1938 unsigned Opc = RegSize == 8 ? X86::ROL8rCL :
1939 (RegSize == 16 ? X86::ROL16rCL : X86::ROL32rCL);
1940 BuildMI(BB, Opc, 1, DestReg).addReg(Reg);
1942 } else if (RegSize != 8) {
1943 unsigned AReg, BReg;
1944 if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
1945 AReg = SelectExpr(ShlVal);
1946 BReg = SelectExpr(ShrVal);
1948 BReg = SelectExpr(ShrVal);
1949 AReg = SelectExpr(ShlVal);
1951 unsigned ShAmt = SelectExpr(ShlAmt);
1952 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShAmt);
1953 unsigned Opc = RegSize == 16 ? X86::SHLD16rrCL : X86::SHLD32rrCL;
1954 BuildMI(BB, Opc, 2, DestReg).addReg(AReg).addReg(BReg);
1959 if (ConstantSDNode *ShrCst = dyn_cast<ConstantSDNode>(ShrAmt))
1960 if (ConstantSDNode *ShlCst = dyn_cast<ConstantSDNode>(ShlAmt))
1961 if (ShrCst->getValue() < RegSize && ShlCst->getValue() < RegSize)
1962 if (ShrCst->getValue() == RegSize-ShlCst->getValue()) {
1963 // (A >> 5) | (A << 27) --> ROR A, 5
1964 // (A >> 5) | (B << 27) --> SHRD A, B, 5
1965 if (ShrVal == ShlVal) {
1966 unsigned Reg = SelectExpr(ShrVal);
1967 unsigned Opc = RegSize == 8 ? X86::ROR8ri :
1968 (RegSize == 16 ? X86::ROR16ri : X86::ROR32ri);
1969 BuildMI(BB, Opc, 2, DestReg).addReg(Reg).addImm(ShrCst->getValue());
1971 } else if (RegSize != 8) {
1972 unsigned AReg, BReg;
1973 if (getRegPressure(ShlVal) > getRegPressure(ShrVal)) {
1974 BReg = SelectExpr(ShlVal);
1975 AReg = SelectExpr(ShrVal);
1977 AReg = SelectExpr(ShrVal);
1978 BReg = SelectExpr(ShlVal);
1980 unsigned Opc = RegSize == 16 ? X86::SHRD16rri8 : X86::SHRD32rri8;
1981 BuildMI(BB, Opc, 3, DestReg).addReg(AReg).addReg(BReg)
1982 .addImm(ShrCst->getValue());
1990 unsigned ISel::SelectExpr(SDOperand N) {
1992 unsigned Tmp1, Tmp2, Tmp3;
1994 SDNode *Node = N.Val;
1997 if (Node->getOpcode() == ISD::CopyFromReg) {
1998 if (MRegisterInfo::isVirtualRegister(cast<RegSDNode>(Node)->getReg()) ||
1999 cast<RegSDNode>(Node)->getReg() == X86::ESP) {
2000 // Just use the specified register as our input.
2001 return cast<RegSDNode>(Node)->getReg();
2005 unsigned &Reg = ExprMap[N];
2006 if (Reg) return Reg;
2008 switch (N.getOpcode()) {
2010 Reg = Result = (N.getValueType() != MVT::Other) ?
2011 MakeReg(N.getValueType()) : 1;
2013 case X86ISD::TAILCALL:
2015 // If this is a call instruction, make sure to prepare ALL of the result
2016 // values as well as the chain.
2017 ExprMap[N.getValue(0)] = 1;
2018 if (Node->getNumValues() > 1) {
2019 Result = MakeReg(Node->getValueType(1));
2020 ExprMap[N.getValue(1)] = Result;
2021 for (unsigned i = 2, e = Node->getNumValues(); i != e; ++i)
2022 ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
2027 case ISD::ADD_PARTS:
2028 case ISD::SUB_PARTS:
2029 case ISD::SHL_PARTS:
2030 case ISD::SRL_PARTS:
2031 case ISD::SRA_PARTS:
2032 Result = MakeReg(Node->getValueType(0));
2033 ExprMap[N.getValue(0)] = Result;
2034 for (unsigned i = 1, e = N.Val->getNumValues(); i != e; ++i)
2035 ExprMap[N.getValue(i)] = MakeReg(Node->getValueType(i));
2039 switch (N.getOpcode()) {
2042 assert(0 && "Node not handled!\n");
2043 case ISD::CopyFromReg:
2044 Select(N.getOperand(0));
2046 Reg = Result = ExprMap[N.getValue(0)] =
2047 MakeReg(N.getValue(0).getValueType());
2049 switch (Node->getValueType(0)) {
2050 default: assert(0 && "Cannot CopyFromReg this!");
2053 BuildMI(BB, X86::MOV8rr, 1,
2054 Result).addReg(cast<RegSDNode>(Node)->getReg());
2057 BuildMI(BB, X86::MOV16rr, 1,
2058 Result).addReg(cast<RegSDNode>(Node)->getReg());
2061 BuildMI(BB, X86::MOV32rr, 1,
2062 Result).addReg(cast<RegSDNode>(Node)->getReg());
2066 case ISD::FrameIndex:
2067 Tmp1 = cast<FrameIndexSDNode>(N)->getIndex();
2068 addFrameReference(BuildMI(BB, X86::LEA32r, 4, Result), (int)Tmp1);
2070 case ISD::ConstantPool:
2071 Tmp1 = cast<ConstantPoolSDNode>(N)->getIndex();
2072 addConstantPoolReference(BuildMI(BB, X86::LEA32r, 4, Result), Tmp1);
2074 case ISD::ConstantFP:
2075 ContainsFPCode = true;
2076 Tmp1 = Result; // Intermediate Register
2077 if (cast<ConstantFPSDNode>(N)->getValue() < 0.0 ||
2078 cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
2079 Tmp1 = MakeReg(MVT::f64);
2081 if (cast<ConstantFPSDNode>(N)->isExactlyValue(+0.0) ||
2082 cast<ConstantFPSDNode>(N)->isExactlyValue(-0.0))
2083 BuildMI(BB, X86::FLD0, 0, Tmp1);
2084 else if (cast<ConstantFPSDNode>(N)->isExactlyValue(+1.0) ||
2085 cast<ConstantFPSDNode>(N)->isExactlyValue(-1.0))
2086 BuildMI(BB, X86::FLD1, 0, Tmp1);
2088 assert(0 && "Unexpected constant!");
2090 BuildMI(BB, X86::FCHS, 1, Result).addReg(Tmp1);
2093 switch (N.getValueType()) {
2094 default: assert(0 && "Cannot use constants of this type!");
2096 case MVT::i8: Opc = X86::MOV8ri; break;
2097 case MVT::i16: Opc = X86::MOV16ri; break;
2098 case MVT::i32: Opc = X86::MOV32ri; break;
2100 BuildMI(BB, Opc, 1,Result).addImm(cast<ConstantSDNode>(N)->getValue());
2103 if (Node->getValueType(0) == MVT::f64) {
2104 // FIXME: SHOULD TEACH STACKIFIER ABOUT UNDEF VALUES!
2105 BuildMI(BB, X86::FLD0, 0, Result);
2107 BuildMI(BB, X86::IMPLICIT_DEF, 0, Result);
2110 case ISD::GlobalAddress: {
2111 GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
2112 BuildMI(BB, X86::MOV32ri, 1, Result).addGlobalAddress(GV);
2115 case ISD::ExternalSymbol: {
2116 const char *Sym = cast<ExternalSymbolSDNode>(N)->getSymbol();
2117 BuildMI(BB, X86::MOV32ri, 1, Result).addExternalSymbol(Sym);
2120 case ISD::ZERO_EXTEND: {
2121 int DestIs16 = N.getValueType() == MVT::i16;
2122 int SrcIs16 = N.getOperand(0).getValueType() == MVT::i16;
2124 // FIXME: This hack is here for zero extension casts from bool to i8. This
2125 // would not be needed if bools were promoted by Legalize.
2126 if (N.getValueType() == MVT::i8) {
2127 Tmp1 = SelectExpr(N.getOperand(0));
2128 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(Tmp1);
2132 if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2133 static const unsigned Opc[3] = {
2134 X86::MOVZX32rm8, X86::MOVZX32rm16, X86::MOVZX16rm8
2138 EmitFoldedLoad(N.getOperand(0), AM);
2139 addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
2144 static const unsigned Opc[3] = {
2145 X86::MOVZX32rr8, X86::MOVZX32rr16, X86::MOVZX16rr8
2147 Tmp1 = SelectExpr(N.getOperand(0));
2148 BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
2151 case ISD::SIGN_EXTEND: {
2152 int DestIs16 = N.getValueType() == MVT::i16;
2153 int SrcIs16 = N.getOperand(0).getValueType() == MVT::i16;
2155 // FIXME: Legalize should promote bools to i8!
2156 assert(N.getOperand(0).getValueType() != MVT::i1 &&
2157 "Sign extend from bool not implemented!");
2159 if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2160 static const unsigned Opc[3] = {
2161 X86::MOVSX32rm8, X86::MOVSX32rm16, X86::MOVSX16rm8
2165 EmitFoldedLoad(N.getOperand(0), AM);
2166 addFullAddress(BuildMI(BB, Opc[SrcIs16+DestIs16*2], 4, Result), AM);
2170 static const unsigned Opc[3] = {
2171 X86::MOVSX32rr8, X86::MOVSX32rr16, X86::MOVSX16rr8
2173 Tmp1 = SelectExpr(N.getOperand(0));
2174 BuildMI(BB, Opc[SrcIs16+DestIs16*2], 1, Result).addReg(Tmp1);
2178 // Fold TRUNCATE (LOAD P) into a smaller load from P.
2179 // FIXME: This should be performed by the DAGCombiner.
2180 if (isFoldableLoad(N.getOperand(0), SDOperand())) {
2181 switch (N.getValueType()) {
2182 default: assert(0 && "Unknown truncate!");
2184 case MVT::i8: Opc = X86::MOV8rm; break;
2185 case MVT::i16: Opc = X86::MOV16rm; break;
2188 EmitFoldedLoad(N.getOperand(0), AM);
2189 addFullAddress(BuildMI(BB, Opc, 4, Result), AM);
2193 // Handle cast of LARGER int to SMALLER int using a move to EAX followed by
2194 // a move out of AX or AL.
2195 switch (N.getOperand(0).getValueType()) {
2196 default: assert(0 && "Unknown truncate!");
2197 case MVT::i8: Tmp2 = X86::AL; Opc = X86::MOV8rr; break;
2198 case MVT::i16: Tmp2 = X86::AX; Opc = X86::MOV16rr; break;
2199 case MVT::i32: Tmp2 = X86::EAX; Opc = X86::MOV32rr; break;
2201 Tmp1 = SelectExpr(N.getOperand(0));
2202 BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
2204 switch (N.getValueType()) {
2205 default: assert(0 && "Unknown truncate!");
2207 case MVT::i8: Tmp2 = X86::AL; Opc = X86::MOV8rr; break;
2208 case MVT::i16: Tmp2 = X86::AX; Opc = X86::MOV16rr; break;
2210 BuildMI(BB, Opc, 1, Result).addReg(Tmp2);
2213 case ISD::SINT_TO_FP:
2214 case ISD::UINT_TO_FP: {
2215 // FIXME: Most of this grunt work should be done by legalize!
2216 ContainsFPCode = true;
2218 // Promote the integer to a type supported by FLD. We do this because there
2219 // are no unsigned FLD instructions, so we must promote an unsigned value to
2220 // a larger signed value, then use FLD on the larger value.
2222 MVT::ValueType PromoteType = MVT::Other;
2223 MVT::ValueType SrcTy = N.getOperand(0).getValueType();
2224 unsigned PromoteOpcode = 0;
2225 unsigned RealDestReg = Result;
2229 // We don't have the facilities for directly loading byte sized data from
2230 // memory (even signed). Promote it to 16 bits.
2231 PromoteType = MVT::i16;
2232 PromoteOpcode = Node->getOpcode() == ISD::SINT_TO_FP ?
2233 X86::MOVSX16rr8 : X86::MOVZX16rr8;
2236 if (Node->getOpcode() == ISD::UINT_TO_FP) {
2237 PromoteType = MVT::i32;
2238 PromoteOpcode = X86::MOVZX32rr16;
2242 // Don't fild into the real destination.
2243 if (Node->getOpcode() == ISD::UINT_TO_FP)
2244 Result = MakeReg(Node->getValueType(0));
2248 Tmp1 = SelectExpr(N.getOperand(0)); // Get the operand register
2250 if (PromoteType != MVT::Other) {
2251 Tmp2 = MakeReg(PromoteType);
2252 BuildMI(BB, PromoteOpcode, 1, Tmp2).addReg(Tmp1);
2253 SrcTy = PromoteType;
2257 // Spill the integer to memory and reload it from there.
2258 unsigned Size = MVT::getSizeInBits(SrcTy)/8;
2259 MachineFunction *F = BB->getParent();
2260 int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
2264 addFrameReference(BuildMI(BB, X86::MOV32mr, 5),
2265 FrameIdx).addReg(Tmp1);
2266 addFrameReference(BuildMI(BB, X86::FILD32m, 5, Result), FrameIdx);
2269 addFrameReference(BuildMI(BB, X86::MOV16mr, 5),
2270 FrameIdx).addReg(Tmp1);
2271 addFrameReference(BuildMI(BB, X86::FILD16m, 5, Result), FrameIdx);
2273 default: break; // No promotion required.
2276 if (Node->getOpcode() == ISD::UINT_TO_FP && Result != RealDestReg) {
2277 // If this is a cast from uint -> double, we need to be careful when if
2278 // the "sign" bit is set. If so, we don't want to make a negative number,
2279 // we want to make a positive number. Emit code to add an offset if the
2282 // Compute whether the sign bit is set by shifting the reg right 31 bits.
2283 unsigned IsNeg = MakeReg(MVT::i32);
2284 BuildMI(BB, X86::SHR32ri, 2, IsNeg).addReg(Tmp1).addImm(31);
2286 // Create a CP value that has the offset in one word and 0 in the other.
2287 static ConstantInt *TheOffset = ConstantUInt::get(Type::ULongTy,
2288 0x4f80000000000000ULL);
2289 unsigned CPI = F->getConstantPool()->getConstantPoolIndex(TheOffset);
2290 BuildMI(BB, X86::FADD32m, 5, RealDestReg).addReg(Result)
2291 .addConstantPoolIndex(CPI).addZImm(4).addReg(IsNeg).addSImm(0);
2295 case ISD::FP_TO_SINT:
2296 case ISD::FP_TO_UINT: {
2297 // FIXME: Most of this grunt work should be done by legalize!
2298 Tmp1 = SelectExpr(N.getOperand(0)); // Get the operand register
2300 // Change the floating point control register to use "round towards zero"
2301 // mode when truncating to an integer value.
2303 MachineFunction *F = BB->getParent();
2304 int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2);
2305 addFrameReference(BuildMI(BB, X86::FNSTCW16m, 4), CWFrameIdx);
2307 // Load the old value of the high byte of the control word...
2308 unsigned HighPartOfCW = MakeReg(MVT::i8);
2309 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, HighPartOfCW),
2312 // Set the high part to be round to zero...
2313 addFrameReference(BuildMI(BB, X86::MOV8mi, 5),
2314 CWFrameIdx, 1).addImm(12);
2316 // Reload the modified control word now...
2317 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
2319 // Restore the memory image of control word to original value
2320 addFrameReference(BuildMI(BB, X86::MOV8mr, 5),
2321 CWFrameIdx, 1).addReg(HighPartOfCW);
2323 // We don't have the facilities for directly storing byte sized data to
2324 // memory. Promote it to 16 bits. We also must promote unsigned values to
2325 // larger classes because we only have signed FP stores.
2326 MVT::ValueType StoreClass = Node->getValueType(0);
2327 if (StoreClass == MVT::i8 || Node->getOpcode() == ISD::FP_TO_UINT)
2328 switch (StoreClass) {
2330 case MVT::i8: StoreClass = MVT::i16; break;
2331 case MVT::i16: StoreClass = MVT::i32; break;
2332 case MVT::i32: StoreClass = MVT::i64; break;
2333 default: assert(0 && "Unknown store class!");
2336 // Spill the integer to memory and reload it from there.
2337 unsigned Size = MVT::getSizeInBits(StoreClass)/8;
2338 int FrameIdx = F->getFrameInfo()->CreateStackObject(Size, Size);
2340 switch (StoreClass) {
2341 default: assert(0 && "Unknown store class!");
2343 addFrameReference(BuildMI(BB, X86::FIST16m, 5), FrameIdx).addReg(Tmp1);
2346 addFrameReference(BuildMI(BB, X86::FIST32m, 5), FrameIdx).addReg(Tmp1);
2349 addFrameReference(BuildMI(BB, X86::FISTP64m, 5), FrameIdx).addReg(Tmp1);
2352 switch (Node->getValueType(0)) {
2354 assert(0 && "Unknown integer type!");
2356 addFrameReference(BuildMI(BB, X86::MOV32rm, 4, Result), FrameIdx);
2359 addFrameReference(BuildMI(BB, X86::MOV16rm, 4, Result), FrameIdx);
2363 addFrameReference(BuildMI(BB, X86::MOV8rm, 4, Result), FrameIdx);
2367 // Reload the original control word now.
2368 addFrameReference(BuildMI(BB, X86::FLDCW16m, 4), CWFrameIdx);
2372 Op0 = N.getOperand(0);
2373 Op1 = N.getOperand(1);
2375 if (isFoldableLoad(Op0, Op1, true)) {
2376 std::swap(Op0, Op1);
2380 if (isFoldableLoad(Op1, Op0, true)) {
2382 switch (N.getValueType()) {
2383 default: assert(0 && "Cannot add this type!");
2385 case MVT::i8: Opc = X86::ADD8rm; break;
2386 case MVT::i16: Opc = X86::ADD16rm; break;
2387 case MVT::i32: Opc = X86::ADD32rm; break;
2389 // For F64, handle promoted load operations (from F32) as well!
2390 Opc = Op1.getOpcode() == ISD::LOAD ? X86::FADD64m : X86::FADD32m;
2394 EmitFoldedLoad(Op1, AM);
2395 Tmp1 = SelectExpr(Op0);
2396 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2400 // See if we can codegen this as an LEA to fold operations together.
2401 if (N.getValueType() == MVT::i32) {
2403 X86ISelAddressMode AM;
2404 MatchAddress(N, AM);
2405 ExprMap[N] = Result;
2407 // If this is not just an add, emit the LEA. For a simple add (like
2408 // reg+reg or reg+imm), we just emit an add. It might be a good idea to
2409 // leave this as LEA, then peephole it to 'ADD' after two address elim
2411 if (AM.Scale != 1 || AM.BaseType == X86ISelAddressMode::FrameIndexBase||
2412 AM.GV || (AM.Base.Reg.Val && AM.IndexReg.Val && AM.Disp)) {
2413 X86AddressMode XAM = SelectAddrExprs(AM);
2414 addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), XAM);
2419 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
2421 if (CN->getValue() == 1) { // add X, 1 -> inc X
2422 switch (N.getValueType()) {
2423 default: assert(0 && "Cannot integer add this type!");
2424 case MVT::i8: Opc = X86::INC8r; break;
2425 case MVT::i16: Opc = X86::INC16r; break;
2426 case MVT::i32: Opc = X86::INC32r; break;
2428 } else if (CN->isAllOnesValue()) { // add X, -1 -> dec X
2429 switch (N.getValueType()) {
2430 default: assert(0 && "Cannot integer add this type!");
2431 case MVT::i8: Opc = X86::DEC8r; break;
2432 case MVT::i16: Opc = X86::DEC16r; break;
2433 case MVT::i32: Opc = X86::DEC32r; break;
2438 Tmp1 = SelectExpr(Op0);
2439 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2443 switch (N.getValueType()) {
2444 default: assert(0 && "Cannot add this type!");
2445 case MVT::i8: Opc = X86::ADD8ri; break;
2446 case MVT::i16: Opc = X86::ADD16ri; break;
2447 case MVT::i32: Opc = X86::ADD32ri; break;
2450 Tmp1 = SelectExpr(Op0);
2451 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2456 switch (N.getValueType()) {
2457 default: assert(0 && "Cannot add this type!");
2458 case MVT::i8: Opc = X86::ADD8rr; break;
2459 case MVT::i16: Opc = X86::ADD16rr; break;
2460 case MVT::i32: Opc = X86::ADD32rr; break;
2461 case MVT::f64: Opc = X86::FpADD; break;
2464 if (getRegPressure(Op0) > getRegPressure(Op1)) {
2465 Tmp1 = SelectExpr(Op0);
2466 Tmp2 = SelectExpr(Op1);
2468 Tmp2 = SelectExpr(Op1);
2469 Tmp1 = SelectExpr(Op0);
2472 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2480 assert(N.getValueType()==MVT::f64 && "Illegal type for this operation");
2481 Tmp1 = SelectExpr(Node->getOperand(0));
2482 switch (N.getOpcode()) {
2483 default: assert(0 && "Unreachable!");
2484 case ISD::FABS: BuildMI(BB, X86::FABS, 1, Result).addReg(Tmp1); break;
2485 case ISD::FNEG: BuildMI(BB, X86::FCHS, 1, Result).addReg(Tmp1); break;
2486 case ISD::FSQRT: BuildMI(BB, X86::FSQRT, 1, Result).addReg(Tmp1); break;
2487 case ISD::FSIN: BuildMI(BB, X86::FSIN, 1, Result).addReg(Tmp1); break;
2488 case ISD::FCOS: BuildMI(BB, X86::FCOS, 1, Result).addReg(Tmp1); break;
2493 switch (N.getValueType()) {
2494 default: assert(0 && "Unsupported VT!");
2495 case MVT::i8: Tmp2 = X86::MUL8r; break;
2496 case MVT::i16: Tmp2 = X86::MUL16r; break;
2497 case MVT::i32: Tmp2 = X86::MUL32r; break;
2501 unsigned MovOpc, LowReg, HiReg;
2502 switch (N.getValueType()) {
2503 default: assert(0 && "Unsupported VT!");
2505 MovOpc = X86::MOV8rr;
2511 MovOpc = X86::MOV16rr;
2517 MovOpc = X86::MOV32rr;
2523 if (Node->getOpcode() != ISD::MULHS)
2524 Opc = Tmp2; // Get the MULHU opcode.
2526 Op0 = Node->getOperand(0);
2527 Op1 = Node->getOperand(1);
2528 if (getRegPressure(Op0) > getRegPressure(Op1)) {
2529 Tmp1 = SelectExpr(Op0);
2530 Tmp2 = SelectExpr(Op1);
2532 Tmp2 = SelectExpr(Op1);
2533 Tmp1 = SelectExpr(Op0);
2536 // FIXME: Implement folding of loads into the memory operands here!
2537 BuildMI(BB, MovOpc, 1, LowReg).addReg(Tmp1);
2538 BuildMI(BB, Opc, 1).addReg(Tmp2);
2539 BuildMI(BB, MovOpc, 1, Result).addReg(HiReg);
2548 static const unsigned SUBTab[] = {
2549 X86::SUB8ri, X86::SUB16ri, X86::SUB32ri, 0, 0,
2550 X86::SUB8rm, X86::SUB16rm, X86::SUB32rm, X86::FSUB32m, X86::FSUB64m,
2551 X86::SUB8rr, X86::SUB16rr, X86::SUB32rr, X86::FpSUB , X86::FpSUB,
2553 static const unsigned MULTab[] = {
2554 0, X86::IMUL16rri, X86::IMUL32rri, 0, 0,
2555 0, X86::IMUL16rm , X86::IMUL32rm, X86::FMUL32m, X86::FMUL64m,
2556 0, X86::IMUL16rr , X86::IMUL32rr, X86::FpMUL , X86::FpMUL,
2558 static const unsigned ANDTab[] = {
2559 X86::AND8ri, X86::AND16ri, X86::AND32ri, 0, 0,
2560 X86::AND8rm, X86::AND16rm, X86::AND32rm, 0, 0,
2561 X86::AND8rr, X86::AND16rr, X86::AND32rr, 0, 0,
2563 static const unsigned ORTab[] = {
2564 X86::OR8ri, X86::OR16ri, X86::OR32ri, 0, 0,
2565 X86::OR8rm, X86::OR16rm, X86::OR32rm, 0, 0,
2566 X86::OR8rr, X86::OR16rr, X86::OR32rr, 0, 0,
2568 static const unsigned XORTab[] = {
2569 X86::XOR8ri, X86::XOR16ri, X86::XOR32ri, 0, 0,
2570 X86::XOR8rm, X86::XOR16rm, X86::XOR32rm, 0, 0,
2571 X86::XOR8rr, X86::XOR16rr, X86::XOR32rr, 0, 0,
2574 Op0 = Node->getOperand(0);
2575 Op1 = Node->getOperand(1);
2577 if (Node->getOpcode() == ISD::OR && Op0.hasOneUse() && Op1.hasOneUse())
2578 if (EmitOrOpOp(Op0, Op1, Result)) // Match SHLD, SHRD, and rotates.
2581 if (Node->getOpcode() == ISD::SUB)
2582 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(0)))
2583 if (CN->isNullValue()) { // 0 - N -> neg N
2584 switch (N.getValueType()) {
2585 default: assert(0 && "Cannot sub this type!");
2587 case MVT::i8: Opc = X86::NEG8r; break;
2588 case MVT::i16: Opc = X86::NEG16r; break;
2589 case MVT::i32: Opc = X86::NEG32r; break;
2591 Tmp1 = SelectExpr(N.getOperand(1));
2592 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2596 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
2597 if (CN->isAllOnesValue() && Node->getOpcode() == ISD::XOR) {
2599 switch (N.getValueType()) {
2600 default: assert(0 && "Cannot add this type!");
2601 case MVT::i1: break; // Not supported, don't invert upper bits!
2602 case MVT::i8: Opc = X86::NOT8r; break;
2603 case MVT::i16: Opc = X86::NOT16r; break;
2604 case MVT::i32: Opc = X86::NOT32r; break;
2607 Tmp1 = SelectExpr(Op0);
2608 BuildMI(BB, Opc, 1, Result).addReg(Tmp1);
2613 // Fold common multiplies into LEA instructions.
2614 if (Node->getOpcode() == ISD::MUL && N.getValueType() == MVT::i32) {
2615 switch ((int)CN->getValue()) {
2620 // Remove N from exprmap so SelectAddress doesn't get confused.
2623 SelectAddress(N, AM);
2624 // Restore it to the map.
2625 ExprMap[N] = Result;
2626 addFullAddress(BuildMI(BB, X86::LEA32r, 4, Result), AM);
2631 switch (N.getValueType()) {
2632 default: assert(0 && "Cannot xor this type!");
2634 case MVT::i8: Opc = 0; break;
2635 case MVT::i16: Opc = 1; break;
2636 case MVT::i32: Opc = 2; break;
2638 switch (Node->getOpcode()) {
2639 default: assert(0 && "Unreachable!");
2640 case ISD::SUB: Opc = SUBTab[Opc]; break;
2641 case ISD::MUL: Opc = MULTab[Opc]; break;
2642 case ISD::AND: Opc = ANDTab[Opc]; break;
2643 case ISD::OR: Opc = ORTab[Opc]; break;
2644 case ISD::XOR: Opc = XORTab[Opc]; break;
2646 if (Opc) { // Can't fold MUL:i8 R, imm
2647 Tmp1 = SelectExpr(Op0);
2648 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
2653 if (isFoldableLoad(Op0, Op1, true))
2654 if (Node->getOpcode() != ISD::SUB) {
2655 std::swap(Op0, Op1);
2658 // For FP, emit 'reverse' subract, with a memory operand.
2659 if (N.getValueType() == MVT::f64) {
2660 if (Op0.getOpcode() == ISD::EXTLOAD)
2661 Opc = X86::FSUBR32m;
2663 Opc = X86::FSUBR64m;
2666 EmitFoldedLoad(Op0, AM);
2667 Tmp1 = SelectExpr(Op1);
2668 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2673 if (isFoldableLoad(Op1, Op0, true)) {
2675 switch (N.getValueType()) {
2676 default: assert(0 && "Cannot operate on this type!");
2678 case MVT::i8: Opc = 5; break;
2679 case MVT::i16: Opc = 6; break;
2680 case MVT::i32: Opc = 7; break;
2681 // For F64, handle promoted load operations (from F32) as well!
2682 case MVT::f64: Opc = Op1.getOpcode() == ISD::LOAD ? 9 : 8; break;
2684 switch (Node->getOpcode()) {
2685 default: assert(0 && "Unreachable!");
2686 case ISD::SUB: Opc = SUBTab[Opc]; break;
2687 case ISD::MUL: Opc = MULTab[Opc]; break;
2688 case ISD::AND: Opc = ANDTab[Opc]; break;
2689 case ISD::OR: Opc = ORTab[Opc]; break;
2690 case ISD::XOR: Opc = XORTab[Opc]; break;
2694 EmitFoldedLoad(Op1, AM);
2695 Tmp1 = SelectExpr(Op0);
2697 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2699 assert(Node->getOpcode() == ISD::MUL &&
2700 N.getValueType() == MVT::i8 && "Unexpected situation!");
2701 // Must use the MUL instruction, which forces use of AL.
2702 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
2703 addFullAddress(BuildMI(BB, X86::MUL8m, 1), AM);
2704 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2709 if (getRegPressure(Op0) > getRegPressure(Op1)) {
2710 Tmp1 = SelectExpr(Op0);
2711 Tmp2 = SelectExpr(Op1);
2713 Tmp2 = SelectExpr(Op1);
2714 Tmp1 = SelectExpr(Op0);
2717 switch (N.getValueType()) {
2718 default: assert(0 && "Cannot add this type!");
2720 case MVT::i8: Opc = 10; break;
2721 case MVT::i16: Opc = 11; break;
2722 case MVT::i32: Opc = 12; break;
2723 case MVT::f32: Opc = 13; break;
2724 case MVT::f64: Opc = 14; break;
2726 switch (Node->getOpcode()) {
2727 default: assert(0 && "Unreachable!");
2728 case ISD::SUB: Opc = SUBTab[Opc]; break;
2729 case ISD::MUL: Opc = MULTab[Opc]; break;
2730 case ISD::AND: Opc = ANDTab[Opc]; break;
2731 case ISD::OR: Opc = ORTab[Opc]; break;
2732 case ISD::XOR: Opc = XORTab[Opc]; break;
2735 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
2737 assert(Node->getOpcode() == ISD::MUL &&
2738 N.getValueType() == MVT::i8 && "Unexpected situation!");
2739 // Must use the MUL instruction, which forces use of AL.
2740 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
2741 BuildMI(BB, X86::MUL8r, 1).addReg(Tmp2);
2742 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
2746 case ISD::ADD_PARTS:
2747 case ISD::SUB_PARTS: {
2748 assert(N.getNumOperands() == 4 && N.getValueType() == MVT::i32 &&
2749 "Not an i64 add/sub!");
2750 // Emit all of the operands.
2751 std::vector<unsigned> InVals;
2752 for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)
2753 InVals.push_back(SelectExpr(N.getOperand(i)));
2754 if (N.getOpcode() == ISD::ADD_PARTS) {
2755 BuildMI(BB, X86::ADD32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
2756 BuildMI(BB, X86::ADC32rr,2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
2758 BuildMI(BB, X86::SUB32rr, 2, Result).addReg(InVals[0]).addReg(InVals[2]);
2759 BuildMI(BB, X86::SBB32rr, 2,Result+1).addReg(InVals[1]).addReg(InVals[3]);
2761 return Result+N.ResNo;
2764 case ISD::SHL_PARTS:
2765 case ISD::SRA_PARTS:
2766 case ISD::SRL_PARTS: {
2767 assert(N.getNumOperands() == 3 && N.getValueType() == MVT::i32 &&
2768 "Not an i64 shift!");
2769 unsigned ShiftOpLo = SelectExpr(N.getOperand(0));
2770 unsigned ShiftOpHi = SelectExpr(N.getOperand(1));
2771 unsigned TmpReg = MakeReg(MVT::i32);
2772 if (N.getOpcode() == ISD::SRA_PARTS) {
2773 // If this is a SHR of a Long, then we need to do funny sign extension
2774 // stuff. TmpReg gets the value to use as the high-part if we are
2775 // shifting more than 32 bits.
2776 BuildMI(BB, X86::SAR32ri, 2, TmpReg).addReg(ShiftOpHi).addImm(31);
2778 // Other shifts use a fixed zero value if the shift is more than 32 bits.
2779 BuildMI(BB, X86::MOV32ri, 1, TmpReg).addImm(0);
2782 // Initialize CL with the shift amount.
2783 unsigned ShiftAmountReg = SelectExpr(N.getOperand(2));
2784 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(ShiftAmountReg);
2786 unsigned TmpReg2 = MakeReg(MVT::i32);
2787 unsigned TmpReg3 = MakeReg(MVT::i32);
2788 if (N.getOpcode() == ISD::SHL_PARTS) {
2789 // TmpReg2 = shld inHi, inLo
2790 BuildMI(BB, X86::SHLD32rrCL, 2,TmpReg2).addReg(ShiftOpHi)
2792 // TmpReg3 = shl inLo, CL
2793 BuildMI(BB, X86::SHL32rCL, 1, TmpReg3).addReg(ShiftOpLo);
2795 // Set the flags to indicate whether the shift was by more than 32 bits.
2796 BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2798 // DestHi = (>32) ? TmpReg3 : TmpReg2;
2799 BuildMI(BB, X86::CMOVNE32rr, 2,
2800 Result+1).addReg(TmpReg2).addReg(TmpReg3);
2801 // DestLo = (>32) ? TmpReg : TmpReg3;
2802 BuildMI(BB, X86::CMOVNE32rr, 2,
2803 Result).addReg(TmpReg3).addReg(TmpReg);
2805 // TmpReg2 = shrd inLo, inHi
2806 BuildMI(BB, X86::SHRD32rrCL,2,TmpReg2).addReg(ShiftOpLo)
2808 // TmpReg3 = s[ah]r inHi, CL
2809 BuildMI(BB, N.getOpcode() == ISD::SRA_PARTS ? X86::SAR32rCL
2810 : X86::SHR32rCL, 1, TmpReg3)
2813 // Set the flags to indicate whether the shift was by more than 32 bits.
2814 BuildMI(BB, X86::TEST8ri, 2).addReg(X86::CL).addImm(32);
2816 // DestLo = (>32) ? TmpReg3 : TmpReg2;
2817 BuildMI(BB, X86::CMOVNE32rr, 2,
2818 Result).addReg(TmpReg2).addReg(TmpReg3);
2820 // DestHi = (>32) ? TmpReg : TmpReg3;
2821 BuildMI(BB, X86::CMOVNE32rr, 2,
2822 Result+1).addReg(TmpReg3).addReg(TmpReg);
2824 return Result+N.ResNo;
2828 if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
2829 Tmp2 = SelectExpr(N.getOperand(1));
2830 Tmp3 = SelectExpr(N.getOperand(2));
2832 Tmp3 = SelectExpr(N.getOperand(2));
2833 Tmp2 = SelectExpr(N.getOperand(1));
2835 EmitSelectCC(N.getOperand(0), N.getValueType(), Tmp2, Tmp3, Result);
2842 assert((N.getOpcode() != ISD::SREM || MVT::isInteger(N.getValueType())) &&
2843 "We don't support this operator!");
2845 if (N.getOpcode() == ISD::SDIV) {
2846 // We can fold loads into FpDIVs, but not really into any others.
2847 if (N.getValueType() == MVT::f64) {
2848 // Check for reversed and unreversed DIV.
2849 if (isFoldableLoad(N.getOperand(0), N.getOperand(1), true)) {
2850 if (N.getOperand(0).getOpcode() == ISD::EXTLOAD)
2851 Opc = X86::FDIVR32m;
2853 Opc = X86::FDIVR64m;
2855 EmitFoldedLoad(N.getOperand(0), AM);
2856 Tmp1 = SelectExpr(N.getOperand(1));
2857 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2859 } else if (isFoldableLoad(N.getOperand(1), N.getOperand(0), true) &&
2860 N.getOperand(1).getOpcode() == ISD::LOAD) {
2861 if (N.getOperand(1).getOpcode() == ISD::EXTLOAD)
2866 EmitFoldedLoad(N.getOperand(1), AM);
2867 Tmp1 = SelectExpr(N.getOperand(0));
2868 addFullAddress(BuildMI(BB, Opc, 5, Result).addReg(Tmp1), AM);
2873 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2874 // FIXME: These special cases should be handled by the lowering impl!
2875 unsigned RHS = CN->getValue();
2881 if (RHS && (RHS & (RHS-1)) == 0) { // Signed division by power of 2?
2882 unsigned Log = log2(RHS);
2883 unsigned SAROpc, SHROpc, ADDOpc, NEGOpc;
2884 switch (N.getValueType()) {
2885 default: assert("Unknown type to signed divide!");
2887 SAROpc = X86::SAR8ri;
2888 SHROpc = X86::SHR8ri;
2889 ADDOpc = X86::ADD8rr;
2890 NEGOpc = X86::NEG8r;
2893 SAROpc = X86::SAR16ri;
2894 SHROpc = X86::SHR16ri;
2895 ADDOpc = X86::ADD16rr;
2896 NEGOpc = X86::NEG16r;
2899 SAROpc = X86::SAR32ri;
2900 SHROpc = X86::SHR32ri;
2901 ADDOpc = X86::ADD32rr;
2902 NEGOpc = X86::NEG32r;
2905 unsigned RegSize = MVT::getSizeInBits(N.getValueType());
2906 Tmp1 = SelectExpr(N.getOperand(0));
2909 TmpReg = MakeReg(N.getValueType());
2910 BuildMI(BB, SAROpc, 2, TmpReg).addReg(Tmp1).addImm(Log-1);
2914 unsigned TmpReg2 = MakeReg(N.getValueType());
2915 BuildMI(BB, SHROpc, 2, TmpReg2).addReg(TmpReg).addImm(RegSize-Log);
2916 unsigned TmpReg3 = MakeReg(N.getValueType());
2917 BuildMI(BB, ADDOpc, 2, TmpReg3).addReg(Tmp1).addReg(TmpReg2);
2919 unsigned TmpReg4 = isNeg ? MakeReg(N.getValueType()) : Result;
2920 BuildMI(BB, SAROpc, 2, TmpReg4).addReg(TmpReg3).addImm(Log);
2922 BuildMI(BB, NEGOpc, 1, Result).addReg(TmpReg4);
2928 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
2929 Tmp1 = SelectExpr(N.getOperand(0));
2930 Tmp2 = SelectExpr(N.getOperand(1));
2932 Tmp2 = SelectExpr(N.getOperand(1));
2933 Tmp1 = SelectExpr(N.getOperand(0));
2936 bool isSigned = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::SREM;
2937 bool isDiv = N.getOpcode() == ISD::SDIV || N.getOpcode() == ISD::UDIV;
2938 unsigned LoReg, HiReg, DivOpcode, MovOpcode, ClrOpcode, SExtOpcode;
2939 switch (N.getValueType()) {
2940 default: assert(0 && "Cannot sdiv this type!");
2942 DivOpcode = isSigned ? X86::IDIV8r : X86::DIV8r;
2945 MovOpcode = X86::MOV8rr;
2946 ClrOpcode = X86::MOV8ri;
2947 SExtOpcode = X86::CBW;
2950 DivOpcode = isSigned ? X86::IDIV16r : X86::DIV16r;
2953 MovOpcode = X86::MOV16rr;
2954 ClrOpcode = X86::MOV16ri;
2955 SExtOpcode = X86::CWD;
2958 DivOpcode = isSigned ? X86::IDIV32r : X86::DIV32r;
2961 MovOpcode = X86::MOV32rr;
2962 ClrOpcode = X86::MOV32ri;
2963 SExtOpcode = X86::CDQ;
2966 BuildMI(BB, X86::FpDIV, 2, Result).addReg(Tmp1).addReg(Tmp2);
2970 // Set up the low part.
2971 BuildMI(BB, MovOpcode, 1, LoReg).addReg(Tmp1);
2974 // Sign extend the low part into the high part.
2975 BuildMI(BB, SExtOpcode, 0);
2977 // Zero out the high part, effectively zero extending the input.
2978 BuildMI(BB, ClrOpcode, 1, HiReg).addImm(0);
2981 // Emit the DIV/IDIV instruction.
2982 BuildMI(BB, DivOpcode, 1).addReg(Tmp2);
2984 // Get the result of the divide or rem.
2985 BuildMI(BB, MovOpcode, 1, Result).addReg(isDiv ? LoReg : HiReg);
2990 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
2991 if (CN->getValue() == 1) { // X = SHL Y, 1 -> X = ADD Y, Y
2992 switch (N.getValueType()) {
2993 default: assert(0 && "Cannot shift this type!");
2994 case MVT::i8: Opc = X86::ADD8rr; break;
2995 case MVT::i16: Opc = X86::ADD16rr; break;
2996 case MVT::i32: Opc = X86::ADD32rr; break;
2998 Tmp1 = SelectExpr(N.getOperand(0));
2999 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp1);
3003 switch (N.getValueType()) {
3004 default: assert(0 && "Cannot shift this type!");
3005 case MVT::i8: Opc = X86::SHL8ri; break;
3006 case MVT::i16: Opc = X86::SHL16ri; break;
3007 case MVT::i32: Opc = X86::SHL32ri; break;
3009 Tmp1 = SelectExpr(N.getOperand(0));
3010 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3014 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3015 Tmp1 = SelectExpr(N.getOperand(0));
3016 Tmp2 = SelectExpr(N.getOperand(1));
3018 Tmp2 = SelectExpr(N.getOperand(1));
3019 Tmp1 = SelectExpr(N.getOperand(0));
3022 switch (N.getValueType()) {
3023 default: assert(0 && "Cannot shift this type!");
3024 case MVT::i8 : Opc = X86::SHL8rCL; break;
3025 case MVT::i16: Opc = X86::SHL16rCL; break;
3026 case MVT::i32: Opc = X86::SHL32rCL; break;
3028 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3029 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3032 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3033 switch (N.getValueType()) {
3034 default: assert(0 && "Cannot shift this type!");
3035 case MVT::i8: Opc = X86::SHR8ri; break;
3036 case MVT::i16: Opc = X86::SHR16ri; break;
3037 case MVT::i32: Opc = X86::SHR32ri; break;
3039 Tmp1 = SelectExpr(N.getOperand(0));
3040 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3044 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3045 Tmp1 = SelectExpr(N.getOperand(0));
3046 Tmp2 = SelectExpr(N.getOperand(1));
3048 Tmp2 = SelectExpr(N.getOperand(1));
3049 Tmp1 = SelectExpr(N.getOperand(0));
3052 switch (N.getValueType()) {
3053 default: assert(0 && "Cannot shift this type!");
3054 case MVT::i8 : Opc = X86::SHR8rCL; break;
3055 case MVT::i16: Opc = X86::SHR16rCL; break;
3056 case MVT::i32: Opc = X86::SHR32rCL; break;
3058 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3059 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3062 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3063 switch (N.getValueType()) {
3064 default: assert(0 && "Cannot shift this type!");
3065 case MVT::i8: Opc = X86::SAR8ri; break;
3066 case MVT::i16: Opc = X86::SAR16ri; break;
3067 case MVT::i32: Opc = X86::SAR32ri; break;
3069 Tmp1 = SelectExpr(N.getOperand(0));
3070 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addImm(CN->getValue());
3074 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3075 Tmp1 = SelectExpr(N.getOperand(0));
3076 Tmp2 = SelectExpr(N.getOperand(1));
3078 Tmp2 = SelectExpr(N.getOperand(1));
3079 Tmp1 = SelectExpr(N.getOperand(0));
3082 switch (N.getValueType()) {
3083 default: assert(0 && "Cannot shift this type!");
3084 case MVT::i8 : Opc = X86::SAR8rCL; break;
3085 case MVT::i16: Opc = X86::SAR16rCL; break;
3086 case MVT::i32: Opc = X86::SAR32rCL; break;
3088 BuildMI(BB, X86::MOV8rr, 1, X86::CL).addReg(Tmp2);
3089 BuildMI(BB, Opc, 2, Result).addReg(Tmp1).addReg(Tmp2);
3093 EmitCMP(N.getOperand(0), N.getOperand(1), Node->hasOneUse());
3094 EmitSetCC(BB, Result, cast<SetCCSDNode>(N)->getCondition(),
3095 MVT::isFloatingPoint(N.getOperand(1).getValueType()));
3098 // Make sure we generate both values.
3099 if (Result != 1) { // Generate the token
3100 if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3101 assert(0 && "Load already emitted!?");
3103 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3105 switch (Node->getValueType(0)) {
3106 default: assert(0 && "Cannot load this type!");
3108 case MVT::i8: Opc = X86::MOV8rm; break;
3109 case MVT::i16: Opc = X86::MOV16rm; break;
3110 case MVT::i32: Opc = X86::MOV32rm; break;
3111 case MVT::f64: Opc = X86::FLD64m; ContainsFPCode = true; break;
3114 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1))){
3115 Select(N.getOperand(0));
3116 addConstantPoolReference(BuildMI(BB, Opc, 4, Result), CP->getIndex());
3120 SDOperand Chain = N.getOperand(0);
3121 SDOperand Address = N.getOperand(1);
3122 if (getRegPressure(Chain) > getRegPressure(Address)) {
3124 SelectAddress(Address, AM);
3126 SelectAddress(Address, AM);
3130 addFullAddress(BuildMI(BB, Opc, 4, Result), AM);
3133 case X86ISD::FILD64m:
3134 // Make sure we generate both values.
3135 assert(Result != 1 && N.getValueType() == MVT::f64);
3136 if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3137 assert(0 && "Load already emitted!?");
3142 SDOperand Chain = N.getOperand(0);
3143 SDOperand Address = N.getOperand(1);
3144 if (getRegPressure(Chain) > getRegPressure(Address)) {
3146 SelectAddress(Address, AM);
3148 SelectAddress(Address, AM);
3152 addFullAddress(BuildMI(BB, X86::FILD64m, 4, Result), AM);
3156 case ISD::EXTLOAD: // Arbitrarily codegen extloads as MOVZX*
3157 case ISD::ZEXTLOAD: {
3158 // Make sure we generate both values.
3160 ExprMap[N.getValue(1)] = 1; // Generate the token
3162 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3164 if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(N.getOperand(1)))
3165 if (Node->getValueType(0) == MVT::f64) {
3166 assert(cast<MVTSDNode>(Node)->getExtraValueType() == MVT::f32 &&
3168 addConstantPoolReference(BuildMI(BB, X86::FLD32m, 4, Result),
3174 if (getRegPressure(Node->getOperand(0)) >
3175 getRegPressure(Node->getOperand(1))) {
3176 Select(Node->getOperand(0)); // chain
3177 SelectAddress(Node->getOperand(1), AM);
3179 SelectAddress(Node->getOperand(1), AM);
3180 Select(Node->getOperand(0)); // chain
3183 switch (Node->getValueType(0)) {
3184 default: assert(0 && "Unknown type to sign extend to.");
3186 assert(cast<MVTSDNode>(Node)->getExtraValueType() == MVT::f32 &&
3188 addFullAddress(BuildMI(BB, X86::FLD32m, 5, Result), AM);
3191 switch (cast<MVTSDNode>(Node)->getExtraValueType()) {
3193 assert(0 && "Bad zero extend!");
3196 addFullAddress(BuildMI(BB, X86::MOVZX32rm8, 5, Result), AM);
3199 addFullAddress(BuildMI(BB, X86::MOVZX32rm16, 5, Result), AM);
3204 assert(cast<MVTSDNode>(Node)->getExtraValueType() <= MVT::i8 &&
3205 "Bad zero extend!");
3206 addFullAddress(BuildMI(BB, X86::MOVSX16rm8, 5, Result), AM);
3209 assert(cast<MVTSDNode>(Node)->getExtraValueType() == MVT::i1 &&
3210 "Bad zero extend!");
3211 addFullAddress(BuildMI(BB, X86::MOV8rm, 5, Result), AM);
3216 case ISD::SEXTLOAD: {
3217 // Make sure we generate both values.
3219 ExprMap[N.getValue(1)] = 1; // Generate the token
3221 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3224 if (getRegPressure(Node->getOperand(0)) >
3225 getRegPressure(Node->getOperand(1))) {
3226 Select(Node->getOperand(0)); // chain
3227 SelectAddress(Node->getOperand(1), AM);
3229 SelectAddress(Node->getOperand(1), AM);
3230 Select(Node->getOperand(0)); // chain
3233 switch (Node->getValueType(0)) {
3234 case MVT::i8: assert(0 && "Cannot sign extend from bool!");
3235 default: assert(0 && "Unknown type to sign extend to.");
3237 switch (cast<MVTSDNode>(Node)->getExtraValueType()) {
3239 case MVT::i1: assert(0 && "Cannot sign extend from bool!");
3241 addFullAddress(BuildMI(BB, X86::MOVSX32rm8, 5, Result), AM);
3244 addFullAddress(BuildMI(BB, X86::MOVSX32rm16, 5, Result), AM);
3249 assert(cast<MVTSDNode>(Node)->getExtraValueType() == MVT::i8 &&
3250 "Cannot sign extend from bool!");
3251 addFullAddress(BuildMI(BB, X86::MOVSX16rm8, 5, Result), AM);
3257 case ISD::DYNAMIC_STACKALLOC:
3258 // Generate both result values.
3260 ExprMap[N.getValue(1)] = 1; // Generate the token
3262 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3264 // FIXME: We are currently ignoring the requested alignment for handling
3265 // greater than the stack alignment. This will need to be revisited at some
3266 // point. Align = N.getOperand(2);
3268 if (!isa<ConstantSDNode>(N.getOperand(2)) ||
3269 cast<ConstantSDNode>(N.getOperand(2))->getValue() != 0) {
3270 std::cerr << "Cannot allocate stack object with greater alignment than"
3271 << " the stack alignment yet!";
3275 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
3276 Select(N.getOperand(0));
3277 BuildMI(BB, X86::SUB32ri, 2, X86::ESP).addReg(X86::ESP)
3278 .addImm(CN->getValue());
3280 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3281 Select(N.getOperand(0));
3282 Tmp1 = SelectExpr(N.getOperand(1));
3284 Tmp1 = SelectExpr(N.getOperand(1));
3285 Select(N.getOperand(0));
3288 // Subtract size from stack pointer, thereby allocating some space.
3289 BuildMI(BB, X86::SUB32rr, 2, X86::ESP).addReg(X86::ESP).addReg(Tmp1);
3292 // Put a pointer to the space into the result register, by copying the stack
3294 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::ESP);
3297 case X86ISD::TAILCALL:
3298 case X86ISD::CALL: {
3299 // The chain for this call is now lowered.
3300 ExprMap.insert(std::make_pair(N.getValue(0), 1));
3302 bool isDirect = isa<GlobalAddressSDNode>(N.getOperand(1)) ||
3303 isa<ExternalSymbolSDNode>(N.getOperand(1));
3304 unsigned Callee = 0;
3306 Select(N.getOperand(0));
3308 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3309 Select(N.getOperand(0));
3310 Callee = SelectExpr(N.getOperand(1));
3312 Callee = SelectExpr(N.getOperand(1));
3313 Select(N.getOperand(0));
3317 // If this call has values to pass in registers, do so now.
3318 if (Node->getNumOperands() > 4) {
3319 // The first value is passed in (a part of) EAX, the second in EDX.
3320 unsigned RegOp1 = SelectExpr(N.getOperand(4));
3322 Node->getNumOperands() > 5 ? SelectExpr(N.getOperand(5)) : 0;
3324 switch (N.getOperand(4).getValueType()) {
3325 default: assert(0 && "Bad thing to pass in regs");
3327 case MVT::i8: BuildMI(BB, X86::MOV8rr , 1,X86::AL).addReg(RegOp1); break;
3328 case MVT::i16: BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1); break;
3329 case MVT::i32: BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);break;
3332 switch (N.getOperand(5).getValueType()) {
3333 default: assert(0 && "Bad thing to pass in regs");
3336 BuildMI(BB, X86::MOV8rr , 1, X86::DL).addReg(RegOp2);
3339 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
3342 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
3347 if (GlobalAddressSDNode *GASD =
3348 dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
3349 BuildMI(BB, X86::CALLpcrel32, 1).addGlobalAddress(GASD->getGlobal(),true);
3350 } else if (ExternalSymbolSDNode *ESSDN =
3351 dyn_cast<ExternalSymbolSDNode>(N.getOperand(1))) {
3352 BuildMI(BB, X86::CALLpcrel32,
3353 1).addExternalSymbol(ESSDN->getSymbol(), true);
3355 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3356 Select(N.getOperand(0));
3357 Tmp1 = SelectExpr(N.getOperand(1));
3359 Tmp1 = SelectExpr(N.getOperand(1));
3360 Select(N.getOperand(0));
3363 BuildMI(BB, X86::CALL32r, 1).addReg(Tmp1);
3366 // Get caller stack amount and amount the callee added to the stack pointer.
3367 Tmp1 = cast<ConstantSDNode>(N.getOperand(2))->getValue();
3368 Tmp2 = cast<ConstantSDNode>(N.getOperand(3))->getValue();
3369 BuildMI(BB, X86::ADJCALLSTACKUP, 2).addImm(Tmp1).addImm(Tmp2);
3371 if (Node->getNumValues() != 1)
3372 switch (Node->getValueType(1)) {
3373 default: assert(0 && "Unknown value type for call result!");
3374 case MVT::Other: return 1;
3377 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3380 BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3383 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3384 if (Node->getNumValues() == 3 && Node->getValueType(2) == MVT::i32)
3385 BuildMI(BB, X86::MOV32rr, 1, Result+1).addReg(X86::EDX);
3387 case MVT::f64: // Floating-point return values live in %ST(0)
3388 ContainsFPCode = true;
3389 BuildMI(BB, X86::FpGETRESULT, 1, Result);
3392 return Result+N.ResNo-1;
3395 // First, determine that the size of the operand falls within the acceptable
3396 // range for this architecture.
3398 if (Node->getOperand(1).getValueType() != MVT::i16) {
3399 std::cerr << "llvm.readport: Address size is not 16 bits\n";
3403 // Make sure we generate both values.
3404 if (Result != 1) { // Generate the token
3405 if (!ExprMap.insert(std::make_pair(N.getValue(1), 1)).second)
3406 assert(0 && "readport already emitted!?");
3408 Result = ExprMap[N.getValue(0)] = MakeReg(N.getValue(0).getValueType());
3410 Select(Node->getOperand(0)); // Select the chain.
3412 // If the port is a single-byte constant, use the immediate form.
3413 if (ConstantSDNode *Port = dyn_cast<ConstantSDNode>(Node->getOperand(1)))
3414 if ((Port->getValue() & 255) == Port->getValue()) {
3415 switch (Node->getValueType(0)) {
3417 BuildMI(BB, X86::IN8ri, 1).addImm(Port->getValue());
3418 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3421 BuildMI(BB, X86::IN16ri, 1).addImm(Port->getValue());
3422 BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3425 BuildMI(BB, X86::IN32ri, 1).addImm(Port->getValue());
3426 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3432 // Now, move the I/O port address into the DX register and use the IN
3433 // instruction to get the input data.
3435 Tmp1 = SelectExpr(Node->getOperand(1));
3436 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Tmp1);
3437 switch (Node->getValueType(0)) {
3439 BuildMI(BB, X86::IN8rr, 0);
3440 BuildMI(BB, X86::MOV8rr, 1, Result).addReg(X86::AL);
3443 BuildMI(BB, X86::IN16rr, 0);
3444 BuildMI(BB, X86::MOV16rr, 1, Result).addReg(X86::AX);
3447 BuildMI(BB, X86::IN32rr, 0);
3448 BuildMI(BB, X86::MOV32rr, 1, Result).addReg(X86::EAX);
3451 std::cerr << "Cannot do input on this data type";
3460 /// TryToFoldLoadOpStore - Given a store node, try to fold together a
3461 /// load/op/store instruction. If successful return true.
3462 bool ISel::TryToFoldLoadOpStore(SDNode *Node) {
3463 assert(Node->getOpcode() == ISD::STORE && "Can only do this for stores!");
3464 SDOperand Chain = Node->getOperand(0);
3465 SDOperand StVal = Node->getOperand(1);
3466 SDOperand StPtr = Node->getOperand(2);
3468 // The chain has to be a load, the stored value must be an integer binary
3469 // operation with one use.
3470 if (!StVal.Val->hasOneUse() || StVal.Val->getNumOperands() != 2 ||
3471 MVT::isFloatingPoint(StVal.getValueType()))
3474 // Token chain must either be a factor node or the load to fold.
3475 if (Chain.getOpcode() != ISD::LOAD && Chain.getOpcode() != ISD::TokenFactor)
3480 // Check to see if there is a load from the same pointer that we're storing
3481 // to in either operand of the binop.
3482 if (StVal.getOperand(0).getOpcode() == ISD::LOAD &&
3483 StVal.getOperand(0).getOperand(1) == StPtr)
3484 TheLoad = StVal.getOperand(0);
3485 else if (StVal.getOperand(1).getOpcode() == ISD::LOAD &&
3486 StVal.getOperand(1).getOperand(1) == StPtr)
3487 TheLoad = StVal.getOperand(1);
3489 return false; // No matching load operand.
3491 // We can only fold the load if there are no intervening side-effecting
3492 // operations. This means that the store uses the load as its token chain, or
3493 // there are only token factor nodes in between the store and load.
3494 if (Chain != TheLoad.getValue(1)) {
3495 // Okay, the other option is that we have a store referring to (possibly
3496 // nested) token factor nodes. For now, just try peeking through one level
3497 // of token factors to see if this is the case.
3498 bool ChainOk = false;
3499 if (Chain.getOpcode() == ISD::TokenFactor) {
3500 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3501 if (Chain.getOperand(i) == TheLoad.getValue(1)) {
3507 if (!ChainOk) return false;
3510 if (TheLoad.getOperand(1) != StPtr)
3513 // Make sure that one of the operands of the binop is the load, and that the
3514 // load folds into the binop.
3515 if (((StVal.getOperand(0) != TheLoad ||
3516 !isFoldableLoad(TheLoad, StVal.getOperand(1))) &&
3517 (StVal.getOperand(1) != TheLoad ||
3518 !isFoldableLoad(TheLoad, StVal.getOperand(0)))))
3521 // Finally, check to see if this is one of the ops we can handle!
3522 static const unsigned ADDTAB[] = {
3523 X86::ADD8mi, X86::ADD16mi, X86::ADD32mi,
3524 X86::ADD8mr, X86::ADD16mr, X86::ADD32mr,
3526 static const unsigned SUBTAB[] = {
3527 X86::SUB8mi, X86::SUB16mi, X86::SUB32mi,
3528 X86::SUB8mr, X86::SUB16mr, X86::SUB32mr,
3530 static const unsigned ANDTAB[] = {
3531 X86::AND8mi, X86::AND16mi, X86::AND32mi,
3532 X86::AND8mr, X86::AND16mr, X86::AND32mr,
3534 static const unsigned ORTAB[] = {
3535 X86::OR8mi, X86::OR16mi, X86::OR32mi,
3536 X86::OR8mr, X86::OR16mr, X86::OR32mr,
3538 static const unsigned XORTAB[] = {
3539 X86::XOR8mi, X86::XOR16mi, X86::XOR32mi,
3540 X86::XOR8mr, X86::XOR16mr, X86::XOR32mr,
3542 static const unsigned SHLTAB[] = {
3543 X86::SHL8mi, X86::SHL16mi, X86::SHL32mi,
3544 /*Have to put the reg in CL*/0, 0, 0,
3546 static const unsigned SARTAB[] = {
3547 X86::SAR8mi, X86::SAR16mi, X86::SAR32mi,
3548 /*Have to put the reg in CL*/0, 0, 0,
3550 static const unsigned SHRTAB[] = {
3551 X86::SHR8mi, X86::SHR16mi, X86::SHR32mi,
3552 /*Have to put the reg in CL*/0, 0, 0,
3555 const unsigned *TabPtr = 0;
3556 switch (StVal.getOpcode()) {
3558 std::cerr << "CANNOT [mem] op= val: ";
3559 StVal.Val->dump(); std::cerr << "\n";
3564 case ISD::UREM: return false;
3566 case ISD::ADD: TabPtr = ADDTAB; break;
3567 case ISD::SUB: TabPtr = SUBTAB; break;
3568 case ISD::AND: TabPtr = ANDTAB; break;
3569 case ISD:: OR: TabPtr = ORTAB; break;
3570 case ISD::XOR: TabPtr = XORTAB; break;
3571 case ISD::SHL: TabPtr = SHLTAB; break;
3572 case ISD::SRA: TabPtr = SARTAB; break;
3573 case ISD::SRL: TabPtr = SHRTAB; break;
3576 // Handle: [mem] op= CST
3577 SDOperand Op0 = StVal.getOperand(0);
3578 SDOperand Op1 = StVal.getOperand(1);
3580 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Op1)) {
3581 switch (Op0.getValueType()) { // Use Op0's type because of shifts.
3584 case MVT::i8: Opc = TabPtr[0]; break;
3585 case MVT::i16: Opc = TabPtr[1]; break;
3586 case MVT::i32: Opc = TabPtr[2]; break;
3590 if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
3591 assert(0 && "Already emitted?");
3595 if (getRegPressure(TheLoad.getOperand(0)) >
3596 getRegPressure(TheLoad.getOperand(1))) {
3597 Select(TheLoad.getOperand(0));
3598 SelectAddress(TheLoad.getOperand(1), AM);
3600 SelectAddress(TheLoad.getOperand(1), AM);
3601 Select(TheLoad.getOperand(0));
3604 if (StVal.getOpcode() == ISD::ADD) {
3605 if (CN->getValue() == 1) {
3606 switch (Op0.getValueType()) {
3609 addFullAddress(BuildMI(BB, X86::INC8m, 4), AM);
3611 case MVT::i16: Opc = TabPtr[1];
3612 addFullAddress(BuildMI(BB, X86::INC16m, 4), AM);
3614 case MVT::i32: Opc = TabPtr[2];
3615 addFullAddress(BuildMI(BB, X86::INC32m, 4), AM);
3618 } else if (CN->getValue()+1 == 0) { // [X] += -1 -> DEC [X]
3619 switch (Op0.getValueType()) {
3622 addFullAddress(BuildMI(BB, X86::DEC8m, 4), AM);
3624 case MVT::i16: Opc = TabPtr[1];
3625 addFullAddress(BuildMI(BB, X86::DEC16m, 4), AM);
3627 case MVT::i32: Opc = TabPtr[2];
3628 addFullAddress(BuildMI(BB, X86::DEC32m, 4), AM);
3634 addFullAddress(BuildMI(BB, Opc, 4+1),AM).addImm(CN->getValue());
3639 // If we have [mem] = V op [mem], try to turn it into:
3640 // [mem] = [mem] op V.
3641 if (Op1 == TheLoad && StVal.getOpcode() != ISD::SUB &&
3642 StVal.getOpcode() != ISD::SHL && StVal.getOpcode() != ISD::SRA &&
3643 StVal.getOpcode() != ISD::SRL)
3644 std::swap(Op0, Op1);
3646 if (Op0 != TheLoad) return false;
3648 switch (Op0.getValueType()) {
3649 default: return false;
3651 case MVT::i8: Opc = TabPtr[3]; break;
3652 case MVT::i16: Opc = TabPtr[4]; break;
3653 case MVT::i32: Opc = TabPtr[5]; break;
3656 // Table entry doesn't exist?
3657 if (Opc == 0) return false;
3659 if (!ExprMap.insert(std::make_pair(TheLoad.getValue(1), 1)).second)
3660 assert(0 && "Already emitted?");
3662 Select(TheLoad.getOperand(0));
3665 SelectAddress(TheLoad.getOperand(1), AM);
3666 unsigned Reg = SelectExpr(Op1);
3667 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Reg);
3671 /// If node is a ret(tailcall) node, emit the specified tail call and return
3672 /// true, otherwise return false.
3674 /// FIXME: This whole thing should be a post-legalize optimization pass which
3675 /// recognizes and transforms the dag. We don't want the selection phase doing
3678 bool ISel::EmitPotentialTailCall(SDNode *RetNode) {
3679 assert(RetNode->getOpcode() == ISD::RET && "Not a return");
3681 SDOperand Chain = RetNode->getOperand(0);
3683 // If this is a token factor node where one operand is a call, dig into it.
3684 SDOperand TokFactor;
3685 unsigned TokFactorOperand = 0;
3686 if (Chain.getOpcode() == ISD::TokenFactor) {
3687 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3688 if (Chain.getOperand(i).getOpcode() == ISD::CALLSEQ_END ||
3689 Chain.getOperand(i).getOpcode() == X86ISD::TAILCALL) {
3690 TokFactorOperand = i;
3692 Chain = Chain.getOperand(i);
3695 if (TokFactor.Val == 0) return false; // No call operand.
3698 // Skip the CALLSEQ_END node if present.
3699 if (Chain.getOpcode() == ISD::CALLSEQ_END)
3700 Chain = Chain.getOperand(0);
3702 // Is a tailcall the last control operation that occurs before the return?
3703 if (Chain.getOpcode() != X86ISD::TAILCALL)
3706 // If we return a value, is it the value produced by the call?
3707 if (RetNode->getNumOperands() > 1) {
3708 // Not returning the ret val of the call?
3709 if (Chain.Val->getNumValues() == 1 ||
3710 RetNode->getOperand(1) != Chain.getValue(1))
3713 if (RetNode->getNumOperands() > 2) {
3714 if (Chain.Val->getNumValues() == 2 ||
3715 RetNode->getOperand(2) != Chain.getValue(2))
3718 assert(RetNode->getNumOperands() <= 3);
3721 // CalleeCallArgAmt - The total number of bytes used for the callee arg area.
3722 // For FastCC, this will always be > 0.
3723 unsigned CalleeCallArgAmt =
3724 cast<ConstantSDNode>(Chain.getOperand(2))->getValue();
3726 // CalleeCallArgPopAmt - The number of bytes in the call area popped by the
3727 // callee. For FastCC this will always be > 0, for CCC this is always 0.
3728 unsigned CalleeCallArgPopAmt =
3729 cast<ConstantSDNode>(Chain.getOperand(3))->getValue();
3731 // There are several cases we can handle here. First, if the caller and
3732 // callee are both CCC functions, we can tailcall if the callee takes <= the
3733 // number of argument bytes that the caller does.
3734 if (CalleeCallArgPopAmt == 0 && // Callee is C CallingConv?
3735 X86Lowering.getBytesToPopOnReturn() == 0) { // Caller is C CallingConv?
3736 // Check to see if caller arg area size >= callee arg area size.
3737 if (X86Lowering.getBytesCallerReserves() >= CalleeCallArgAmt) {
3738 //std::cerr << "CCC TAILCALL UNIMP!\n";
3739 // If TokFactor is non-null, emit all operands.
3741 //EmitCCCToCCCTailCall(Chain.Val);
3747 // Second, if both are FastCC functions, we can always perform the tail call.
3748 if (CalleeCallArgPopAmt && X86Lowering.getBytesToPopOnReturn()) {
3749 // If TokFactor is non-null, emit all operands before the call.
3750 if (TokFactor.Val) {
3751 for (unsigned i = 0, e = TokFactor.getNumOperands(); i != e; ++i)
3752 if (i != TokFactorOperand)
3753 Select(TokFactor.getOperand(i));
3756 EmitFastCCToFastCCTailCall(Chain.Val);
3760 // We don't support mixed calls, due to issues with alignment. We could in
3761 // theory handle some mixed calls from CCC -> FastCC if the stack is properly
3762 // aligned (which depends on the number of arguments to the callee). TODO.
3766 static SDOperand GetAdjustedArgumentStores(SDOperand Chain, int Offset,
3767 SelectionDAG &DAG) {
3768 MVT::ValueType StoreVT;
3769 switch (Chain.getOpcode()) {
3770 case ISD::CALLSEQ_START:
3771 // If we found the start of the call sequence, we're done. We actually
3772 // strip off the CALLSEQ_START node, to avoid generating the
3773 // ADJCALLSTACKDOWN marker for the tail call.
3774 return Chain.getOperand(0);
3775 case ISD::TokenFactor: {
3776 std::vector<SDOperand> Ops;
3777 Ops.reserve(Chain.getNumOperands());
3778 for (unsigned i = 0, e = Chain.getNumOperands(); i != e; ++i)
3779 Ops.push_back(GetAdjustedArgumentStores(Chain.getOperand(i), Offset,DAG));
3780 return DAG.getNode(ISD::TokenFactor, MVT::Other, Ops);
3782 case ISD::STORE: // Normal store
3783 StoreVT = Chain.getOperand(1).getValueType();
3785 case ISD::TRUNCSTORE: // FLOAT store
3786 StoreVT = cast<MVTSDNode>(Chain)->getExtraValueType();
3790 SDOperand OrigDest = Chain.getOperand(2);
3791 unsigned OrigOffset;
3793 if (OrigDest.getOpcode() == ISD::CopyFromReg) {
3795 assert(cast<RegSDNode>(OrigDest)->getReg() == X86::ESP);
3797 // We expect only (ESP+C)
3798 assert(OrigDest.getOpcode() == ISD::ADD &&
3799 isa<ConstantSDNode>(OrigDest.getOperand(1)) &&
3800 OrigDest.getOperand(0).getOpcode() == ISD::CopyFromReg &&
3801 cast<RegSDNode>(OrigDest.getOperand(0))->getReg() == X86::ESP);
3802 OrigOffset = cast<ConstantSDNode>(OrigDest.getOperand(1))->getValue();
3805 // Compute the new offset from the incoming ESP value we wish to use.
3806 unsigned NewOffset = OrigOffset + Offset;
3808 unsigned OpSize = (MVT::getSizeInBits(StoreVT)+7)/8; // Bits -> Bytes
3809 MachineFunction &MF = DAG.getMachineFunction();
3810 int FI = MF.getFrameInfo()->CreateFixedObject(OpSize, NewOffset);
3811 SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
3813 SDOperand InChain = GetAdjustedArgumentStores(Chain.getOperand(0), Offset,
3815 if (Chain.getOpcode() == ISD::STORE)
3816 return DAG.getNode(ISD::STORE, MVT::Other, InChain, Chain.getOperand(1),
3818 assert(Chain.getOpcode() == ISD::TRUNCSTORE);
3819 return DAG.getNode(ISD::TRUNCSTORE, MVT::Other, InChain, Chain.getOperand(1),
3820 FIN, DAG.getSrcValue(NULL), StoreVT);
3824 /// EmitFastCCToFastCCTailCall - Given a tailcall in the tail position to a
3825 /// fastcc function from a fastcc function, emit the code to emit a 'proper'
3827 void ISel::EmitFastCCToFastCCTailCall(SDNode *TailCallNode) {
3828 unsigned CalleeCallArgSize =
3829 cast<ConstantSDNode>(TailCallNode->getOperand(2))->getValue();
3830 unsigned CallerArgSize = X86Lowering.getBytesToPopOnReturn();
3832 //std::cerr << "****\n*** EMITTING TAIL CALL!\n****\n";
3834 // Adjust argument stores. Instead of storing to [ESP], f.e., store to frame
3835 // indexes that are relative to the incoming ESP. If the incoming and
3836 // outgoing arg sizes are the same we will store to [InESP] instead of
3837 // [CurESP] and the ESP referenced will be relative to the incoming function
3839 int ESPOffset = CallerArgSize-CalleeCallArgSize;
3840 SDOperand AdjustedArgStores =
3841 GetAdjustedArgumentStores(TailCallNode->getOperand(0), ESPOffset, *TheDAG);
3843 // Copy the return address of the caller into a virtual register so we don't
3847 SDOperand RetValAddr = X86Lowering.getReturnAddressFrameIndex(*TheDAG);
3848 RetVal = TheDAG->getLoad(MVT::i32, TheDAG->getEntryNode(),
3849 RetValAddr, TheDAG->getSrcValue(NULL));
3853 // Codegen all of the argument stores.
3854 Select(AdjustedArgStores);
3857 // Emit a store of the saved ret value to the new location.
3858 MachineFunction &MF = TheDAG->getMachineFunction();
3859 int ReturnAddrFI = MF.getFrameInfo()->CreateFixedObject(4, ESPOffset-4);
3860 SDOperand RetValAddr = TheDAG->getFrameIndex(ReturnAddrFI, MVT::i32);
3861 Select(TheDAG->getNode(ISD::STORE, MVT::Other, TheDAG->getEntryNode(),
3862 RetVal, RetValAddr));
3865 // Get the destination value.
3866 SDOperand Callee = TailCallNode->getOperand(1);
3867 bool isDirect = isa<GlobalAddressSDNode>(Callee) ||
3868 isa<ExternalSymbolSDNode>(Callee);
3869 unsigned CalleeReg = 0;
3870 if (!isDirect) CalleeReg = SelectExpr(Callee);
3872 unsigned RegOp1 = 0;
3873 unsigned RegOp2 = 0;
3875 if (TailCallNode->getNumOperands() > 4) {
3876 // The first value is passed in (a part of) EAX, the second in EDX.
3877 RegOp1 = SelectExpr(TailCallNode->getOperand(4));
3878 if (TailCallNode->getNumOperands() > 5)
3879 RegOp2 = SelectExpr(TailCallNode->getOperand(5));
3881 switch (TailCallNode->getOperand(4).getValueType()) {
3882 default: assert(0 && "Bad thing to pass in regs");
3885 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(RegOp1);
3889 BuildMI(BB, X86::MOV16rr, 1,X86::AX).addReg(RegOp1);
3893 BuildMI(BB, X86::MOV32rr, 1,X86::EAX).addReg(RegOp1);
3898 switch (TailCallNode->getOperand(5).getValueType()) {
3899 default: assert(0 && "Bad thing to pass in regs");
3902 BuildMI(BB, X86::MOV8rr, 1, X86::DL).addReg(RegOp2);
3906 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(RegOp2);
3910 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(RegOp2);
3918 BuildMI(BB, X86::ADJSTACKPTRri, 2,
3919 X86::ESP).addReg(X86::ESP).addImm(ESPOffset);
3921 // TODO: handle jmp [mem]
3923 BuildMI(BB, X86::TAILJMPr, 1).addReg(CalleeReg);
3924 } else if (GlobalAddressSDNode *GASD = dyn_cast<GlobalAddressSDNode>(Callee)){
3925 BuildMI(BB, X86::TAILJMPd, 1).addGlobalAddress(GASD->getGlobal(), true);
3927 ExternalSymbolSDNode *ESSDN = cast<ExternalSymbolSDNode>(Callee);
3928 BuildMI(BB, X86::TAILJMPd, 1).addExternalSymbol(ESSDN->getSymbol(), true);
3930 // ADD IMPLICIT USE RegOp1/RegOp2's
3934 void ISel::Select(SDOperand N) {
3935 unsigned Tmp1, Tmp2, Opc;
3937 if (!ExprMap.insert(std::make_pair(N, 1)).second)
3938 return; // Already selected.
3940 SDNode *Node = N.Val;
3942 switch (Node->getOpcode()) {
3944 Node->dump(); std::cerr << "\n";
3945 assert(0 && "Node not handled yet!");
3946 case ISD::EntryToken: return; // Noop
3947 case ISD::TokenFactor:
3948 if (Node->getNumOperands() == 2) {
3950 getRegPressure(Node->getOperand(1))>getRegPressure(Node->getOperand(0));
3951 Select(Node->getOperand(OneFirst));
3952 Select(Node->getOperand(!OneFirst));
3954 std::vector<std::pair<unsigned, unsigned> > OpsP;
3955 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
3956 OpsP.push_back(std::make_pair(getRegPressure(Node->getOperand(i)), i));
3957 std::sort(OpsP.begin(), OpsP.end());
3958 std::reverse(OpsP.begin(), OpsP.end());
3959 for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
3960 Select(Node->getOperand(OpsP[i].second));
3963 case ISD::CopyToReg:
3964 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
3965 Select(N.getOperand(0));
3966 Tmp1 = SelectExpr(N.getOperand(1));
3968 Tmp1 = SelectExpr(N.getOperand(1));
3969 Select(N.getOperand(0));
3971 Tmp2 = cast<RegSDNode>(N)->getReg();
3974 switch (N.getOperand(1).getValueType()) {
3975 default: assert(0 && "Invalid type for operation!");
3977 case MVT::i8: Opc = X86::MOV8rr; break;
3978 case MVT::i16: Opc = X86::MOV16rr; break;
3979 case MVT::i32: Opc = X86::MOV32rr; break;
3980 case MVT::f64: Opc = X86::FpMOV; ContainsFPCode = true; break;
3982 BuildMI(BB, Opc, 1, Tmp2).addReg(Tmp1);
3986 if (N.getOperand(0).getOpcode() == ISD::CALLSEQ_END ||
3987 N.getOperand(0).getOpcode() == X86ISD::TAILCALL ||
3988 N.getOperand(0).getOpcode() == ISD::TokenFactor)
3989 if (EmitPotentialTailCall(Node))
3992 switch (N.getNumOperands()) {
3994 assert(0 && "Unknown return instruction!");
3996 assert(N.getOperand(1).getValueType() == MVT::i32 &&
3997 N.getOperand(2).getValueType() == MVT::i32 &&
3998 "Unknown two-register value!");
3999 if (getRegPressure(N.getOperand(1)) > getRegPressure(N.getOperand(2))) {
4000 Tmp1 = SelectExpr(N.getOperand(1));
4001 Tmp2 = SelectExpr(N.getOperand(2));
4003 Tmp2 = SelectExpr(N.getOperand(2));
4004 Tmp1 = SelectExpr(N.getOperand(1));
4006 Select(N.getOperand(0));
4008 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4009 BuildMI(BB, X86::MOV32rr, 1, X86::EDX).addReg(Tmp2);
4012 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
4013 Select(N.getOperand(0));
4014 Tmp1 = SelectExpr(N.getOperand(1));
4016 Tmp1 = SelectExpr(N.getOperand(1));
4017 Select(N.getOperand(0));
4019 switch (N.getOperand(1).getValueType()) {
4020 default: assert(0 && "All other types should have been promoted!!");
4022 BuildMI(BB, X86::FpSETRESULT, 1).addReg(Tmp1);
4025 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4030 Select(N.getOperand(0));
4033 if (X86Lowering.getBytesToPopOnReturn() == 0)
4034 BuildMI(BB, X86::RET, 0); // Just emit a 'ret' instruction
4036 BuildMI(BB, X86::RETI, 1).addImm(X86Lowering.getBytesToPopOnReturn());
4039 Select(N.getOperand(0));
4040 MachineBasicBlock *Dest =
4041 cast<BasicBlockSDNode>(N.getOperand(1))->getBasicBlock();
4042 BuildMI(BB, X86::JMP, 1).addMBB(Dest);
4047 MachineBasicBlock *Dest =
4048 cast<BasicBlockSDNode>(N.getOperand(2))->getBasicBlock();
4050 // Try to fold a setcc into the branch. If this fails, emit a test/jne
4052 if (EmitBranchCC(Dest, N.getOperand(0), N.getOperand(1))) {
4053 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(1))) {
4054 Select(N.getOperand(0));
4055 Tmp1 = SelectExpr(N.getOperand(1));
4057 Tmp1 = SelectExpr(N.getOperand(1));
4058 Select(N.getOperand(0));
4060 BuildMI(BB, X86::TEST8rr, 2).addReg(Tmp1).addReg(Tmp1);
4061 BuildMI(BB, X86::JNE, 1).addMBB(Dest);
4068 // If this load could be folded into the only using instruction, and if it
4069 // is safe to emit the instruction here, try to do so now.
4070 if (Node->hasNUsesOfValue(1, 0)) {
4071 SDOperand TheVal = N.getValue(0);
4073 for (SDNode::use_iterator UI = Node->use_begin(); ; ++UI) {
4074 assert(UI != Node->use_end() && "Didn't find use!");
4076 for (unsigned i = 0, e = UN->getNumOperands(); i != e; ++i)
4077 if (UN->getOperand(i) == TheVal) {
4083 // Only handle unary operators right now.
4084 if (User->getNumOperands() == 1) {
4086 SelectExpr(SDOperand(User, 0));
4097 case ISD::DYNAMIC_STACKALLOC:
4098 case X86ISD::TAILCALL:
4103 case ISD::CopyFromReg:
4104 case X86ISD::FILD64m:
4106 SelectExpr(N.getValue(0));
4109 case ISD::TRUNCSTORE: { // truncstore chain, val, ptr :storety
4110 // On X86, we can represent all types except for Bool and Float natively.
4112 MVT::ValueType StoredTy = cast<MVTSDNode>(Node)->getExtraValueType();
4113 assert((StoredTy == MVT::i1 || StoredTy == MVT::f32 ||
4114 StoredTy == MVT::i16 /*FIXME: THIS IS JUST FOR TESTING!*/)
4115 && "Unsupported TRUNCSTORE for this target!");
4117 if (StoredTy == MVT::i16) {
4118 // FIXME: This is here just to allow testing. X86 doesn't really have a
4119 // TRUNCSTORE i16 operation, but this is required for targets that do not
4120 // have 16-bit integer registers. We occasionally disable 16-bit integer
4121 // registers to test the promotion code.
4122 Select(N.getOperand(0));
4123 Tmp1 = SelectExpr(N.getOperand(1));
4124 SelectAddress(N.getOperand(2), AM);
4126 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4127 addFullAddress(BuildMI(BB, X86::MOV16mr, 5), AM).addReg(X86::AX);
4131 // Store of constant bool?
4132 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
4133 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4134 Select(N.getOperand(0));
4135 SelectAddress(N.getOperand(2), AM);
4137 SelectAddress(N.getOperand(2), AM);
4138 Select(N.getOperand(0));
4140 addFullAddress(BuildMI(BB, X86::MOV8mi, 5), AM).addImm(CN->getValue());
4145 default: assert(0 && "Cannot truncstore this type!");
4146 case MVT::i1: Opc = X86::MOV8mr; break;
4147 case MVT::f32: Opc = X86::FST32m; break;
4150 std::vector<std::pair<unsigned, unsigned> > RP;
4151 RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
4152 RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
4153 RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
4154 std::sort(RP.begin(), RP.end());
4156 Tmp1 = 0; // Silence a warning.
4157 for (unsigned i = 0; i != 3; ++i)
4158 switch (RP[2-i].second) {
4159 default: assert(0 && "Unknown operand number!");
4160 case 0: Select(N.getOperand(0)); break;
4161 case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
4162 case 2: SelectAddress(N.getOperand(2), AM); break;
4165 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
4171 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N.getOperand(1))) {
4173 switch (CN->getValueType(0)) {
4174 default: assert(0 && "Invalid type for operation!");
4176 case MVT::i8: Opc = X86::MOV8mi; break;
4177 case MVT::i16: Opc = X86::MOV16mi; break;
4178 case MVT::i32: Opc = X86::MOV32mi; break;
4179 case MVT::f64: break;
4182 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4183 Select(N.getOperand(0));
4184 SelectAddress(N.getOperand(2), AM);
4186 SelectAddress(N.getOperand(2), AM);
4187 Select(N.getOperand(0));
4189 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addImm(CN->getValue());
4192 } else if (GlobalAddressSDNode *GA =
4193 dyn_cast<GlobalAddressSDNode>(N.getOperand(1))) {
4194 assert(GA->getValueType(0) == MVT::i32 && "Bad pointer operand");
4196 if (getRegPressure(N.getOperand(0)) > getRegPressure(N.getOperand(2))) {
4197 Select(N.getOperand(0));
4198 SelectAddress(N.getOperand(2), AM);
4200 SelectAddress(N.getOperand(2), AM);
4201 Select(N.getOperand(0));
4203 addFullAddress(BuildMI(BB, X86::MOV32mi, 4+1),
4204 AM).addGlobalAddress(GA->getGlobal());
4208 // Check to see if this is a load/op/store combination.
4209 if (TryToFoldLoadOpStore(Node))
4212 switch (N.getOperand(1).getValueType()) {
4213 default: assert(0 && "Cannot store this type!");
4215 case MVT::i8: Opc = X86::MOV8mr; break;
4216 case MVT::i16: Opc = X86::MOV16mr; break;
4217 case MVT::i32: Opc = X86::MOV32mr; break;
4218 case MVT::f64: Opc = X86::FST64m; break;
4221 std::vector<std::pair<unsigned, unsigned> > RP;
4222 RP.push_back(std::make_pair(getRegPressure(N.getOperand(0)), 0));
4223 RP.push_back(std::make_pair(getRegPressure(N.getOperand(1)), 1));
4224 RP.push_back(std::make_pair(getRegPressure(N.getOperand(2)), 2));
4225 std::sort(RP.begin(), RP.end());
4227 Tmp1 = 0; // Silence a warning.
4228 for (unsigned i = 0; i != 3; ++i)
4229 switch (RP[2-i].second) {
4230 default: assert(0 && "Unknown operand number!");
4231 case 0: Select(N.getOperand(0)); break;
4232 case 1: Tmp1 = SelectExpr(N.getOperand(1)); break;
4233 case 2: SelectAddress(N.getOperand(2), AM); break;
4236 addFullAddress(BuildMI(BB, Opc, 4+1), AM).addReg(Tmp1);
4239 case ISD::CALLSEQ_START:
4240 Select(N.getOperand(0));
4242 Tmp1 = cast<ConstantSDNode>(N.getOperand(1))->getValue();
4243 BuildMI(BB, X86::ADJCALLSTACKDOWN, 1).addImm(Tmp1);
4245 case ISD::CALLSEQ_END:
4246 Select(N.getOperand(0));
4249 Select(N.getOperand(0)); // Select the chain.
4251 (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
4252 if (Align == 0) Align = 1;
4254 // Turn the byte code into # iterations
4257 if (ConstantSDNode *ValC = dyn_cast<ConstantSDNode>(Node->getOperand(2))) {
4258 unsigned Val = ValC->getValue() & 255;
4260 // If the value is a constant, then we can potentially use larger sets.
4261 switch (Align & 3) {
4262 case 2: // WORD aligned
4263 CountReg = MakeReg(MVT::i32);
4264 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4265 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
4267 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4268 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
4270 BuildMI(BB, X86::MOV16ri, 1, X86::AX).addImm((Val << 8) | Val);
4271 Opcode = X86::REP_STOSW;
4273 case 0: // DWORD aligned
4274 CountReg = MakeReg(MVT::i32);
4275 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4276 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
4278 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4279 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
4281 Val = (Val << 8) | Val;
4282 BuildMI(BB, X86::MOV32ri, 1, X86::EAX).addImm((Val << 16) | Val);
4283 Opcode = X86::REP_STOSD;
4285 default: // BYTE aligned
4286 CountReg = SelectExpr(Node->getOperand(3));
4287 BuildMI(BB, X86::MOV8ri, 1, X86::AL).addImm(Val);
4288 Opcode = X86::REP_STOSB;
4292 // If it's not a constant value we are storing, just fall back. We could
4293 // try to be clever to form 16 bit and 32 bit values, but we don't yet.
4294 unsigned ValReg = SelectExpr(Node->getOperand(2));
4295 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(ValReg);
4296 CountReg = SelectExpr(Node->getOperand(3));
4297 Opcode = X86::REP_STOSB;
4300 // No matter what the alignment is, we put the source in ESI, the
4301 // destination in EDI, and the count in ECX.
4302 unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
4303 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
4304 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
4305 BuildMI(BB, Opcode, 0);
4309 Select(N.getOperand(0)); // Select the chain.
4311 (unsigned)cast<ConstantSDNode>(Node->getOperand(4))->getValue();
4312 if (Align == 0) Align = 1;
4314 // Turn the byte code into # iterations
4317 switch (Align & 3) {
4318 case 2: // WORD aligned
4319 CountReg = MakeReg(MVT::i32);
4320 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4321 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/2);
4323 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4324 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(1);
4326 Opcode = X86::REP_MOVSW;
4328 case 0: // DWORD aligned
4329 CountReg = MakeReg(MVT::i32);
4330 if (ConstantSDNode *I = dyn_cast<ConstantSDNode>(Node->getOperand(3))) {
4331 BuildMI(BB, X86::MOV32ri, 1, CountReg).addImm(I->getValue()/4);
4333 unsigned ByteReg = SelectExpr(Node->getOperand(3));
4334 BuildMI(BB, X86::SHR32ri, 2, CountReg).addReg(ByteReg).addImm(2);
4336 Opcode = X86::REP_MOVSD;
4338 default: // BYTE aligned
4339 CountReg = SelectExpr(Node->getOperand(3));
4340 Opcode = X86::REP_MOVSB;
4344 // No matter what the alignment is, we put the source in ESI, the
4345 // destination in EDI, and the count in ECX.
4346 unsigned TmpReg1 = SelectExpr(Node->getOperand(1));
4347 unsigned TmpReg2 = SelectExpr(Node->getOperand(2));
4348 BuildMI(BB, X86::MOV32rr, 1, X86::ECX).addReg(CountReg);
4349 BuildMI(BB, X86::MOV32rr, 1, X86::EDI).addReg(TmpReg1);
4350 BuildMI(BB, X86::MOV32rr, 1, X86::ESI).addReg(TmpReg2);
4351 BuildMI(BB, Opcode, 0);
4354 case ISD::WRITEPORT:
4355 if (Node->getOperand(2).getValueType() != MVT::i16) {
4356 std::cerr << "llvm.writeport: Address size is not 16 bits\n";
4359 Select(Node->getOperand(0)); // Emit the chain.
4361 Tmp1 = SelectExpr(Node->getOperand(1));
4362 switch (Node->getOperand(1).getValueType()) {
4364 BuildMI(BB, X86::MOV8rr, 1, X86::AL).addReg(Tmp1);
4365 Tmp2 = X86::OUT8ir; Opc = X86::OUT8rr;
4368 BuildMI(BB, X86::MOV16rr, 1, X86::AX).addReg(Tmp1);
4369 Tmp2 = X86::OUT16ir; Opc = X86::OUT16rr;
4372 BuildMI(BB, X86::MOV32rr, 1, X86::EAX).addReg(Tmp1);
4373 Tmp2 = X86::OUT32ir; Opc = X86::OUT32rr;
4376 std::cerr << "llvm.writeport: invalid data type for X86 target";
4380 // If the port is a single-byte constant, use the immediate form.
4381 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Node->getOperand(2)))
4382 if ((CN->getValue() & 255) == CN->getValue()) {
4383 BuildMI(BB, Tmp2, 1).addImm(CN->getValue());
4387 // Otherwise, move the I/O port address into the DX register.
4388 unsigned Reg = SelectExpr(Node->getOperand(2));
4389 BuildMI(BB, X86::MOV16rr, 1, X86::DX).addReg(Reg);
4390 BuildMI(BB, Opc, 0);
4393 assert(0 && "Should not be reached!");
4397 /// createX86PatternInstructionSelector - This pass converts an LLVM function
4398 /// into a machine code representation using pattern matching and a machine
4399 /// description file.
4401 FunctionPass *llvm::createX86PatternInstructionSelector(TargetMachine &TM) {
4402 return new ISel(TM);